@n3rdw1z4rd/core 0.18.5 → 0.19.1

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