@n3rdw1z4rd/core 0.18.5 → 0.19.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 (109) hide show
  1. package/README.md +72 -10
  2. package/dist/astar.d.ts +44 -0
  3. package/dist/astar.js +118 -0
  4. package/dist/canvas-renderer.d.ts +154 -0
  5. package/dist/canvas-renderer.js +200 -0
  6. package/dist/clock.d.ts +69 -0
  7. package/dist/clock.js +108 -0
  8. package/dist/color-palette.d.ts +25 -0
  9. package/dist/color-palette.js +112 -0
  10. package/dist/color.d.ts +90 -0
  11. package/dist/color.js +224 -0
  12. package/dist/css/main.css +1 -3
  13. package/dist/disposable.d.ts +27 -0
  14. package/dist/disposable.js +32 -0
  15. package/dist/dungeon-generator.d.ts +142 -0
  16. package/dist/dungeon-generator.js +288 -0
  17. package/dist/ecs.d.ts +87 -0
  18. package/dist/ecs.js +101 -0
  19. package/dist/emitter.d.ts +40 -0
  20. package/dist/emitter.js +54 -0
  21. package/dist/event-queue.d.ts +29 -0
  22. package/dist/event-queue.js +40 -0
  23. package/dist/index.cjs +3813 -0
  24. package/dist/index.d.cts +2655 -0
  25. package/dist/index.d.ts +35 -873
  26. package/dist/index.js +34 -3981
  27. package/dist/input/action-map.d.ts +79 -0
  28. package/dist/input/action-map.js +131 -0
  29. package/dist/input/bindings.d.ts +273 -0
  30. package/dist/input/bindings.js +250 -0
  31. package/dist/input/gestures.d.ts +108 -0
  32. package/dist/input/gestures.js +159 -0
  33. package/dist/input/index.d.ts +5 -0
  34. package/dist/input/index.js +5 -0
  35. package/dist/input/input.d.ts +297 -0
  36. package/dist/input/input.js +695 -0
  37. package/dist/log.d.ts +8 -0
  38. package/dist/log.js +9 -0
  39. package/dist/map2d.d.ts +83 -0
  40. package/dist/map2d.js +120 -0
  41. package/dist/map3d-CHDJiq5T.d.cts +236 -0
  42. package/dist/map3d.d.ts +94 -0
  43. package/dist/map3d.js +148 -0
  44. package/dist/math.d.ts +176 -0
  45. package/dist/math.js +206 -0
  46. package/dist/misc.d.ts +46 -0
  47. package/dist/misc.js +71 -0
  48. package/dist/observable.d.ts +43 -0
  49. package/dist/observable.js +53 -0
  50. package/dist/particle-renderer.d.ts +47 -0
  51. package/dist/particle-renderer.js +82 -0
  52. package/dist/particle-system-2d.d.ts +60 -0
  53. package/dist/particle-system-2d.js +147 -0
  54. package/dist/random.d.ts +46 -0
  55. package/dist/random.js +74 -0
  56. package/dist/rectangle.d.ts +44 -0
  57. package/dist/rectangle.js +69 -0
  58. package/dist/rng.d.ts +72 -0
  59. package/dist/rng.js +152 -0
  60. package/dist/signal.d.ts +34 -0
  61. package/dist/signal.js +41 -0
  62. package/dist/spatial-partition-2d.d.ts +42 -0
  63. package/dist/spatial-partition-2d.js +52 -0
  64. package/dist/spatial-partition-3d-Ba-VBveM.cjs +1324 -0
  65. package/dist/spatial-partition-3d.d.ts +44 -0
  66. package/dist/spatial-partition-3d.js +57 -0
  67. package/dist/three/asteroid-mesh.d.ts +41 -0
  68. package/dist/three/asteroid-mesh.js +44 -0
  69. package/dist/three/camera-rig.d.ts +140 -0
  70. package/dist/three/camera-rig.js +197 -0
  71. package/dist/three/cube-sphere-geometry.d.ts +55 -0
  72. package/dist/three/cube-sphere-geometry.js +239 -0
  73. package/dist/three/ecs.d.ts +75 -0
  74. package/dist/three/ecs.js +64 -0
  75. package/dist/three/index.d.ts +12 -0
  76. package/dist/three/index.js +12 -0
  77. package/dist/three/particle-system-3d.d.ts +53 -0
  78. package/dist/three/particle-system-3d.js +224 -0
  79. package/dist/three/renderer.d.ts +38 -0
  80. package/dist/three/renderer.js +57 -0
  81. package/dist/three/starfield.d.ts +23 -0
  82. package/dist/three/starfield.js +64 -0
  83. package/dist/three/texture-atlas.d.ts +76 -0
  84. package/dist/three/texture-atlas.js +84 -0
  85. package/dist/three/texture-utils.d.ts +31 -0
  86. package/dist/three/texture-utils.js +44 -0
  87. package/dist/three/voxel-geometry.d.ts +72 -0
  88. package/dist/three/voxel-geometry.js +231 -0
  89. package/dist/three/voxel-mesh.d.ts +67 -0
  90. package/dist/three/voxel-mesh.js +71 -0
  91. package/dist/three.cjs +1307 -0
  92. package/dist/three.d.cts +655 -0
  93. package/dist/tilemap.d.ts +17 -0
  94. package/dist/tilemap.js +26 -0
  95. package/dist/types.d.ts +34 -0
  96. package/dist/types.js +0 -0
  97. package/dist/vector.d.ts +78 -0
  98. package/dist/vector.js +169 -0
  99. package/dist/webgl-renderer.d.ts +89 -0
  100. package/dist/webgl-renderer.js +140 -0
  101. package/dist/webgl.d.ts +357 -0
  102. package/dist/webgl.js +628 -0
  103. package/dist/worker-interface.d.ts +30 -0
  104. package/dist/worker-interface.js +39 -0
  105. package/package.json +55 -13
  106. package/dist/css/index.ts +0 -1
  107. package/dist/index.css +0 -104
  108. package/dist/index.d.mts +0 -873
  109. package/dist/index.mjs +0 -3977
