@zylem/game-lib 0.6.4 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (156) hide show
  1. package/README.md +18 -2
  2. package/dist/actions.d.ts +321 -11
  3. package/dist/actions.js +1 -936
  4. package/dist/api/game-lib.api.json +54074 -0
  5. package/dist/api/game-lib.api.md +4544 -0
  6. package/dist/api/game-lib.d.ts +8258 -0
  7. package/dist/api/game-lib.typedoc.json +345421 -0
  8. package/dist/audio.d.ts +13 -0
  9. package/dist/audio.js +1 -0
  10. package/dist/base-node-life-cycle-D2NuN1VB.d.ts +151 -0
  11. package/dist/behavior.d.ts +2 -0
  12. package/dist/behavior.js +1 -0
  13. package/dist/blueprints-TbGY-h53.d.ts +162 -0
  14. package/dist/chunk-4QLJUQSJ.js +1 -0
  15. package/dist/chunk-7FR5JSQ2.js +1 -0
  16. package/dist/chunk-7GYFZKK7.js +1 -0
  17. package/dist/chunk-7WRQ2UAN.js +1 -0
  18. package/dist/chunk-BH53MBAZ.js +1 -0
  19. package/dist/chunk-BIGH6D34.js +0 -0
  20. package/dist/chunk-CM5YRNBJ.js +19 -0
  21. package/dist/chunk-COM6HJ2L.js +1 -0
  22. package/dist/chunk-D2PATZCC.js +1 -0
  23. package/dist/chunk-DFLI7ICU.js +0 -0
  24. package/dist/chunk-E3UBSUPX.js +1 -0
  25. package/dist/chunk-FKIKN7RP.js +24 -0
  26. package/dist/chunk-G4HONLWC.js +1 -0
  27. package/dist/chunk-IKWE2W6L.js +1 -0
  28. package/dist/chunk-IPWUDOV5.js +1 -0
  29. package/dist/chunk-JEHFHUH4.js +0 -0
  30. package/dist/chunk-JNKPTL77.js +1 -0
  31. package/dist/chunk-JQKS42G4.js +1 -0
  32. package/dist/chunk-M3XNO56P.js +1 -0
  33. package/dist/chunk-MSC2BEO5.js +1 -0
  34. package/dist/chunk-ORIDWL3T.js +0 -0
  35. package/dist/chunk-QB3NL7VQ.js +1 -0
  36. package/dist/chunk-QXVH6POE.js +1 -0
  37. package/dist/chunk-RXDTAWI2.js +29 -0
  38. package/dist/chunk-TAUWDQZF.js +9 -0
  39. package/dist/chunk-VS2D4B3W.js +1 -0
  40. package/dist/chunk-WQ3WMMZD.js +1 -0
  41. package/dist/chunk-XK63E4SX.js +1 -0
  42. package/dist/chunk-XNDS4YFR.js +1 -0
  43. package/dist/chunk-XNHVRFAK.js +1 -0
  44. package/dist/chunk-XRP4JJXL.js +1 -0
  45. package/dist/chunk-YHEWKN7N.js +1 -0
  46. package/dist/chunk-ZRT3ZQVH.js +1 -0
  47. package/dist/collision-builder-jF-toPIl.d.ts +38 -0
  48. package/dist/core.d.ts +223 -16
  49. package/dist/core.js +1 -12424
  50. package/dist/debug-state-BPT6jEog.d.ts +17 -0
  51. package/dist/debug.d.ts +76 -0
  52. package/dist/debug.js +1 -0
  53. package/dist/default-controls-0-vCnli7.d.ts +111 -0
  54. package/dist/{entity-vj-HTjzU.d.ts → entity-BdSI8CL3.d.ts} +119 -626
  55. package/dist/{entity-Bq_eNEDI.d.ts → entity-DZbFQ1Wg.d.ts} +4 -4
  56. package/dist/entity-type-map-Bd69SpAS.d.ts +928 -0
  57. package/dist/entity.d.ts +268 -0
  58. package/dist/entity.js +1 -0
  59. package/dist/events.d.ts +181 -0
  60. package/dist/events.js +1 -0
  61. package/dist/game-C1FHVqXl.d.ts +1886 -0
  62. package/dist/game-default-QHROHW2O.js +1 -0
  63. package/dist/game-interfaces-mchNYSZE.d.ts +90 -0
  64. package/dist/globals.d.ts +115 -0
  65. package/dist/globals.js +1 -0
  66. package/dist/graphics.d.ts +53 -0
  67. package/dist/graphics.js +1 -0
  68. package/dist/input-ui.d.ts +35 -0
  69. package/dist/input-ui.js +1 -0
  70. package/dist/input.d.ts +73 -0
  71. package/dist/input.js +1 -0
  72. package/dist/material-9vJ6SZaI.d.ts +126 -0
  73. package/dist/public.d.ts +38 -0
  74. package/dist/public.js +1 -0
  75. package/dist/runtime.d.ts +59 -0
  76. package/dist/runtime.js +1 -0
  77. package/dist/schema/entity.schema.json +244 -0
  78. package/dist/schema/game-config.schema.json +625 -0
  79. package/dist/schema/input-config.schema.json +499 -0
  80. package/dist/schema/stage-config.schema.json +93 -0
  81. package/dist/schema/stage.schema.json +271 -0
  82. package/dist/schema.d.ts +538 -0
  83. package/dist/schema.js +1 -0
  84. package/dist/stage-transition-CmGpV4tc.d.ts +46 -0
  85. package/dist/vector-CiSHbivc.d.ts +133 -0
  86. package/dist/web-components.d.ts +70 -0
  87. package/dist/web-components.js +1 -0
  88. package/dist/zylem-camera-C3bn6BTI.d.ts +575 -0
  89. package/package.json +70 -73
  90. package/dist/actions.js.map +0 -1
  91. package/dist/behavior/jumper-2d.d.ts +0 -114
  92. package/dist/behavior/jumper-2d.js +0 -711
  93. package/dist/behavior/jumper-2d.js.map +0 -1
  94. package/dist/behavior/platformer-3d.d.ts +0 -296
  95. package/dist/behavior/platformer-3d.js +0 -761
  96. package/dist/behavior/platformer-3d.js.map +0 -1
  97. package/dist/behavior/ricochet-2d.d.ts +0 -275
  98. package/dist/behavior/ricochet-2d.js +0 -425
  99. package/dist/behavior/ricochet-2d.js.map +0 -1
  100. package/dist/behavior/ricochet-3d.d.ts +0 -117
  101. package/dist/behavior/ricochet-3d.js +0 -443
  102. package/dist/behavior/ricochet-3d.js.map +0 -1
  103. package/dist/behavior/screen-visibility.d.ts +0 -79
  104. package/dist/behavior/screen-visibility.js +0 -358
  105. package/dist/behavior/screen-visibility.js.map +0 -1
  106. package/dist/behavior/screen-wrap.d.ts +0 -87
  107. package/dist/behavior/screen-wrap.js +0 -246
  108. package/dist/behavior/screen-wrap.js.map +0 -1
  109. package/dist/behavior/shooter-2d.d.ts +0 -79
  110. package/dist/behavior/shooter-2d.js +0 -180
  111. package/dist/behavior/shooter-2d.js.map +0 -1
  112. package/dist/behavior/thruster.d.ts +0 -11
  113. package/dist/behavior/thruster.js +0 -292
  114. package/dist/behavior/thruster.js.map +0 -1
  115. package/dist/behavior/top-down-movement.d.ts +0 -56
  116. package/dist/behavior/top-down-movement.js +0 -125
  117. package/dist/behavior/top-down-movement.js.map +0 -1
  118. package/dist/behavior/world-boundary-2d.d.ts +0 -142
  119. package/dist/behavior/world-boundary-2d.js +0 -235
  120. package/dist/behavior/world-boundary-2d.js.map +0 -1
  121. package/dist/behavior/world-boundary-3d.d.ts +0 -76
  122. package/dist/behavior/world-boundary-3d.js +0 -274
  123. package/dist/behavior/world-boundary-3d.js.map +0 -1
  124. package/dist/behavior-descriptor-BXnVR8Ki.d.ts +0 -159
  125. package/dist/blueprints-DmbK2dki.d.ts +0 -26
  126. package/dist/camera-4XO5gbQH.d.ts +0 -905
  127. package/dist/camera.d.ts +0 -6
  128. package/dist/camera.js +0 -1993
  129. package/dist/camera.js.map +0 -1
  130. package/dist/composition-BASvMKrW.d.ts +0 -218
  131. package/dist/core-CARRaS55.d.ts +0 -541
  132. package/dist/core.js.map +0 -1
  133. package/dist/entities-ChFirVL9.d.ts +0 -410
  134. package/dist/entities.d.ts +0 -9
  135. package/dist/entities.js +0 -4986
  136. package/dist/entities.js.map +0 -1
  137. package/dist/entity-types-DAu8sGJH.d.ts +0 -26
  138. package/dist/global-change-2JvMaz44.d.ts +0 -25
  139. package/dist/main.d.ts +0 -1353
  140. package/dist/main.js +0 -19525
  141. package/dist/main.js.map +0 -1
  142. package/dist/physics-pose-DCc4oE44.d.ts +0 -25
  143. package/dist/physics-protocol-BDD3P5W2.d.ts +0 -200
  144. package/dist/physics-worker.d.ts +0 -21
  145. package/dist/physics-worker.js +0 -306
  146. package/dist/physics-worker.js.map +0 -1
  147. package/dist/physics.d.ts +0 -205
  148. package/dist/physics.js +0 -577
  149. package/dist/physics.js.map +0 -1
  150. package/dist/stage-types-C19IhuzA.d.ts +0 -731
  151. package/dist/stage.d.ts +0 -52
  152. package/dist/stage.js +0 -8479
  153. package/dist/stage.js.map +0 -1
  154. package/dist/sync-state-machine-CZyspBpj.d.ts +0 -16
  155. package/dist/thruster-23lzoPZd.d.ts +0 -180
  156. package/dist/world-DfgxoNMt.d.ts +0 -105
@@ -0,0 +1,1886 @@
1
+ import { e as InputPlayerNumber, f as InputProvider, I as Inputs, h as SetupFunction, g as UpdateFunction, j as DestroyFunction, a as SetupContext, U as UpdateContext, D as DestroyContext, L as LoadingEvent, m as IGame, S as StageNavigationOptions } from './base-node-life-cycle-D2NuN1VB.js';
2
+ import { G as GameInputConfig, B as BaseGlobals, Z as ZylemGameConfig } from './game-interfaces-mchNYSZE.js';
3
+ import { G as GameEntity, a as GameEntityOptions, B as BaseNode, y as GameEntityLifeCycle } from './entity-BdSI8CL3.js';
4
+ import { Scene, Color, Object3D, Vector3, BufferGeometry, Material, Group, Texture } from 'three';
5
+ import { ak as ZylemWorld, ai as EntityTypeMap } from './entity-type-map-Bd69SpAS.js';
6
+ import { E as Entity, L as LifecycleFunction, S as StageEntity } from './entity-DZbFQ1Wg.js';
7
+ import { k as ZylemCamera, R as RendererManager, e as CameraPerspective, d as CameraContext, C as CameraPose, P as PerspectiveType, f as CameraBehavior, g as CameraAction, h as CameraPipelineState, V as Viewport, Z as ZylemPostEffect } from './zylem-camera-C3bn6BTI.js';
8
+ import { d as ZylemShader } from './material-9vJ6SZaI.js';
9
+ import { l as SimulationBody, e as Vec3Input, b as Vec2Input, d as Vec3Components } from './vector-CiSHbivc.js';
10
+ import { BehaviorSystem, BehaviorEntityLink, BehaviorRuntime, BehaviorSystemFactory, Simulation } from '@zylem/behaviors/core';
11
+ import { StageEvents, GameEvents } from './events.js';
12
+ import { D as DefaultTouchControlsOptions } from './default-controls-0-vCnli7.js';
13
+ import { S as StageTransitionConfig } from './stage-transition-CmGpV4tc.js';
14
+
15
+ declare class InputManager {
16
+ private inputMap;
17
+ private currentInputs;
18
+ private previousInputs;
19
+ private readonly targetElement?;
20
+ private readonly mouseTargetElement?;
21
+ constructor(config?: GameInputConfig, options?: {
22
+ targetElement?: HTMLElement;
23
+ mouseTargetElement?: HTMLElement;
24
+ });
25
+ /**
26
+ * Reconfigure keyboard and mouse providers at runtime without affecting gamepad providers.
27
+ * Disposes existing keyboard/mouse providers and creates new ones from the given config.
28
+ */
29
+ configure(config: GameInputConfig): void;
30
+ addInputProvider(playerNumber: InputPlayerNumber, provider: InputProvider): void;
31
+ dispose(): void;
32
+ getInputs(delta: number): Inputs;
33
+ private buildPlayerEntries;
34
+ private addConfigurableProviders;
35
+ private createConfigurableProviders;
36
+ private mergeInputs;
37
+ }
38
+
39
+ /**
40
+ * This class is an alternative to {@link Clock} with a different API design and behavior.
41
+ * The goal is to avoid the conceptual flaws that became apparent in `Clock` over time.
42
+ *
43
+ * - `Timer` has an `update()` method that updates its internal state. That makes it possible to
44
+ * call `getDelta()` and `getElapsed()` multiple times per simulation step without getting different values.
45
+ * - The class can make use of the Page Visibility API to avoid large time delta values when the app
46
+ * is inactive (e.g. tab switched or browser hidden).
47
+ *
48
+ * ```js
49
+ * const timer = new Timer();
50
+ * timer.connect( document ); // use Page Visibility API
51
+ * ```
52
+ *
53
+ * @three_import import { Timer } from 'three/addons/misc/Timer.js';
54
+ */
55
+ declare class Timer {
56
+ protected _previousTime: number;
57
+ protected _currentTime: number;
58
+ protected _startTime: number;
59
+ protected _delta: number;
60
+ protected _elapsed: number;
61
+ protected _timescale: number;
62
+ protected _document: Document | null;
63
+ protected _pageVisibilityHandler: (() => void) | null;
64
+ /**
65
+ * Constructs a new timer.
66
+ */
67
+ constructor();
68
+ /**
69
+ * Connect the timer to the given document.Calling this method is not mandatory to
70
+ * use the timer but enables the usage of the Page Visibility API to avoid large time
71
+ * delta values.
72
+ *
73
+ * @param {Document} document - The document.
74
+ */
75
+ connect(document: Document): void;
76
+ /**
77
+ * Disconnects the timer from the DOM and also disables the usage of the Page Visibility API.
78
+ */
79
+ disconnect(): void;
80
+ /**
81
+ * Returns the time delta in seconds.
82
+ *
83
+ * @return {number} The time delta in second.
84
+ */
85
+ getDelta(): number;
86
+ /**
87
+ * Returns the elapsed time in seconds.
88
+ *
89
+ * @return {number} The elapsed time in second.
90
+ */
91
+ getElapsed(): number;
92
+ /**
93
+ * Returns the timescale.
94
+ *
95
+ * @return {number} The timescale.
96
+ */
97
+ getTimescale(): number;
98
+ /**
99
+ * Sets the given timescale which scale the time delta computation
100
+ * in `update()`.
101
+ *
102
+ * @param {number} timescale - The timescale to set.
103
+ * @return {Timer} A reference to this timer.
104
+ */
105
+ setTimescale(timescale: number): Timer;
106
+ /**
107
+ * Resets the time computation for the current simulation step.
108
+ *
109
+ * @return {Timer} A reference to this timer.
110
+ */
111
+ reset(): Timer;
112
+ /**
113
+ * Can be used to free all internal resources. Usually called when
114
+ * the timer instance isn't required anymore.
115
+ */
116
+ dispose(): void;
117
+ /**
118
+ * Updates the internal state of the timer. This method should be called
119
+ * once per simulation step and before you perform queries against the timer
120
+ * (e.g. via `getDelta()`).
121
+ *
122
+ * @param {number} timestamp - The current time in milliseconds. Can be obtained
123
+ * from the `requestAnimationFrame` callback argument. If not provided, the current
124
+ * time will be determined with `performance.now`.
125
+ * @return {Timer} A reference to this timer.
126
+ */
127
+ update(timestamp?: number): Timer;
128
+ }
129
+
130
+ /**
131
+ * CameraManager orchestrates multiple cameras per stage.
132
+ *
133
+ * Responsibilities:
134
+ * - Named camera registry (add/remove/get by name or reference)
135
+ * - Active camera list management (determines which cameras render)
136
+ * - Always-available debug camera with orbit controls
137
+ * - Per-frame update of all active cameras' perspective controllers
138
+ * - Coordinating rendering via RendererManager for all active viewports
139
+ */
140
+ declare class CameraManager {
141
+ /** Named camera registry */
142
+ private cameras;
143
+ /** Currently active cameras, ordered by render layer (first = bottom) */
144
+ private _activeCameras;
145
+ /** Auto-created debug camera with orbit controls */
146
+ private _debugCamera;
147
+ /** Reference to the shared renderer manager */
148
+ private _rendererManager;
149
+ /** Scene reference */
150
+ private _sceneRef;
151
+ /** Counter for auto-generated camera names */
152
+ private _autoNameCounter;
153
+ constructor();
154
+ /**
155
+ * Get the list of currently active cameras.
156
+ */
157
+ get activeCameras(): ReadonlyArray<ZylemCamera>;
158
+ /**
159
+ * Get the primary active camera (first in the active list).
160
+ */
161
+ get primaryCamera(): ZylemCamera | null;
162
+ /**
163
+ * Get the debug camera.
164
+ */
165
+ get debugCamera(): ZylemCamera | null;
166
+ /**
167
+ * Get all registered cameras.
168
+ */
169
+ get allCameras(): ReadonlyArray<ZylemCamera>;
170
+ /**
171
+ * Add a camera to the manager.
172
+ * If no name is provided, one is auto-generated.
173
+ * The first camera added becomes the active camera.
174
+ *
175
+ * @param camera The ZylemCamera instance to add
176
+ * @param name Optional name for lookup
177
+ * @returns The assigned name
178
+ */
179
+ addCamera(camera: ZylemCamera, name?: string): string;
180
+ /**
181
+ * Remove a camera by name or reference.
182
+ * Cannot remove the debug camera via this method.
183
+ */
184
+ removeCamera(nameOrRef: string | ZylemCamera): boolean;
185
+ /**
186
+ * Set a camera as the primary active camera (replaces all active cameras
187
+ * except additional viewport cameras).
188
+ *
189
+ * @param nameOrRef Camera name or reference to activate
190
+ */
191
+ setActiveCamera(nameOrRef: string | ZylemCamera): boolean;
192
+ /**
193
+ * Add a camera as an additional active camera (for split-screen or PiP).
194
+ */
195
+ addActiveCamera(nameOrRef: string | ZylemCamera): boolean;
196
+ /**
197
+ * Remove a camera from the active render list (does not remove from registry).
198
+ */
199
+ deactivateCamera(nameOrRef: string | ZylemCamera): boolean;
200
+ /**
201
+ * Get a camera by name.
202
+ */
203
+ getCamera(name: string): ZylemCamera | null;
204
+ /**
205
+ * Setup all cameras with the given scene and renderer manager.
206
+ * Also creates the debug camera.
207
+ */
208
+ setup(scene: Scene, rendererManager: RendererManager): Promise<void>;
209
+ /**
210
+ * Update all active cameras' controllers.
211
+ */
212
+ update(delta: number): void;
213
+ /**
214
+ * Render all active cameras through the renderer manager.
215
+ * RTT cameras (those with a renderTarget) are rendered first to their
216
+ * offscreen textures, then viewport cameras are rendered to the screen.
217
+ */
218
+ render(scene: Scene): void;
219
+ private updateOrbitingCamerasForRender;
220
+ /**
221
+ * Create a default third-person camera if no cameras have been added.
222
+ */
223
+ ensureDefaultCamera(): ZylemCamera;
224
+ /**
225
+ * Dispose all cameras and cleanup.
226
+ */
227
+ dispose(): void;
228
+ /**
229
+ * Create the always-available debug camera with orbit controls.
230
+ */
231
+ private createDebugCamera;
232
+ /**
233
+ * Resolve a camera from a name or reference.
234
+ */
235
+ private resolveCamera;
236
+ }
237
+
238
+ interface SceneState {
239
+ backgroundColor: Color | string;
240
+ backgroundImage: string | null;
241
+ backgroundShader?: ZylemShader | null;
242
+ /**
243
+ * When `false`, skip the engine's built-in ambient + directional lights so
244
+ * the caller can configure the scene's lighting entirely via
245
+ * `createLight(...)` entities. Defaults to `true` for backward
246
+ * compatibility with existing demos.
247
+ */
248
+ defaultLighting?: boolean;
249
+ }
250
+ declare class ZylemScene implements Entity<ZylemScene> {
251
+ type: string;
252
+ _setup?: SetupFunction<ZylemScene>;
253
+ scene: Scene;
254
+ /** @deprecated Use cameraManager instead */
255
+ zylemCamera: ZylemCamera;
256
+ cameraManager: CameraManager | null;
257
+ containerElement: HTMLElement | null;
258
+ update: LifecycleFunction<ZylemScene>;
259
+ _collision?: ((entity: any, other: any, globals?: any) => void) | undefined;
260
+ _destroy?: ((globals?: any) => void) | undefined;
261
+ name?: string | undefined;
262
+ tag?: Set<string> | undefined;
263
+ constructor(id: string, camera: ZylemCamera, state: SceneState);
264
+ /**
265
+ * Render the shader as a true skybox via the WebGPU renderer's
266
+ * `scene.backgroundNode`. The node is evaluated per background pixel at
267
+ * infinite depth — inside it, `normalWorld` (from `three/tsl`) is the
268
+ * per-pixel view direction, so the sky is stable under camera movement
269
+ * with no skybox mesh, far-plane sizing, or camera-follow logic.
270
+ *
271
+ * WebGPU-only: background shaders must be authored in TSL
272
+ * ({@link ZylemTSLShader}). A GLSL shader logs a warning and is ignored
273
+ * (the solid background color is kept).
274
+ */
275
+ private setupBackgroundShader;
276
+ setup(): void;
277
+ destroy(): void;
278
+ /**
279
+ * Setup camera with the scene.
280
+ * Supports both legacy single camera and CameraManager modes.
281
+ */
282
+ setupCamera(scene: Scene, camera: ZylemCamera, rendererManager?: RendererManager): Promise<void>;
283
+ /**
284
+ * Setup with a CameraManager (multi-camera support).
285
+ */
286
+ setupCameraManager(scene: Scene, cameraManager: CameraManager, rendererManager: RendererManager): Promise<void>;
287
+ /**
288
+ * Add a camera (rig or direct) to the scene graph.
289
+ */
290
+ private addCameraToScene;
291
+ /**
292
+ * Setup scene lighting
293
+ */
294
+ setupLighting(scene: Scene): void;
295
+ /**
296
+ * Update renderer size - delegates to camera manager or camera
297
+ */
298
+ updateRenderer(width: number, height: number): void;
299
+ /**
300
+ * Add object to scene
301
+ */
302
+ add(object: Object3D, position?: Vector3): void;
303
+ /**
304
+ * Add game entity to scene
305
+ */
306
+ addEntity(entity: GameEntity<any>): void;
307
+ /**
308
+ * Add an entity's group or mesh to the scene (for late-loaded models).
309
+ * Uses entity's current body position if physics is active.
310
+ *
311
+ * Fog entities ({@link ZylemFog}) are routed through the normal add
312
+ * pipeline so their empty placeholder group is parented for cleanup,
313
+ * but they also get an `attachToScene` call that wires `scene.fog`
314
+ * and starts the optional material patcher.
315
+ */
316
+ addEntityGroup(entity: GameEntity<any>): void;
317
+ private isAttachedOutsideScene;
318
+ /**
319
+ * Add debug helpers to scene
320
+ */
321
+ debugScene(): void;
322
+ }
323
+
324
+ /** Configuration for pack key generation */
325
+ interface PackKeyConfig {
326
+ geometryType: string;
327
+ dimensions: Record<string, number>;
328
+ materialPath?: string | null;
329
+ shaderType?: 'standard' | 'custom';
330
+ colorHex?: number;
331
+ }
332
+ /** Manages instanced mesh packs for `category: 'pack'` entities */
333
+ declare class InstanceManager {
334
+ private packs;
335
+ private entityToPack;
336
+ private scene;
337
+ /** Default initial capacity for new packs */
338
+ static DEFAULT_CAPACITY: number;
339
+ /** Factor to grow a pack when full */
340
+ static GROWTH_FACTOR: number;
341
+ setScene(scene: Object3D): void;
342
+ static generatePackKey(config: PackKeyConfig): string;
343
+ static generateEntityPackKey(entity: Pick<GameEntity<GameEntityOptions>, 'options' | 'materials'> & {
344
+ constructor: any;
345
+ }): string;
346
+ /**
347
+ * Register an entity with the instance manager.
348
+ * @returns The instance index, or -1 if registration failed
349
+ */
350
+ register(entity: GameEntity<any>, geometry: BufferGeometry, material: Material, packKey: string): number;
351
+ unregister(entity: GameEntity<any>): void;
352
+ markDirty(entity: GameEntity<any>): void;
353
+ /**
354
+ * Update all active instance transforms.
355
+ * Call once per frame after the simulation step and render-buffer sync.
356
+ */
357
+ update(interpolationAlpha?: number): void;
358
+ private updateInstanceMatrix;
359
+ getPackInfo(entity: GameEntity<any>): {
360
+ packKey: string;
361
+ instanceId: number;
362
+ } | null;
363
+ getStats(): {
364
+ packCount: number;
365
+ totalInstances: number;
366
+ packs: {
367
+ key: string;
368
+ count: number;
369
+ capacity: number;
370
+ }[];
371
+ };
372
+ dispose(): void;
373
+ private createPack;
374
+ private growPack;
375
+ }
376
+
377
+ /**
378
+ * Groups static environment meshes into WebGPU `BundleGroup`s for record-once
379
+ * replay. Dynamic entities must use `pack` (instancing) or `none` (scene-direct).
380
+ */
381
+ declare class RenderBundleManager {
382
+ private readonly bundles;
383
+ private readonly entityToBundle;
384
+ private scene;
385
+ setScene(scene: Object3D): void;
386
+ /**
387
+ * Parent the entity's renderable into a static bundle group.
388
+ * @returns `true` when registration succeeded.
389
+ */
390
+ register(entity: GameEntity<any>, _geometry: BufferGeometry, _material: Material, bundleKey: string): boolean;
391
+ unregister(entity: GameEntity<any>): void;
392
+ getStats(): {
393
+ bundleCount: number;
394
+ entityCount: number;
395
+ };
396
+ dispose(): void;
397
+ private getOrCreateBundle;
398
+ }
399
+
400
+ /**
401
+ * Routes entities to scene-direct (`none`), WebGPU bundles (`environment`), or
402
+ * instanced meshes (`pack`) based on `options.category`.
403
+ */
404
+ declare class RenderStrategyManager {
405
+ readonly bundles: RenderBundleManager;
406
+ readonly instances: InstanceManager;
407
+ setScene(scene: Object3D): void;
408
+ /**
409
+ * Register an entity with the appropriate managed render path.
410
+ * @returns `true` when the entity was placed into bundle or instanced rendering.
411
+ */
412
+ register(entity: GameEntity<any>): boolean;
413
+ unregister(entity: GameEntity<any>): void;
414
+ update(interpolationAlpha?: number): void;
415
+ dispose(): void;
416
+ }
417
+
418
+ /**
419
+ * Base entity interface - shared across modules to prevent circular dependencies
420
+ */
421
+ interface BaseEntityInterface {
422
+ uuid: string;
423
+ name: string;
424
+ group: Group | null | undefined;
425
+ body: SimulationBody | null | undefined;
426
+ }
427
+ /**
428
+ * Game entity interface - minimal interface to break circular dependencies
429
+ */
430
+ interface GameEntityInterface extends BaseEntityInterface {
431
+ type: string;
432
+ isStatic: boolean;
433
+ setPosition(x: number, y: number, z: number): void;
434
+ setRotation(x: number, y: number, z: number): void;
435
+ setScale(x: number, y: number, z: number): void;
436
+ }
437
+
438
+ /**
439
+ * Provides BaseNode-like lifecycle without ECS/children. Consumers implement
440
+ * the protected hooks and may assign public setup/update/destroy callbacks.
441
+ */
442
+ declare abstract class LifeCycleBase<TSelf> {
443
+ update: UpdateFunction<TSelf>;
444
+ setup: SetupFunction<TSelf>;
445
+ destroy: DestroyFunction<TSelf>;
446
+ protected abstract _setup(context: SetupContext<TSelf>): void;
447
+ protected abstract _update(context: UpdateContext<TSelf>): void;
448
+ protected abstract _destroy(context: DestroyContext<TSelf>): void;
449
+ nodeSetup(context: SetupContext<TSelf>): void;
450
+ nodeUpdate(context: UpdateContext<TSelf>): void;
451
+ nodeDestroy(context: DestroyContext<TSelf>): void;
452
+ }
453
+
454
+ /**
455
+ * Configuration for the third-person perspective.
456
+ */
457
+ interface ThirdPersonOptions {
458
+ /** Distance behind the target. Default 8. */
459
+ distance?: number;
460
+ /** Height above the target. Default 5. */
461
+ height?: number;
462
+ /** Lateral offset from the target (shoulder cam). Default 0. */
463
+ shoulderOffset?: number;
464
+ /** Key in CameraContext.targets to follow. Default 'primary'. */
465
+ targetKey?: string;
466
+ /** Perspective field of view. Default 75. */
467
+ fov?: number;
468
+ /** Padding multiplier when framing multiple targets. Default 1.5. */
469
+ paddingFactor?: number;
470
+ /** Minimum camera distance when multi-framing. Default 5. */
471
+ minDistance?: number;
472
+ /** Fallback camera position when no targets exist (e.g. the user-specified initial position). */
473
+ initialPosition?: Vec3Input;
474
+ /** Fallback lookAt point when no targets exist. */
475
+ initialLookAt?: Vec3Input;
476
+ /**
477
+ * Seconds the camera lags behind the target's actual position. The camera
478
+ * samples target moves from `now - trailDelay` so brief, fast Y motion
479
+ * (jump apex / fall start) doesn't get tracked 1:1 — eliminates the
480
+ * shimmer-on-fall effect at high refresh rates. 0 disables the trail and
481
+ * restores instantaneous tracking. Default 0.1 (100 ms).
482
+ */
483
+ trailDelay?: number;
484
+ /**
485
+ * Maximum number of samples to keep in the trailing ring buffer.
486
+ * Sized to cover ~1 s at 120 Hz; larger only matters if `trailDelay` is
487
+ * raised significantly. Default 120.
488
+ */
489
+ trailBufferSize?: number;
490
+ }
491
+ /**
492
+ * Third-person 3D perspective.
493
+ *
494
+ * - 0 targets: returns a static pose behind the origin.
495
+ * - 1 target: camera positioned behind and above the target, looking at it.
496
+ * - 2+ targets: weighted-centroid framing with dynamic distance.
497
+ */
498
+ declare class ThirdPersonPerspective implements CameraPerspective {
499
+ readonly id = "third-person";
500
+ /**
501
+ * Slightly looser than the previous 0.15 to compose better with the
502
+ * trailing-delay follow: the trail absorbs short, fast moves and the
503
+ * damping smooths the rest.
504
+ */
505
+ readonly defaults: {
506
+ damping: number;
507
+ };
508
+ private opts;
509
+ private initialPosition?;
510
+ private initialLookAt?;
511
+ /** Per-target ring buffers for trailing-delay sampling, keyed by target key. */
512
+ private _trailBuffers;
513
+ constructor(options?: ThirdPersonOptions);
514
+ getBasePose(ctx: CameraContext): CameraPose;
515
+ /**
516
+ * No targets: use the user-specified initial position if available,
517
+ * otherwise fall back to a default pose behind the origin.
518
+ */
519
+ private staticPose;
520
+ /**
521
+ * Single target: position = trailedTarget + offset, lookAt = trailedTarget.
522
+ *
523
+ * The trailed position lags `targetPos` by `trailDelay` seconds (default
524
+ * 100 ms), so transient spikes in target Y (the start of a fall, jump apex)
525
+ * don't propagate into the camera every frame. Both `position` and
526
+ * `lookAt` are derived from the same trailed point so the relative offset
527
+ * is preserved exactly.
528
+ */
529
+ private singleTargetPose;
530
+ /**
531
+ * Multi-target: compute centroid (using trailed positions) and adjust
532
+ * distance to frame all targets.
533
+ */
534
+ private multiTargetPose;
535
+ /**
536
+ * Push the current target position into the per-target ring buffer and
537
+ * return a position interpolated at `now - trailDelay`.
538
+ *
539
+ * - When `trailDelay` is 0 the call short-circuits and returns `targetPos`
540
+ * unchanged (no allocation, no buffer growth).
541
+ * - During the warmup window (the first `trailDelay` seconds of life)
542
+ * the oldest sample is returned so the camera starts from rest rather
543
+ * than snapping to the live target.
544
+ */
545
+ private getTrailedPosition;
546
+ }
547
+
548
+ /**
549
+ * Configuration for the fixed 2D perspective.
550
+ */
551
+ interface Fixed2DOptions {
552
+ /** Fixed camera position. Default (0, 0, 10). */
553
+ position?: Vec3Input;
554
+ /** Orthographic zoom (frustum size). Default 10. */
555
+ zoom?: number;
556
+ }
557
+ /**
558
+ * Fixed 2D perspective.
559
+ *
560
+ * Returns a static orthographic pose looking down the Z-axis.
561
+ * No target following -- the camera stays at the configured position.
562
+ */
563
+ declare class Fixed2DPerspective implements CameraPerspective {
564
+ readonly id = "fixed-2d";
565
+ readonly defaults: {
566
+ damping: number;
567
+ };
568
+ private opts;
569
+ constructor(options?: Fixed2DOptions);
570
+ getBasePose(_ctx: CameraContext): CameraPose;
571
+ }
572
+
573
+ /**
574
+ * Configuration for the first-person perspective.
575
+ */
576
+ interface FirstPersonOptions {
577
+ /** Vertical offset above the target entity's position (eye height). @default 1.7 */
578
+ eyeHeight?: number;
579
+ /** Default field of view in degrees. @default 75 */
580
+ defaultFov?: number;
581
+ /** Maximum pitch angle in radians. @default Math.PI/2 - 0.01 */
582
+ pitchLimit?: number;
583
+ /** Lerp speed for smooth look-at transitions. @default 5 */
584
+ lookAtLerpSpeed?: number;
585
+ /** Lerp speed for FOV zoom transitions. @default 8 */
586
+ fovLerpSpeed?: number;
587
+ /** Key in CameraContext.targets to follow. @default 'primary' */
588
+ targetKey?: string;
589
+ /** Fallback position when no target entity is attached. */
590
+ initialPosition?: Vec3Input;
591
+ /** Fallback look-at point used to derive initial yaw/pitch when no target. */
592
+ initialLookAt?: Vec3Input;
593
+ /**
594
+ * Vertical (eye-height) smoothing factor in 0..1, applied per 60Hz frame.
595
+ * 1 = instant snap (no smoothing), lower = smoother. Hides physics
596
+ * micro-jitter and Rapier sub-step Y corrections without adding perceptible
597
+ * input lag. Smooths only Y; X/Z still snap to the target every frame so
598
+ * horizontal aim is never laggy.
599
+ * @default 1 (disabled)
600
+ */
601
+ verticalSmoothing?: number;
602
+ }
603
+ /**
604
+ * First-person camera perspective.
605
+ *
606
+ * Position is derived from the attached target entity (+ eye height).
607
+ * Rotation is driven via `look()` / `setLook()` methods called by game code
608
+ * or a future FPS behavior. Supports smooth FOV zoom and lerp'd look-at.
609
+ */
610
+ declare class FirstPersonPerspective implements CameraPerspective {
611
+ readonly id = "first-person";
612
+ readonly defaults: {
613
+ damping: number;
614
+ };
615
+ private opts;
616
+ /** Fallback position when no target entity is attached. Mutate directly for manual movement. */
617
+ initialPosition?: Vector3;
618
+ private initialLookAt?;
619
+ private _yaw;
620
+ private _pitch;
621
+ private _currentFov;
622
+ private _targetFov;
623
+ private _lookAtTarget;
624
+ private _lookAtLerpSpeed;
625
+ private _currentRotation;
626
+ private _rotationInitialized;
627
+ private _smoothedY;
628
+ constructor(options?: FirstPersonOptions);
629
+ /** Accumulate yaw and pitch deltas. Pitch is clamped to the configured limit. */
630
+ look(deltaYaw: number, deltaPitch: number): void;
631
+ /** Set absolute yaw and pitch. Pitch is clamped to the configured limit. */
632
+ setLook(yaw: number, pitch: number): void;
633
+ /** Current yaw in radians. */
634
+ get yaw(): number;
635
+ /** Current pitch in radians. */
636
+ get pitch(): number;
637
+ /** Set the target FOV for a smooth zoom transition (e.g. sniper scope). */
638
+ zoom(fov: number): void;
639
+ /** Return to the default FOV. */
640
+ resetZoom(): void;
641
+ /** Current field of view. */
642
+ get currentFov(): number;
643
+ /**
644
+ * Enable smooth look-at toward a world position.
645
+ * The camera will slerp from the current rotation toward the look-at direction.
646
+ */
647
+ lookAt(target: Vector3, lerpSpeed?: number): void;
648
+ /** Disable look-at and return to manual yaw/pitch control. */
649
+ clearLookAt(): void;
650
+ getBasePose(ctx: CameraContext): CameraPose;
651
+ private computePosition;
652
+ /**
653
+ * Low-pass filter the eye Y so Rapier sub-step corrections and probe-driven
654
+ * micro-bobs don't show up as visible head jitter. X/Z are left un-smoothed
655
+ * so horizontal aim remains 1:1 with input.
656
+ */
657
+ private smoothVertical;
658
+ private computeRotation;
659
+ private lerpFov;
660
+ private deriveYawPitchFromLookAt;
661
+ private deriveYawPitchFromQuaternion;
662
+ }
663
+
664
+ /**
665
+ * Perspective-specific options union.
666
+ * Extend as new perspective types are added.
667
+ */
668
+ type PerspectiveOptions = ThirdPersonOptions | Fixed2DOptions | FirstPersonOptions;
669
+ /**
670
+ * Factory: create a CameraPerspective from a PerspectiveType string.
671
+ * Unrecognized types default to ThirdPersonPerspective.
672
+ */
673
+ declare function createPerspective(type: PerspectiveType, options?: PerspectiveOptions): CameraPerspective;
674
+
675
+ interface CameraOptions {
676
+ perspective?: PerspectiveType;
677
+ position?: Vec3Input;
678
+ target?: Vec3Input;
679
+ zoom?: number;
680
+ screenResolution?: Vec2Input;
681
+ /**
682
+ * Enable orbital controls for this camera.
683
+ * Can be toggled at runtime via enableOrbitalControls() / disableOrbitalControls().
684
+ * @default false
685
+ */
686
+ useOrbitalControls?: boolean;
687
+ /**
688
+ * Viewport in normalized coordinates (0-1).
689
+ * Defines where this camera renders on the canvas.
690
+ * @default { x: 0, y: 0, width: 1, height: 1 } (fullscreen)
691
+ */
692
+ viewport?: Viewport;
693
+ /**
694
+ * Optional name for camera manager lookup.
695
+ */
696
+ name?: string;
697
+ /**
698
+ * Initial behaviors to attach to the camera pipeline.
699
+ * Keys are used for idempotent add/remove.
700
+ */
701
+ behaviors?: Record<string, CameraBehavior>;
702
+ /**
703
+ * Pipeline smoothing factor (0-1).
704
+ * 1 = instant snap, 0 = no movement.
705
+ * @default 0.15
706
+ */
707
+ damping?: number;
708
+ /**
709
+ * When set, the camera renders to an offscreen texture instead of a
710
+ * screen viewport. Use with setCameraFeed() to display the feed on
711
+ * an in-scene mesh (jumbotron, security monitor, portal, etc.).
712
+ *
713
+ * @default undefined (renders to screen)
714
+ */
715
+ renderToTexture?: {
716
+ /** Texture width in pixels. @default 512 */
717
+ width?: number;
718
+ /** Texture height in pixels. @default 512 */
719
+ height?: number;
720
+ };
721
+ /**
722
+ * When true, this camera will not activate orbital controls in debug mode.
723
+ * The pipeline (and its behaviors) will always run for this camera.
724
+ * Use for cameras with custom behaviors (e.g. FPS mouse-look) that must
725
+ * control the camera through the pipeline rather than debug orbit controls.
726
+ * @default false
727
+ */
728
+ skipDebugOrbit?: boolean;
729
+ }
730
+ /**
731
+ * CameraWrapper is the user-facing camera handle returned by createCamera().
732
+ * It provides convenience methods for target management, orbital controls,
733
+ * viewport configuration, and the camera pose pipeline.
734
+ */
735
+ declare class CameraWrapper {
736
+ cameraRef: ZylemCamera;
737
+ constructor(camera: ZylemCamera);
738
+ /**
739
+ * Add a target entity for the camera to follow/frame.
740
+ * With multiple targets, the camera auto-frames to include all of them.
741
+ */
742
+ addTarget(entity: StageEntity): void;
743
+ /**
744
+ * Remove a target entity from the camera.
745
+ */
746
+ removeTarget(entity: StageEntity): void;
747
+ /**
748
+ * Clear all targets. Camera will look at world origin.
749
+ */
750
+ clearTargets(): void;
751
+ /**
752
+ * Enable orbital controls for this camera.
753
+ * Allows the user to orbit, pan, and zoom the camera.
754
+ */
755
+ enableOrbitalControls(): void;
756
+ /**
757
+ * Disable orbital controls for this camera.
758
+ */
759
+ disableOrbitalControls(): void;
760
+ /**
761
+ * Set the viewport for this camera (normalized 0-1 coordinates).
762
+ * @param x Left edge (0 = left of canvas)
763
+ * @param y Bottom edge (0 = bottom of canvas)
764
+ * @param width Width as fraction of canvas
765
+ * @param height Height as fraction of canvas
766
+ */
767
+ setViewport(x: number, y: number, width: number, height: number): void;
768
+ /**
769
+ * Add or replace a behavior by key (idempotent).
770
+ * Behaviors modify the desired camera pose each frame.
771
+ *
772
+ * @param key Unique key for this behavior (used for replacement/removal).
773
+ * @param behavior The CameraBehavior implementation.
774
+ */
775
+ addBehavior(key: string, behavior: CameraBehavior): void;
776
+ /**
777
+ * Remove a behavior by key.
778
+ */
779
+ removeBehavior(key: string): boolean;
780
+ /**
781
+ * Add a transient action (screenshake, recoil, etc.).
782
+ * Actions apply additive deltas and self-expire when isDone() returns true.
783
+ */
784
+ addAction(action: CameraAction): void;
785
+ /**
786
+ * Switch the camera's active perspective at runtime.
787
+ * The first frame after switching snaps to the new pose (no lerp).
788
+ *
789
+ * @param type Perspective type string (e.g. Perspectives.ThirdPerson).
790
+ * @param options Perspective-specific options (distance, height, zoom, etc.).
791
+ */
792
+ setPerspective(type: PerspectiveType, options?: PerspectiveOptions): void;
793
+ /**
794
+ * Retrieve the active perspective instance, cast to the desired type.
795
+ * Useful for calling perspective-specific methods (e.g. FirstPersonPerspective.look()).
796
+ *
797
+ * @example
798
+ * const fps = camera.getPerspective<FirstPersonPerspective>();
799
+ * fps.look(dx, dy);
800
+ */
801
+ getPerspective<T extends CameraPerspective = CameraPerspective>(): T;
802
+ /**
803
+ * Return a debug snapshot of the camera pipeline state.
804
+ * Includes: active perspective, desired/final pose, behavior keys, action count.
805
+ */
806
+ getState(): CameraPipelineState;
807
+ /**
808
+ * Get the offscreen render texture for this camera.
809
+ * Returns null if the camera was not created with renderToTexture.
810
+ * Use with setCameraFeed() or apply directly to a mesh material.
811
+ */
812
+ getRenderTexture(): Texture | null;
813
+ }
814
+ /**
815
+ * Create a camera with the given options.
816
+ * Returns a CameraWrapper for convenient access to camera features.
817
+ */
818
+ declare function createCamera(options: CameraOptions): CameraWrapper;
819
+
820
+ /**
821
+ * Owns the stage's in-world debug/editor interaction layer.
822
+ *
823
+ * Self-manages around the global `debugState`: when debug is enabled it draws
824
+ * the wasm simulation's collider wireframes, attaches mouse listeners,
825
+ * raycasts into the physics world to hover/select/delete/spawn entities, and
826
+ * drives the `DebugEntityCursor` highlight. When disabled it tears down
827
+ * visuals but stays alive to re-activate. Centralizes all debug-tool plumbing
828
+ * so `ZylemStage` doesn't have to know about raycasting, DOM input, or debug
829
+ * rendering.
830
+ */
831
+
832
+ type AddEntityFactory = (params: {
833
+ position: Vector3;
834
+ normal?: Vector3;
835
+ }) => Promise<any> | any;
836
+ interface StageDebugDelegateOptions {
837
+ maxRayDistance?: number;
838
+ addEntityFactory?: AddEntityFactory | null;
839
+ }
840
+ /**
841
+ * Self-managing debug delegate that subscribes to `debugState` internally.
842
+ *
843
+ * When debug is enabled it lazily initializes visuals and DOM listeners.
844
+ * When debug is disabled it tears down visuals but stays alive so it can
845
+ * re-activate without being recreated. Call `dispose()` to fully tear down.
846
+ */
847
+ declare class StageDebugDelegate {
848
+ private stage;
849
+ private options;
850
+ private mouseNdc;
851
+ private raycaster;
852
+ private isMouseDown;
853
+ private domDisposeFns;
854
+ private domListenersAttached;
855
+ private debugCursor;
856
+ private debugLines;
857
+ private cameraDebugDelegate;
858
+ private debugStateUnsubscribe;
859
+ private focusContextUnregister;
860
+ constructor(stage: ZylemStage, options?: StageDebugDelegateOptions);
861
+ private resolveEntity;
862
+ /** Copy all stage children into debugMap so raycast/select tools work after enabling debug mid-session. */
863
+ private populateDebugMap;
864
+ private ensureCameraDebugDelegate;
865
+ private syncWithDebugState;
866
+ /** Initialize DOM listeners and camera debug delegate when debug is turned on. */
867
+ private activate;
868
+ /** Tear down visuals and camera debug delegate when debug is turned off. */
869
+ private deactivate;
870
+ private initDebugVisuals;
871
+ private disposeDebugVisuals;
872
+ update(): void;
873
+ /** Full teardown — unsubscribes from debugState and cleans up all resources. */
874
+ dispose(): void;
875
+ private handleActionOnHit;
876
+ private attachDomListeners;
877
+ }
878
+
879
+ /**
880
+ * Stage configuration: types, defaults, and option parsing.
881
+ *
882
+ * Defines the user-facing stage config shape (`StageConfigLike`), the internal
883
+ * `StageConfig` class, and the engine defaults applied to every stage. Its core
884
+ * job is `parseStageOptions`, which untangles the heterogeneous `createStage(...)`
885
+ * argument list (config objects, camera wrappers, sync/async entities) into a
886
+ * normalized `ParsedStageOptions` that `ZylemStage` can consume directly.
887
+ */
888
+
889
+ type StageGLTFAssetLoaderConfig = {
890
+ meshopt?: boolean;
891
+ ktx2TranscoderPath?: URL | string;
892
+ };
893
+ type StageAssetLoaderConfig = {
894
+ gltf?: StageGLTFAssetLoaderConfig;
895
+ };
896
+ /**
897
+ * Stage configuration type for user-facing options.
898
+ */
899
+ type StageConfigLike = Partial<{
900
+ inputs: Record<string, string[]>;
901
+ backgroundColor: Color | string;
902
+ backgroundImage: string | null;
903
+ backgroundShader: ZylemShader;
904
+ gravity: Vector3 | Vec3Components;
905
+ variables: Record<string, any>;
906
+ /** Physics update rate in Hz (default 60). */
907
+ physicsRate: number;
908
+ assetLoaders: StageAssetLoaderConfig;
909
+ /**
910
+ * When `false`, the engine's built-in ambient + directional lights are
911
+ * suppressed so the stage can be lit entirely via `createLight(...)`
912
+ * entities. Defaults to `true`.
913
+ */
914
+ defaultLighting: boolean;
915
+ /**
916
+ * Postprocessing effects applied in order between the scene pass and the
917
+ * display output (e.g. effects from `@zylem/shaders`). Only active for
918
+ * single fullscreen-camera rendering.
919
+ */
920
+ postProcessingEffects: ZylemPostEffect[];
921
+ }>;
922
+ /**
923
+ * Factory for authoring stage configuration objects in user code.
924
+ * Returns a plain object that can be passed to `createStage(...)`.
925
+ */
926
+ declare function stageConfig(config: StageConfigLike): StageConfigLike;
927
+
928
+ /**
929
+ * Fan-out hub for a stage's loading lifecycle events.
930
+ *
931
+ * Collects start/progress/complete loading events and broadcasts them both to
932
+ * direct per-stage subscribers and to the global `gameEventBus` (tagged with
933
+ * stage name/index) for game-level loading UIs. Exists so the entity-load
934
+ * generator and stage code can emit progress through one place without knowing
935
+ * who is listening.
936
+ */
937
+
938
+ /**
939
+ * Delegate for managing loading events and progress within a stage.
940
+ * Handles subscription to loading events and broadcasting progress.
941
+ * Emits to game event bus for game-level observation.
942
+ */
943
+ declare class StageLoadingDelegate {
944
+ private loadingHandlers;
945
+ private stageName?;
946
+ private stageIndex?;
947
+ /**
948
+ * Set stage context for event bus emissions.
949
+ */
950
+ setStageContext(stageName: string, stageIndex: number): void;
951
+ /**
952
+ * Subscribe to loading events.
953
+ *
954
+ * @param callback Invoked for each loading event (start, progress, complete)
955
+ * @returns Unsubscribe function
956
+ */
957
+ onLoading(callback: (event: LoadingEvent) => void): () => void;
958
+ /**
959
+ * Emit a loading event to all subscribers and to the game event bus.
960
+ *
961
+ * @param event The loading event to broadcast
962
+ */
963
+ emit(event: LoadingEvent): void;
964
+ /**
965
+ * Emit a start loading event.
966
+ */
967
+ emitStart(message?: string): void;
968
+ /**
969
+ * Emit a progress loading event.
970
+ */
971
+ emitProgress(message: string, current: number, total: number): void;
972
+ /**
973
+ * Emit a complete loading event.
974
+ */
975
+ emitComplete(message?: string): void;
976
+ /**
977
+ * Clear all loading handlers.
978
+ */
979
+ dispose(): void;
980
+ }
981
+
982
+ /**
983
+ * Delegate for handling deferred model loading in entities.
984
+ * Subscribes to model:loaded events and adds entity groups to the scene
985
+ * when they become available after async loading completes.
986
+ */
987
+ declare class StageEntityModelDelegate {
988
+ private scene;
989
+ private onEntityReady;
990
+ private pendingEntities;
991
+ private modelLoadedHandler;
992
+ /**
993
+ * Initialize the delegate with the scene reference and start listening.
994
+ */
995
+ attach(scene: ZylemScene, onEntityReady?: (entity: GameEntity<any>) => void): void;
996
+ /**
997
+ * Register an entity for observation.
998
+ * When its model loads, the group will be added to the scene.
999
+ */
1000
+ observe(entity: GameEntity<any>): void;
1001
+ /**
1002
+ * Unregister an entity (e.g., when removed before model loads).
1003
+ */
1004
+ unobserve(entityId: string): void;
1005
+ /**
1006
+ * Handle model loaded event - add group to scene if entity is pending.
1007
+ */
1008
+ private handleModelLoaded;
1009
+ /**
1010
+ * Cleanup all subscriptions and pending entities.
1011
+ */
1012
+ dispose(): void;
1013
+ }
1014
+
1015
+ /**
1016
+ * The stage's entity lifecycle engine.
1017
+ *
1018
+ * Owns everything about entities within a stage: queuing (sync, async, and
1019
+ * factory inputs), progressive load via a yielding generator, spawning into
1020
+ * scene/world/runtime, instanced-mesh batching, deferred-model handling,
1021
+ * removal, name/UUID lookup, and ECS behavior-system registration/indexing.
1022
+ * Extracted from `ZylemStage` so entity bookkeeping lives in one cohesive place
1023
+ * and can be shared with the debug delegate and transform system.
1024
+ */
1025
+
1026
+ type NodeLike$1 = {
1027
+ create: Function;
1028
+ };
1029
+ type StageEntityInput = NodeLike$1 | Promise<any> | (() => NodeLike$1 | Promise<any>);
1030
+ /**
1031
+ * Runtime context provided by ZylemStage after scene and world are initialized.
1032
+ */
1033
+ interface EntityDelegateContext {
1034
+ scene: ZylemScene;
1035
+ world: ZylemWorld;
1036
+ renderStrategy: RenderStrategyManager | null;
1037
+ /** Resolved camera for entity setup contexts. */
1038
+ camera: ZylemCamera;
1039
+ }
1040
+ /**
1041
+ * Delegate responsible for entity spawning, tracking, queuing, removal, and lookup.
1042
+ *
1043
+ * Owns all entity-related state and exposes it to ZylemStage for orchestration
1044
+ * and to external consumers (debug delegate, transform system) via public getters.
1045
+ */
1046
+ declare class StageEntityDelegate {
1047
+ private static readonly EMPTY_BEHAVIOR_LINKS;
1048
+ /** Entities queued before load completes. */
1049
+ children: BaseNode[];
1050
+ /** UUID → BaseNode map of all live entities. */
1051
+ readonly childrenMap: Map<string, BaseNode>;
1052
+ /** UUID → BaseNode map populated when debug mode is active. */
1053
+ readonly debugMap: Map<string, BaseNode>;
1054
+ private pendingEntities;
1055
+ private pendingPromises;
1056
+ private _isLoaded;
1057
+ private entityAddedHandlers;
1058
+ /** ECS behavior systems auto-registered from entity refs or manually added. */
1059
+ readonly behaviorSystems: BehaviorSystem[];
1060
+ readonly behaviorSystemByKey: Map<symbol, BehaviorSystem>;
1061
+ readonly registeredSystemKeys: Set<symbol>;
1062
+ readonly behaviorEntityIndex: Map<symbol, Set<BehaviorEntityLink>>;
1063
+ private readonly behaviorLinksByUuid;
1064
+ private scene;
1065
+ private world;
1066
+ private renderStrategy;
1067
+ private camera;
1068
+ /**
1069
+ * The behaviors runtime adapter backing the world's Simulation; shared with
1070
+ * descriptor `systemFactory` calls as `ctx.wasmStage`.
1071
+ */
1072
+ wasmStage: BehaviorRuntime | null;
1073
+ private loadingDelegate;
1074
+ private entityModelDelegate;
1075
+ constructor(loadingDelegate: StageLoadingDelegate, entityModelDelegate: StageEntityModelDelegate);
1076
+ get isLoaded(): boolean;
1077
+ set isLoaded(value: boolean);
1078
+ /**
1079
+ * Bind runtime context after scene and world are initialized.
1080
+ * Must be called before any spawn/enqueue operations.
1081
+ */
1082
+ attach(context: EntityDelegateContext): void;
1083
+ /**
1084
+ * Create, register, and add an entity to the scene/world.
1085
+ * Safe to call only after `attach` when scene/world exist.
1086
+ */
1087
+ spawnEntity(child: BaseNode): Promise<void>;
1088
+ handleLateModelReady(entity: GameEntity<any>): void;
1089
+ /**
1090
+ * Register an entity for bundle or instanced rendering when opted in via
1091
+ * `category: 'environment'` or `category: 'pack'`.
1092
+ */
1093
+ private tryRegisterRenderStrategy;
1094
+ /**
1095
+ * Environment bundles require static bodies. Force static collision and
1096
+ * patch any already-built body description.
1097
+ */
1098
+ private ensureEnvironmentStatic;
1099
+ private maybeAttachEntityPhysics;
1100
+ /** Add the entity to internal maps and notify listeners. */
1101
+ addEntityToStage(entity: BaseNode): void;
1102
+ /**
1103
+ * Remove an entity and its resources by its UUID.
1104
+ * @returns true if removed, false if not found or stage not ready
1105
+ */
1106
+ removeEntityByUuid(uuid: string): boolean;
1107
+ /** Get an entity by its name; returns null if not found. */
1108
+ getEntityByName(name: string): BaseNode | null;
1109
+ /** Build a serializable state snapshot for an entity. */
1110
+ buildEntityState(child: BaseNode): Partial<BaseEntityInterface>;
1111
+ /**
1112
+ * Subscribe to entity-added events.
1113
+ * @param callback Invoked for each entity when added
1114
+ * @param options.replayExisting If true and stage already loaded, replays existing entities
1115
+ * @returns Unsubscribe function
1116
+ */
1117
+ onEntityAdded(callback: (entity: BaseNode) => void, options?: {
1118
+ replayExisting?: boolean;
1119
+ }): () => void;
1120
+ /**
1121
+ * Enqueue items to be spawned. Items can be:
1122
+ * - BaseNode instances (immediate or deferred until load)
1123
+ * - Factory functions returning BaseNode or Promise<BaseNode>
1124
+ * - Promises resolving to BaseNode
1125
+ */
1126
+ enqueue(...items: StageEntityInput[]): void;
1127
+ private handleEntityImmediatelyOrQueue;
1128
+ private handlePromiseWithSpawnOnResolve;
1129
+ /** Yields to the event loop via MessageChannel (~0.1ms vs ~4ms for setTimeout). */
1130
+ private yieldToEventLoop;
1131
+ /**
1132
+ * Spawns all queued entities, awaiting each attach before the stage is
1133
+ * marked loaded so the game loop never steps wasm while bodies are still
1134
+ * being added. Yields to the event loop in batches for loading UI updates.
1135
+ */
1136
+ runEntityLoadGenerator(): Promise<void>;
1137
+ /**
1138
+ * Register an ECS behavior system to run each frame.
1139
+ * @param systemOrFactory A BehaviorSystem instance or factory function
1140
+ */
1141
+ registerSystem(systemOrFactory: BehaviorSystem | BehaviorSystemFactory): void;
1142
+ /**
1143
+ * Destroy all entities and clear internal state.
1144
+ * Called by ZylemStage._destroy().
1145
+ */
1146
+ destroyAll(): void;
1147
+ private registerBehaviorLinks;
1148
+ private unregisterBehaviorLinks;
1149
+ }
1150
+
1151
+ /**
1152
+ * The runtime heart of a loaded stage.
1153
+ *
1154
+ * `ZylemStage` is the disposable per-load object that actually owns and drives
1155
+ * the scene, physics world, cameras, optional wasm runtime, and the suite of
1156
+ * delegates (entity, camera, loading, model, debug). It parses options into
1157
+ * config, builds scene/world during `load()`, runs the per-frame update loop
1158
+ * (physics step, behavior systems, entity updates, transform sync, camera
1159
+ * updates, render), and tears everything down on destroy. The author-facing
1160
+ * `Stage` wraps and recreates one of these on each load.
1161
+ */
1162
+
1163
+ interface ZylemStageConfig {
1164
+ inputs: Record<string, string[]>;
1165
+ backgroundColor: Color | string;
1166
+ backgroundImage: string | null;
1167
+ backgroundShader: any | null;
1168
+ gravity: Vector3 | Vec3Components;
1169
+ variables: Record<string, any>;
1170
+ /** Physics update rate in Hz (default 60). */
1171
+ physicsRate: number;
1172
+ /** Optional runtime loader configuration for stage-managed assets. */
1173
+ assetLoaders?: StageAssetLoaderConfig;
1174
+ /**
1175
+ * When `false`, suppress the engine's built-in ambient + directional
1176
+ * lights so the stage owns its lighting rig entirely (usually via
1177
+ * `createLight(...)` entities). Defaults to `true`.
1178
+ */
1179
+ defaultLighting: boolean;
1180
+ /**
1181
+ * Postprocessing effects applied in order between the scene pass and the
1182
+ * display output (e.g. effects from `@zylem/shaders`). Only active for
1183
+ * single fullscreen-camera rendering.
1184
+ */
1185
+ postProcessingEffects?: ZylemPostEffect[];
1186
+ stageRef?: Stage;
1187
+ }
1188
+ type StageOptionItem = Partial<ZylemStageConfig> | CameraWrapper | StageEntityInput;
1189
+ type StageOptions = [] | [Partial<ZylemStageConfig>, ...StageOptionItem[]];
1190
+ type StageState = ZylemStageConfig & {
1191
+ entities: GameEntityInterface[];
1192
+ };
1193
+ /**
1194
+ * ZylemStage orchestrates scene, physics world, entities, and lifecycle.
1195
+ *
1196
+ * Responsibilities:
1197
+ * - Manage stage configuration (background, inputs, gravity, variables)
1198
+ * - Initialize and own `ZylemScene` and `ZylemWorld`
1199
+ * - Coordinate delegates for entities, camera, loading, debug, and models
1200
+ * - Drive per-frame updates and transform system
1201
+ */
1202
+ declare class ZylemStage extends LifeCycleBase<ZylemStage> {
1203
+ type: string;
1204
+ state: StageState;
1205
+ gravity: Vector3 | Vec3Components;
1206
+ world: ZylemWorld | null;
1207
+ scene: ZylemScene | null;
1208
+ renderStrategy: RenderStrategyManager | null;
1209
+ debugDelegate: StageDebugDelegate | null;
1210
+ uuid: string;
1211
+ wrapperRef: Stage | null;
1212
+ camera?: CameraWrapper;
1213
+ cameras: CameraWrapper[];
1214
+ cameraRef?: ZylemCamera | null;
1215
+ /** Camera manager for multi-camera support */
1216
+ cameraManagerRef: CameraManager | null;
1217
+ /** Shared renderer manager (injected by the game) */
1218
+ rendererManager: RendererManager | null;
1219
+ private cameraDelegate;
1220
+ private loadingDelegate;
1221
+ private entityModelDelegate;
1222
+ private readonly childUpdateParams;
1223
+ /** Entity management delegate — public for external consumers (debug, transform system). */
1224
+ readonly entityDelegate: StageEntityDelegate;
1225
+ /**
1226
+ * Create a new stage.
1227
+ * @param options Stage options: partial config, camera, and initial entities or factories
1228
+ */
1229
+ constructor(options?: StageOptions);
1230
+ private setState;
1231
+ /**
1232
+ * Resolve the active renderer, preferring the shared renderer manager and
1233
+ * falling back to the camera's own renderer.
1234
+ */
1235
+ private resolveRenderer;
1236
+ /**
1237
+ * Load and initialize the stage's scene and world.
1238
+ * Uses generator pattern to yield control to event loop for real-time progress.
1239
+ * @param id DOM element id for the renderer container
1240
+ * @param camera Optional camera override
1241
+ */
1242
+ load(id: string, camera?: ZylemCamera | null, rendererManager?: RendererManager | null): Promise<void>;
1243
+ /**
1244
+ * Idempotency guard for `_setup`. The initial stage is currently set up
1245
+ * twice — once when `ZylemGame.loadStage` runs for non-initial stages
1246
+ * (so every stage gets a `StageDebugDelegate`, stage.onSetup callbacks,
1247
+ * etc.), and once from `ZylemGame.start()` for the very first stage.
1248
+ * Keeping a flag here lets both call sites invoke `stage.start(...)`
1249
+ * safely; the second call is a no-op.
1250
+ */
1251
+ hasSetup: boolean;
1252
+ protected _setup(params: SetupContext<ZylemStage>): void;
1253
+ protected _update(params: UpdateContext<ZylemStage>): void;
1254
+ outOfLoop(): void;
1255
+ /** Update debug overlays and helpers if enabled. */
1256
+ debugUpdate(): void;
1257
+ /** Cleanup owned resources when the stage is destroyed. */
1258
+ protected _destroy(params: DestroyContext<ZylemStage>): void;
1259
+ /** Forward to entity delegate. */
1260
+ spawnEntity(child: BaseNode): Promise<void>;
1261
+ /** Forward to entity delegate. */
1262
+ buildEntityState(child: BaseNode): Partial<BaseEntityInterface>;
1263
+ /** Forward to entity delegate. */
1264
+ onEntityAdded(callback: (entity: BaseNode) => void, options?: {
1265
+ replayExisting?: boolean;
1266
+ }): () => void;
1267
+ onLoading(callback: (event: LoadingEvent) => void): () => void;
1268
+ /**
1269
+ * Register an ECS behavior system to run each frame.
1270
+ * @param systemOrFactory A BehaviorSystem instance or factory function
1271
+ * @returns this for chaining
1272
+ */
1273
+ registerSystem(systemOrFactory: BehaviorSystem | BehaviorSystemFactory): this;
1274
+ /** Forward to entity delegate. */
1275
+ removeEntityByUuid(uuid: string): boolean;
1276
+ /** Forward to entity delegate. */
1277
+ getEntityByName(name: string): BaseNode<any, any> | null;
1278
+ /** Forward to entity delegate. */
1279
+ enqueue(...items: StageEntityInput[]): void;
1280
+ logMissingEntities(): void;
1281
+ /** Add a camera to this stage's camera manager. */
1282
+ addCamera(camera: ZylemCamera, name?: string): string | null;
1283
+ /** Remove a camera from this stage's camera manager. */
1284
+ removeCamera(nameOrRef: string | ZylemCamera): boolean;
1285
+ /** Set the active camera by name or reference. */
1286
+ setActiveCamera(nameOrRef: string | ZylemCamera): boolean;
1287
+ /** Get a camera by name from the camera manager. */
1288
+ getCamera(name: string): ZylemCamera | null;
1289
+ /** Resize renderer viewport. */
1290
+ resize(width: number, height: number): void;
1291
+ }
1292
+
1293
+ /**
1294
+ * The user-facing stage handle and its fluent authoring API.
1295
+ *
1296
+ * `Stage` is the durable, author-time wrapper game code holds onto: it stores
1297
+ * options, pending entities, and lifecycle/loading callbacks, then constructs
1298
+ * and drives a fresh internal `ZylemStage` on each `load()`. Exists to give a
1299
+ * stable, ergonomic surface (`add`, `onSetup/onUpdate/onDestroy`, camera, input,
1300
+ * and event helpers) that survives stage reloads, while `ZylemStage` owns the
1301
+ * disposable per-load runtime. `createStage(...)` is the entry point.
1302
+ */
1303
+
1304
+ type NodeLike = {
1305
+ create: Function;
1306
+ };
1307
+ type AnyNode = NodeLike | Promise<NodeLike>;
1308
+ type EntityInput = AnyNode | (() => AnyNode) | (() => Promise<any>);
1309
+ declare class Stage {
1310
+ wrappedStage: ZylemStage | null;
1311
+ options: StageOptionItem[];
1312
+ private _pendingEntities;
1313
+ private setupCallbacks;
1314
+ private updateCallbacks;
1315
+ private destroyCallbacks;
1316
+ private pendingLoadingCallbacks;
1317
+ private eventDelegate;
1318
+ /** Per-stage input configuration overrides. Merged with game-level defaults on stage load. */
1319
+ inputConfig: GameInputConfig | null;
1320
+ /**
1321
+ * Callback set by the game to trigger input reconfiguration
1322
+ * when this stage's input config changes at runtime.
1323
+ * @internal
1324
+ */
1325
+ onInputConfigChanged: (() => void) | null;
1326
+ constructor(options: StageOptions);
1327
+ /**
1328
+ * Set composable input configuration for this stage.
1329
+ * Multiple configs are deep-merged (later configs win on key conflicts).
1330
+ * If this stage is currently active, the change takes effect immediately.
1331
+ * @example stage.setInputConfiguration(useArrowsForAxes('p1'), useWASDForDirections('p2'));
1332
+ */
1333
+ setInputConfiguration(...configs: GameInputConfig[]): this;
1334
+ load(id: string, camera?: ZylemCamera | CameraWrapper | null, rendererManager?: RendererManager | null): Promise<void>;
1335
+ private applyLifecycleCallbacks;
1336
+ addEntities(entities: BaseNode[]): Promise<void>;
1337
+ add(...inputs: Array<EntityInput>): void;
1338
+ private addToBlueprints;
1339
+ private addToStage;
1340
+ start(params: SetupContext<ZylemStage>): void;
1341
+ onUpdate(...callbacks: UpdateFunction<ZylemStage>[]): this;
1342
+ onSetup(...callbacks: SetupFunction<ZylemStage>[]): this;
1343
+ onDestroy(...callbacks: DestroyFunction<ZylemStage>[]): this;
1344
+ onLoading(callback: (event: LoadingEvent) => void): () => void;
1345
+ /**
1346
+ * Find an entity by name on the current stage.
1347
+ * @param name The name of the entity to find
1348
+ * @param type Optional type symbol for type inference (e.g., TEXT_TYPE, SPRITE_TYPE)
1349
+ * @returns The entity if found, or undefined
1350
+ * @example stage.getEntityByName('scoreText', TEXT_TYPE)
1351
+ */
1352
+ getEntityByName<T extends symbol | void = void>(name: string, type?: T): T extends keyof EntityTypeMap ? EntityTypeMap[T] | undefined : BaseNode | undefined;
1353
+ /**
1354
+ * Add a camera to this stage.
1355
+ * @param camera The ZylemCamera or CameraWrapper to add
1356
+ * @param name Optional name for lookup
1357
+ */
1358
+ addCamera(camera: ZylemCamera | CameraWrapper, name?: string): string | null;
1359
+ /**
1360
+ * Remove a camera from this stage by name or reference.
1361
+ */
1362
+ removeCamera(nameOrRef: string | ZylemCamera | CameraWrapper): boolean;
1363
+ /**
1364
+ * Set the active camera by name or reference.
1365
+ */
1366
+ setActiveCamera(nameOrRef: string | ZylemCamera | CameraWrapper): boolean;
1367
+ /**
1368
+ * Get a camera by name from the camera manager.
1369
+ */
1370
+ getCamera(name: string): ZylemCamera | null;
1371
+ /**
1372
+ * Dispatch an event from the stage.
1373
+ * Events are emitted both locally and to the global event bus.
1374
+ */
1375
+ dispatch<K extends keyof StageEvents>(event: K, payload: StageEvents[K]): void;
1376
+ /**
1377
+ * Listen for events on this stage instance.
1378
+ * @returns Unsubscribe function
1379
+ */
1380
+ listen<K extends keyof StageEvents>(event: K, handler: (payload: StageEvents[K]) => void): () => void;
1381
+ /**
1382
+ * Clean up stage resources including event subscriptions.
1383
+ */
1384
+ dispose(): void;
1385
+ }
1386
+ /**
1387
+ * Create a stage with optional camera
1388
+ */
1389
+ declare function createStage(...options: StageOptions): Stage;
1390
+
1391
+ /**
1392
+ * Stage state interface - minimal to prevent circular dependencies
1393
+ */
1394
+ interface StageStateInterface {
1395
+ backgroundColor: Color;
1396
+ backgroundImage: string | null;
1397
+ inputs: {
1398
+ p1: string[];
1399
+ p2: string[];
1400
+ };
1401
+ variables: Record<string, any>;
1402
+ gravity: Vector3 | Vec3Components;
1403
+ entities: Partial<BaseEntityInterface>[];
1404
+ stageRef?: any;
1405
+ }
1406
+ /**
1407
+ * Minimal stage interface to break circular dependencies
1408
+ */
1409
+ interface StageInterface {
1410
+ uuid: string;
1411
+ children: any[];
1412
+ state: StageStateInterface;
1413
+ }
1414
+
1415
+ declare const AspectRatio: {
1416
+ readonly FourByThree: number;
1417
+ readonly SixteenByNine: number;
1418
+ readonly NineBySixteen: number;
1419
+ readonly TwentyOneByNine: number;
1420
+ readonly OneByOne: number;
1421
+ };
1422
+ type AspectRatioValue = (typeof AspectRatio)[keyof typeof AspectRatio] | number;
1423
+ /**
1424
+ * AspectRatioDelegate manages sizing a canvas to fit within a container
1425
+ * while preserving a target aspect ratio. It notifies a consumer via
1426
+ * onResize when the final width/height are applied so renderers/cameras
1427
+ * can update their viewports.
1428
+ */
1429
+ declare class AspectRatioDelegate {
1430
+ container: HTMLElement;
1431
+ canvas: HTMLCanvasElement;
1432
+ aspectRatio: number;
1433
+ onResize?: (width: number, height: number) => void;
1434
+ private handleResizeBound;
1435
+ private resizeObserver;
1436
+ constructor(params: {
1437
+ container: HTMLElement;
1438
+ canvas: HTMLCanvasElement;
1439
+ aspectRatio: AspectRatioValue;
1440
+ onResize?: (width: number, height: number) => void;
1441
+ });
1442
+ /** Attach window resize listener and apply once. */
1443
+ attach(): void;
1444
+ /** Detach window resize listener. */
1445
+ detach(): void;
1446
+ /** Compute the largest size that fits container while preserving aspect. */
1447
+ measure(): {
1448
+ width: number;
1449
+ height: number;
1450
+ };
1451
+ /** Apply measured size to canvas and notify. */
1452
+ apply(): void;
1453
+ }
1454
+
1455
+ interface ViewportSize {
1456
+ width: number;
1457
+ height: number;
1458
+ }
1459
+
1460
+ type RetroResolution = {
1461
+ key: string;
1462
+ width: number;
1463
+ height: number;
1464
+ notes?: string;
1465
+ };
1466
+ type RetroPreset = {
1467
+ displayAspect: number;
1468
+ resolutions: RetroResolution[];
1469
+ };
1470
+ /**
1471
+ * Retro, console, and device display presets.
1472
+ * displayAspect represents the intended display aspect (letterboxing target),
1473
+ * not necessarily the raw pixel aspect of internal buffers.
1474
+ */
1475
+ declare const RetroPresets: Record<string, RetroPreset>;
1476
+ type RetroPresetKey = keyof typeof RetroPresets;
1477
+ declare function getDisplayAspect(preset: RetroPresetKey): number;
1478
+ declare function getPresetResolution(preset: RetroPresetKey, key?: string): RetroResolution | undefined;
1479
+ declare function parseResolution(text: string): {
1480
+ width: number;
1481
+ height: number;
1482
+ } | null;
1483
+
1484
+ /**
1485
+ * Resolution descriptor for the game's internal render buffer.
1486
+ * - `string` : a "WxH" literal or a known retro preset (e.g. `'NES'`).
1487
+ * - `{ width, height }` : explicit pixel dimensions.
1488
+ * - `'native'` : skip internal-resolution scaling — render at the
1489
+ * canvas' CSS size × DPR (i.e. 1:1 with the device viewport).
1490
+ */
1491
+ type ResolutionInput = string | {
1492
+ width: number;
1493
+ height: number;
1494
+ } | 'native';
1495
+ type DeviceProfile = 'auto' | 'desktop' | 'mobile';
1496
+ interface ResolveGameConfigRuntime {
1497
+ deviceProfile?: DeviceProfile;
1498
+ viewportSize?: ViewportSize;
1499
+ }
1500
+ type GameDeviceConfig = Partial<{
1501
+ /** numeric value or key in AspectRatio */
1502
+ aspectRatio: AspectRatioValue | keyof typeof AspectRatio;
1503
+ /** console/display preset to derive aspect ratio */
1504
+ preset: RetroPresetKey;
1505
+ /** lock internal render buffer for this device profile */
1506
+ resolution: ResolutionInput;
1507
+ /**
1508
+ * Auto-merge built-in virtual touch controls into the resolved input
1509
+ * config. The provider auto-enables on mobile devices via
1510
+ * `enabled: 'auto'`, so on desktop runtimes the UI stays dormant.
1511
+ * - `true` : default joystick + A/B layout, default theme.
1512
+ * - options object : forwarded to `defaultTouchControls('p1', ...)`.
1513
+ * - `false` / unset: no auto-injection (caller wires controls manually).
1514
+ */
1515
+ controls: boolean | DefaultTouchControlsOptions;
1516
+ }>;
1517
+ type GameConfigLike = Partial<{
1518
+ id: string;
1519
+ globals: Record<string, any>;
1520
+ stages: StageInterface[];
1521
+ debug: boolean;
1522
+ time: number;
1523
+ input: GameInputConfig;
1524
+ /** numeric value or key in AspectRatio */
1525
+ aspectRatio: AspectRatioValue | keyof typeof AspectRatio;
1526
+ /** console/display preset to derive aspect ratio */
1527
+ preset: RetroPresetKey;
1528
+ /** lock internal render buffer to this desktop/default resolution */
1529
+ resolution: ResolutionInput;
1530
+ /** mobile-specific aspect/preset/resolution overrides */
1531
+ mobile: GameDeviceConfig;
1532
+ fullscreen: boolean;
1533
+ /** CSS background value for document body */
1534
+ bodyBackground: string;
1535
+ /** existing container by reference */
1536
+ container: HTMLElement;
1537
+ /** create/find container by id */
1538
+ containerId: string;
1539
+ /** optional canvas if caller wants to manage it */
1540
+ canvas: HTMLCanvasElement;
1541
+ }>;
1542
+ declare class GameConfig {
1543
+ id: string;
1544
+ globals: Record<string, any>;
1545
+ stages: StageInterface[];
1546
+ debug: boolean;
1547
+ time: number;
1548
+ input: GameInputConfig | undefined;
1549
+ aspectRatio: number;
1550
+ internalResolution: {
1551
+ width: number;
1552
+ height: number;
1553
+ } | undefined;
1554
+ fullscreen: boolean;
1555
+ bodyBackground: string | undefined;
1556
+ container: HTMLElement;
1557
+ containerId?: string | undefined;
1558
+ canvas?: HTMLCanvasElement | undefined;
1559
+ constructor(id: string, globals: Record<string, any>, stages: StageInterface[], debug: boolean, time: number, input: GameInputConfig | undefined, aspectRatio: number, internalResolution: {
1560
+ width: number;
1561
+ height: number;
1562
+ } | undefined, fullscreen: boolean, bodyBackground: string | undefined, container: HTMLElement, containerId?: string | undefined, canvas?: HTMLCanvasElement | undefined);
1563
+ }
1564
+ /**
1565
+ * Factory for authoring configuration objects in user code.
1566
+ * Returns a plain object that can be passed to `game(...)`.
1567
+ */
1568
+ declare function gameConfig(config: GameConfigLike): GameConfigLike;
1569
+
1570
+ interface GameCanvasOptions {
1571
+ id: string;
1572
+ container?: HTMLElement;
1573
+ containerId?: string;
1574
+ canvas?: HTMLCanvasElement;
1575
+ bodyBackground?: string;
1576
+ fullscreen?: boolean;
1577
+ aspectRatio: AspectRatioValue | number;
1578
+ }
1579
+ /**
1580
+ * GameCanvas is a DOM delegate that owns:
1581
+ * - container lookup/creation and styling (including fullscreen centering)
1582
+ * - body background application
1583
+ * - canvas mounting into container
1584
+ * - aspect ratio sizing via AspectRatioDelegate
1585
+ */
1586
+ declare class GameCanvas {
1587
+ id: string;
1588
+ container: HTMLElement;
1589
+ canvas: HTMLCanvasElement;
1590
+ bodyBackground?: string;
1591
+ fullscreen: boolean;
1592
+ aspectRatio: number;
1593
+ private ratioDelegate;
1594
+ private overlayContainer;
1595
+ constructor(options: GameCanvasOptions);
1596
+ applyBodyBackground(): void;
1597
+ mountCanvas(): void;
1598
+ mountRenderer(rendererDom: HTMLCanvasElement, onResize: (width: number, height: number) => void): void;
1599
+ getOverlayContainer(): HTMLElement;
1600
+ centerIfFullscreen(): void;
1601
+ attachAspectRatio(onResize: (width: number, height: number) => void): void;
1602
+ setAspectRatio(aspectRatio: number): void;
1603
+ reapplyLayout(): void;
1604
+ destroy(): void;
1605
+ private mountChildren;
1606
+ private ensureOverlayContainer;
1607
+ private ensureContainer;
1608
+ }
1609
+
1610
+ /**
1611
+ * Game-level loading event that includes stage context.
1612
+ */
1613
+ interface GameLoadingEvent {
1614
+ type: 'start' | 'progress' | 'complete';
1615
+ stageName?: string;
1616
+ stageIndex?: number;
1617
+ message: string;
1618
+ progress: number;
1619
+ current?: number;
1620
+ total?: number;
1621
+ }
1622
+
1623
+ type ZylemGameOptions<TGlobals extends BaseGlobals> = ZylemGameConfig<Stage, ZylemGame<TGlobals>, TGlobals> & Partial<GameConfig>;
1624
+ declare class ZylemGame<TGlobals extends BaseGlobals> {
1625
+ id: string;
1626
+ initialGlobals: TGlobals;
1627
+ customSetup: ((params: SetupContext<ZylemGame<TGlobals>, TGlobals>) => void) | null;
1628
+ customUpdate: ((params: UpdateContext<ZylemGame<TGlobals>, TGlobals>) => void) | null;
1629
+ customDestroy: ((params: DestroyContext<ZylemGame<TGlobals>, TGlobals>) => void) | null;
1630
+ stages: Stage[];
1631
+ stageMap: Map<string, Stage>;
1632
+ currentStageId: string;
1633
+ previousTimeStamp: number;
1634
+ totalTime: number;
1635
+ timer: Timer;
1636
+ inputManager: InputManager;
1637
+ wrapperRef: Game<TGlobals>;
1638
+ globalInputConfig: GameInputConfig | undefined;
1639
+ defaultCamera: ZylemCamera | null;
1640
+ /** Shared renderer manager for all stages */
1641
+ rendererManager: RendererManager | null;
1642
+ container: HTMLElement | null;
1643
+ canvas: HTMLCanvasElement | null;
1644
+ aspectRatioDelegate: AspectRatioDelegate | null;
1645
+ resolvedConfig: GameConfig | null;
1646
+ gameCanvas: GameCanvas | null;
1647
+ private animationFrameId;
1648
+ private isDisposed;
1649
+ /**
1650
+ * True while a `loadStage` is in progress. Used to reject re-entrant stage
1651
+ * navigation (e.g. a button press during a transition), which would race
1652
+ * two loads on `stageMap`/the render loop and, because `currentStageId` is
1653
+ * transiently `''`, misresolve the target stage.
1654
+ */
1655
+ private loadInFlight;
1656
+ /**
1657
+ * True once `start()` has been invoked for this game's initial stage.
1658
+ * Used by `loadStage` to decide whether to drive the stage's `_setup`
1659
+ * lifecycle directly (for subsequent stages loaded via `nextStage`
1660
+ * / `loadStage`) or defer to `start()` (for the very first stage).
1661
+ */
1662
+ private hasStarted;
1663
+ private debugDelegate;
1664
+ private loadingDelegate;
1665
+ private rendererObserver;
1666
+ private eventBusUnsubscribes;
1667
+ private thumbnailUnsubscribes;
1668
+ /**
1669
+ * Trailing-debounce timer for entity-driven state dispatches. Building a
1670
+ * `state:dispatch` payload is O(entities) (and downstream editor stores
1671
+ * re-proxy/reconcile every entity), so bursts of thumbnail/destroy events
1672
+ * must coalesce into a single dispatch instead of one per entity.
1673
+ */
1674
+ private entityDispatchTimer;
1675
+ private pendingEntityDispatchPath;
1676
+ /** Debounce window (ms) for coalescing entity-driven state dispatches. */
1677
+ private static readonly ENTITY_DISPATCH_DEBOUNCE_MS;
1678
+ private readonly gameUpdateParams;
1679
+ private readonly stageSetupParams;
1680
+ private readonly stageUpdateParams;
1681
+ private readonly frameCallback;
1682
+ private readonly sourceOptions;
1683
+ private displayRuntime;
1684
+ static FRAME_LIMIT: number;
1685
+ static FRAME_DURATION: number;
1686
+ static MAX_DELTA_SECONDS: number;
1687
+ constructor(options: ZylemGameOptions<TGlobals>, wrapperRef: Game<TGlobals>, displayRuntime?: ResolveGameConfigRuntime);
1688
+ setDisplayRuntime(runtime: ResolveGameConfigRuntime): void;
1689
+ loadGameCanvas(config: GameConfig): void;
1690
+ loadDebugOptions(options: ZylemGameOptions<TGlobals>): void;
1691
+ /** Whether a stage load is currently in progress. */
1692
+ isLoading(): boolean;
1693
+ loadStage(stage: Stage, stageIndex?: number, transition?: StageTransitionConfig): Promise<void>;
1694
+ private performLoadStage;
1695
+ /**
1696
+ * Merges game-level global input config with the stage's per-stage overrides
1697
+ * and reconfigures the InputManager.
1698
+ */
1699
+ applyInputConfig(stage: Stage): void;
1700
+ /**
1701
+ * Update the game-level global input config and re-apply to the current stage.
1702
+ */
1703
+ setGlobalInputConfig(config: GameInputConfig): void;
1704
+ unloadCurrentStage(): void;
1705
+ setGlobals(options: ZylemGameConfig<Stage, ZylemGame<TGlobals>, TGlobals>): void;
1706
+ params(): UpdateContext<ZylemGame<TGlobals>, TGlobals>;
1707
+ start(): void;
1708
+ /**
1709
+ * Execute a single frame update.
1710
+ * This method can be called directly for testing or from the game loop.
1711
+ * @param deltaTime Optional delta time in seconds. If not provided, uses timer delta.
1712
+ */
1713
+ step(deltaTime?: number): void;
1714
+ loop(timestamp: number): void;
1715
+ dispose(): void;
1716
+ outOfLoop(): void;
1717
+ getStage(id: string): Stage | undefined;
1718
+ currentStage(): Stage | undefined;
1719
+ /**
1720
+ * Subscribe to loading events from the game.
1721
+ * Events include stage context (stageName, stageIndex).
1722
+ * @param callback Invoked for each loading event
1723
+ * @returns Unsubscribe function
1724
+ */
1725
+ onLoading(callback: (event: GameLoadingEvent) => void): () => void;
1726
+ /**
1727
+ * Build the stage config payload for the current stage.
1728
+ */
1729
+ private buildStageConfigPayload;
1730
+ /**
1731
+ * Build the entities payload for the current stage.
1732
+ */
1733
+ private buildEntitiesPayload;
1734
+ /**
1735
+ * Generate entity thumbnails as entities become available, then refresh editor state.
1736
+ */
1737
+ private wireEntityThumbnails;
1738
+ private clearEntityThumbnailWiring;
1739
+ /**
1740
+ * Coalesce entity-driven state dispatches (thumbnail resolutions, entity
1741
+ * destruction) into one trailing `emitStateDispatch` per burst.
1742
+ */
1743
+ private queueEntityStateDispatch;
1744
+ /**
1745
+ * Emit a state:dispatch event to the zylemEventBus.
1746
+ * Called after stage load and on global state changes.
1747
+ */
1748
+ private emitStateDispatch;
1749
+ /**
1750
+ * Subscribe to the game event bus for stage loading and state events.
1751
+ * Emits events to zylemEventBus for cross-package communication.
1752
+ */
1753
+ private subscribeToEventBus;
1754
+ }
1755
+
1756
+ type GameOptions<TGlobals extends BaseGlobals> = Array<ZylemGameConfig<Stage, any, TGlobals> | GameConfigLike | Stage | GameEntityLifeCycle | BaseNode>;
1757
+
1758
+ declare class Game<TGlobals extends BaseGlobals> implements IGame<TGlobals> {
1759
+ private wrappedGame;
1760
+ options: GameOptions<TGlobals>;
1761
+ private setupCallbacks;
1762
+ private updateCallbacks;
1763
+ private destroyCallbacks;
1764
+ private pendingLoadingCallbacks;
1765
+ private globalChangeCallbacks;
1766
+ private globalChangesCallbacks;
1767
+ private activeGlobalSubscriptions;
1768
+ private eventDelegate;
1769
+ /** Pending global input config set before the game starts. */
1770
+ private pendingInputConfig;
1771
+ private displayRuntime;
1772
+ refErrorMessage: string;
1773
+ constructor(options: GameOptions<TGlobals>);
1774
+ onSetup(...callbacks: Array<SetupFunction<ZylemGame<TGlobals>, TGlobals>>): this;
1775
+ onUpdate(...callbacks: Array<UpdateFunction<ZylemGame<TGlobals>, TGlobals>>): this;
1776
+ onDestroy(...callbacks: Array<DestroyFunction<ZylemGame<TGlobals>, TGlobals>>): this;
1777
+ /**
1778
+ * Set composable input configuration as global defaults for the entire game.
1779
+ * Multiple configs are deep-merged (later configs win on key conflicts).
1780
+ * Per-stage overrides (via stage.setInputConfiguration) are merged on top.
1781
+ * Can be called before or after start().
1782
+ * @example game.setInputConfiguration(useArrowsForAxes('p1'), useWASDForDirections('p2'));
1783
+ */
1784
+ setInputConfiguration(...configs: GameInputConfig[]): this;
1785
+ start(): Promise<this>;
1786
+ setDisplayRuntime(runtime: Partial<ResolveGameConfigRuntime>): this;
1787
+ setDeviceProfile(profile: DeviceProfile): this;
1788
+ setViewportSize(width: number, height: number): this;
1789
+ private load;
1790
+ private setOverrides;
1791
+ /**
1792
+ * Subscribe to changes on a global value. Subscriptions are registered
1793
+ * when the game starts and cleaned up when disposed.
1794
+ * The callback receives the value and the current stage.
1795
+ * @example game.onGlobalChange('score', (val, stage) => console.log(val));
1796
+ */
1797
+ onGlobalChange<T = unknown>(path: string, callback: (value: T, stage: Stage | null) => void): this;
1798
+ /**
1799
+ * Subscribe to changes on multiple global paths. Subscriptions are registered
1800
+ * when the game starts and cleaned up when disposed.
1801
+ * The callback receives the values and the current stage.
1802
+ * @example game.onGlobalChanges(['score', 'lives'], ([score, lives], stage) => console.log(score, lives));
1803
+ */
1804
+ onGlobalChanges<T extends unknown[] = unknown[]>(paths: string[], callback: (values: T, stage: Stage | null) => void): this;
1805
+ /**
1806
+ * Register all stored global change callbacks.
1807
+ * Called internally during start().
1808
+ */
1809
+ private registerGlobalSubscriptions;
1810
+ /**
1811
+ * Get the current stage wrapper.
1812
+ */
1813
+ getCurrentStage(): Stage | null;
1814
+ /**
1815
+ * Experimental escape hatches. APIs here are unstable and may change or be
1816
+ * removed without a major version bump.
1817
+ */
1818
+ readonly experimental: {
1819
+ /**
1820
+ * The `@zylem/behaviors` {@link Simulation} backing the current stage's
1821
+ * physics world, or `null` before a stage is loaded. Intended for debug
1822
+ * tooling and the editor; games should not need it.
1823
+ */
1824
+ getRuntime: () => Simulation | null;
1825
+ };
1826
+ pause(): Promise<void>;
1827
+ resume(): Promise<void>;
1828
+ /**
1829
+ * Execute a single frame update.
1830
+ * Useful for testing or manual frame stepping.
1831
+ * @param deltaTime Optional delta time in seconds (defaults to 1/60)
1832
+ */
1833
+ step(deltaTime?: number): void;
1834
+ /**
1835
+ * Reload the first stage. Pass `{ transition }` to blend from the current
1836
+ * stage instead of cutting.
1837
+ * @example game.reset({ transition: { duration: 1 } });
1838
+ */
1839
+ reset(options?: StageNavigationOptions): Promise<void>;
1840
+ /**
1841
+ * Go to the previous stage in the stage array. Pass `{ transition }` to
1842
+ * blend from the current stage instead of cutting.
1843
+ */
1844
+ previousStage(options?: StageNavigationOptions): void;
1845
+ loadStageFromId(stageId: string): Promise<void>;
1846
+ /**
1847
+ * Go to the next stage. Pass `{ transition }` to blend from the current
1848
+ * stage instead of cutting.
1849
+ * @example
1850
+ * game.nextStage({
1851
+ * transition: { duration: 1.2, shader: createStageTransition({ pattern: 'noise' }) },
1852
+ * });
1853
+ */
1854
+ nextStage(options?: StageNavigationOptions): void;
1855
+ goToStage(): Promise<void>;
1856
+ end(): Promise<void>;
1857
+ dispose(): void;
1858
+ /**
1859
+ * Dispatch an event from the game.
1860
+ * Events are emitted both locally and to the global event bus.
1861
+ */
1862
+ dispatch<K extends keyof GameEvents>(event: K, payload: GameEvents[K]): void;
1863
+ /**
1864
+ * Listen for events on this game instance.
1865
+ * @returns Unsubscribe function
1866
+ */
1867
+ listen<K extends keyof GameEvents>(event: K, handler: (payload: GameEvents[K]) => void): () => void;
1868
+ /**
1869
+ * Subscribe to loading events from the game.
1870
+ * Events include stage context (stageName, stageIndex).
1871
+ * @param callback Invoked for each loading event
1872
+ * @returns Unsubscribe function
1873
+ */
1874
+ onLoading(callback: (event: GameLoadingEvent) => void): () => void;
1875
+ }
1876
+ /**
1877
+ * create a new game
1878
+ * @param options GameOptions - Array of IGameOptions, Stage, GameEntity, or BaseNode objects
1879
+ * @param options.id Game name string (when using IGameOptions)
1880
+ * @param options.globals Game globals object (when using IGameOptions)
1881
+ * @param options.stages Array of stage objects (when using IGameOptions)
1882
+ * @returns Game
1883
+ */
1884
+ declare function createGame<TGlobals extends BaseGlobals>(...options: GameOptions<TGlobals>): Game<TGlobals>;
1885
+
1886
+ export { AspectRatio as A, Stage as B, CameraWrapper as C, type DeviceProfile as D, type StageStateInterface as E, Fixed2DPerspective as F, Game as G, type PerspectiveOptions as P, type ResolutionInput as R, type StageConfigLike as S, ThirdPersonPerspective as T, type GameLoadingEvent as a, type GameConfigLike as b, createGame as c, type GameDeviceConfig as d, type ResolveGameConfigRuntime as e, createStage as f, gameConfig as g, type StageOptions as h, createCamera as i, type CameraOptions as j, CameraManager as k, FirstPersonPerspective as l, createPerspective as m, type ThirdPersonOptions as n, type Fixed2DOptions as o, type FirstPersonOptions as p, type AspectRatioValue as q, getDisplayAspect as r, stageConfig as s, getPresetResolution as t, parseResolution as u, type RetroPreset as v, type RetroPresetKey as w, type RetroResolution as x, RenderBundleManager as y, RenderStrategyManager as z };