@@ -0,0 +1,2655 @@
1
+ import { _ as XYZ, a as Map3DCell, c as MAP_2D_MIN_COORD, d as ColorPalette, f as RGB, g as XY, h as NoiseFunction3D, i as Map3D, l as Map2D, m as KeyValue, n as MAP_3D_MAX_COORD, o as DEFAULT_MAP_2D_VALUE, p as buildColorPalette, r as MAP_3D_MIN_COORD, s as MAP_2D_MAX_COORD, t as DEFAULT_MAP_3D_VALUE, u as Map2DData } from "./map3d-CHDJiq5T.cjs";
2
+ //#region src/astar.d.ts
3
+ /**
4
+ * Cost of stepping onto tile (x, y). Return `Infinity` for blocked tiles. Costs should be >= 1
5
+ * (the heuristic assumes it); use larger values for slower terrain or occupied tiles.
6
+ *
7
+ * @category Pathfinding & Procedural
8
+ */
9
+ export type StepCost = (x: number, y: number) => number;
10
+ /**
11
+ * Options for {@link findPath}.
12
+ *
13
+ * @category Pathfinding & Procedural
14
+ */
15
+ export interface PathOptions {
16
+ /** 8-way movement; a diagonal step costs SQRT2 * the tile's cost. Default false. */
17
+ diagonal?: boolean;
18
+ /** allow a diagonal step past a blocked orthogonal neighbour. Default false. */
19
+ cutCorners?: boolean;
20
+ /** stop on a tile next to the goal (the goal itself may be blocked). Default false. */
21
+ adjacent?: boolean;
22
+ /** give up after expanding this many tiles. Default 10,000. */
23
+ maxNodes?: number;
24
+ /** if the goal isn't reached, return the path to the closest tile found. Default false. */
25
+ partial?: boolean;
26
+ }
27
+ /**
28
+ * Finds a lowest-cost path on an unbounded grid with A*.
29
+ *
30
+ * The returned path excludes `start` and ends on the goal (or, with `adjacent`, on a tile next to
31
+ * it). Returns [] if `start` already satisfies the goal, or if no path is found (unless `partial`).
32
+ * The same inputs always produce the same path.
33
+ *
34
+ * ```ts
35
+ * const walls = new Set(['2,0', '2,1', '2,2']);
36
+ * const cost: StepCost = (x, y) => walls.has(`${x},${y}`) ? Infinity : 1;
37
+ *
38
+ * const path = findPath({ x: 0, y: 1 }, { x: 4, y: 1 }, cost, { diagonal: true });
39
+ * ```
40
+ *
41
+ * @category Pathfinding & Procedural
42
+ */
43
+ export declare function findPath(start: XY, goal: XY, cost: StepCost, options?: PathOptions): XY[];
44
+ //#endregion
45
+ //#region src/canvas-renderer.d.ts
46
+ /**
47
+ * Anything a 2D context accepts as a fill or stroke style: a CSS color string, a gradient or a pattern.
48
+ *
49
+ * @category Canvas 2D
50
+ */
51
+ export type CanvasColor = string | CanvasGradient | CanvasPattern;
52
+ /**
53
+ * Fill / stroke color used when {@link DrawParams.color} is not given.
54
+ *
55
+ * @category Canvas 2D
56
+ */
57
+ export declare const DEFAULT_COLOR: CanvasColor;
58
+ /**
59
+ * Side length in pixels of {@link CanvasRenderer.drawPixel} when {@link DrawParams.size} is not given.
60
+ *
61
+ * @category Canvas 2D
62
+ */
63
+ export declare const DEFAULT_PIXEL_SIZE: number;
64
+ /**
65
+ * Font size in pixels for {@link CanvasRenderer.drawText}.
66
+ *
67
+ * @category Canvas 2D
68
+ */
69
+ export declare const DEFAULT_FONT_SIZE = 14;
70
+ /**
71
+ * Font family for {@link CanvasRenderer.drawText}.
72
+ *
73
+ * @category Canvas 2D
74
+ */
75
+ export declare const DEFAULT_FONT_NAME = "monospace";
76
+ /**
77
+ * CSS font built from {@link DEFAULT_FONT_SIZE} and {@link DEFAULT_FONT_NAME} (`'14px monospace'`).
78
+ *
79
+ * @category Canvas 2D
80
+ */
81
+ export declare const DEFAULT_FONT = "14px monospace";
82
+ /**
83
+ * Default `textAlign` for {@link CanvasRenderer.drawText}.
84
+ *
85
+ * @category Canvas 2D
86
+ */
87
+ export declare const DEFAULT_TEXTALIGN = "left";
88
+ /**
89
+ * Default `textBaseline` for {@link CanvasRenderer.drawText}.
90
+ *
91
+ * @category Canvas 2D
92
+ */
93
+ export declare const DEFAULT_TEXTBASELINE = "alphabetic";
94
+ /**
95
+ * Optional style settings for the {@link CanvasRenderer} draw methods. Each method uses only the fields that apply to it.
96
+ *
97
+ * @category Canvas 2D
98
+ */
99
+ export interface DrawParams {
100
+ /** fill and stroke color, default {@link DEFAULT_COLOR} */
101
+ color?: CanvasColor;
102
+ /** shapes: fill instead of stroking the outline, default false */
103
+ filled?: boolean;
104
+ /** pixels: line width for outlines and lines (default 1), side length for drawPixel (default {@link DEFAULT_PIXEL_SIZE}), font size for drawText (default {@link DEFAULT_FONT_SIZE}) */
105
+ size?: number;
106
+ /** shapes and lines: dash pattern (see `setLineDash`), reset after drawing; default solid */
107
+ lineDash?: number[];
108
+ /** text: default {@link DEFAULT_TEXTALIGN} */
109
+ textAlign?: CanvasTextAlign;
110
+ /** text: default {@link DEFAULT_TEXTBASELINE} */
111
+ textBaseline?: CanvasTextBaseline;
112
+ /** text: a full CSS font; overrides `size` and `fontName` */
113
+ font?: string;
114
+ /** text: font family, default {@link DEFAULT_FONT_NAME} */
115
+ fontName?: string;
116
+ }
117
+ /**
118
+ * Parameters for {@link CanvasRenderer.drawSprite}: an optional source rectangle within the image (for sprite sheets). The rectangle is used only when both `sourceWidth` and `sourceHeight` are set; otherwise the whole image is drawn. The inherited style fields are ignored.
119
+ *
120
+ * @category Canvas 2D
121
+ */
122
+ export interface SpriteParams extends DrawParams {
123
+ /** pixels, default 0 */
124
+ sourceX?: number;
125
+ /** pixels, default 0 */
126
+ sourceY?: number;
127
+ /** pixels */
128
+ sourceWidth?: number;
129
+ /** pixels */
130
+ sourceHeight?: number;
131
+ }
132
+ /**
133
+ * Immediate-mode drawing of simple shapes, text and sprites on a 2D canvas. Rectangles, pixels and
134
+ * sprites are positioned by their center; circles and polygons by their center and radius.
135
+ *
136
+ * ```ts
137
+ * const renderer = new CanvasRenderer();
138
+ * document.body.appendChild(renderer.canvas);
139
+ * renderer.resize(); // to the parent's size
140
+ *
141
+ * renderer.clear();
142
+ * renderer.drawCircle(100, 100, 20, { color: 'red', filled: true });
143
+ * renderer.drawText(10, 20, 'hello', { size: 16 });
144
+ * ```
145
+ *
146
+ * @category Canvas 2D
147
+ */
148
+ export declare class CanvasRenderer {
149
+ /** the 2D context all drawing goes through */
150
+ context: CanvasRenderingContext2D;
151
+ /** the canvas being drawn on */
152
+ get canvas(): HTMLCanvasElement;
153
+ /** canvas width in pixels */
154
+ get width(): number;
155
+ /** canvas height in pixels */
156
+ get height(): number;
157
+ /**
158
+ * @param canvas defaults to a new canvas element, not attached to the page (append {@link CanvasRenderer.canvas} yourself)
159
+ */
160
+ constructor(canvas?: HTMLCanvasElement);
161
+ private _applyDefaults;
162
+ /**
163
+ * Sets the canvas size in pixels; a missing dimension defaults to the parent element's client
164
+ * size (or the current size without a parent, or while the parent has no size). Resizing clears
165
+ * the canvas and resets the context state; the renderer's default font and alignment are
166
+ * applied again. Returns whether the size changed.
167
+ */
168
+ resize(width?: number, height?: number): boolean;
169
+ /** Clears the whole canvas to transparent. */
170
+ clear(): void;
171
+ private drawPath;
172
+ /** Draws a `width` x `height` rectangle centered on (`x`, `y`): its outline, or filled with `filled`. */
173
+ drawRect(x: number, y: number, width: number, height: number, params?: DrawParams): void;
174
+ /** Draws a filled square of side `params.size` (default {@link DEFAULT_PIXEL_SIZE}) centered on (`x`, `y`). */
175
+ drawPixel(x: number, y: number, params?: DrawParams): void;
176
+ /** Draws a line segment from (`x1`, `y1`) to (`x2`, `y2`); `params.size` is the line width. */
177
+ drawLine(x1: number, y1: number, x2: number, y2: number, params?: DrawParams): void;
178
+ /** Draws a circle centered on (`x`, `y`). */
179
+ drawCircle(x: number, y: number, radius: number, params?: DrawParams): void;
180
+ /**
181
+ * Draws a regular polygon centered on (`x`, `y`) with its first vertex straight up.
182
+ *
183
+ * @param radius distance from the center to each vertex
184
+ * @param sides floored and clamped to 3..36
185
+ */
186
+ drawPolygon(x: number, y: number, radius: number, sides: number, params?: DrawParams): void;
187
+ /**
188
+ * Fills `text` at (`x`, `y`), aligned by `params.textAlign` / `params.textBaseline` (default
189
+ * left / alphabetic). The font is `params.font`, or `params.size` px `params.fontName`.
190
+ */
191
+ drawText(x: number, y: number, text: string, params?: DrawParams): void;
192
+ /**
193
+ * Draws `image` (or the `params` source rectangle of it) scaled to `width` x `height`, centered
194
+ * on (`x`, `y`).
195
+ */
196
+ drawSprite(x: number, y: number, image: CanvasImageSource, width: number, height: number, params?: SpriteParams): void;
197
+ }
198
+ //#endregion
199
+ //#region src/clock.d.ts
200
+ /**
201
+ * Milliseconds in one second.
202
+ *
203
+ * @category Events & Timing
204
+ */
205
+ export declare const ONE_SECOND = 1000;
206
+ /**
207
+ * Called by {@link Clock.start} every animation frame with the capped delta time and the elapsed
208
+ * time, both in seconds.
209
+ *
210
+ * @category Events & Timing
211
+ */
212
+ export type ClockCallback = (deltaTime: number, elapsedTime: number) => void;
213
+ /**
214
+ * Frame timing: delta time, elapsed time and FPS.
215
+ *
216
+ * Either let the clock run the loop:
217
+ *
218
+ * clock.start((dt) => { update(dt); render(); });
219
+ *
220
+ * or advance it from a loop something else drives (three.js, WebXR):
221
+ *
222
+ * renderer.setAnimationLoop((time) => { const dt = clock.tick(time); ... });
223
+ *
224
+ * @category Events & Timing
225
+ */
226
+ export declare class Clock {
227
+ /**
228
+ * seconds; caps the delta time after a stall or a hidden tab (browsers pause the frame loop
229
+ * in background tabs, so the first frame back would otherwise cover the whole absence)
230
+ */
231
+ maxDeltaTime: number;
232
+ private _callback?;
233
+ private _rafId;
234
+ private _isRunning;
235
+ private _lastTime;
236
+ private _deltaTime;
237
+ private _elapsedTime;
238
+ private _fps;
239
+ private _fpsFrames;
240
+ private _fpsTime;
241
+ /** seconds since the previous tick, capped at `maxDeltaTime`; 0 on the first tick */
242
+ get deltaTime(): number;
243
+ /**
244
+ * seconds since start() (or the first tick), summed from the capped delta times,
245
+ * so it stays in step with the simulation rather than wall-clock time
246
+ */
247
+ get elapsedTime(): number;
248
+ /** frames per second, rounded; recomputed about once a second, 0 until the first second has passed */
249
+ get fps(): number;
250
+ /** whether {@link Clock.start} is driving the loop (manual {@link Clock.tick} calls don't count) */
251
+ get isRunning(): boolean;
252
+ /**
253
+ * Advances the clock and returns the delta time in seconds. The first tick returns 0.
254
+ *
255
+ * @param time timestamp in milliseconds, e.g. from requestAnimationFrame or setAnimationLoop
256
+ */
257
+ tick(time?: number): number;
258
+ /**
259
+ * Runs `callback` every animation frame with the delta and elapsed time in seconds.
260
+ * Restarts timing from zero; calling it while running just swaps the callback.
261
+ */
262
+ start(callback: ClockCallback): void;
263
+ /** Stops the loop started by {@link Clock.start}. Timing state is kept until the next `start()`. */
264
+ stop(): void;
265
+ private _reset;
266
+ }
267
+ //#endregion
268
+ //#region src/color.d.ts
269
+ /**
270
+ * RGBA color with 8-bit channels (integers 0-255), kept in sync with an 8-digit hex string.
271
+ * Setting a channel rounds and clamps it to 0-255.
272
+ *
273
+ * ```ts
274
+ * new Color(255, 128, 0); // opaque orange
275
+ * new Color('#ff8000'); // same, from a hex string
276
+ * Color.fromHsv(0.5, 1, 1).hexStr; // '#00ffffff'
277
+ * ```
278
+ * @category Color
279
+ */
280
+ export declare class Color {
281
+ private _hex;
282
+ private _r;
283
+ private _g;
284
+ private _b;
285
+ private _a;
286
+ /** red, 0-255 */
287
+ get r(): number;
288
+ /** rounded and clamped to 0-255 */
289
+ set r(value: number);
290
+ /** green, 0-255 */
291
+ get g(): number;
292
+ /** rounded and clamped to 0-255 */
293
+ set g(value: number);
294
+ /** blue, 0-255 */
295
+ get b(): number;
296
+ /** rounded and clamped to 0-255 */
297
+ set b(value: number);
298
+ /** alpha, 0-255 (255 = opaque) */
299
+ get a(): number;
300
+ /** rounded and clamped to 0-255 */
301
+ set a(value: number);
302
+ /**
303
+ * lowercase `'#rrggbbaa'`. Accepts `#rgb`, `#rgba`, `#rrggbb` or `#rrggbbaa` when set (alpha
304
+ * defaults to ff); an invalid string is logged and the color is left unchanged.
305
+ */
306
+ get hexStr(): string;
307
+ /** `#rgb`, `#rgba`, `#rrggbb` or `#rrggbbaa`; invalid strings are logged and ignored */
308
+ set hexStr(value: string);
309
+ /** a new `[r, g, b, a]` array, each 0-255 */
310
+ get rgba(): number[];
311
+ /**
312
+ * Creates a color from a hex string (as accepted by {@link Color.hexStr}) or from channel
313
+ * values, each rounded and clamped to 0-255 like the channel setters. An invalid string is
314
+ * logged and gives opaque white. Defaults to opaque white.
315
+ */
316
+ constructor(r?: string | number, g?: number, b?: number, a?: number);
317
+ private static _channel;
318
+ private _to_hex;
319
+ private static _parse_hex_color_string;
320
+ /**
321
+ * Creates a color from hue, saturation and value, each in [0, 1]
322
+ * (hues outside [0, 1) wrap around).
323
+ * @param a alpha, 0-255 (default 255)
324
+ */
325
+ static fromHsv(h: number, s: number, v: number, a?: number): Color;
326
+ /** new opaque black */
327
+ static get BLACK(): Color;
328
+ /** new opaque gray (128, 128, 128) */
329
+ static get GRAY(): Color;
330
+ /** new opaque white */
331
+ static get WHITE(): Color;
332
+ /** new opaque red (255, 0, 0) */
333
+ static get RED(): Color;
334
+ /** new opaque green (0, 255, 0) */
335
+ static get GREEN(): Color;
336
+ /** new opaque blue (0, 0, 255) */
337
+ static get BLUE(): Color;
338
+ /** new opaque yellow (255, 255, 0) */
339
+ static get YELLOW(): Color;
340
+ /** new opaque orange (255, 128, 0) */
341
+ static get ORANGE(): Color;
342
+ /** new opaque purple (128, 0, 128) */
343
+ static get PURPLE(): Color;
344
+ /** new opaque cyan (0, 255, 255) */
345
+ static get CYAN(): Color;
346
+ /** new opaque magenta (255, 0, 255) */
347
+ static get MAGENTA(): Color;
348
+ /**
349
+ * Creates a color from any CSS color string (e.g. `'rebeccapurple'`, `'rgb(0 0 0 / 50%)'`) by
350
+ * letting the browser compute it. Needs a DOM: it briefly appends an element to
351
+ * `document.body`. An unrecognised name is logged and gives {@link Color.TRANSPARENT}.
352
+ */
353
+ static fromName(name: string): Color;
354
+ /** new fully transparent black (0, 0, 0, 0) */
355
+ static get TRANSPARENT(): Color;
356
+ }
357
+ //#endregion
358
+ //#region src/disposable.d.ts
359
+ /**
360
+ * Collects cleanup functions (e.g. the unsubscribe functions returned by {@link Observable.subscribe}
361
+ * and {@link Signal.subscribe}) and runs them all at once.
362
+ *
363
+ * ```ts
364
+ * const subscriptions = new Disposable();
365
+ *
366
+ * subscriptions.add(health.subscribe(updateHealthBar));
367
+ * subscriptions.add(onLoaded.subscribe(uploadToGpu));
368
+ *
369
+ * subscriptions.dispose(); // later
370
+ * ```
371
+ *
372
+ * @category Events & Timing
373
+ */
374
+ export declare class Disposable {
375
+ private readonly disposers;
376
+ /** Adds a cleanup function to run on {@link Disposable.dispose}. */
377
+ add(disposer: () => void): void;
378
+ /**
379
+ * Runs and removes every cleanup function, in reverse order of adding. The instance can be
380
+ * reused afterwards.
381
+ */
382
+ dispose(): void;
383
+ }
384
+ //#endregion
385
+ //#region src/vector.d.ts
386
+ /**
387
+ * Mutable 2D vector. Most methods modify the vector in place and return `this` for chaining;
388
+ * {@link Vector.clone} and {@link Vector.floored} return new vectors.
389
+ *
390
+ * ```ts
391
+ * const v = new Vector(3, 4);
392
+ * v.length(); // 5
393
+ * v.clone().normalize().times(10); // (6, 8), v unchanged
394
+ * v.plus(1).minus(new Vector(0, 2)); // v is now (4, 3)
395
+ * ```
396
+ * @category Math & Random
397
+ */
398
+ export declare class Vector {
399
+ /** horizontal component */
400
+ x: number;
401
+ /** vertical component (down in screen coordinates) */
402
+ y: number;
403
+ constructor(x?: number, y?: number);
404
+ /** A new vector with the same components. */
405
+ clone(): Vector;
406
+ /** Copies `that`'s components into this vector. */
407
+ copy(that: Vector): this;
408
+ /** Writes this vector's components into `target`; returns this vector, not `target`. */
409
+ copyTo(target: {
410
+ x: number;
411
+ y: number;
412
+ }): this;
413
+ /** Sets both components. */
414
+ set(x: number, y: number): this;
415
+ /** Exact (`===`) component-wise equality. */
416
+ equals(that: Vector): boolean;
417
+ /** Euclidean distance to `that`. */
418
+ distanceTo(that: Vector): number;
419
+ /** Euclidean length (magnitude). */
420
+ length(): number;
421
+ /** Scales to unit length in place; a zero vector is left unchanged. */
422
+ normalize(): this;
423
+ /** Scales to the given length in place, keeping the direction; a zero vector stays zero. */
424
+ setLength(length: number): this;
425
+ /** Dot product with `that`. */
426
+ dot(that: Vector): number;
427
+ /** Direction in radians, `Math.atan2(y, x)`, in (-π, π]. */
428
+ angle(): number;
429
+ /** Unsigned angle between this vector and `that`, in radians in [0, π]; 0 if either is a zero vector. */
430
+ angleTo(that: Vector): number;
431
+ /** Rotates in place about the origin by `radians` (counter-clockwise with y up, clockwise on screen with y down). */
432
+ rotate(radians: number): this;
433
+ /** Rotates in place about `origin` by `radians`. */
434
+ rotateAround(origin: Vector, radians: number): this;
435
+ /** A new vector with both components floored; this vector is unchanged. */
436
+ floored(): Vector;
437
+ /** Adds in place: another vector, a scalar to both components (`plus(n)`), or separate `x` and `y` amounts. */
438
+ plus(x: number | Vector, y?: number): this;
439
+ /** Subtracts in place; arguments as for {@link Vector.plus}. */
440
+ minus(x: number | Vector, y?: number): this;
441
+ /** Multiplies component-wise in place; arguments as for {@link Vector.plus}. */
442
+ times(x: number | Vector, y?: number): this;
443
+ /**
444
+ * Divides component-wise in place; arguments as for {@link Vector.plus}. Plain division: a zero
445
+ * divisor gives `Infinity` (or `NaN` for 0 / 0), as with numbers.
446
+ */
447
+ dividedBy(x: number | Vector, y?: number): this;
448
+ /** A new vector from any `{ x, y }` object. */
449
+ static from(value: XY): Vector;
450
+ /** new (0, 0) */
451
+ static get ZERO(): Vector;
452
+ /** new (0, -1): up in screen coordinates (y down) */
453
+ static get NORTH(): Vector;
454
+ /** new (0, 1): down in screen coordinates */
455
+ static get SOUTH(): Vector;
456
+ /** new (1, 0) */
457
+ static get EAST(): Vector;
458
+ /** new (-1, 0) */
459
+ static get WEST(): Vector;
460
+ }
461
+ //#endregion
462
+ //#region src/rectangle.d.ts
463
+ /**
464
+ * Axis-aligned rectangle given by its top-left corner (`x`, `y`) and size. Edges are inclusive
465
+ * in the containment and intersection tests.
466
+ * @category Math & Random
467
+ */
468
+ export declare class Rectangle {
469
+ /** left edge */
470
+ x: number;
471
+ /** top edge (minimum y; y points down) */
472
+ y: number;
473
+ /** extent along x from `x` */
474
+ width: number;
475
+ /** extent along y from `y` */
476
+ height: number;
477
+ /** Defaults to a 1 x 1 rectangle at the origin. */
478
+ constructor(x?: number, y?: number, width?: number, height?: number);
479
+ /** `width * height`. */
480
+ area(): number;
481
+ /**
482
+ * True if `target` (a point, or a whole rectangle) is inside or on the edge, with this rectangle
483
+ * grown by `padding` on every side (negative shrinks).
484
+ */
485
+ contains(target: Vector | Rectangle, padding?: number): boolean;
486
+ /**
487
+ * True if the rectangles overlap or touch, or are at most `padding` apart (negative requires
488
+ * that much overlap).
489
+ */
490
+ intersects(other: Rectangle, padding?: number): boolean;
491
+ /** A new vector at the rectangle's centre. */
492
+ center(): Vector;
493
+ /** Distance between the two rectangles' centres. */
494
+ distanceTo(other: Rectangle): number;
495
+ /** A new rectangle with the same position and size. */
496
+ clone(): Rectangle;
497
+ /** Exact (`===`) equality of position and size. */
498
+ equals(other: Rectangle): boolean;
499
+ /** A new rectangle expanded by `padding` on every side (negative shrinks); this one is unchanged. */
500
+ grow(padding: number): Rectangle;
501
+ /** Same as {@link Rectangle.contains} with a point. */
502
+ vectorInside(vec: Vector, padding?: number): boolean;
503
+ }
504
+ //#endregion
505
+ //#region src/dungeon-generator.d.ts
506
+ /**
507
+ * Two rooms to be joined by a corridor.
508
+ *
509
+ * @property a first room
510
+ * @property b second room
511
+ * @category Pathfinding & Procedural
512
+ */
513
+ export type RectPair = {
514
+ a: Rectangle;
515
+ b: Rectangle;
516
+ };
517
+ /**
518
+ * Two tiles, e.g. the closest edge tiles of two rooms.
519
+ *
520
+ * @property a first point
521
+ * @property b second point
522
+ * @category Pathfinding & Procedural
523
+ */
524
+ export type PointPair = {
525
+ a: XY;
526
+ b: XY;
527
+ };
528
+ /**
529
+ * Room placement options for {@link GenerateRooms}.
530
+ *
531
+ * @category Pathfinding & Procedural
532
+ */
533
+ export interface RoomsParams {
534
+ /** level width and height in tiles, default 64 */
535
+ size?: number;
536
+ /** smallest room side in tiles, default 3 */
537
+ minSize?: number;
538
+ /** largest room side in tiles, default 9 */
539
+ maxSize?: number;
540
+ /** spacing kept around each room and from the level edge in tiles, default 1 */
541
+ padding?: number;
542
+ /** stop after this many consecutive failed placements, default 1000 */
543
+ maxIterations?: number;
544
+ }
545
+ /**
546
+ * Corridor options for {@link GenerateRooms}.
547
+ *
548
+ * @category Pathfinding & Procedural
549
+ */
550
+ export interface PathsParams {
551
+ /** number of shortest unused room connections considered as extra (loop) corridors, default 0 */
552
+ extraPaths?: number;
553
+ /** chance (0-1) that each considered extra connection is added, default 0.1 */
554
+ extraPathDensity?: number;
555
+ /** tile values corridors may be carved through, default: the map's default value (empty space) */
556
+ walkableValues?: number[];
557
+ }
558
+ /**
559
+ * Options for {@link GenerateDoors}.
560
+ *
561
+ * @category Pathfinding & Procedural
562
+ */
563
+ export interface DoorsParams {
564
+ /** chance (0-1) that a door is placed at each eligible corridor end, default 0.5 */
565
+ chanceExists?: number;
566
+ }
567
+ /**
568
+ * Options for {@link GenerateRooms}.
569
+ *
570
+ * @category Pathfinding & Procedural
571
+ */
572
+ export interface GenerateRoomsParams {
573
+ /** map to draw into, default a new {@link Map2D} filled with {@link TILE_EMPTY} */
574
+ map?: Map2D;
575
+ /** room placement options */
576
+ rooms?: RoomsParams;
577
+ /** corridor options */
578
+ paths?: PathsParams;
579
+ }
580
+ /**
581
+ * Tile value for empty (unused) space.
582
+ *
583
+ * @category Pathfinding & Procedural
584
+ */
585
+ export declare const TILE_EMPTY = 0;
586
+ /**
587
+ * Tile value for room floor.
588
+ *
589
+ * @category Pathfinding & Procedural
590
+ */
591
+ export declare const TILE_FLOOR = 1;
592
+ /**
593
+ * Tile value for corridor floor.
594
+ *
595
+ * @category Pathfinding & Procedural
596
+ */
597
+ export declare const TILE_PATH = 2;
598
+ /**
599
+ * Generates a dungeon level: scatters non-overlapping rectangular rooms, joins them with a minimum
600
+ * spanning tree of A* corridors (plus optional extra ones) and plots both into the map as
601
+ * {@link TILE_FLOOR} and {@link TILE_PATH}.
602
+ *
603
+ * Rooms are placed at random until {@link RoomsParams.maxIterations} placements in a row fail.
604
+ * Corridors are carved only through {@link PathsParams.walkableValues} tiles; each runs from next to
605
+ * one room's edge to next to the other's, and is empty if no route exists. Randomness comes from the
606
+ * shared {@link rng}, so set `rng.seed` first for a reproducible level. Logs its duration.
607
+ *
608
+ * ```ts
609
+ * rng.seed = 1234;
610
+ * const { map, rooms, paths } = GenerateRooms({ rooms: { size: 48 } });
611
+ * const doors = GenerateDoors(map, paths);
612
+ * const walls = GenerateWalls(map);
613
+ * ```
614
+ *
615
+ * @category Pathfinding & Procedural
616
+ */
617
+ export declare function GenerateRooms(params?: GenerateRoomsParams): {
618
+ /** the given map (modified) or a new one */
619
+ map: Map2D;
620
+ /** the placed rooms */
621
+ rooms: Rectangle[];
622
+ /** one tile list per corridor */
623
+ paths: XY[][];
624
+ };
625
+ /**
626
+ * Picks door tiles from the two end tiles of each corridor (corridors shorter than 2 tiles are
627
+ * skipped). An end qualifies when both its up/down or both its left/right neighbours hold the map's
628
+ * default value, i.e. it sits in a 1-wide gap; each qualifying end becomes a door with probability
629
+ * {@link DoorsParams.chanceExists}, using the shared {@link rng}. Does not modify the map.
630
+ *
631
+ * @param paths corridors as returned by {@link GenerateRooms}
632
+ * @returns the door tiles
633
+ * @category Pathfinding & Procedural
634
+ */
635
+ export declare function GenerateDoors(map: Map2D, paths: XY[][], params?: DoorsParams): XY[];
636
+ /**
637
+ * Returns every tile holding the map's default value that touches (8-way) a non-default tile, each
638
+ * once: the walls around all rooms and corridors. Does not modify the map.
639
+ *
640
+ * @category Pathfinding & Procedural
641
+ */
642
+ export declare function GenerateWalls(map: Map2D): XY[];
643
+ //#endregion
644
+ //#region src/ecs.d.ts
645
+ /**
646
+ * An entity id: a plain integer handed out by {@link ECS.createEntity}.
647
+ *
648
+ * @category ECS
649
+ */
650
+ export type Entity = number;
651
+ /**
652
+ * Any object used as a component. Components are stored by their constructor, so each entity holds
653
+ * at most one component per class.
654
+ *
655
+ * @category ECS
656
+ */
657
+ export type Component = object;
658
+ /**
659
+ * A component class; used as the key for lookups and queries.
660
+ *
661
+ * @category ECS
662
+ */
663
+ export type ComponentType<T extends Component = Component> = new (...args: any[]) => T;
664
+ /**
665
+ * The component instances for a tuple of component types, as yielded by {@link ECS.query}.
666
+ *
667
+ * @category ECS
668
+ */
669
+ export type ComponentInstances<T extends readonly ComponentType[]> = { [K in keyof T]: T[K] extends ComponentType<infer U> ? U : never; };
670
+ /**
671
+ * A function run once per frame with the elapsed time. Not used by {@link ECS} itself; a convention
672
+ * for callers that keep their own system list.
673
+ *
674
+ * @category ECS
675
+ */
676
+ export type System = (deltaTime: number) => void;
677
+ /**
678
+ * A minimal entity-component store. Entities are integers; components are class instances stored
679
+ * per class, and {@link ECS.query} iterates the entities that have every requested component.
680
+ *
681
+ * ```ts
682
+ * class Position { constructor(public x = 0, public y = 0) {} }
683
+ * class Velocity { constructor(public x = 0, public y = 0) {} }
684
+ *
685
+ * const world = new ECS();
686
+ * const e = world.createEntity();
687
+ * world.addComponent(e, new Position());
688
+ * world.addComponent(e, new Velocity(1, 0));
689
+ *
690
+ * for (const [entity, pos, vel] of world.query(Position, Velocity)) {
691
+ * pos.x += vel.x;
692
+ * }
693
+ * ```
694
+ *
695
+ * @category ECS
696
+ */
697
+ export declare class ECS {
698
+ #private;
699
+ private readonly components;
700
+ /** Returns a new entity id (0, 1, 2, ...). Ids are never reused until {@link ECS.clear}. */
701
+ createEntity(): Entity;
702
+ /**
703
+ * Attaches `component` to `entity`, keyed by `component.constructor`; replaces any existing
704
+ * component of the same class.
705
+ */
706
+ addComponent<T extends Component>(entity: Entity, component: T): void;
707
+ /** The entity's component of class `type`, or `undefined` if it has none. */
708
+ getComponent<T extends Component>(entity: Entity, type: ComponentType<T>): T | undefined;
709
+ /** Whether the entity has a component of class `type`. */
710
+ hasComponent<T extends Component>(entity: Entity, type: ComponentType<T>): boolean;
711
+ /** Removes the entity's component of class `type`, if any. */
712
+ removeComponent<T extends Component>(entity: Entity, type: ComponentType<T>): void;
713
+ /**
714
+ * Iterates `[entity, ...components]` for every entity that has all of `types`, with the
715
+ * components in the same order as `types`. Yields nothing when `types` is empty or any type has
716
+ * never been added. Order follows insertion into the least-populated component type.
717
+ */
718
+ query<T extends readonly ComponentType[]>(...types: T): IterableIterator<[Entity, ...ComponentInstances<T>]>;
719
+ /** Removes all of the entity's components. The id is not recycled. */
720
+ destroyEntity(entity: Entity): void;
721
+ /** Removes every component and resets entity ids to start from 0 again. */
722
+ clear(): void;
723
+ }
724
+ /**
725
+ * A shared {@link ECS} instance.
726
+ *
727
+ * @category ECS
728
+ */
729
+ export declare const ecs: ECS;
730
+ //#endregion
731
+ //#region src/emitter.d.ts
732
+ /**
733
+ * An {@link Emitter} listener: called with the emitted arguments, followed by the event name.
734
+ *
735
+ * @category Events & Timing
736
+ */
737
+ export type Listener = (...args: any[]) => void;
738
+ /**
739
+ * A string-keyed event emitter. Listeners get the emitted arguments followed by the event name,
740
+ * so one listener can tell apart the events it was added to.
741
+ *
742
+ * ```ts
743
+ * const events = new Emitter();
744
+ *
745
+ * events.on('hit', 'miss', (target, eventName) => console.log(eventName, target));
746
+ * events.emit('hit', enemy); // logs 'hit', enemy
747
+ * ```
748
+ *
749
+ * @category Events & Timing
750
+ */
751
+ export declare class Emitter {
752
+ private listeners;
753
+ constructor();
754
+ /**
755
+ * Adds a listener (the last argument) to one or more event names (the arguments before it).
756
+ * Adding the same listener twice makes it fire twice. Returns `this` for chaining.
757
+ */
758
+ on<T extends string[]>(...eventName: [...T, Listener]): this;
759
+ /**
760
+ * Calls the listeners of `eventName` in the order they were added, with `args` followed by
761
+ * `eventName`. Returns `this` for chaining.
762
+ */
763
+ emit(eventName: string, ...args: any[]): this;
764
+ /**
765
+ * Removes `listener` from `eventName` (one registration of it, if it was added more than
766
+ * once), or every listener of `eventName` when `listener` is left out. Returns `this`.
767
+ */
768
+ off(eventName: string, listener?: Listener): this;
769
+ }
770
+ //#endregion
771
+ //#region src/event-queue.d.ts
772
+ /**
773
+ * A buffered queue of events: producers `emit()` events, and a consumer reads them later (e.g.
774
+ * once per frame) with `drain()`, or with `consume()` followed by `clear()`.
775
+ *
776
+ * ```ts
777
+ * const collisions = new EventQueue<{ a: number, b: number }>();
778
+ *
779
+ * collisions.emit({ a: 1, b: 2 }); // physics system
780
+ *
781
+ * for (const { a, b } of collisions.drain()) { } // gameplay system; the queue is now empty
782
+ * ```
783
+ *
784
+ * @category Events & Timing
785
+ */
786
+ export declare class EventQueue<T> {
787
+ private readonly events;
788
+ /** Appends an event to the queue. */
789
+ emit(event: T): void;
790
+ /** Returns a copy of the queued events, oldest first, without removing them. */
791
+ consume(): T[];
792
+ /** Removes all queued events. */
793
+ clear(): void;
794
+ /** Removes and returns all queued events, oldest first. */
795
+ drain(): T[];
796
+ /** number of queued events */
797
+ get size(): number;
798
+ }
799
+ //#endregion
800
+ //#region src/input/bindings.d.ts
801
+ /**
802
+ * Modifier keys that must also be held for a key {@link Binding} to count (left or right side).
803
+ * Modifiers left out are not checked, so a binding without `ctrl` still fires while Ctrl is held.
804
+ *
805
+ * @category Input
806
+ */
807
+ export interface KeyModifiers {
808
+ /** require Shift */
809
+ shift?: boolean;
810
+ /** require Ctrl */
811
+ ctrl?: boolean;
812
+ /** require Alt */
813
+ alt?: boolean;
814
+ /** require Meta (Windows / Command key) */
815
+ meta?: boolean;
816
+ }
817
+ /**
818
+ * A mouse or pen button, as numbered by `PointerEvent.button` (0 to 4).
819
+ *
820
+ * @category Input
821
+ */
822
+ export type MouseButton = 'left' | 'middle' | 'right' | 'back' | 'forward';
823
+ /**
824
+ * A mouse wheel direction.
825
+ *
826
+ * @category Input
827
+ */
828
+ export type WheelDirection = 'up' | 'down' | 'left' | 'right';
829
+ /**
830
+ * W3C "standard" gamepad mapping, in button-index order (Xbox names; on PlayStation A = Cross,
831
+ * B = Circle, X = Square, Y = Triangle).
832
+ *
833
+ * @category Input
834
+ */
835
+ export declare const GAMEPAD_BUTTONS: readonly ["A", "B", "X", "Y", "LB", "RB", "LT", "RT", "Select", "Start", "LS", "RS", "DpadUp", "DpadDown", "DpadLeft", "DpadRight", "Home"];
836
+ /**
837
+ * A gamepad button name from {@link GAMEPAD_BUTTONS}.
838
+ *
839
+ * @category Input
840
+ */
841
+ export type GamepadButton = typeof GAMEPAD_BUTTONS[number];
842
+ /**
843
+ * Standard-mapping gamepad stick axes, in axis-index order; Y is positive downwards.
844
+ *
845
+ * @category Input
846
+ */
847
+ export declare const GAMEPAD_AXES: readonly ["leftX", "leftY", "rightX", "rightY"];
848
+ /**
849
+ * A gamepad axis name from {@link GAMEPAD_AXES}.
850
+ *
851
+ * @category Input
852
+ */
853
+ export type GamepadAxis = typeof GAMEPAD_AXES[number];
854
+ /**
855
+ * The touch gestures recognized by {@link GestureRecognizer}.
856
+ *
857
+ * @category Input
858
+ */
859
+ export declare const GESTURES: readonly ["tap", "doubleTap", "longPress", "swipeLeft", "swipeRight", "swipeUp", "swipeDown", "pinchIn", "pinchOut"];
860
+ /**
861
+ * A gesture name from {@link GESTURES}.
862
+ *
863
+ * @category Input
864
+ */
865
+ export type Gesture = typeof GESTURES[number];
866
+ /**
867
+ * Which hand a VR controller is held in.
868
+ *
869
+ * @category Input
870
+ */
871
+ export type XRHand = 'left' | 'right';
872
+ /**
873
+ * WebXR "xr-standard" controller buttons, in button-index order; A/X and B/Y are the
874
+ * primary/secondary face buttons of each hand.
875
+ *
876
+ * @category Input
877
+ */
878
+ export declare const XR_BUTTONS: readonly ["trigger", "squeeze", "touchpad", "thumbstick", "primary", "secondary"];
879
+ /**
880
+ * A VR controller button name from {@link XR_BUTTONS}.
881
+ *
882
+ * @category Input
883
+ */
884
+ export type XRButton = typeof XR_BUTTONS[number];
885
+ /**
886
+ * WebXR "xr-standard" controller axes (touchpad, thumbstick), in axis-index order; Y is positive downwards.
887
+ *
888
+ * @category Input
889
+ */
890
+ export declare const XR_AXES: readonly ["padX", "padY", "thumbX", "thumbY"];
891
+ /**
892
+ * A VR controller axis name from {@link XR_AXES}.
893
+ *
894
+ * @category Input
895
+ */
896
+ export type XRAxis = typeof XR_AXES[number];
897
+ /**
898
+ * A keyboard key, made with {@link key}.
899
+ *
900
+ * @category Input
901
+ */
902
+ export interface KeyBinding {
903
+ /** always 'key' */
904
+ type: 'key';
905
+ /** `KeyboardEvent.code`, e.g. 'KeyW' (layout independent) */
906
+ code: string;
907
+ /** modifiers that must also be held, see {@link KeyModifiers} */
908
+ modifiers?: KeyModifiers;
909
+ }
910
+ /**
911
+ * A mouse (or pen) button, made with {@link mouse}.
912
+ *
913
+ * @category Input
914
+ */
915
+ export interface MouseBinding {
916
+ /** always 'mouse' */
917
+ type: 'mouse';
918
+ /** which button */
919
+ button: MouseButton;
920
+ }
921
+ /**
922
+ * A wheel direction, made with {@link wheel}.
923
+ *
924
+ * @category Input
925
+ */
926
+ export interface WheelBinding {
927
+ /** always 'wheel' */
928
+ type: 'wheel';
929
+ /** which way the wheel moves */
930
+ direction: WheelDirection;
931
+ }
932
+ /**
933
+ * A gamepad button (standard mapping), made with {@link pad}.
934
+ *
935
+ * @category Input
936
+ */
937
+ export interface PadBinding {
938
+ /** always 'pad' */
939
+ type: 'pad';
940
+ /** button name from the standard mapping */
941
+ button: GamepadButton;
942
+ }
943
+ /**
944
+ * One half of a gamepad stick axis, made with {@link padAxis}.
945
+ *
946
+ * @category Input
947
+ */
948
+ export interface PadAxisBinding {
949
+ /** always 'padAxis' */
950
+ type: 'padAxis';
951
+ /** which stick axis */
952
+ axis: GamepadAxis;
953
+ /** 1 = positive half (right / down), -1 = negative half (left / up) */
954
+ direction: 1 | -1;
955
+ }
956
+ /**
957
+ * A touch gesture, made with {@link gesture}.
958
+ *
959
+ * @category Input
960
+ */
961
+ export interface GestureBinding {
962
+ /** always 'gesture' */
963
+ type: 'gesture';
964
+ /** which gesture */
965
+ gesture: Gesture;
966
+ }
967
+ /**
968
+ * A VR controller button, made with {@link xr}.
969
+ *
970
+ * @category Input
971
+ */
972
+ export interface XRBinding {
973
+ /** always 'xr' */
974
+ type: 'xr';
975
+ /** which controller */
976
+ hand: XRHand;
977
+ /** button name from the xr-standard mapping */
978
+ button: XRButton;
979
+ }
980
+ /**
981
+ * One half of a VR controller axis, made with {@link xrAxis}.
982
+ *
983
+ * @category Input
984
+ */
985
+ export interface XRAxisBinding {
986
+ /** always 'xrAxis' */
987
+ type: 'xrAxis';
988
+ /** which controller */
989
+ hand: XRHand;
990
+ /** which touchpad or thumbstick axis */
991
+ axis: XRAxis;
992
+ /** 1 = positive half (right / down), -1 = negative half (left / up) */
993
+ direction: 1 | -1;
994
+ }
995
+ /**
996
+ * One physical input that can trigger an action: a plain, JSON-serializable object, usually made
997
+ * with {@link key}, {@link mouse}, {@link wheel}, {@link pad}, {@link padAxis}, {@link gesture},
998
+ * {@link xr} or {@link xrAxis}. `type` selects the variant.
999
+ *
1000
+ * @category Input
1001
+ */
1002
+ export type Binding = KeyBinding | MouseBinding | WheelBinding | PadBinding | PadAxisBinding | GestureBinding | XRBinding | XRAxisBinding;
1003
+ /**
1004
+ * A physical key, by `KeyboardEvent.code` (layout independent: 'KeyW' is W on QWERTY, Z on AZERTY).
1005
+ *
1006
+ * @category Input
1007
+ */
1008
+ export declare const key: (code: string, modifiers?: KeyModifiers) => KeyBinding;
1009
+ /**
1010
+ * A mouse (or pen) button.
1011
+ *
1012
+ * @category Input
1013
+ */
1014
+ export declare const mouse: (button: MouseButton) => MouseBinding;
1015
+ /**
1016
+ * A wheel direction: pressed for one frame whenever the wheel moves that way.
1017
+ *
1018
+ * @category Input
1019
+ */
1020
+ export declare const wheel: (direction: WheelDirection) => WheelBinding;
1021
+ /**
1022
+ * A gamepad button (standard mapping).
1023
+ *
1024
+ * @category Input
1025
+ */
1026
+ export declare const pad: (button: GamepadButton) => PadBinding;
1027
+ /**
1028
+ * One direction of a gamepad stick axis, e.g. padAxis('leftX', -1) for "left stick left".
1029
+ *
1030
+ * @category Input
1031
+ */
1032
+ export declare const padAxis: (axis: GamepadAxis, direction: 1 | -1) => PadAxisBinding;
1033
+ /**
1034
+ * A touch gesture.
1035
+ *
1036
+ * @category Input
1037
+ */
1038
+ export declare const gesture: (name: Gesture) => GestureBinding;
1039
+ /**
1040
+ * A VR controller button.
1041
+ *
1042
+ * @category Input
1043
+ */
1044
+ export declare const xr: (hand: XRHand, button: XRButton) => XRBinding;
1045
+ /**
1046
+ * One direction of a VR controller axis.
1047
+ *
1048
+ * @category Input
1049
+ */
1050
+ export declare const xrAxis: (hand: XRHand, axis: XRAxis, direction: 1 | -1) => XRAxisBinding;
1051
+ /**
1052
+ * Identifies the physical control behind a binding (modifiers aside), e.g. `'key:KeyW'` or
1053
+ * `'padAxis:leftX:-1'`.
1054
+ *
1055
+ * @category Input
1056
+ */
1057
+ export declare function controlId(binding: Binding): string;
1058
+ /**
1059
+ * Whether two bindings refer to the same control; key bindings must also require the same modifiers
1060
+ * (a missing modifier counts as `false`).
1061
+ *
1062
+ * @category Input
1063
+ */
1064
+ export declare function bindingsEqual(a: Binding, b: Binding): boolean;
1065
+ /**
1066
+ * A readable name for a binding, e.g. for "Press Space to jump" prompts. Pass `keyLabels` (from
1067
+ * {@link Input.loadKeyboardLayout}) to name keys as printed on the player's keyboard.
1068
+ *
1069
+ * @category Input
1070
+ */
1071
+ export declare function bindingLabel(binding: Binding, keyLabels?: ReadonlyMap<string, string>): string;
1072
+ //#endregion
1073
+ //#region src/input/action-map.d.ts
1074
+ /**
1075
+ * Deadzone given to new actions when none is specified.
1076
+ *
1077
+ * @category Input
1078
+ */
1079
+ export declare const DEFAULT_DEADZONE = 0.2;
1080
+ /**
1081
+ * A named action in an {@link ActionMap}.
1082
+ *
1083
+ * @category Input
1084
+ */
1085
+ export interface Action {
1086
+ /** the action's name */
1087
+ readonly name: string;
1088
+ /** raw values at or below this don't count (sticks, triggers) */
1089
+ deadzone: number;
1090
+ /** inputs that trigger the action; the strongest one wins */
1091
+ readonly bindings: Binding[];
1092
+ }
1093
+ /**
1094
+ * The serialized form of an {@link ActionMap} (from {@link ActionMap.toJSON}), keyed by action name.
1095
+ *
1096
+ * @category Input
1097
+ */
1098
+ export type ActionMapJSON = Record<string, {
1099
+ /** see {@link Action.deadzone} */
1100
+ deadzone: number;
1101
+ /** the action's bindings, in order */
1102
+ bindings: Binding[];
1103
+ }>;
1104
+ /**
1105
+ * Named actions and the inputs bound to them, like Godot's InputMap. Every {@link Input} has one as
1106
+ * {@link Input.actions}; the methods that change it return `this` for chaining.
1107
+ *
1108
+ * ```ts
1109
+ * input.actions
1110
+ * .add('jump', [key('Space'), pad('A')])
1111
+ * .bind('jump', gesture('tap'));
1112
+ *
1113
+ * localStorage.setItem('bindings', JSON.stringify(input.actions));
1114
+ * ```
1115
+ *
1116
+ * @category Input
1117
+ */
1118
+ export declare class ActionMap {
1119
+ private readonly _actions;
1120
+ /** action names, in the order they were added */
1121
+ get names(): string[];
1122
+ /** Whether an action with this name exists. */
1123
+ has(name: string): boolean;
1124
+ /** The action with this name, or `undefined`. */
1125
+ get(name: string): Action | undefined;
1126
+ /** Adds an action, or replaces its bindings (and deadzone, if given) if it exists. */
1127
+ add(name: string, bindings?: Binding[], options?: {
1128
+ deadzone?: number;
1129
+ }): this;
1130
+ /** Removes an action, if it exists. */
1131
+ remove(name: string): this;
1132
+ /** Adds a binding to an action (creating the action if needed); duplicates are ignored. */
1133
+ bind(name: string, binding: Binding): this;
1134
+ /** Removes a binding (compared with {@link bindingsEqual}) from an action, if present. */
1135
+ unbind(name: string, binding: Binding): this;
1136
+ /** Actions that already use this binding, e.g. to warn about conflicts when rebinding. */
1137
+ findBinding(binding: Binding): string[];
1138
+ /** Removes all actions. */
1139
+ clear(): this;
1140
+ /** A JSON-serializable copy of all actions, for saving rebinds; see {@link ActionMap.load}. */
1141
+ toJSON(): ActionMapJSON;
1142
+ /** Replaces all actions with the saved ones (e.g. a player's rebinds). */
1143
+ load(json: ActionMapJSON): this;
1144
+ /**
1145
+ * Godot-style `ui_*` actions for menus and dialogs (`ui_accept`, `ui_cancel`, `ui_left`, `ui_right`,
1146
+ * `ui_up`, `ui_down`, `ui_page_up`, `ui_page_down`), with a 0.5 deadzone; replaces existing ones.
1147
+ */
1148
+ addDefaults(): this;
1149
+ }
1150
+ //#endregion
1151
+ //#region src/input/gestures.d.ts
1152
+ /**
1153
+ * A finger currently on the screen, as reported by {@link GestureRecognizer.touches}.
1154
+ *
1155
+ * @property y current position, pixels
1156
+ * @property startY where the finger went down, pixels
1157
+ * @category Input
1158
+ */
1159
+ export interface TouchPoint {
1160
+ /** pointer id, from `PointerEvent.pointerId` */
1161
+ id: number;
1162
+ /** current position, pixels relative to the input target */
1163
+ x: number;
1164
+ y: number;
1165
+ /** where the finger went down, pixels */
1166
+ startX: number;
1167
+ startY: number;
1168
+ /** when the finger went down, ms */
1169
+ startTime: number;
1170
+ }
1171
+ /**
1172
+ * Tuning values for {@link GestureRecognizer}.
1173
+ *
1174
+ * @category Input
1175
+ */
1176
+ export interface GestureThresholds {
1177
+ /** ms, default 250 */
1178
+ tapMaxDuration: number;
1179
+ /** px; also how far a long press may drift. Default 10 */
1180
+ tapMaxMovement: number;
1181
+ /** ms between the two taps, default 300 */
1182
+ doubleTapMaxDelay: number;
1183
+ /** px between the two taps, default 30 */
1184
+ doubleTapMaxDistance: number;
1185
+ /** ms, default 500 */
1186
+ longPressDuration: number;
1187
+ /** px, default 50 */
1188
+ swipeMinDistance: number;
1189
+ /** ms, default 500 */
1190
+ swipeMaxDuration: number;
1191
+ /** relative scale change per frame that counts as pinching (0.005 = 0.5%, the default) */
1192
+ pinchMinChange: number;
1193
+ }
1194
+ /**
1195
+ * What {@link GestureRecognizer.update} recognized since the previous update.
1196
+ *
1197
+ * @category Input
1198
+ */
1199
+ export interface GestureFrame {
1200
+ /** recognized since the last update */
1201
+ gestures: Gesture[];
1202
+ /** two-finger scale change this frame (1 = none, > 1 = fingers apart) */
1203
+ pinch: number;
1204
+ /** two-finger movement this frame, px */
1205
+ pan: {
1206
+ /** px, positive = right */
1207
+ x: number;
1208
+ /** px, positive = down */
1209
+ y: number;
1210
+ };
1211
+ /** two-finger rotation this frame, radians (clockwise on screen) */
1212
+ rotate: number;
1213
+ }
1214
+ /**
1215
+ * Turns touch points into gestures: tap, double tap, long press, swipes (one finger) and
1216
+ * pinch / pan / rotate (two fingers). Feed it with down / move / up, call update() once per frame.
1217
+ * Times are in ms and positions in pixels, from any consistent clock and origin. {@link Input} drives
1218
+ * one for you; use this class directly only for custom touch handling.
1219
+ *
1220
+ * Tap, double tap and swipe are reported when the finger lifts, long press while it is still held;
1221
+ * a finger that was ever down together with another one never produces one-finger gestures.
1222
+ *
1223
+ * ```ts
1224
+ * const recognizer = new GestureRecognizer({ longPressDuration: 400 });
1225
+ * el.addEventListener('pointerdown', e => recognizer.down(e.pointerId, e.offsetX, e.offsetY, performance.now()));
1226
+ * // ... move / up / cancel likewise
1227
+ *
1228
+ * const { gestures, pinch } = recognizer.update(performance.now());
1229
+ * ```
1230
+ *
1231
+ * @category Input
1232
+ */
1233
+ export declare class GestureRecognizer {
1234
+ /** current thresholds; may be changed at any time */
1235
+ readonly thresholds: GestureThresholds;
1236
+ private readonly _touches;
1237
+ private _pending;
1238
+ private _lastTap?;
1239
+ private _pair?;
1240
+ /** Copies of the fingers currently down. */
1241
+ get touches(): TouchPoint[];
1242
+ /** @param thresholds overrides for the default thresholds */
1243
+ constructor(thresholds?: Partial<GestureThresholds>);
1244
+ /** A finger touched down. */
1245
+ down(id: number, x: number, y: number, time: number): void;
1246
+ /** A finger moved; unknown ids are ignored. */
1247
+ move(id: number, x: number, y: number): void;
1248
+ /** A finger lifted; may queue a tap, double tap or swipe for the next update. */
1249
+ up(id: number, x: number, y: number, time: number): void;
1250
+ /** Forgets a finger without recognizing anything (e.g. on `pointercancel`). */
1251
+ cancel(id: number): void;
1252
+ /** Forgets all fingers, gestures not yet reported, and the first tap of a pending double tap (e.g. on blur). */
1253
+ clear(): void;
1254
+ /** Returns what happened since the last update. `time` is the current time in ms. */
1255
+ update(time: number): GestureFrame;
1256
+ }
1257
+ //#endregion
1258
+ //#region src/observable.d.ts
1259
+ /**
1260
+ * An {@link Observable} observer: called with the notified value (and any extra arguments).
1261
+ *
1262
+ * @category Events & Timing
1263
+ */
1264
+ export type Observer<T> = (value: T, ...args: any[]) => void;
1265
+ /**
1266
+ * A set of observers notified with a value (plus optional extra arguments). Observers are
1267
+ * called in subscription order; subscribing the same function twice has no effect.
1268
+ *
1269
+ * ```ts
1270
+ * const onLoaded = new Observable<string>();
1271
+ * const unsubscribe = onLoaded.subscribe(url => console.log('loaded', url));
1272
+ *
1273
+ * onLoaded.notify('a.png');
1274
+ * unsubscribe();
1275
+ * ```
1276
+ *
1277
+ * @category Events & Timing
1278
+ */
1279
+ export declare class Observable<T> {
1280
+ private readonly observers;
1281
+ /** Adds an observer; returns a function that removes it. */
1282
+ subscribe(observer: Observer<T>): () => void;
1283
+ /**
1284
+ * Subscribes for the next notification only; the observer gets the same arguments as with
1285
+ * {@link Observable.subscribe}.
1286
+ *
1287
+ * @returns a function that removes the observer before it fires
1288
+ */
1289
+ once(observer: Observer<T>): () => void;
1290
+ /**
1291
+ * Calls every observer with `value` and `args`. Iterates over a snapshot, so observers may
1292
+ * subscribe or unsubscribe during the call.
1293
+ */
1294
+ notify(value: T, ...args: any[]): void;
1295
+ /** Removes all observers. */
1296
+ clear(): void;
1297
+ /** number of observers */
1298
+ get size(): number;
1299
+ }
1300
+ //#endregion
1301
+ //#region src/input/input.d.ts
1302
+ /**
1303
+ * 0 = keyboard, mouse, pen, touch and VR; 1, 2, ... = gamepads.
1304
+ *
1305
+ * @category Input
1306
+ */
1307
+ export type InputDevice = number;
1308
+ /**
1309
+ * The kind of device the player last used, see {@link Input.lastDevice}.
1310
+ *
1311
+ * @category Input
1312
+ */
1313
+ export type InputDeviceType = 'keyboard' | 'mouse' | 'pen' | 'touch' | 'gamepad' | 'xr';
1314
+ /**
1315
+ * When an {@link Input.onAction} callback fires: as the action becomes pressed, or released.
1316
+ *
1317
+ * @category Input
1318
+ */
1319
+ export type ActionPhase = 'pressed' | 'released';
1320
+ /**
1321
+ * Options for the {@link Input} constructor.
1322
+ *
1323
+ * @category Input
1324
+ */
1325
+ export interface InputOptions {
1326
+ /** where key events are read; default: window */
1327
+ keyboardTarget?: EventTarget;
1328
+ /** add the ui_* actions. Default true. */
1329
+ defaults?: boolean;
1330
+ /** stop bound keys / the wheel from scrolling the page. Default true. */
1331
+ preventDefault?: boolean;
1332
+ /** no right-click menu on the target. Default true. */
1333
+ preventContextMenu?: boolean;
1334
+ }
1335
+ /**
1336
+ * Restricts an action query to one {@link InputDevice}; without it, any device counts.
1337
+ *
1338
+ * @category Input
1339
+ */
1340
+ export interface DeviceQuery {
1341
+ /** only this device; default: any */
1342
+ device?: InputDevice;
1343
+ }
1344
+ /**
1345
+ * A connected gamepad, see {@link Input.gamepads}.
1346
+ *
1347
+ * @category Input
1348
+ */
1349
+ export interface GamepadInfo {
1350
+ /** gamepad.index + 1 */
1351
+ device: InputDevice;
1352
+ /** the browser's description of the controller */
1353
+ id: string;
1354
+ /** uses the standard mapping (button names are reliable); others map by index */
1355
+ standard: boolean;
1356
+ }
1357
+ /**
1358
+ * The parts of a WebXR XRSession that Input reads (structural, so no WebXR typings are required).
1359
+ *
1360
+ * @category Input
1361
+ */
1362
+ export interface XRSessionLike extends EventTarget {
1363
+ /** the session's controllers */
1364
+ readonly inputSources: Iterable<{
1365
+ /** `'left'` or `'right'`; other values are ignored */
1366
+ readonly handedness: string;
1367
+ /** buttons in {@link XR_BUTTONS} order (value 0..1) and axes in {@link XR_AXES} order (-1..1) */
1368
+ readonly gamepad?: {
1369
+ /** in {@link XR_BUTTONS} order */
1370
+ readonly buttons: readonly {
1371
+ /** held down */
1372
+ pressed: boolean;
1373
+ /** 0..1 (analog for triggers and squeeze) */
1374
+ value: number;
1375
+ }[];
1376
+ /** in {@link XR_AXES} order, -1..1 */
1377
+ readonly axes: readonly number[];
1378
+ } | null;
1379
+ }>;
1380
+ }
1381
+ /**
1382
+ * Mouse or pen state, see {@link Input.pointer}. Positions update on pointer events; deltas and
1383
+ * wheel totals on each {@link Input.update}.
1384
+ *
1385
+ * @property y pixels, relative to the target's top-left, y down
1386
+ * @property ndcY -1..1, y up
1387
+ * @property deltaY movement during the last frame, pixels
1388
+ * @property wheelY wheel movement during the last frame, in pixels (positive = down)
1389
+ * @property tiltY pen: degrees
1390
+ *
1391
+ * @category Input
1392
+ */
1393
+ export interface PointerState {
1394
+ /** the kind of pointer that last moved or pressed */
1395
+ type: 'mouse' | 'pen';
1396
+ /** pixels, relative to the target's top-left */
1397
+ x: number;
1398
+ y: number;
1399
+ /** -1..1, y up (for raycasting) */
1400
+ ndcX: number;
1401
+ ndcY: number;
1402
+ /** movement during the last frame, pixels (works under pointer lock) */
1403
+ deltaX: number;
1404
+ deltaY: number;
1405
+ /** wheel movement during the last frame, in pixels */
1406
+ wheelX: number;
1407
+ wheelY: number;
1408
+ /** pen: 0..1 */
1409
+ pressure: number;
1410
+ /** pen: degrees */
1411
+ tiltX: number;
1412
+ tiltY: number;
1413
+ }
1414
+ /**
1415
+ * Options for {@link Input.captureBinding}.
1416
+ *
1417
+ * @category Input
1418
+ */
1419
+ export interface CaptureOptions {
1420
+ /** KeyboardEvent.code that cancels (resolves null); `null` for none. Default 'Escape'. */
1421
+ cancelKey?: string | null;
1422
+ /** only accept these kinds of input; others are ignored and still reach actions */
1423
+ types?: Binding['type'][];
1424
+ }
1425
+ /**
1426
+ * Game input with a Godot-style action map: bind keys, buttons, sticks, gestures and VR controls
1427
+ * to named actions, then query actions instead of devices.
1428
+ *
1429
+ * const input = new Input(canvas);
1430
+ * input.actions.add('jump', [key('Space'), pad('A')]);
1431
+ *
1432
+ * // every frame, before game logic:
1433
+ * input.update();
1434
+ * if (input.isActionJustPressed('jump')) player.jump();
1435
+ *
1436
+ * Call `dispose()` to remove all listeners.
1437
+ *
1438
+ * @category Input
1439
+ */
1440
+ export declare class Input {
1441
+ /** the actions to query; holds the `ui_*` defaults unless {@link InputOptions.defaults} is false */
1442
+ readonly actions: ActionMap;
1443
+ /** Thresholds for taps, swipes etc. can be tuned via `gestureRecognizer.thresholds`. */
1444
+ readonly gestureRecognizer: GestureRecognizer;
1445
+ /** Two-finger gesture values for the last frame (pinch 1 / pan 0 / rotate 0 when not gesturing). */
1446
+ readonly gestures: Omit<GestureFrame, 'gestures'>;
1447
+ /** Fingers currently on the target. */
1448
+ get touches(): TouchPoint[];
1449
+ /** the mouse or pen; not updated by touch */
1450
+ readonly pointer: PointerState;
1451
+ /** notified when {@link Input.lastDevice} changes, e.g. to switch on-screen button prompts */
1452
+ readonly onDeviceChange: Observable<InputDeviceType>;
1453
+ /** notified from update() when a gamepad is first seen */
1454
+ readonly onGamepadConnected: Observable<GamepadInfo>;
1455
+ /** notified from update() when a gamepad goes away; its held controls are released */
1456
+ readonly onGamepadDisconnected: Observable<GamepadInfo>;
1457
+ private readonly _gamepads;
1458
+ /** Connected gamepads, as found by the last update(). */
1459
+ get gamepads(): GamepadInfo[];
1460
+ private _lastDevice;
1461
+ private _keyLabels?;
1462
+ private readonly _target?;
1463
+ private readonly _options;
1464
+ private readonly _listeners;
1465
+ private readonly _controls;
1466
+ private readonly _actionStates;
1467
+ private readonly _actionListeners;
1468
+ private readonly _warned;
1469
+ private readonly _pending;
1470
+ private _capture?;
1471
+ /** The kind of device that produced the most recent input (initially `'keyboard'`). */
1472
+ get lastDevice(): InputDeviceType;
1473
+ /** Whether the pointer is locked to the target, see {@link Input.lockPointer}. */
1474
+ get isPointerLocked(): boolean;
1475
+ /**
1476
+ * @param target element that receives pointer, wheel and touch input (usually the canvas)
1477
+ */
1478
+ constructor(target?: EventTarget, options?: InputOptions);
1479
+ /**
1480
+ * Call once per frame, before reading input: polls devices and advances "just pressed" /
1481
+ * "just released" by one frame. Action callbacks fire from here.
1482
+ */
1483
+ update(): void;
1484
+ /** Whether the action is held past its deadzone. Unknown actions return false (and warn once). */
1485
+ isActionPressed(action: string, query?: DeviceQuery): boolean;
1486
+ /** Whether the action became pressed in the last update(). */
1487
+ isActionJustPressed(action: string, query?: DeviceQuery): boolean;
1488
+ /** Whether the action was released in the last update(). */
1489
+ isActionJustReleased(action: string, query?: DeviceQuery): boolean;
1490
+ /** 0..1, rescaled past the action's deadzone (analog triggers and sticks give values in between). */
1491
+ getActionStrength(action: string, query?: DeviceQuery): number;
1492
+ /** 0..1 before the deadzone is applied. */
1493
+ getActionRawStrength(action: string, query?: DeviceQuery): number;
1494
+ /** -1..1: `positive` minus `negative`. */
1495
+ getAxis(negative: string, positive: string, query?: DeviceQuery): number;
1496
+ /**
1497
+ * A 2D direction from four actions, with a circular deadzone and length at most 1 (diagonals
1498
+ * aren't faster). Y is positive towards `positiveY`, as in Godot's get_vector("left", "right", "up", "down").
1499
+ *
1500
+ * @param options.deadzone default: the average of the four actions' deadzones
1501
+ * @returns `x` and `y` in -1..1; `{ x: 0, y: 0 }` inside the deadzone
1502
+ */
1503
+ getVector(negativeX: string, positiveX: string, negativeY: string, positiveY: string, options?: DeviceQuery & {
1504
+ deadzone?: number;
1505
+ }): {
1506
+ /** -1..1, positive towards `positiveX` */
1507
+ x: number;
1508
+ /** -1..1, positive towards `positiveY` */
1509
+ y: number;
1510
+ };
1511
+ /** Calls `callback` when the action is pressed or released (during update()). Returns an unsubscribe function. */
1512
+ onAction(action: string, phase: ActionPhase, callback: () => void, query?: DeviceQuery): () => void;
1513
+ /** Whether a key (by `KeyboardEvent.code`) is held right now, regardless of actions. */
1514
+ isKeyPressed(code: string): boolean;
1515
+ /** Whether a mouse or pen button is held right now, regardless of actions. */
1516
+ isMouseButtonPressed(button: MouseButton): boolean;
1517
+ /**
1518
+ * Releases every held key and button, on one device or all. Keyboard, mouse and touch (device 0)
1519
+ * are released automatically when the window loses focus, since their release events get lost.
1520
+ */
1521
+ releaseAll(device?: InputDevice): void;
1522
+ /** Requests pointer lock on the target (browsers only allow it from a user gesture, e.g. a click). */
1523
+ lockPointer(): void;
1524
+ /** Exits pointer lock if the target holds it. */
1525
+ unlockPointer(): void;
1526
+ /**
1527
+ * Waits for the player's next input and resolves with a binding for it, for rebinding menus.
1528
+ * Resolves `null` if the cancel key is pressed or another capture starts. The captured press
1529
+ * doesn't trigger any actions.
1530
+ */
1531
+ captureBinding(options?: CaptureOptions): Promise<Binding | null>;
1532
+ /** Ends a pending {@link Input.captureBinding}, resolving it with `null`. */
1533
+ cancelCapture(): void;
1534
+ /**
1535
+ * Loads the keyboard layout (where supported, e.g. Chromium) so {@link bindingLabel} names keys
1536
+ * as printed on the player's keyboard: KeyW is "Z" on AZERTY.
1537
+ */
1538
+ loadKeyboardLayout(): Promise<ReadonlyMap<string, string> | undefined>;
1539
+ /** The layout loaded by {@link Input.loadKeyboardLayout}, if any: `KeyboardEvent.code` to printed key. */
1540
+ get keyLabels(): ReadonlyMap<string, string> | undefined;
1541
+ /** Removes all event listeners and action callbacks, cancels any capture and detaches XR. */
1542
+ dispose(): void;
1543
+ private _listen;
1544
+ private _state;
1545
+ private _advance;
1546
+ private _controlValue;
1547
+ private _bindingValue;
1548
+ private _control;
1549
+ /** Updates a held control (key, button, axis direction: 0..1); `binding` describes it for captureBinding(). */
1550
+ protected _setControl(device: InputDevice, binding: Binding, value: number): void;
1551
+ /** A one-frame press with no held state: wheel steps, gestures. */
1552
+ protected _pulse(device: InputDevice, binding: Binding): void;
1553
+ private _tryCapture;
1554
+ private _setLastDevice;
1555
+ /**
1556
+ * Vibrates a gamepad (where supported). Magnitudes are 0..1; `strong` defaults to 1, `weak` to
1557
+ * `strong`, `duration` to 200 ms.
1558
+ */
1559
+ rumble(device: InputDevice, options?: {
1560
+ strong?: number;
1561
+ weak?: number;
1562
+ duration?: number;
1563
+ }): void;
1564
+ private _pollGamepads;
1565
+ private _updateGestures;
1566
+ private _xrSession?;
1567
+ private _xrEnd?;
1568
+ private readonly _xrHeld;
1569
+ /** The session set by {@link Input.attachXR}, until detached or ended. */
1570
+ get xrSession(): XRSessionLike | undefined;
1571
+ /**
1572
+ * Reads VR controller buttons and sticks from a WebXR session (e.g. `renderer.xr.getSession()`)
1573
+ * into the action map. Controller poses stay with three.js (`renderer.xr.getController(i)`).
1574
+ * XR controller state only updates during XR frames, so call update() from the XR animation
1575
+ * loop (`renderer.setAnimationLoop`). Detaches automatically when the session ends.
1576
+ */
1577
+ attachXR(session: XRSessionLike): void;
1578
+ /** Stops reading the XR session and releases its controls. */
1579
+ detachXR(): void;
1580
+ private _pollXR;
1581
+ private _releaseXR;
1582
+ private _isBound;
1583
+ private _onKeyDown;
1584
+ private _onKeyUp;
1585
+ private _updatePointer;
1586
+ private _local;
1587
+ private _onPointerDown;
1588
+ private _onPointerUp;
1589
+ private _onPointerCancel;
1590
+ private _onPointerMove;
1591
+ private _onWheel;
1592
+ }
1593
+ //#endregion
1594
+ //#region src/log.d.ts
1595
+ /**
1596
+ * `console.debug` with a bold gray `[dev]` prefix; takes the same arguments. Visible only when the
1597
+ * console shows verbose/debug messages.
1598
+ * @category Utilities
1599
+ */
1600
+ export declare const log: (...args: any[]) => void;
1601
+ //#endregion
1602
+ //#region src/math.d.ts
1603
+ /**
1604
+ * π, half a turn in radians.
1605
+ * @category Math & Random
1606
+ */
1607
+ export declare const PI: number;
1608
+ /**
1609
+ * 2π, a full turn in radians.
1610
+ * @category Math & Random
1611
+ */
1612
+ export declare const TAU: number;
1613
+ /**
1614
+ * π / 2, a quarter turn in radians.
1615
+ * @category Math & Random
1616
+ */
1617
+ export declare const HALF_PI: number;
1618
+ /**
1619
+ * π / 4, an eighth of a turn in radians.
1620
+ * @category Math & Random
1621
+ */
1622
+ export declare const QUARTER_PI: number;
1623
+ /**
1624
+ * Euler's number, the base of natural logarithms.
1625
+ * @category Math & Random
1626
+ */
1627
+ export declare const E: number;
1628
+ /**
1629
+ * Multiply degrees by this to get radians.
1630
+ * @category Math & Random
1631
+ */
1632
+ export declare const DEG2RAD: number;
1633
+ /**
1634
+ * Multiply radians by this to get degrees.
1635
+ * @category Math & Random
1636
+ */
1637
+ export declare const RAD2DEG: number;
1638
+ /**
1639
+ * Natural logarithm of 2.
1640
+ * @category Math & Random
1641
+ */
1642
+ export declare const LN2: number;
1643
+ /**
1644
+ * Natural logarithm of 10.
1645
+ * @category Math & Random
1646
+ */
1647
+ export declare const LN10: number;
1648
+ /**
1649
+ * Base-2 logarithm of e.
1650
+ * @category Math & Random
1651
+ */
1652
+ export declare const LOG2E: number;
1653
+ /**
1654
+ * Base-10 logarithm of e.
1655
+ * @category Math & Random
1656
+ */
1657
+ export declare const LOG10E: number;
1658
+ /**
1659
+ * Square root of 2.
1660
+ * @category Math & Random
1661
+ */
1662
+ export declare const SQRT2: number;
1663
+ /**
1664
+ * Square root of 1/2.
1665
+ * @category Math & Random
1666
+ */
1667
+ export declare const SQRT1_2: number;
1668
+ /**
1669
+ * `Number.EPSILON` (about 2.2e-16), the default tolerance of {@link nearlyEqual}.
1670
+ * @category Math & Random
1671
+ */
1672
+ export declare const EPSILON: number;
1673
+ /**
1674
+ * Limits `value` to the inclusive range [`minValue`, `maxValue`].
1675
+ * @category Math & Random
1676
+ */
1677
+ export declare const clamp: (value: number, minValue: number, maxValue: number) => number;
1678
+ /**
1679
+ * Clamps `value` to [0, 1].
1680
+ * @category Math & Random
1681
+ */
1682
+ export declare const saturate: (value: number) => number;
1683
+ /**
1684
+ * Linearly interpolates from `start` (t = 0) to `end` (t = 1). `t` is not clamped, so values
1685
+ * outside [0, 1] extrapolate.
1686
+ * @category Math & Random
1687
+ */
1688
+ export declare const lerp: (start: number, end: number, t: number) => number;
1689
+ /**
1690
+ * The inverse of {@link lerp}: returns the `t` at which `value` lies between `start` and `end`
1691
+ * (0 at `start`, 1 at `end`, unclamped). Returns 0 when `start === end`.
1692
+ * @category Math & Random
1693
+ */
1694
+ export declare const inverseLerp: (start: number, end: number, value: number) => number;
1695
+ /**
1696
+ * Hermite smoothstep, as in GLSL: 0 at or below `edge0`, 1 at or above `edge1`, with a smooth
1697
+ * S-curve (3t² - 2t³) in between. With `edge0 === edge1` it is a step: 0 below the edge, 1 at or above.
1698
+ * @category Math & Random
1699
+ */
1700
+ export declare const smoothstep: (edge0: number, edge1: number, value: number) => number;
1701
+ /**
1702
+ * Fractional part of `value`, always in [0, 1) (e.g. `fract(-0.25)` is 0.75).
1703
+ * @category Math & Random
1704
+ */
1705
+ export declare const fract: (value: number) => number;
1706
+ /**
1707
+ * Modulo whose result takes the sign of `divisor` (so `mod(-1, 4)` is 3), unlike JavaScript's `%`.
1708
+ * @category Math & Random
1709
+ */
1710
+ export declare const mod: (value: number, divisor: number) => number;
1711
+ /**
1712
+ * Wraps `value` into the half-open range [`minValue`, `maxValue`), e.g. `wrap(370, 0, 360)` is 10.
1713
+ * An empty range (`minValue === maxValue`) returns `minValue`.
1714
+ * @category Math & Random
1715
+ */
1716
+ export declare const wrap: (value: number, minValue: number, maxValue: number) => number;
1717
+ /**
1718
+ * Converts degrees to radians.
1719
+ * @category Math & Random
1720
+ */
1721
+ export declare const radians: (degrees: number) => number;
1722
+ /**
1723
+ * Converts radians to degrees.
1724
+ * @category Math & Random
1725
+ */
1726
+ export declare const degrees: (radians: number) => number;
1727
+ /**
1728
+ * Wraps an angle in radians into [-π, π).
1729
+ * @category Math & Random
1730
+ */
1731
+ export declare const normalizeRadians: (radians: number) => number;
1732
+ /**
1733
+ * Euclidean distance between (`x1`, `y1`) and (`x2`, `y2`).
1734
+ * @category Math & Random
1735
+ */
1736
+ export declare const distance2d: (x1: number, y1: number, x2: number, y2: number) => number;
1737
+ /**
1738
+ * Euclidean distance between (`x1`, `y1`, `z1`) and (`x2`, `y2`, `z2`).
1739
+ * @category Math & Random
1740
+ */
1741
+ export declare const distance3d: (x1: number, y1: number, z1: number, x2: number, y2: number, z2: number) => number;
1742
+ /**
1743
+ * Squared 2D Euclidean distance; cheaper than {@link distance2d} when only comparing distances.
1744
+ * @category Math & Random
1745
+ */
1746
+ export declare const squaredDistance: (x1: number, y1: number, x2: number, y2: number) => number;
1747
+ /**
1748
+ * 2D Manhattan (taxicab) distance: `|dx| + |dy|`.
1749
+ * @category Math & Random
1750
+ */
1751
+ export declare const manhattanDistance: (x1: number, y1: number, x2: number, y2: number) => number;
1752
+ /**
1753
+ * True when `a` and `b` differ by at most `epsilon` (default {@link EPSILON}), scaled by the larger
1754
+ * magnitude once that exceeds 1: absolute near zero, relative for large values.
1755
+ * @category Math & Random
1756
+ */
1757
+ export declare const nearlyEqual: (a: number, b: number, epsilon?: number) => boolean;
1758
+ /**
1759
+ * Rounds `value` to `digits` decimal places (default 0); negative `digits` round to tens,
1760
+ * hundreds, etc.
1761
+ * @category Math & Random
1762
+ */
1763
+ export declare const roundTo: (value: number, digits?: number) => number;
1764
+ /**
1765
+ * Deterministic 32-bit integer hash (the MurmurHash3 finalizer). `n` is truncated to a 32-bit
1766
+ * integer first.
1767
+ * @returns an unsigned 32-bit integer in [0, 2³²)
1768
+ * @category Math & Random
1769
+ */
1770
+ export declare const hash32: (n: number) => number;
1771
+ /**
1772
+ * Deterministically hashes any number of values (each truncated to a 32-bit integer) into one
1773
+ * unsigned 32-bit integer by folding them through {@link hash32}. Order matters; no values gives 0.
1774
+ * @category Math & Random
1775
+ */
1776
+ export declare const hash32mix: (...values: number[]) => number;
1777
+ //#endregion
1778
+ //#region src/misc.d.ts
1779
+ /**
1780
+ * True if `target` is `null` or `undefined`.
1781
+ * @category Utilities
1782
+ */
1783
+ export declare function isNullOrUndefined(target: any): boolean;
1784
+ /**
1785
+ * True if `target` is a non-empty string.
1786
+ * @category Utilities
1787
+ */
1788
+ export declare function isPositiveString(target: string): boolean;
1789
+ /**
1790
+ * Maps `value / max` onto an 11-step red -> yellow -> green gradient and returns its `'#rrggbb'`
1791
+ * color; ratios at or below 0 (or a `max` at or below 0) are red, ratios at or above 1 are green.
1792
+ * `max` defaults to 1, so a single argument is rated as a 0-1 fraction.
1793
+ * @category Utilities
1794
+ */
1795
+ export declare const getRedYellowGreenGradientHex: (value: number, max?: number) => string;
1796
+ /**
1797
+ * The current page's query-string parameters as a plain object of strings (the last value wins
1798
+ * for repeated keys). Needs `location`, so browser only.
1799
+ * @category Utilities
1800
+ */
1801
+ export declare function GetUrlParams(): KeyValue;
1802
+ /**
1803
+ * Joins `x` and `y` into a string key such as `'3,4'`, e.g. for use in a `Map` or `Set`.
1804
+ * @category Utilities
1805
+ */
1806
+ export declare const xy2k: (x: number, y: number, delimiter?: string) => string;
1807
+ /**
1808
+ * Splits a key made by {@link xy2k} back into `[x, y]` (parsed with `parseFloat`).
1809
+ * @category Utilities
1810
+ */
1811
+ export declare const k2xy: (key: string, delimiter?: string) => [number, number];
1812
+ /**
1813
+ * Joins `x`, `y` and `z` into a string key such as `'1,2,3'`.
1814
+ * @category Utilities
1815
+ */
1816
+ export declare const xyz2k: (x: number, y: number, z: number, delimiter?: string) => string;
1817
+ /**
1818
+ * Splits a key made by {@link xyz2k} back into `[x, y, z]` (parsed with `parseFloat`).
1819
+ * @category Utilities
1820
+ */
1821
+ export declare const k2xyz: (key: string, delimiter?: string) => [number, number, number];
1822
+ //#endregion
1823
+ //#region src/particle-renderer.d.ts
1824
+ /**
1825
+ * Double-buffered square-pixel renderer for particle effects: draw with `setPixel()` into an
1826
+ * offscreen buffer, then `render()` copies the buffer to the visible canvas and clears it.
1827
+ * Requires `OffscreenCanvas`. Used by {@link ParticleSystem2d}.
1828
+ *
1829
+ * ```ts
1830
+ * const renderer = new ParticleRenderer();
1831
+ * renderer.appendTo(document.body);
1832
+ *
1833
+ * renderer.setPixel(10, 10, Color.RED);
1834
+ * renderer.render();
1835
+ * ```
1836
+ *
1837
+ * @category Canvas 2D
1838
+ */
1839
+ export declare class ParticleRenderer {
1840
+ private _screenCanvas;
1841
+ private _bufferCanvas;
1842
+ /** context of the visible canvas */
1843
+ screenContext: CanvasRenderingContext2D;
1844
+ /** context of the offscreen buffer that `setPixel()` draws into */
1845
+ bufferContext: OffscreenCanvasRenderingContext2D;
1846
+ /** canvas width in pixels */
1847
+ get width(): number;
1848
+ /** canvas height in pixels */
1849
+ get height(): number;
1850
+ /**
1851
+ * @param canvas the visible canvas; defaults to a new canvas element, not attached to the page
1852
+ * @throws an `Error` if a 2D context can't be created
1853
+ */
1854
+ constructor(canvas?: HTMLCanvasElement);
1855
+ /** Moves the canvas into `target` and, with `autoResize` (default true), resizes it to fit. */
1856
+ appendTo(target: HTMLElement, autoResize?: boolean): void;
1857
+ /**
1858
+ * Sets the canvas and buffer size in pixels (truncated to integers). A missing dimension
1859
+ * defaults to the parent element's size (or the canvas's own size on the page). Resizing
1860
+ * clears the buffer. Returns whether the size changed.
1861
+ */
1862
+ resize(displayWidth?: number, displayHeight?: number): boolean;
1863
+ /** Draws a filled `size` x `size` square (pixels, default 2) centered on (`x`, `y`) into the buffer. */
1864
+ setPixel(x: number, y: number, color: Color, size?: number): void;
1865
+ /** Replaces the visible canvas with the buffer's contents, then clears the buffer for the next frame. */
1866
+ render(): void;
1867
+ }
1868
+ //#endregion
1869
+ //#region src/particle-system-2d.d.ts
1870
+ /**
1871
+ * A `size` x `size` attraction matrix with values in [-1, 1). Deterministic: the same `size` and
1872
+ * `seed` always give the same matrix.
1873
+ *
1874
+ * @category Particles
1875
+ */
1876
+ export declare function randomMatrix(size: number, seed?: number): number[][];
1877
+ /**
1878
+ * A "particle life" simulation: 2000 particles of 5 colors attract or repel each other according
1879
+ * to a seeded {@link randomMatrix} and are drawn with a {@link ParticleRenderer}. The world is the
1880
+ * unit square [0, 1) and wraps at the edges (forces act across them too).
1881
+ *
1882
+ * ```ts
1883
+ * const renderer = new ParticleRenderer();
1884
+ * const particles = new ParticleSystem2d(42);
1885
+ * const clock = new Clock();
1886
+ *
1887
+ * renderer.appendTo(document.body);
1888
+ *
1889
+ * clock.start((dt) => {
1890
+ * particles.update(renderer, dt);
1891
+ * renderer.render();
1892
+ * });
1893
+ * ```
1894
+ *
1895
+ * @category Particles
1896
+ */
1897
+ export declare class ParticleSystem2d {
1898
+ /** number of particles (fixed) */
1899
+ readonly particleCount = 2000;
1900
+ /** the seed the starting state was generated from */
1901
+ readonly seed: number;
1902
+ /** seconds; larger `dt` values passed to `update()` are capped to this so a stall can't blow the simulation up */
1903
+ maxDeltaTime: number;
1904
+ private _particleSize;
1905
+ private _frictionHalfLife;
1906
+ private _range;
1907
+ private _forceFactor;
1908
+ private _attractionMatrix;
1909
+ private _particles;
1910
+ private _spatialPartition;
1911
+ /**
1912
+ * The same seed always produces the same starting state (positions, colors, attraction matrix).
1913
+ *
1914
+ * @param seed defaults to a random seed from the shared `rng`, so each instance differs
1915
+ */
1916
+ constructor(seed?: number);
1917
+ private _calcForce;
1918
+ private _updateVelocities;
1919
+ private _updatePositions;
1920
+ /**
1921
+ * Advances the simulation by `dt` seconds and draws every particle into the renderer's buffer
1922
+ * with {@link ParticleRenderer.setPixel}. Does not call {@link ParticleRenderer.render}.
1923
+ * `dt` is capped to {@link ParticleSystem2d.maxDeltaTime}.
1924
+ */
1925
+ update(renderer: ParticleRenderer, dt: number): void;
1926
+ }
1927
+ //#endregion
1928
+ //#region src/random.d.ts
1929
+ /**
1930
+ * Hash-based random numbers. The static methods are pure functions of their arguments (the same
1931
+ * inputs always give the same result), which makes them handy for coordinate-based noise; an
1932
+ * instance is a seeded sequence that hashes its seed and then increments it on every call.
1933
+ *
1934
+ * ```ts
1935
+ * Random.float(x, y); // same value for the same (x, y), in [0, 1)
1936
+ *
1937
+ * const random = new Random(42);
1938
+ * random.float(); // deterministic sequence for seed 42
1939
+ * ```
1940
+ *
1941
+ * See {@link Rng} for ranges, picking, shuffling and other helpers built on top of it.
1942
+ * @category Math & Random
1943
+ */
1944
+ export declare class Random {
1945
+ private _seed;
1946
+ /** @param seed truncated to a 32-bit integer, default `Date.now()` */
1947
+ constructor(seed?: number);
1948
+ /** the next value to be hashed; truncated to a 32-bit integer when set */
1949
+ get seed(): number;
1950
+ /** truncated to a 32-bit integer */
1951
+ set seed(value: number);
1952
+ /** Unsigned 32-bit integer in [0, 2³²) derived from `values` (a {@link hash32mix} hash). */
1953
+ static uint(...values: number[]): number;
1954
+ /** Float in [0, 1) derived from `values`. */
1955
+ static float(...values: number[]): number;
1956
+ /** Boolean derived from `values`. */
1957
+ static bool(...values: number[]): boolean;
1958
+ /** -1 or 1 derived from `values`. */
1959
+ static sign(...values: number[]): -1 | 1;
1960
+ /** Angle in radians in [0, 2π) derived from `values`. */
1961
+ static angle(...values: number[]): number;
1962
+ /** Next unsigned 32-bit integer in [0, 2³²); advances the seed. */
1963
+ uint(): number;
1964
+ /** Next float in [0, 1); advances the seed. */
1965
+ float(): number;
1966
+ /** Next boolean; advances the seed. */
1967
+ bool(): boolean;
1968
+ /** Next -1 or 1; advances the seed. */
1969
+ sign(): -1 | 1;
1970
+ /** Next angle in radians in [0, 2π); advances the seed. */
1971
+ angle(): number;
1972
+ }
1973
+ //#endregion
1974
+ //#region src/rng.d.ts
1975
+ /**
1976
+ * Seeded random number generator with helpers for ranges, picking, shuffling, geometric points,
1977
+ * Gaussian samples and matrices. Every call advances the underlying {@link Random}, so a given
1978
+ * seed always reproduces the same sequence of calls.
1979
+ *
1980
+ * ```ts
1981
+ * const r = new Rng(1234);
1982
+ * r.range(1, 7); // integer in [1, 7), like a die roll
1983
+ * r.pick(['a', 'b', 'c']);
1984
+ * r.shuffle([1, 2, 3, 4]); // new array, input untouched
1985
+ * ```
1986
+ *
1987
+ * A shared, time-seeded instance is exported as {@link rng}.
1988
+ * @category Math & Random
1989
+ */
1990
+ export declare class Rng {
1991
+ /** the underlying generator; shared if one was passed to the constructor */
1992
+ readonly random: Random;
1993
+ /** the underlying {@link Random}'s current seed; setting it restarts the sequence */
1994
+ get seed(): number;
1995
+ /** sets the underlying {@link Random}'s seed */
1996
+ set seed(seed: number);
1997
+ /** @param seed a seed (default `Date.now()`), or an existing {@link Random} to wrap */
1998
+ constructor(seed?: number | Random);
1999
+ /** Float in [0, 1). */
2000
+ nextFloat(): number;
2001
+ /** Unsigned 32-bit integer in [0, 2³²). */
2002
+ nextUint(): number;
2003
+ /**
2004
+ * random integer in [min, max); range(max) is [0, max). Non-integer bounds are rounded up,
2005
+ * so the result is always an integer inside the requested range.
2006
+ */
2007
+ range(min: number, max?: number): number;
2008
+ /** A uniformly chosen element of `array`; `undefined` if the array is empty. */
2009
+ pick<T>(array: readonly [T, ...T[]]): T;
2010
+ pick<T>(array: readonly T[]): T | undefined;
2011
+ /** Up to `count` distinct elements of `array` in random order (all of them if `count` exceeds its length). */
2012
+ sample<T>(array: readonly T[], count: number): T[];
2013
+ /** A shuffled copy of `array` (Fisher-Yates); the input is not modified. */
2014
+ shuffle<T>(array: readonly T[]): T[];
2015
+ /** True with the given probability (0 = never, 1 = always). */
2016
+ chance(probability: number): boolean;
2017
+ /** Random unit-length 2D direction as `[x, y]`. */
2018
+ vector2(): [number, number];
2019
+ /** Uniform point on a circle of `radius` (default 1) centred on the origin, as `[x, y]`. */
2020
+ pointOnCircle(radius?: number): [number, number];
2021
+ /** Uniform point inside a disc of `radius` (default 1) centred on the origin, as `[x, y]`. */
2022
+ pointInCircle(radius?: number): [number, number];
2023
+ /** Uniform point on the surface of a sphere of `radius` (default 1) centred on the origin, as `[x, y, z]`. */
2024
+ pointOnSphere(radius?: number): [number, number, number];
2025
+ /** Uniform point inside a ball of `radius` (default 1) centred on the origin, as `[x, y, z]`. */
2026
+ pointInSphere(radius?: number): [number, number, number];
2027
+ /** Normally distributed sample (Box-Muller), default mean 0 and standard deviation 1. */
2028
+ gaussian(mean?: number, standardDeviation?: number): number;
2029
+ /**
2030
+ * `rows` x `columns` array of uniform floats in [`min`, `max`) (default [0, 1)); `columns`
2031
+ * defaults to `rows`.
2032
+ */
2033
+ matrix(rows: number, columns?: number, min?: number, max?: number): number[][];
2034
+ /** Same as {@link Rng.matrix} with values in [-1, 1). */
2035
+ transformMatrix(rows: number, columns?: number): number[][];
2036
+ /** Random color as `[r, g, b]`, each an integer in [0, 255]. */
2037
+ rgb(): [number, number, number];
2038
+ }
2039
+ /**
2040
+ * Shared {@link Rng} seeded from `Date.now()` at module load; set `rng.seed` for reproducible results.
2041
+ * @category Math & Random
2042
+ */
2043
+ export declare const rng: Rng;
2044
+ //#endregion
2045
+ //#region src/signal.d.ts
2046
+ /**
2047
+ * A {@link Signal} subscriber: called with the new value.
2048
+ *
2049
+ * @category Events & Timing
2050
+ */
2051
+ export type Subscriber<T> = (value: T) => void;
2052
+ /**
2053
+ * A value holder that notifies subscribers when the value changes (compared with `Object.is`).
2054
+ * Subscribers are called immediately with the current value when they subscribe.
2055
+ *
2056
+ * ```ts
2057
+ * const health = new Signal(100);
2058
+ * const unsubscribe = health.subscribe(value => console.log(value)); // logs 100
2059
+ *
2060
+ * health.set(80); // logs 80
2061
+ * health.set(80); // unchanged: nothing logged
2062
+ * unsubscribe();
2063
+ * ```
2064
+ *
2065
+ * @category Events & Timing
2066
+ */
2067
+ export declare class Signal<T> {
2068
+ private value;
2069
+ private readonly subscribers;
2070
+ constructor(initialValue: T);
2071
+ /** Returns the current value. */
2072
+ get(): T;
2073
+ /** Sets the value and notifies subscribers; does nothing if it is the same (`Object.is`). */
2074
+ set(value: T): void;
2075
+ /** Adds a subscriber and calls it right away with the current value; returns a function that removes it. */
2076
+ subscribe(subscriber: Subscriber<T>): () => void;
2077
+ }
2078
+ //#endregion
2079
+ //#region src/spatial-partition-2d.d.ts
2080
+ /**
2081
+ * Anything with a position that a {@link SpatialPartition2d} can bucket.
2082
+ *
2083
+ * @category Maps & Spatial
2084
+ */
2085
+ export interface SpatialPartitionEntity2d {
2086
+ /** in [0, 1) */
2087
+ x: number;
2088
+ /** in [0, 1) */
2089
+ y: number;
2090
+ }
2091
+ /**
2092
+ * Uniform grid over the wrapping unit square [0, 1)², for finding nearby entities without
2093
+ * comparing every pair. The grid has `ceil(1 / cellSize)` cells per axis.
2094
+ *
2095
+ * Entities are bucketed by position when added; the partition doesn't track movement, so move an
2096
+ * entity between cells yourself (see {@link SpatialPartition2d.getCell}) when it changes cell.
2097
+ *
2098
+ * @category Maps & Spatial
2099
+ */
2100
+ export declare class SpatialPartition2d {
2101
+ /** buckets, indexed `cells[cellY][cellX]` */
2102
+ cells: SpatialPartitionEntity2d[][][];
2103
+ /** cell edge length in unit-square units, e.g. 0.1 for a 10 x 10 grid */
2104
+ cellSize: number;
2105
+ /** the array passed to the constructor; `addEntity()` doesn't add to it */
2106
+ entities: SpatialPartitionEntity2d[];
2107
+ /** Builds the grid and adds every entity in `entities`. */
2108
+ constructor(cellSize: number, entities: SpatialPartitionEntity2d[]);
2109
+ /** Puts `entity` in the cell its current position falls in. */
2110
+ addEntity(entity: SpatialPartitionEntity2d): void;
2111
+ /** positions are expected in [0, 1); anything outside wraps around, matching getCellNeighbors */
2112
+ getCell(x: number, y: number): SpatialPartitionEntity2d[];
2113
+ /**
2114
+ * The 3 x 3 block of cells around cell (`x`, `y`), including that cell, wrapping at the edges.
2115
+ * Takes cell indices, not positions. Each cell appears once, so with fewer than 3 cells per
2116
+ * axis the block has fewer than 9 cells.
2117
+ */
2118
+ getCellNeighbors(x: number, y: number): SpatialPartitionEntity2d[][];
2119
+ }
2120
+ //#endregion
2121
+ //#region src/spatial-partition-3d.d.ts
2122
+ /**
2123
+ * Anything with a position that a {@link SpatialPartition3d} can bucket.
2124
+ *
2125
+ * @category Maps & Spatial
2126
+ */
2127
+ export interface SpatialPartitionEntity3d {
2128
+ /** in [0, 1) */
2129
+ x: number;
2130
+ /** in [0, 1) */
2131
+ y: number;
2132
+ /** in [0, 1) */
2133
+ z: number;
2134
+ }
2135
+ /**
2136
+ * Uniform grid over the wrapping unit cube [0, 1)³, for finding nearby entities without comparing
2137
+ * every pair. The grid has `ceil(1 / cellSize)` cells per axis.
2138
+ *
2139
+ * Entities are bucketed by position when added; the partition doesn't track movement, so move an
2140
+ * entity between cells yourself (see {@link SpatialPartition3d.getCell}) when it changes cell.
2141
+ *
2142
+ * @category Maps & Spatial
2143
+ */
2144
+ export declare class SpatialPartition3d {
2145
+ /** buckets, indexed `cells[cellZ][cellY][cellX]` */
2146
+ cells: SpatialPartitionEntity3d[][][][];
2147
+ /** cell edge length in unit-cube units, e.g. 0.2 for a 5 x 5 x 5 grid */
2148
+ cellSize: number;
2149
+ /** the array passed to the constructor; `addEntity()` doesn't add to it */
2150
+ entities: SpatialPartitionEntity3d[];
2151
+ /** Builds the grid and adds every entity in `entities`. */
2152
+ constructor(cellSize: number, entities: SpatialPartitionEntity3d[]);
2153
+ /** positions are expected in [0, 1); anything outside wraps around, matching getCellNeighbors */
2154
+ getCell(x: number, y: number, z: number): SpatialPartitionEntity3d[];
2155
+ /**
2156
+ * The 3 x 3 x 3 block of cells around cell (`cx`, `cy`, `cz`), including that cell, wrapping at
2157
+ * the edges. Takes cell indices, not positions. Each cell appears once, so with fewer than 3
2158
+ * cells per axis the block has fewer than 27 cells.
2159
+ */
2160
+ getCellNeighbors(cx: number, cy: number, cz: number): SpatialPartitionEntity3d[][];
2161
+ /** Puts `entity` in the cell its current position falls in. */
2162
+ addEntity(entity: SpatialPartitionEntity3d): void;
2163
+ }
2164
+ //#endregion
2165
+ //#region src/tilemap.d.ts
2166
+ /**
2167
+ * Sparse 2D grid of arbitrary values, keyed by floored integer coordinates. Simpler than
2168
+ * {@link Map2D} (string keys, any value type, no default value or range limit).
2169
+ *
2170
+ * @category Maps & Spatial
2171
+ */
2172
+ export declare class Tilemap<T = number> {
2173
+ /** backing store, keyed `"<x>x<y>"` (floored) */
2174
+ map: Map<string, T>;
2175
+ private _key;
2176
+ /** Value of the tile containing (x, y), or `undefined` if none was set. */
2177
+ get(x: number, y: number): T | undefined;
2178
+ /** Sets the tile containing (x, y). */
2179
+ set(x: number, y: number, v: T): void;
2180
+ }
2181
+ //#endregion
2182
+ //#region src/webgl.d.ts
2183
+ /**
2184
+ * Literal GLenum values, so importing this module doesn't require `WebGL2RenderingContext` to exist.
2185
+ *
2186
+ * @category WebGL
2187
+ */
2188
+ export declare enum ShaderType {
2189
+ /** gl.VERTEX_SHADER */
2190
+ VERTEX = 35633,
2191
+ /** gl.FRAGMENT_SHADER */
2192
+ FRAGMENT = 35632
2193
+ }
2194
+ /**
2195
+ * Creates a WebGL2 context. Throws (instead of returning null) when WebGL2 isn't available.
2196
+ *
2197
+ * @param canvas defaults to a new canvas element
2198
+ *
2199
+ * @category WebGL
2200
+ */
2201
+ export declare function CreateWebGlContext(canvas?: HTMLCanvasElement | OffscreenCanvas, attributes?: WebGLContextAttributes): WebGL2RenderingContext;
2202
+ /**
2203
+ * Sizes the drawing buffer to `width` x `height` CSS pixels times the pixel ratio (sharp on
2204
+ * high-DPI screens) and sets the viewport. Without a size, uses the canvas's parent (or its own)
2205
+ * size on the page. Returns whether the size changed.
2206
+ *
2207
+ * @category WebGL
2208
+ */
2209
+ export declare function ResizeWebGlContext(gl: WebGL2RenderingContext, width?: number, height?: number, pixelRatio?: number): boolean;
2210
+ /**
2211
+ * Compiles a shader; throws an Error quoting the failing source lines.
2212
+ *
2213
+ * @category WebGL
2214
+ */
2215
+ export declare function CompileShader(gl: WebGL2RenderingContext, type: ShaderType, source: string): WebGLShader;
2216
+ /**
2217
+ * Links a program from shader sources (or compiled shaders). Shaders compiled here are deleted
2218
+ * after linking; ones passed in are left to the caller.
2219
+ *
2220
+ * @category WebGL
2221
+ */
2222
+ export declare function CreateProgram(gl: WebGL2RenderingContext, vertexShader: WebGLShader | string, fragmentShader: WebGLShader | string): WebGLProgram;
2223
+ /**
2224
+ * An active vertex attribute of a linked program, from {@link GetProgramLocations}.
2225
+ *
2226
+ * @category WebGL
2227
+ */
2228
+ export interface AttributeInfo {
2229
+ /** attribute location (the first one, for matrices) */
2230
+ location: number;
2231
+ /** GL type of the attribute (gl.FLOAT_VEC3, gl.FLOAT_MAT4, ...) */
2232
+ type: number;
2233
+ /** array length (1 for non-arrays) */
2234
+ size: number;
2235
+ }
2236
+ /**
2237
+ * An active uniform of a linked program, from {@link GetProgramLocations}.
2238
+ *
2239
+ * @category WebGL
2240
+ */
2241
+ export interface UniformInfo {
2242
+ /** location to pass to `gl.uniform*` */
2243
+ location: WebGLUniformLocation;
2244
+ /** GL type (gl.FLOAT_VEC3, gl.SAMPLER_2D, ...) */
2245
+ type: number;
2246
+ /** array length (1 for non-arrays) */
2247
+ size: number;
2248
+ /** samplers: first texture unit assigned to this uniform */
2249
+ textureUnit?: number;
2250
+ }
2251
+ /**
2252
+ * A program's active attributes and uniforms, by name.
2253
+ *
2254
+ * @category WebGL
2255
+ */
2256
+ export type ProgramLocations = {
2257
+ /** by attribute name; built-ins (`gl_*`) are left out */
2258
+ attributes: Record<string, AttributeInfo>;
2259
+ /** by uniform name (arrays by their base name); uniform block members are left out */
2260
+ uniforms: Record<string, UniformInfo>;
2261
+ };
2262
+ /**
2263
+ * A linked program (`program`) with its attribute and uniform info, from {@link CreateProgramInfo}.
2264
+ *
2265
+ * @category WebGL
2266
+ */
2267
+ export type ProgramInfo = ProgramLocations & {
2268
+ /** the linked program */
2269
+ program: WebGLProgram;
2270
+ };
2271
+ /**
2272
+ * Active attributes and uniforms of a linked program. Array uniforms are listed by their base
2273
+ * name (`uLights[0]` -> `uLights`); samplers are given consecutive texture units.
2274
+ *
2275
+ * @category WebGL
2276
+ */
2277
+ export declare function GetProgramLocations(gl: WebGL2RenderingContext, program: WebGLProgram): ProgramLocations;
2278
+ /**
2279
+ * Links a program and collects its attribute and uniform info.
2280
+ *
2281
+ * @category WebGL
2282
+ */
2283
+ export declare function CreateProgramInfo(gl: WebGL2RenderingContext, vertexShaderSource: string, fragmentShaderSource: string): ProgramInfo;
2284
+ /**
2285
+ * Deletes the program.
2286
+ *
2287
+ * @category WebGL
2288
+ */
2289
+ export declare function DeleteProgramInfo(gl: WebGL2RenderingContext, info: ProgramInfo): void;
2290
+ /**
2291
+ * A value for {@link SetUniforms}: a number or boolean for scalars, a numeric array for vectors,
2292
+ * matrices (column-major) and arrays of them, or a texture (or array of textures) for samplers.
2293
+ *
2294
+ * @category WebGL
2295
+ */
2296
+ export type UniformValue = number | boolean | ArrayLike<number> | WebGLTexture | TextureInfo | (WebGLTexture | TextureInfo)[];
2297
+ /**
2298
+ * Sets uniforms by name; the right `gl.uniform*` call comes from each uniform's declared type.
2299
+ * Textures are bound to the sampler's texture unit. Names the program doesn't use (e.g. optimized
2300
+ * away by the compiler) are ignored. Makes the program current.
2301
+ *
2302
+ * @category WebGL
2303
+ */
2304
+ export declare function SetUniforms(gl: WebGL2RenderingContext, info: ProgramInfo, values: Record<string, UniformValue>): void;
2305
+ /**
2306
+ * Options for {@link CreateBuffer}.
2307
+ *
2308
+ * @category WebGL
2309
+ */
2310
+ export interface BufferOptions {
2311
+ /** default gl.ARRAY_BUFFER (gl.ELEMENT_ARRAY_BUFFER for indices) */
2312
+ target?: number;
2313
+ /** default gl.STATIC_DRAW (gl.DYNAMIC_DRAW for data updated every frame) */
2314
+ usage?: number;
2315
+ }
2316
+ /**
2317
+ * Creates a buffer from data (a plain number array becomes a Float32Array) or with a byte size
2318
+ * to fill later with UpdateBuffer.
2319
+ *
2320
+ * @category WebGL
2321
+ */
2322
+ export declare function CreateBuffer(gl: WebGL2RenderingContext, data: AllowSharedBufferSource | number[] | number, options?: BufferOptions): WebGLBuffer;
2323
+ /**
2324
+ * Writes data into an existing buffer, starting at `byteOffset`.
2325
+ *
2326
+ * @category WebGL
2327
+ */
2328
+ export declare function UpdateBuffer(gl: WebGL2RenderingContext, buffer: WebGLBuffer, data: AllowSharedBufferSource | number[], byteOffset?: number, target?: number): void;
2329
+ /**
2330
+ * Where and how a vertex attribute reads its data, for {@link CreateVertexArray}.
2331
+ *
2332
+ * @category WebGL
2333
+ */
2334
+ export interface AttributeSource {
2335
+ /** the buffer holding the data */
2336
+ buffer: WebGLBuffer;
2337
+ /** components per vertex (per column for matrices) */
2338
+ size: number;
2339
+ /** default gl.FLOAT */
2340
+ type?: number;
2341
+ /** integer data read as 0..1 / -1..1 floats */
2342
+ normalized?: boolean;
2343
+ /** bytes; 0 = tightly packed */
2344
+ stride?: number;
2345
+ /** bytes */
2346
+ offset?: number;
2347
+ /** 1 = advance per instance (instancing); 0 = per vertex */
2348
+ divisor?: number;
2349
+ }
2350
+ /**
2351
+ * A vertex array object and the buffers it reads from, from {@link CreateVertexArray}.
2352
+ *
2353
+ * @category WebGL
2354
+ */
2355
+ export interface VertexArrayInfo {
2356
+ /** the vertex array object */
2357
+ vao: WebGLVertexArrayObject;
2358
+ /** buffers used, for DeleteVertexArray (an index buffer passed in as a buffer is not included) */
2359
+ buffers: WebGLBuffer[];
2360
+ /** the element buffer, when indexed */
2361
+ indexBuffer?: WebGLBuffer;
2362
+ /** gl.UNSIGNED_SHORT etc. when indexed */
2363
+ indexType?: number;
2364
+ /** default draw count: the number of indices (or the given `count`), else the vertices in the shortest per-vertex buffer */
2365
+ count?: number;
2366
+ }
2367
+ /**
2368
+ * Records how the program's attributes read from buffers (and the index buffer) into a vertex
2369
+ * array object. Integer attributes (int / uint / ivec / uvec) use vertexAttribIPointer
2370
+ * automatically; matrix attributes (e.g. per-instance mat4) are spread over their columns.
2371
+ * Attributes the program doesn't use are skipped.
2372
+ *
2373
+ * @param indices an index array (Uint16Array / Uint32Array / Uint8Array), or an existing buffer and its type
2374
+ *
2375
+ * @category WebGL
2376
+ */
2377
+ export declare function CreateVertexArray(gl: WebGL2RenderingContext, info: ProgramInfo, attributes: Record<string, AttributeSource>, indices?: Uint8Array | Uint16Array | Uint32Array | {
2378
+ buffer: WebGLBuffer;
2379
+ type: number;
2380
+ count?: number;
2381
+ }): VertexArrayInfo;
2382
+ /**
2383
+ * Deletes the vertex array; with `buffers`, also the buffers it reads from.
2384
+ *
2385
+ * @category WebGL
2386
+ */
2387
+ export declare function DeleteVertexArray(gl: WebGL2RenderingContext, info: VertexArrayInfo, options?: {
2388
+ buffers?: boolean;
2389
+ }): void;
2390
+ /**
2391
+ * Options for {@link CreateTexture} and {@link LoadWebGlTexture}.
2392
+ *
2393
+ * @category WebGL
2394
+ */
2395
+ export interface TextureOptions {
2396
+ /** default 'linear' */
2397
+ filter?: 'nearest' | 'linear';
2398
+ /** default 'clamp' */
2399
+ wrap?: 'clamp' | 'repeat' | 'mirror';
2400
+ /** default false */
2401
+ mipmaps?: boolean;
2402
+ /** flip images vertically on upload (default false) */
2403
+ flipY?: boolean;
2404
+ /** default false */
2405
+ premultiplyAlpha?: boolean;
2406
+ /** data textures: default gl.RGBA8 */
2407
+ internalFormat?: number;
2408
+ /** data textures: default gl.RGBA */
2409
+ format?: number;
2410
+ /** data textures: default gl.UNSIGNED_BYTE */
2411
+ type?: number;
2412
+ }
2413
+ /**
2414
+ * Raw texture contents (or just a size) for {@link CreateTexture} and {@link UpdateTexture}.
2415
+ *
2416
+ * @category WebGL
2417
+ */
2418
+ export interface TextureData {
2419
+ /** pixels */
2420
+ width: number;
2421
+ /** pixels */
2422
+ height: number;
2423
+ /** null / undefined = allocate only (e.g. render targets) */
2424
+ data?: ArrayBufferView | null;
2425
+ }
2426
+ /**
2427
+ * A 2D texture with its size, from {@link CreateTexture}. Can be passed directly as a sampler uniform.
2428
+ *
2429
+ * @category WebGL
2430
+ */
2431
+ export interface TextureInfo {
2432
+ /** the texture object */
2433
+ texture: WebGLTexture;
2434
+ /** pixels, as of the last upload */
2435
+ width: number;
2436
+ /** pixels, as of the last upload */
2437
+ height: number;
2438
+ /** a copy of the options it was created with, reused by {@link UpdateTexture} */
2439
+ options: TextureOptions;
2440
+ }
2441
+ /**
2442
+ * Creates a 2D texture from an image / canvas / video / bitmap, or from raw data.
2443
+ *
2444
+ * @category WebGL
2445
+ */
2446
+ export declare function CreateTexture(gl: WebGL2RenderingContext, source: TexImageSource | TextureData, options?: TextureOptions): TextureInfo;
2447
+ /**
2448
+ * Re-uploads a texture's contents (the size may change); regenerates mipmaps if it has them.
2449
+ *
2450
+ * @category WebGL
2451
+ */
2452
+ export declare function UpdateTexture(gl: WebGL2RenderingContext, info: TextureInfo, source: TexImageSource | TextureData): void;
2453
+ /**
2454
+ * Loads an image from a URL into a texture.
2455
+ *
2456
+ * @category WebGL
2457
+ */
2458
+ export declare function LoadWebGlTexture(gl: WebGL2RenderingContext, url: string, options?: TextureOptions): Promise<TextureInfo>;
2459
+ /**
2460
+ * Deletes the texture.
2461
+ *
2462
+ * @category WebGL
2463
+ */
2464
+ export declare function DeleteTexture(gl: WebGL2RenderingContext, info: TextureInfo): void;
2465
+ /**
2466
+ * An offscreen framebuffer with a color texture, from {@link CreateRenderTarget}.
2467
+ *
2468
+ * @category WebGL
2469
+ */
2470
+ export interface RenderTarget {
2471
+ /** the framebuffer object */
2472
+ framebuffer: WebGLFramebuffer;
2473
+ /** the color output; use it as a sampler uniform */
2474
+ texture: TextureInfo;
2475
+ /** the DEPTH24_STENCIL8 renderbuffer, unless created with `depth: false` */
2476
+ depth?: WebGLRenderbuffer;
2477
+ /** pixels */
2478
+ width: number;
2479
+ /** pixels */
2480
+ height: number;
2481
+ }
2482
+ /**
2483
+ * Options for {@link CreateRenderTarget}: the color texture's options, plus `depth`.
2484
+ *
2485
+ * @category WebGL
2486
+ */
2487
+ export interface RenderTargetOptions extends Omit<TextureOptions, 'mipmaps' | 'flipY' | 'premultiplyAlpha'> {
2488
+ /** depth (and stencil) attachment. Default true. */
2489
+ depth?: boolean;
2490
+ }
2491
+ /**
2492
+ * An offscreen framebuffer with a color texture (and depth), for render-to-texture and post-processing.
2493
+ *
2494
+ * @category WebGL
2495
+ */
2496
+ export declare function CreateRenderTarget(gl: WebGL2RenderingContext, width: number, height: number, options?: RenderTargetOptions): RenderTarget;
2497
+ /**
2498
+ * Reallocates the target's color texture (and depth buffer) at a new size, discarding their contents. Does nothing if the size is unchanged.
2499
+ *
2500
+ * @category WebGL
2501
+ */
2502
+ export declare function ResizeRenderTarget(gl: WebGL2RenderingContext, target: RenderTarget, width: number, height: number): void;
2503
+ /**
2504
+ * Draws into `target` (or the canvas, with null) and sets the viewport to match.
2505
+ *
2506
+ * @category WebGL
2507
+ */
2508
+ export declare function BindRenderTarget(gl: WebGL2RenderingContext, target: RenderTarget | null): void;
2509
+ /**
2510
+ * Deletes the framebuffer, its color texture and its depth buffer.
2511
+ *
2512
+ * @category WebGL
2513
+ */
2514
+ export declare function DeleteRenderTarget(gl: WebGL2RenderingContext, target: RenderTarget): void;
2515
+ /**
2516
+ * Options for {@link Draw}.
2517
+ *
2518
+ * @category WebGL
2519
+ */
2520
+ export interface DrawOptions {
2521
+ /** default gl.TRIANGLES */
2522
+ mode?: number;
2523
+ /** vertices (or indices); default: the vertex array's count */
2524
+ count?: number;
2525
+ /** first vertex (or index) */
2526
+ offset?: number;
2527
+ /** > 0: instanced draw */
2528
+ instances?: number;
2529
+ /** set with {@link SetUniforms} before drawing */
2530
+ uniforms?: Record<string, UniformValue>;
2531
+ }
2532
+ /**
2533
+ * Draws a vertex array with a program; indexed and instanced draws are picked automatically.
2534
+ *
2535
+ * @category WebGL
2536
+ */
2537
+ export declare function Draw(gl: WebGL2RenderingContext, info: ProgramInfo, vertexArray: VertexArrayInfo, options?: DrawOptions): void;
2538
+ //#endregion
2539
+ //#region src/webgl-renderer.d.ts
2540
+ /**
2541
+ * Options for the {@link WebGlRenderer} constructor.
2542
+ *
2543
+ * @category WebGL
2544
+ */
2545
+ export interface RendererParams {
2546
+ /** default: a new canvas */
2547
+ canvas?: HTMLCanvasElement;
2548
+ /** append the canvas here (and size it to the parent) */
2549
+ parent?: HTMLElement;
2550
+ /** antialias, alpha, preserveDrawingBuffer, ... */
2551
+ attributes?: WebGLContextAttributes;
2552
+ /** default: window.devicePixelRatio */
2553
+ pixelRatio?: number;
2554
+ }
2555
+ /**
2556
+ * A thin owner of a WebGL2 context: sizing (CSS pixels x pixel ratio), clearing, render targets,
2557
+ * drawing, and context-loss notifications. Everything else is the webgl.ts wrappers on `gl`.
2558
+ * There is no render loop and no resource tracking: run your own loop (e.g. with Clock) and
2559
+ * delete what you create.
2560
+ *
2561
+ * ```ts
2562
+ * const renderer = new WebGlRenderer({ parent: document.body });
2563
+ * const program = renderer.createProgram(vertexSource, fragmentSource);
2564
+ * const quad = CreateVertexArray(renderer.gl, program, {
2565
+ * aPosition: { buffer: CreateBuffer(renderer.gl, [-1, -1, 1, -1, -1, 1, 1, 1]), size: 2 },
2566
+ * });
2567
+ *
2568
+ * new Clock().start((dt, time) => {
2569
+ * renderer.clear();
2570
+ * renderer.draw(program, quad, { mode: renderer.gl.TRIANGLE_STRIP, count: 4, uniforms: { uTime: time } });
2571
+ * });
2572
+ * ```
2573
+ *
2574
+ * @category WebGL
2575
+ */
2576
+ export declare class WebGlRenderer {
2577
+ /** the WebGL2 context; use it with the {@link CreateBuffer}, {@link CreateTexture}, ... helpers */
2578
+ readonly gl: WebGL2RenderingContext;
2579
+ /** drawing buffer pixels per CSS pixel; applied on the next `resize()` */
2580
+ pixelRatio: number;
2581
+ /**
2582
+ * The GPU context was lost (driver reset, too many contexts, ...): every program, buffer and
2583
+ * texture is gone. Stop drawing until onContextRestored, then recreate your resources.
2584
+ */
2585
+ readonly onContextLost: Observable<void>;
2586
+ /** The GPU context is back after {@link WebGlRenderer.onContextLost}: recreate programs, buffers and textures. */
2587
+ readonly onContextRestored: Observable<void>;
2588
+ private _width;
2589
+ private _height;
2590
+ private readonly _listeners;
2591
+ /** the canvas the context draws on */
2592
+ get canvas(): HTMLCanvasElement;
2593
+ /** Size in CSS pixels (the drawing buffer is this times `pixelRatio`). */
2594
+ get width(): number;
2595
+ /** Height in CSS pixels. */
2596
+ get height(): number;
2597
+ /** `width / height`, or 1 while the height is 0 */
2598
+ get aspectRatio(): number;
2599
+ /** whether the GPU context is currently lost (`draw()` does nothing meanwhile) */
2600
+ get isContextLost(): boolean;
2601
+ /** Creates the context (throws without WebGL2), enables depth testing, and appends to `params.parent` if given. */
2602
+ constructor(params?: RendererParams);
2603
+ /** Moves the canvas into `element` (or out of the page, without one) and resizes to fit. */
2604
+ appendTo(element?: HTMLElement): void;
2605
+ /**
2606
+ * Sizes the canvas to `width` x `height` CSS pixels (default: its parent's size); the drawing
2607
+ * buffer gets the pixel ratio applied. Returns whether anything changed.
2608
+ */
2609
+ resize(width?: number, height?: number): boolean;
2610
+ /**
2611
+ * Clears the bound target to `color` (RGBA in 0..1, alpha default 1) and, with `depth`
2612
+ * (default true), also the depth and stencil buffers.
2613
+ */
2614
+ clear(color?: ArrayLike<number>, depth?: boolean): void;
2615
+ /** Draws into `target`, or the canvas with null. */
2616
+ setRenderTarget(target: RenderTarget | null): void;
2617
+ /** Compiles and links a program and collects its attributes and uniforms ({@link CreateProgramInfo}). Throws on errors. */
2618
+ createProgram(vertexShaderSource: string, fragmentShaderSource: string): ProgramInfo;
2619
+ /** Draws with {@link Draw}; skipped while the context is lost. */
2620
+ draw(info: ProgramInfo, vertexArray: VertexArrayInfo, options?: DrawOptions): void;
2621
+ /** Removes the renderer's event listeners. GPU resources you created are yours to delete. */
2622
+ dispose(): void;
2623
+ private _listen;
2624
+ }
2625
+ //#endregion
2626
+ //#region src/worker-interface.d.ts
2627
+ /**
2628
+ * Thin wrapper around a module `Worker` that exposes its errors and messages as
2629
+ * {@link Observable}s.
2630
+ *
2631
+ * ```ts
2632
+ * const worker = new WorkerInterface<Result, Job>(new URL('./worker.ts', import.meta.url));
2633
+ * worker.onMessage.subscribe((event) => console.log(event.data));
2634
+ * worker.postMessage(job);
2635
+ * ```
2636
+ *
2637
+ * @typeParam TReceive data the worker posts back (the type of `onMessage` events' `data`)
2638
+ * @typeParam TSend data posted to the worker with `postMessage`
2639
+ * @category Utilities
2640
+ */
2641
+ export declare class WorkerInterface<TReceive = any, TSend = any> {
2642
+ private _worker;
2643
+ /** notified with the worker's `error` events */
2644
+ readonly onError: Observable<ErrorEvent>;
2645
+ /** notified with every message the worker posts back */
2646
+ readonly onMessage: Observable<MessageEvent<TReceive>>;
2647
+ /** Starts a module worker (`{ type: 'module' }`) from `url`. */
2648
+ constructor(url: string | URL);
2649
+ /** Sends `message` to the worker (structured-cloned; `options.transfer` lists objects to transfer). */
2650
+ postMessage(message: TSend, options?: StructuredSerializeOptions | undefined): void;
2651
+ /** Stops the worker immediately. */
2652
+ terminate(): void;
2653
+ }
2654
+ //#endregion
2655
+ export { ColorPalette, DEFAULT_MAP_2D_VALUE, DEFAULT_MAP_3D_VALUE, KeyValue, MAP_2D_MAX_COORD, MAP_2D_MIN_COORD, MAP_3D_MAX_COORD, MAP_3D_MIN_COORD, Map2D, Map2DData, Map3D, Map3DCell, NoiseFunction3D, RGB, XY, XYZ, buildColorPalette };