@n3rdw1z4rd/core 0.18.4 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/README.md +72 -10
  2. package/dist/astar.d.ts +44 -0
  3. package/dist/astar.js +118 -0
  4. package/dist/canvas-renderer.d.ts +154 -0
  5. package/dist/canvas-renderer.js +200 -0
  6. package/dist/clock.d.ts +69 -0
  7. package/dist/clock.js +108 -0
  8. package/dist/color-palette.d.ts +25 -0
  9. package/dist/color-palette.js +112 -0
  10. package/dist/color.d.ts +90 -0
  11. package/dist/color.js +224 -0
  12. package/dist/css/main.css +1 -3
  13. package/dist/disposable.d.ts +27 -0
  14. package/dist/disposable.js +32 -0
  15. package/dist/dungeon-generator.d.ts +142 -0
  16. package/dist/dungeon-generator.js +288 -0
  17. package/dist/ecs.d.ts +87 -0
  18. package/dist/ecs.js +101 -0
  19. package/dist/emitter.d.ts +40 -0
  20. package/dist/emitter.js +54 -0
  21. package/dist/event-queue.d.ts +29 -0
  22. package/dist/event-queue.js +40 -0
  23. package/dist/index.cjs +3813 -0
  24. package/dist/index.d.cts +2655 -0
  25. package/dist/index.d.ts +35 -873
  26. package/dist/index.js +34 -3986
  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 -3982
@@ -0,0 +1,1324 @@
1
+ //#region src/math.ts
2
+ /**
3
+ * π, half a turn in radians.
4
+ * @category Math & Random
5
+ */
6
+ const PI = Math.PI;
7
+ /**
8
+ * 2π, a full turn in radians.
9
+ * @category Math & Random
10
+ */
11
+ const TAU = Math.PI * 2;
12
+ /**
13
+ * π / 2, a quarter turn in radians.
14
+ * @category Math & Random
15
+ */
16
+ const HALF_PI = Math.PI / 2;
17
+ /**
18
+ * π / 4, an eighth of a turn in radians.
19
+ * @category Math & Random
20
+ */
21
+ const QUARTER_PI = Math.PI / 4;
22
+ /**
23
+ * Euler's number, the base of natural logarithms.
24
+ * @category Math & Random
25
+ */
26
+ const E = Math.E;
27
+ /**
28
+ * Multiply degrees by this to get radians.
29
+ * @category Math & Random
30
+ */
31
+ const DEG2RAD = PI / 180;
32
+ /**
33
+ * Multiply radians by this to get degrees.
34
+ * @category Math & Random
35
+ */
36
+ const RAD2DEG = 180 / PI;
37
+ /**
38
+ * Natural logarithm of 2.
39
+ * @category Math & Random
40
+ */
41
+ const LN2 = Math.LN2;
42
+ /**
43
+ * Natural logarithm of 10.
44
+ * @category Math & Random
45
+ */
46
+ const LN10 = Math.LN10;
47
+ /**
48
+ * Base-2 logarithm of e.
49
+ * @category Math & Random
50
+ */
51
+ const LOG2E = Math.LOG2E;
52
+ /**
53
+ * Base-10 logarithm of e.
54
+ * @category Math & Random
55
+ */
56
+ const LOG10E = Math.LOG10E;
57
+ /**
58
+ * Square root of 2.
59
+ * @category Math & Random
60
+ */
61
+ const SQRT2 = Math.SQRT2;
62
+ /**
63
+ * Square root of 1/2.
64
+ * @category Math & Random
65
+ */
66
+ const SQRT1_2 = Math.SQRT1_2;
67
+ /**
68
+ * `Number.EPSILON` (about 2.2e-16), the default tolerance of {@link nearlyEqual}.
69
+ * @category Math & Random
70
+ */
71
+ const EPSILON = Number.EPSILON;
72
+ /**
73
+ * Limits `value` to the inclusive range [`minValue`, `maxValue`].
74
+ * @category Math & Random
75
+ */
76
+ const clamp = (value, minValue, maxValue) => Math.min(Math.max(value, minValue), maxValue);
77
+ /**
78
+ * Clamps `value` to [0, 1].
79
+ * @category Math & Random
80
+ */
81
+ const saturate = (value) => clamp(value, 0, 1);
82
+ /**
83
+ * Linearly interpolates from `start` (t = 0) to `end` (t = 1). `t` is not clamped, so values
84
+ * outside [0, 1] extrapolate.
85
+ * @category Math & Random
86
+ */
87
+ const lerp = (start, end, t) => start + (end - start) * t;
88
+ /**
89
+ * The inverse of {@link lerp}: returns the `t` at which `value` lies between `start` and `end`
90
+ * (0 at `start`, 1 at `end`, unclamped). Returns 0 when `start === end`.
91
+ * @category Math & Random
92
+ */
93
+ const inverseLerp = (start, end, value) => end === start ? 0 : (value - start) / (end - start);
94
+ /**
95
+ * Hermite smoothstep, as in GLSL: 0 at or below `edge0`, 1 at or above `edge1`, with a smooth
96
+ * S-curve (3t² - 2t³) in between. With `edge0 === edge1` it is a step: 0 below the edge, 1 at or above.
97
+ * @category Math & Random
98
+ */
99
+ const smoothstep = (edge0, edge1, value) => {
100
+ if (edge1 === edge0) return value < edge0 ? 0 : 1;
101
+ const t = saturate((value - edge0) / (edge1 - edge0));
102
+ return t * t * (3 - 2 * t);
103
+ };
104
+ /**
105
+ * Fractional part of `value`, always in [0, 1) (e.g. `fract(-0.25)` is 0.75).
106
+ * @category Math & Random
107
+ */
108
+ const fract = (value) => value - Math.floor(value);
109
+ /**
110
+ * Modulo whose result takes the sign of `divisor` (so `mod(-1, 4)` is 3), unlike JavaScript's `%`.
111
+ * @category Math & Random
112
+ */
113
+ const mod = (value, divisor) => (value % divisor + divisor) % divisor;
114
+ /**
115
+ * Wraps `value` into the half-open range [`minValue`, `maxValue`), e.g. `wrap(370, 0, 360)` is 10.
116
+ * An empty range (`minValue === maxValue`) returns `minValue`.
117
+ * @category Math & Random
118
+ */
119
+ const wrap = (value, minValue, maxValue) => {
120
+ const range = maxValue - minValue;
121
+ return range === 0 ? minValue : minValue + mod(value - minValue, range);
122
+ };
123
+ /**
124
+ * Converts degrees to radians.
125
+ * @category Math & Random
126
+ */
127
+ const radians = (degrees) => degrees * DEG2RAD;
128
+ /**
129
+ * Converts radians to degrees.
130
+ * @category Math & Random
131
+ */
132
+ const degrees = (radians) => radians * RAD2DEG;
133
+ /**
134
+ * Wraps an angle in radians into [-π, π).
135
+ * @category Math & Random
136
+ */
137
+ const normalizeRadians = (radians) => wrap(radians, -PI, PI);
138
+ /**
139
+ * Euclidean distance between (`x1`, `y1`) and (`x2`, `y2`).
140
+ * @category Math & Random
141
+ */
142
+ const distance2d = (x1, y1, x2, y2) => Math.hypot(x2 - x1, y2 - y1);
143
+ /**
144
+ * Euclidean distance between (`x1`, `y1`, `z1`) and (`x2`, `y2`, `z2`).
145
+ * @category Math & Random
146
+ */
147
+ const distance3d = (x1, y1, z1, x2, y2, z2) => Math.hypot(x2 - x1, y2 - y1, z2 - z1);
148
+ /**
149
+ * Squared 2D Euclidean distance; cheaper than {@link distance2d} when only comparing distances.
150
+ * @category Math & Random
151
+ */
152
+ const squaredDistance = (x1, y1, x2, y2) => {
153
+ const dx = x2 - x1;
154
+ const dy = y2 - y1;
155
+ return dx * dx + dy * dy;
156
+ };
157
+ /**
158
+ * 2D Manhattan (taxicab) distance: `|dx| + |dy|`.
159
+ * @category Math & Random
160
+ */
161
+ const manhattanDistance = (x1, y1, x2, y2) => Math.abs(x2 - x1) + Math.abs(y2 - y1);
162
+ /**
163
+ * True when `a` and `b` differ by at most `epsilon` (default {@link EPSILON}), scaled by the larger
164
+ * magnitude once that exceeds 1: absolute near zero, relative for large values.
165
+ * @category Math & Random
166
+ */
167
+ const nearlyEqual = (a, b, epsilon = EPSILON) => Math.abs(a - b) <= epsilon * Math.max(1, Math.abs(a), Math.abs(b));
168
+ /**
169
+ * Rounds `value` to `digits` decimal places (default 0); negative `digits` round to tens,
170
+ * hundreds, etc.
171
+ * @category Math & Random
172
+ */
173
+ const roundTo = (value, digits = 0) => {
174
+ const factor = 10 ** digits;
175
+ return Math.round(value * factor) / factor;
176
+ };
177
+ /**
178
+ * Deterministic 32-bit integer hash (the MurmurHash3 finalizer). `n` is truncated to a 32-bit
179
+ * integer first.
180
+ * @returns an unsigned 32-bit integer in [0, 2³²)
181
+ * @category Math & Random
182
+ */
183
+ const hash32 = (n) => {
184
+ n |= 0;
185
+ n ^= n >>> 16;
186
+ n = Math.imul(n, 2246822507);
187
+ n ^= n >>> 13;
188
+ n = Math.imul(n, 3266489909);
189
+ n ^= n >>> 16;
190
+ return n >>> 0;
191
+ };
192
+ /**
193
+ * Deterministically hashes any number of values (each truncated to a 32-bit integer) into one
194
+ * unsigned 32-bit integer by folding them through {@link hash32}. Order matters; no values gives 0.
195
+ * @category Math & Random
196
+ */
197
+ const hash32mix = (...values) => {
198
+ let n = 0;
199
+ for (const value of values) {
200
+ n ^= value | 0;
201
+ n = hash32(n);
202
+ }
203
+ return n;
204
+ };
205
+ //#endregion
206
+ //#region src/log.ts
207
+ /**
208
+ * `console.debug` with a bold gray `[dev]` prefix; takes the same arguments. Visible only when the
209
+ * console shows verbose/debug messages.
210
+ * @category Utilities
211
+ */
212
+ const log = console.debug.bind(console, "%c[dev]", "font-weight: bold; color: #888;");
213
+ //#endregion
214
+ //#region src/color.ts
215
+ /**
216
+ * RGBA color with 8-bit channels (integers 0-255), kept in sync with an 8-digit hex string.
217
+ * Setting a channel rounds and clamps it to 0-255.
218
+ *
219
+ * ```ts
220
+ * new Color(255, 128, 0); // opaque orange
221
+ * new Color('#ff8000'); // same, from a hex string
222
+ * Color.fromHsv(0.5, 1, 1).hexStr; // '#00ffffff'
223
+ * ```
224
+ * @category Color
225
+ */
226
+ var Color = class Color {
227
+ _hex = "#ffffffff";
228
+ _r = 255;
229
+ _g = 255;
230
+ _b = 255;
231
+ _a = 255;
232
+ /** red, 0-255 */
233
+ get r() {
234
+ return this._r;
235
+ }
236
+ /** rounded and clamped to 0-255 */
237
+ set r(value) {
238
+ this._r = Color._channel(value);
239
+ this._hex = this._to_hex();
240
+ }
241
+ /** green, 0-255 */
242
+ get g() {
243
+ return this._g;
244
+ }
245
+ /** rounded and clamped to 0-255 */
246
+ set g(value) {
247
+ this._g = Color._channel(value);
248
+ this._hex = this._to_hex();
249
+ }
250
+ /** blue, 0-255 */
251
+ get b() {
252
+ return this._b;
253
+ }
254
+ /** rounded and clamped to 0-255 */
255
+ set b(value) {
256
+ this._b = Color._channel(value);
257
+ this._hex = this._to_hex();
258
+ }
259
+ /** alpha, 0-255 (255 = opaque) */
260
+ get a() {
261
+ return this._a;
262
+ }
263
+ /** rounded and clamped to 0-255 */
264
+ set a(value) {
265
+ this._a = Color._channel(value);
266
+ this._hex = this._to_hex();
267
+ }
268
+ /**
269
+ * lowercase `'#rrggbbaa'`. Accepts `#rgb`, `#rgba`, `#rrggbb` or `#rrggbbaa` when set (alpha
270
+ * defaults to ff); an invalid string is logged and the color is left unchanged.
271
+ */
272
+ get hexStr() {
273
+ return this._hex;
274
+ }
275
+ /** `#rgb`, `#rgba`, `#rrggbb` or `#rrggbbaa`; invalid strings are logged and ignored */
276
+ set hexStr(value) {
277
+ const rgba = Color._parse_hex_color_string(value);
278
+ if (rgba) {
279
+ [this._r, this._g, this._b, this._a] = rgba;
280
+ this._hex = this._to_hex();
281
+ } else log(`Color: invalid color string: ${value}. Should be a hexadecimal color string (i.e.: '#ffffff' or '#ffffffff'). Keeping the current color.`);
282
+ }
283
+ /** a new `[r, g, b, a]` array, each 0-255 */
284
+ get rgba() {
285
+ return [
286
+ this._r,
287
+ this._g,
288
+ this._b,
289
+ this._a
290
+ ];
291
+ }
292
+ /**
293
+ * Creates a color from a hex string (as accepted by {@link Color.hexStr}) or from channel
294
+ * values, each rounded and clamped to 0-255 like the channel setters. An invalid string is
295
+ * logged and gives opaque white. Defaults to opaque white.
296
+ */
297
+ constructor(r = 255, g = 255, b = 255, a = 255) {
298
+ if (typeof r === "string") {
299
+ const rgba = Color._parse_hex_color_string(r);
300
+ if (rgba) [r, g, b, a] = rgba;
301
+ else {
302
+ log(`Color: invalid color string: ${r}. Should be a hexadecimal color string (i.e.: '#ffffff' or '#ffffffff'). Defaulting to opaque white.`);
303
+ r = g = b = a = 255;
304
+ }
305
+ }
306
+ this.r = r;
307
+ this.g = g;
308
+ this.b = b;
309
+ this.a = a;
310
+ }
311
+ static _channel(value) {
312
+ return clamp(Math.round(value), 0, 255);
313
+ }
314
+ _to_hex() {
315
+ return `#${this.r.toString(16).padStart(2, "0")}${this.g.toString(16).padStart(2, "0")}${this.b.toString(16).padStart(2, "0")}${this.a.toString(16).padStart(2, "0")}`;
316
+ }
317
+ static _parse_hex_color_string(hex) {
318
+ let digits = /^#([a-f\d]{3,4}|[a-f\d]{6}|[a-f\d]{8})$/i.exec(hex)?.[1];
319
+ if (!digits) return void 0;
320
+ if (digits.length <= 4) digits = [...digits].map((d) => d + d).join("");
321
+ return [
322
+ parseInt(digits.slice(0, 2), 16),
323
+ parseInt(digits.slice(2, 4), 16),
324
+ parseInt(digits.slice(4, 6), 16),
325
+ digits.length === 8 ? parseInt(digits.slice(6, 8), 16) : 255
326
+ ];
327
+ }
328
+ /**
329
+ * Creates a color from hue, saturation and value, each in [0, 1]
330
+ * (hues outside [0, 1) wrap around).
331
+ * @param a alpha, 0-255 (default 255)
332
+ */
333
+ static fromHsv(h, s, v, a = 255) {
334
+ let r = 0;
335
+ let g = 0;
336
+ let b = 0;
337
+ h = (h % 1 + 1) % 1;
338
+ let i = Math.floor(h * 6);
339
+ let f = h * 6 - i;
340
+ let p = v * (1 - s);
341
+ let q = v * (1 - f * s);
342
+ let t = v * (1 - (1 - f) * s);
343
+ switch (i % 6) {
344
+ case 0:
345
+ r = v, g = t, b = p;
346
+ break;
347
+ case 1:
348
+ r = q, g = v, b = p;
349
+ break;
350
+ case 2:
351
+ r = p, g = v, b = t;
352
+ break;
353
+ case 3:
354
+ r = p, g = q, b = v;
355
+ break;
356
+ case 4:
357
+ r = t, g = p, b = v;
358
+ break;
359
+ case 5: r = v, g = p, b = q;
360
+ }
361
+ return new Color(Math.round(r * 255), Math.round(g * 255), Math.round(b * 255), a);
362
+ }
363
+ /** new opaque black */
364
+ static get BLACK() {
365
+ return new Color(0, 0, 0, 255);
366
+ }
367
+ /** new opaque gray (128, 128, 128) */
368
+ static get GRAY() {
369
+ return new Color(128, 128, 128, 255);
370
+ }
371
+ /** new opaque white */
372
+ static get WHITE() {
373
+ return new Color(255, 255, 255, 255);
374
+ }
375
+ /** new opaque red (255, 0, 0) */
376
+ static get RED() {
377
+ return new Color(255, 0, 0, 255);
378
+ }
379
+ /** new opaque green (0, 255, 0) */
380
+ static get GREEN() {
381
+ return new Color(0, 255, 0, 255);
382
+ }
383
+ /** new opaque blue (0, 0, 255) */
384
+ static get BLUE() {
385
+ return new Color(0, 0, 255, 255);
386
+ }
387
+ /** new opaque yellow (255, 255, 0) */
388
+ static get YELLOW() {
389
+ return new Color(255, 255, 0, 255);
390
+ }
391
+ /** new opaque orange (255, 128, 0) */
392
+ static get ORANGE() {
393
+ return new Color(255, 128, 0, 255);
394
+ }
395
+ /** new opaque purple (128, 0, 128) */
396
+ static get PURPLE() {
397
+ return new Color(128, 0, 128, 255);
398
+ }
399
+ /** new opaque cyan (0, 255, 255) */
400
+ static get CYAN() {
401
+ return new Color(0, 255, 255, 255);
402
+ }
403
+ /** new opaque magenta (255, 0, 255) */
404
+ static get MAGENTA() {
405
+ return new Color(255, 0, 255, 255);
406
+ }
407
+ /**
408
+ * Creates a color from any CSS color string (e.g. `'rebeccapurple'`, `'rgb(0 0 0 / 50%)'`) by
409
+ * letting the browser compute it. Needs a DOM: it briefly appends an element to
410
+ * `document.body`. An unrecognised name is logged and gives {@link Color.TRANSPARENT}.
411
+ */
412
+ static fromName(name) {
413
+ const element = document.createElement("div");
414
+ element.style.color = name;
415
+ document.body.appendChild(element);
416
+ const computedColor = getComputedStyle(element).color;
417
+ document.body.removeChild(element);
418
+ const rgba = computedColor.match(/[\d.]+/g)?.map(Number);
419
+ if (element.style.color && rgba && (rgba.length === 3 || rgba.length === 4)) {
420
+ const [r, g, b, a = 1] = rgba;
421
+ const color = new Color(r, g, b);
422
+ color.a = a * 255;
423
+ return color;
424
+ } else {
425
+ log(`Color: invalid CSS color name: ${name}. Defaulting to transparent.`);
426
+ return Color.TRANSPARENT;
427
+ }
428
+ }
429
+ /** new fully transparent black (0, 0, 0, 0) */
430
+ static get TRANSPARENT() {
431
+ return new Color(0, 0, 0, 0);
432
+ }
433
+ };
434
+ //#endregion
435
+ //#region src/random.ts
436
+ /**
437
+ * Hash-based random numbers. The static methods are pure functions of their arguments (the same
438
+ * inputs always give the same result), which makes them handy for coordinate-based noise; an
439
+ * instance is a seeded sequence that hashes its seed and then increments it on every call.
440
+ *
441
+ * ```ts
442
+ * Random.float(x, y); // same value for the same (x, y), in [0, 1)
443
+ *
444
+ * const random = new Random(42);
445
+ * random.float(); // deterministic sequence for seed 42
446
+ * ```
447
+ *
448
+ * See {@link Rng} for ranges, picking, shuffling and other helpers built on top of it.
449
+ * @category Math & Random
450
+ */
451
+ var Random = class Random {
452
+ _seed;
453
+ /** @param seed truncated to a 32-bit integer, default `Date.now()` */
454
+ constructor(seed = Date.now()) {
455
+ this._seed = seed | 0;
456
+ }
457
+ /** the next value to be hashed; truncated to a 32-bit integer when set */
458
+ get seed() {
459
+ return this._seed;
460
+ }
461
+ /** truncated to a 32-bit integer */
462
+ set seed(value) {
463
+ this._seed = value | 0;
464
+ }
465
+ /** Unsigned 32-bit integer in [0, 2³²) derived from `values` (a {@link hash32mix} hash). */
466
+ static uint(...values) {
467
+ return hash32mix(...values);
468
+ }
469
+ /** Float in [0, 1) derived from `values`. */
470
+ static float(...values) {
471
+ return hash32mix(...values) / 4294967296;
472
+ }
473
+ /** Boolean derived from `values`. */
474
+ static bool(...values) {
475
+ return (hash32mix(...values) & 1) !== 0;
476
+ }
477
+ /** -1 or 1 derived from `values`. */
478
+ static sign(...values) {
479
+ return this.bool(...values) ? 1 : -1;
480
+ }
481
+ /** Angle in radians in [0, 2π) derived from `values`. */
482
+ static angle(...values) {
483
+ return this.float(...values) * TAU;
484
+ }
485
+ /** Next unsigned 32-bit integer in [0, 2³²); advances the seed. */
486
+ uint() {
487
+ return Random.uint(this._seed++);
488
+ }
489
+ /** Next float in [0, 1); advances the seed. */
490
+ float() {
491
+ return Random.float(this._seed++);
492
+ }
493
+ /** Next boolean; advances the seed. */
494
+ bool() {
495
+ return Random.bool(this._seed++);
496
+ }
497
+ /** Next -1 or 1; advances the seed. */
498
+ sign() {
499
+ return Random.sign(this._seed++);
500
+ }
501
+ /** Next angle in radians in [0, 2π); advances the seed. */
502
+ angle() {
503
+ return Random.angle(this._seed++);
504
+ }
505
+ };
506
+ //#endregion
507
+ //#region src/rng.ts
508
+ /**
509
+ * Seeded random number generator with helpers for ranges, picking, shuffling, geometric points,
510
+ * Gaussian samples and matrices. Every call advances the underlying {@link Random}, so a given
511
+ * seed always reproduces the same sequence of calls.
512
+ *
513
+ * ```ts
514
+ * const r = new Rng(1234);
515
+ * r.range(1, 7); // integer in [1, 7), like a die roll
516
+ * r.pick(['a', 'b', 'c']);
517
+ * r.shuffle([1, 2, 3, 4]); // new array, input untouched
518
+ * ```
519
+ *
520
+ * A shared, time-seeded instance is exported as {@link rng}.
521
+ * @category Math & Random
522
+ */
523
+ var Rng = class {
524
+ /** the underlying generator; shared if one was passed to the constructor */
525
+ random;
526
+ /** the underlying {@link Random}'s current seed; setting it restarts the sequence */
527
+ get seed() {
528
+ return this.random.seed;
529
+ }
530
+ /** sets the underlying {@link Random}'s seed */
531
+ set seed(seed) {
532
+ this.random.seed = seed;
533
+ }
534
+ /** @param seed a seed (default `Date.now()`), or an existing {@link Random} to wrap */
535
+ constructor(seed) {
536
+ this.random = seed instanceof Random ? seed : new Random(seed);
537
+ }
538
+ /** Float in [0, 1). */
539
+ nextFloat() {
540
+ return this.random.float();
541
+ }
542
+ /** Unsigned 32-bit integer in [0, 2³²). */
543
+ nextUint() {
544
+ return this.random.uint();
545
+ }
546
+ /**
547
+ * random integer in [min, max); range(max) is [0, max). Non-integer bounds are rounded up,
548
+ * so the result is always an integer inside the requested range.
549
+ */
550
+ range(min, max) {
551
+ if (typeof max !== "number") {
552
+ max = min;
553
+ min = 0;
554
+ }
555
+ min = Math.ceil(min);
556
+ max = Math.ceil(max);
557
+ return min + Math.floor(this.random.float() * (max - min));
558
+ }
559
+ pick(array) {
560
+ return array[this.range(0, array.length)];
561
+ }
562
+ /** Up to `count` distinct elements of `array` in random order (all of them if `count` exceeds its length). */
563
+ sample(array, count) {
564
+ return this.shuffle(array).slice(0, count);
565
+ }
566
+ /** A shuffled copy of `array` (Fisher-Yates); the input is not modified. */
567
+ shuffle(array) {
568
+ const result = [...array];
569
+ for (let i = result.length - 1; i > 0; --i) {
570
+ const j = this.range(0, i + 1);
571
+ [result[i], result[j]] = [result[j], result[i]];
572
+ }
573
+ return result;
574
+ }
575
+ /** True with the given probability (0 = never, 1 = always). */
576
+ chance(probability) {
577
+ return this.random.float() < probability;
578
+ }
579
+ /** Random unit-length 2D direction as `[x, y]`. */
580
+ vector2() {
581
+ const θ = this.random.angle();
582
+ return [Math.cos(θ), Math.sin(θ)];
583
+ }
584
+ /** Uniform point on a circle of `radius` (default 1) centred on the origin, as `[x, y]`. */
585
+ pointOnCircle(radius = 1) {
586
+ const θ = this.random.angle();
587
+ return [radius * Math.cos(θ), radius * Math.sin(θ)];
588
+ }
589
+ /** Uniform point inside a disc of `radius` (default 1) centred on the origin, as `[x, y]`. */
590
+ pointInCircle(radius = 1) {
591
+ const θ = this.random.angle();
592
+ const r = Math.sqrt(this.random.float()) * radius;
593
+ return [r * Math.cos(θ), r * Math.sin(θ)];
594
+ }
595
+ /** Uniform point on the surface of a sphere of `radius` (default 1) centred on the origin, as `[x, y, z]`. */
596
+ pointOnSphere(radius = 1) {
597
+ const u = this.random.float();
598
+ const v = this.random.float();
599
+ const θ = TAU * u;
600
+ const φ = Math.acos(2 * v - 1);
601
+ const s = Math.sin(φ);
602
+ return [
603
+ radius * s * Math.cos(θ),
604
+ radius * s * Math.sin(θ),
605
+ radius * Math.cos(φ)
606
+ ];
607
+ }
608
+ /** Uniform point inside a ball of `radius` (default 1) centred on the origin, as `[x, y, z]`. */
609
+ pointInSphere(radius = 1) {
610
+ const u = this.random.float();
611
+ const v = this.random.float();
612
+ const θ = TAU * u;
613
+ const φ = Math.acos(2 * v - 1);
614
+ const r = radius * Math.cbrt(this.random.float());
615
+ const s = Math.sin(φ);
616
+ return [
617
+ r * s * Math.cos(θ),
618
+ r * s * Math.sin(θ),
619
+ r * Math.cos(φ)
620
+ ];
621
+ }
622
+ /** Normally distributed sample (Box-Muller), default mean 0 and standard deviation 1. */
623
+ gaussian(mean = 0, standardDeviation = 1) {
624
+ let u = 0;
625
+ let v = 0;
626
+ while (u === 0) u = this.random.float();
627
+ while (v === 0) v = this.random.float();
628
+ return mean + Math.sqrt(-2 * Math.log(u)) * Math.cos(TAU * v) * standardDeviation;
629
+ }
630
+ /**
631
+ * `rows` x `columns` array of uniform floats in [`min`, `max`) (default [0, 1)); `columns`
632
+ * defaults to `rows`.
633
+ */
634
+ matrix(rows, columns = rows, min = 0, max = 1) {
635
+ return Array.from({ length: rows }, () => Array.from({ length: columns }, () => min + this.random.float() * (max - min)));
636
+ }
637
+ /** Same as {@link Rng.matrix} with values in [-1, 1). */
638
+ transformMatrix(rows, columns = rows) {
639
+ return this.matrix(rows, columns, -1, 1);
640
+ }
641
+ /** Random color as `[r, g, b]`, each an integer in [0, 255]. */
642
+ rgb() {
643
+ return [
644
+ this.range(256),
645
+ this.range(256),
646
+ this.range(256)
647
+ ];
648
+ }
649
+ };
650
+ /**
651
+ * Shared {@link Rng} seeded from `Date.now()` at module load; set `rng.seed` for reproducible results.
652
+ * @category Math & Random
653
+ */
654
+ const rng = new Rng();
655
+ //#endregion
656
+ //#region src/map3d.ts
657
+ /**
658
+ * Default "empty" value of a {@link Map3D}: cells holding it are not stored.
659
+ *
660
+ * @category Maps & Spatial
661
+ */
662
+ const DEFAULT_MAP_3D_VALUE = -1;
663
+ const BASE_3D = 131072;
664
+ const OFFSET_3D = 65536;
665
+ /**
666
+ * Lowest supported coordinate on each axis of a {@link Map3D} (inclusive, -65,536); anything
667
+ * outside the range wraps around and collides with other coordinates.
668
+ *
669
+ * @category Maps & Spatial
670
+ */
671
+ const MAP_3D_MIN_COORD = -65536;
672
+ /**
673
+ * Highest supported coordinate on each axis of a {@link Map3D} (inclusive, 65,535).
674
+ *
675
+ * @category Maps & Spatial
676
+ */
677
+ const MAP_3D_MAX_COORD = 65535;
678
+ /**
679
+ * Sparse 3D grid of numbers keyed by integer coordinates, e.g. voxel data. Coordinates are floored,
680
+ * so any point inside a cell addresses that cell. Cells holding `defaultValue` are not stored:
681
+ * setting a cell to it removes the cell, and reading a missing cell returns it.
682
+ *
683
+ * Supports coordinates in [{@link MAP_3D_MIN_COORD}, {@link MAP_3D_MAX_COORD}] per axis; outside
684
+ * that range keys wrap around (a one-time `console.warn` per map reports it).
685
+ *
686
+ * ```ts
687
+ * const voxels = new Map3D(); // empty = -1
688
+ * voxels.setArea(0, 0, 0, 3, 0, 3, 1); // 4x1x4 floor (bounds inclusive)
689
+ * voxels.get(2, 0, 2); // 1
690
+ * const saved = voxels.export(); // [{ x, y, z, n }, ...]
691
+ * ```
692
+ *
693
+ * @category Maps & Spatial
694
+ */
695
+ var Map3D = class Map3D {
696
+ /** value of every cell that hasn't been set; default {@link DEFAULT_MAP_3D_VALUE} */
697
+ defaultValue;
698
+ _data;
699
+ _warnedOutOfRange = false;
700
+ /** the backing map (packed keys), shared, not a copy */
701
+ get data() {
702
+ return this._data;
703
+ }
704
+ /** number of stored (non-default) cells */
705
+ get size() {
706
+ return this._data.size;
707
+ }
708
+ /**
709
+ * @param mapData existing backing data to use as is (not copied), e.g. another map's `data`
710
+ */
711
+ constructor(defaultValue = -1, mapData) {
712
+ this.defaultValue = defaultValue;
713
+ this._data = mapData ?? /* @__PURE__ */ new Map();
714
+ }
715
+ _floor(x, y, z) {
716
+ return [
717
+ Math.floor(x),
718
+ Math.floor(y),
719
+ Math.floor(z)
720
+ ];
721
+ }
722
+ _key(x, y, z) {
723
+ if (!this._warnedOutOfRange && (x < -65536 || x > 65535 || y < -65536 || y > 65535 || z < -65536 || z > 65535)) {
724
+ this._warnedOutOfRange = true;
725
+ console.warn(`Map3D: (${x}, ${y}, ${z}) is outside the supported range [${MAP_3D_MIN_COORD}, ${MAP_3D_MAX_COORD}] per axis; it wraps around and collides with other coordinates. Further warnings for this map are suppressed.`);
726
+ }
727
+ const X = x + OFFSET_3D & 131071;
728
+ const Y = y + OFFSET_3D & 131071;
729
+ const Z = z + OFFSET_3D & 131071;
730
+ return X * BASE_3D * BASE_3D + Y * BASE_3D + Z;
731
+ }
732
+ _pos(key) {
733
+ const Z = key % BASE_3D;
734
+ const Y = Math.floor(key / BASE_3D) % BASE_3D;
735
+ return [
736
+ Math.floor(key / (BASE_3D * BASE_3D)) - OFFSET_3D,
737
+ Y - OFFSET_3D,
738
+ Z - OFFSET_3D
739
+ ];
740
+ }
741
+ /** Removes every stored cell. */
742
+ clear() {
743
+ this._data.clear();
744
+ }
745
+ /**
746
+ * Value of the cell containing (x, y, z) (coordinates are floored).
747
+ *
748
+ * @param defaultValue returned when the cell isn't stored; defaults to the map's `defaultValue`
749
+ */
750
+ get(x, y, z, defaultValue = this.defaultValue) {
751
+ [x, y, z] = this._floor(x, y, z);
752
+ return this._data.get(this._key(x, y, z)) ?? defaultValue;
753
+ }
754
+ /** Sets the cell containing (x, y, z) to `n`; leave out `n` (or pass `defaultValue`) to remove it. */
755
+ set(x, y, z, n = this.defaultValue) {
756
+ [x, y, z] = this._floor(x, y, z);
757
+ const key = this._key(x, y, z);
758
+ if (n === this.defaultValue) this._data.delete(key);
759
+ else this._data.set(key, n);
760
+ }
761
+ /**
762
+ * Sets every cell in the box from (x1, y1, z1) to (x2, y2, z2) to `n`; both corners are
763
+ * inclusive and must be the min / max corner (nothing is set if x2 < x1, etc.).
764
+ */
765
+ setArea(x1, y1, z1, x2, y2, z2, n) {
766
+ for (let z = z1; z <= z2; z++) for (let y = y1; y <= y2; y++) for (let x = x1; x <= x2; x++) this.set(x, y, z, n);
767
+ }
768
+ /** Calls `callback` for every stored cell, in insertion order. Cells holding the default value are not visited. */
769
+ forEach(callback) {
770
+ this._data.forEach((n, key) => {
771
+ const [x, y, z] = this._pos(key);
772
+ callback(x, y, z, n);
773
+ });
774
+ }
775
+ /** Stored cells as a plain array (e.g. for JSON); the inverse of {@link Map3D.import}. */
776
+ export() {
777
+ const data = [];
778
+ this.forEach((x, y, z, n) => {
779
+ data.push({
780
+ x,
781
+ y,
782
+ z,
783
+ n
784
+ });
785
+ });
786
+ return data;
787
+ }
788
+ /** Replaces the map's contents with cells from {@link Map3D.export} (clears it first). */
789
+ import(data) {
790
+ this.clear();
791
+ data.forEach(({ x, y, z, n }) => {
792
+ this.set(x, y, z, n);
793
+ });
794
+ }
795
+ /** Copies every stored cell of a {@link Map2D} into a new map, at z = 0. */
796
+ static fromMap2D(map2d, defaultValue = -1) {
797
+ const map3d = new Map3D(defaultValue);
798
+ map2d.forEach((x, y, n) => map3d.set(x, y, 0, n));
799
+ return map3d;
800
+ }
801
+ };
802
+ //#endregion
803
+ //#region src/spatial-partition-2d.ts
804
+ /**
805
+ * Uniform grid over the wrapping unit square [0, 1)², for finding nearby entities without
806
+ * comparing every pair. The grid has `ceil(1 / cellSize)` cells per axis.
807
+ *
808
+ * Entities are bucketed by position when added; the partition doesn't track movement, so move an
809
+ * entity between cells yourself (see {@link SpatialPartition2d.getCell}) when it changes cell.
810
+ *
811
+ * @category Maps & Spatial
812
+ */
813
+ var SpatialPartition2d = class {
814
+ /** buckets, indexed `cells[cellY][cellX]` */
815
+ cells;
816
+ /** cell edge length in unit-square units, e.g. 0.1 for a 10 x 10 grid */
817
+ cellSize;
818
+ /** the array passed to the constructor; `addEntity()` doesn't add to it */
819
+ entities;
820
+ /** Builds the grid and adds every entity in `entities`. */
821
+ constructor(cellSize, entities) {
822
+ this.cellSize = cellSize;
823
+ this.entities = entities;
824
+ this.cells = Array.from({ length: Math.ceil(1 / cellSize) }, () => Array.from({ length: Math.ceil(1 / cellSize) }, () => []));
825
+ for (const entity of this.entities) this.addEntity(entity);
826
+ }
827
+ /** Puts `entity` in the cell its current position falls in. */
828
+ addEntity(entity) {
829
+ this.getCell(entity.x, entity.y).push(entity);
830
+ }
831
+ /** positions are expected in [0, 1); anything outside wraps around, matching getCellNeighbors */
832
+ getCell(x, y) {
833
+ const cellX = mod(Math.floor(x / this.cellSize), this.cells[0].length);
834
+ const cellY = mod(Math.floor(y / this.cellSize), this.cells.length);
835
+ return this.cells[cellY][cellX];
836
+ }
837
+ /**
838
+ * The 3 x 3 block of cells around cell (`x`, `y`), including that cell, wrapping at the edges.
839
+ * Takes cell indices, not positions. Each cell appears once, so with fewer than 3 cells per
840
+ * axis the block has fewer than 9 cells.
841
+ */
842
+ getCellNeighbors(x, y) {
843
+ const neighbors = /* @__PURE__ */ new Set();
844
+ for (let dy = -1; dy <= 1; dy++) for (let dx = -1; dx <= 1; dx++) {
845
+ const nx = mod(x + dx, this.cells[0].length);
846
+ const ny = mod(y + dy, this.cells.length);
847
+ neighbors.add(this.cells[ny][nx]);
848
+ }
849
+ return [...neighbors];
850
+ }
851
+ };
852
+ //#endregion
853
+ //#region src/particle-system-2d.ts
854
+ /**
855
+ * A `size` x `size` attraction matrix with values in [-1, 1). Deterministic: the same `size` and
856
+ * `seed` always give the same matrix.
857
+ *
858
+ * @category Particles
859
+ */
860
+ function randomMatrix(size, seed = 0) {
861
+ const rows = [];
862
+ for (let i = 0; i < size; i++) {
863
+ const row = [];
864
+ for (let j = 0; j < size; j++) row.push(Random.float(seed, i, j) * 2 - 1);
865
+ rows.push(row);
866
+ }
867
+ return rows;
868
+ }
869
+ const colors = [
870
+ Color.RED,
871
+ Color.GREEN,
872
+ Color.BLUE,
873
+ Color.YELLOW,
874
+ Color.MAGENTA
875
+ ];
876
+ /**
877
+ * A "particle life" simulation: 2000 particles of 5 colors attract or repel each other according
878
+ * to a seeded {@link randomMatrix} and are drawn with a {@link ParticleRenderer}. The world is the
879
+ * unit square [0, 1) and wraps at the edges (forces act across them too).
880
+ *
881
+ * ```ts
882
+ * const renderer = new ParticleRenderer();
883
+ * const particles = new ParticleSystem2d(42);
884
+ * const clock = new Clock();
885
+ *
886
+ * renderer.appendTo(document.body);
887
+ *
888
+ * clock.start((dt) => {
889
+ * particles.update(renderer, dt);
890
+ * renderer.render();
891
+ * });
892
+ * ```
893
+ *
894
+ * @category Particles
895
+ */
896
+ var ParticleSystem2d = class {
897
+ /** number of particles (fixed) */
898
+ particleCount = 2e3;
899
+ /** the seed the starting state was generated from */
900
+ seed;
901
+ /** seconds; larger `dt` values passed to `update()` are capped to this so a stall can't blow the simulation up */
902
+ maxDeltaTime = .1;
903
+ _particleSize = 2;
904
+ _frictionHalfLife = .04;
905
+ _range = .1;
906
+ _forceFactor = 6;
907
+ _attractionMatrix;
908
+ _particles = [];
909
+ _spatialPartition;
910
+ /**
911
+ * The same seed always produces the same starting state (positions, colors, attraction matrix).
912
+ *
913
+ * @param seed defaults to a random seed from the shared `rng`, so each instance differs
914
+ */
915
+ constructor(seed = rng.nextUint()) {
916
+ this.seed = seed;
917
+ this._attractionMatrix = randomMatrix(colors.length, seed);
918
+ for (let i = 0; i < this.particleCount; i++) this._particles.push({
919
+ x: Random.float(seed, i, 0),
920
+ y: Random.float(seed, i, 1),
921
+ vx: 0,
922
+ vy: 0,
923
+ color: Math.floor(Random.float(seed, i, 2) * colors.length)
924
+ });
925
+ this._spatialPartition = new SpatialPartition2d(this._range, this._particles);
926
+ }
927
+ _calcForce(r, a, beta = .3) {
928
+ let f = 0;
929
+ if (r < beta) f = r / beta - 1;
930
+ else if (beta < r && r < 1) f = a * (1 - Math.abs(2 * r - 1 - beta) / (1 - beta));
931
+ return f;
932
+ }
933
+ _updateVelocities(deltaTimeSeconds) {
934
+ const frictionFactor = Math.pow(.5, deltaTimeSeconds / this._frictionHalfLife);
935
+ for (let y = 0; y < this._spatialPartition.cells.length; y++) for (let x = 0; x < this._spatialPartition.cells[y].length; x++) {
936
+ const cell = this._spatialPartition.cells[y][x];
937
+ const neighborCells = this._spatialPartition.getCellNeighbors(x, y);
938
+ for (let i = 0; i < cell.length; i++) {
939
+ let fx = 0;
940
+ let fy = 0;
941
+ const p1 = cell[i];
942
+ for (const neighborCell of neighborCells) for (let j = 0; j < neighborCell.length; j++) {
943
+ if (cell === neighborCell && i === j) continue;
944
+ const p2 = neighborCell[j];
945
+ let rx = p2.x - p1.x;
946
+ if (Math.abs(rx) > .5) rx = rx > 0 ? rx - 1 : rx + 1;
947
+ let ry = p2.y - p1.y;
948
+ if (Math.abs(ry) > .5) ry = ry > 0 ? ry - 1 : ry + 1;
949
+ const d = Math.hypot(rx, ry);
950
+ if (d > 0 && d < this._range) {
951
+ const f = this._calcForce(d / this._range, this._attractionMatrix[p1.color][p2.color]);
952
+ fx += rx / d * f;
953
+ fy += ry / d * f;
954
+ }
955
+ }
956
+ fx *= this._range * this._forceFactor * deltaTimeSeconds;
957
+ fy *= this._range * this._forceFactor * deltaTimeSeconds;
958
+ p1.vx *= frictionFactor;
959
+ p1.vy *= frictionFactor;
960
+ p1.vx += fx;
961
+ p1.vy += fy;
962
+ }
963
+ }
964
+ }
965
+ _updatePositions(deltaTimeSeconds, renderer) {
966
+ for (let i = 0; i < this.particleCount; i++) {
967
+ const particle = this._particles[i];
968
+ const oldCell = this._spatialPartition.getCell(particle.x, particle.y);
969
+ particle.x += particle.vx * deltaTimeSeconds;
970
+ particle.y += particle.vy * deltaTimeSeconds;
971
+ particle.x = fract(particle.x);
972
+ particle.y = fract(particle.y);
973
+ renderer.setPixel(particle.x * renderer.width, particle.y * renderer.height, colors[particle.color], this._particleSize);
974
+ const newCell = this._spatialPartition.getCell(particle.x, particle.y);
975
+ if (newCell !== oldCell) {
976
+ const index = oldCell.indexOf(particle);
977
+ if (index !== -1) oldCell.splice(index, 1);
978
+ newCell.push(particle);
979
+ }
980
+ }
981
+ }
982
+ /**
983
+ * Advances the simulation by `dt` seconds and draws every particle into the renderer's buffer
984
+ * with {@link ParticleRenderer.setPixel}. Does not call {@link ParticleRenderer.render}.
985
+ * `dt` is capped to {@link ParticleSystem2d.maxDeltaTime}.
986
+ */
987
+ update(renderer, dt) {
988
+ dt = Math.min(dt, this.maxDeltaTime);
989
+ this._updateVelocities(dt);
990
+ this._updatePositions(dt, renderer);
991
+ }
992
+ };
993
+ //#endregion
994
+ //#region src/spatial-partition-3d.ts
995
+ /**
996
+ * Uniform grid over the wrapping unit cube [0, 1)³, for finding nearby entities without comparing
997
+ * every pair. The grid has `ceil(1 / cellSize)` cells per axis.
998
+ *
999
+ * Entities are bucketed by position when added; the partition doesn't track movement, so move an
1000
+ * entity between cells yourself (see {@link SpatialPartition3d.getCell}) when it changes cell.
1001
+ *
1002
+ * @category Maps & Spatial
1003
+ */
1004
+ var SpatialPartition3d = class {
1005
+ /** buckets, indexed `cells[cellZ][cellY][cellX]` */
1006
+ cells;
1007
+ /** cell edge length in unit-cube units, e.g. 0.2 for a 5 x 5 x 5 grid */
1008
+ cellSize;
1009
+ /** the array passed to the constructor; `addEntity()` doesn't add to it */
1010
+ entities;
1011
+ /** Builds the grid and adds every entity in `entities`. */
1012
+ constructor(cellSize, entities) {
1013
+ this.cellSize = cellSize;
1014
+ this.entities = entities;
1015
+ const gridSize = Math.ceil(1 / cellSize);
1016
+ this.cells = Array.from({ length: gridSize }, () => Array.from({ length: gridSize }, () => Array.from({ length: gridSize }, () => [])));
1017
+ for (const entity of this.entities) this.addEntity(entity);
1018
+ }
1019
+ /** positions are expected in [0, 1); anything outside wraps around, matching getCellNeighbors */
1020
+ getCell(x, y, z) {
1021
+ const gridSize = this.cells.length;
1022
+ const cx = mod(Math.floor(x / this.cellSize), gridSize);
1023
+ const cy = mod(Math.floor(y / this.cellSize), gridSize);
1024
+ const cz = mod(Math.floor(z / this.cellSize), gridSize);
1025
+ return this.cells[cz][cy][cx];
1026
+ }
1027
+ /**
1028
+ * The 3 x 3 x 3 block of cells around cell (`cx`, `cy`, `cz`), including that cell, wrapping at
1029
+ * the edges. Takes cell indices, not positions. Each cell appears once, so with fewer than 3
1030
+ * cells per axis the block has fewer than 27 cells.
1031
+ */
1032
+ getCellNeighbors(cx, cy, cz) {
1033
+ const neighbors = /* @__PURE__ */ new Set();
1034
+ const gridSize = this.cells.length;
1035
+ for (let dz = -1; dz <= 1; dz++) for (let dy = -1; dy <= 1; dy++) for (let dx = -1; dx <= 1; dx++) {
1036
+ const nx = mod(cx + dx, gridSize);
1037
+ const ny = mod(cy + dy, gridSize);
1038
+ const nz = mod(cz + dz, gridSize);
1039
+ neighbors.add(this.cells[nz][ny][nx]);
1040
+ }
1041
+ return [...neighbors];
1042
+ }
1043
+ /** Puts `entity` in the cell its current position falls in. */
1044
+ addEntity(entity) {
1045
+ this.getCell(entity.x, entity.y, entity.z).push(entity);
1046
+ }
1047
+ };
1048
+ //#endregion
1049
+ Object.defineProperty(exports, "Color", {
1050
+ enumerable: true,
1051
+ get: function() {
1052
+ return Color;
1053
+ }
1054
+ });
1055
+ Object.defineProperty(exports, "DEFAULT_MAP_3D_VALUE", {
1056
+ enumerable: true,
1057
+ get: function() {
1058
+ return DEFAULT_MAP_3D_VALUE;
1059
+ }
1060
+ });
1061
+ Object.defineProperty(exports, "DEG2RAD", {
1062
+ enumerable: true,
1063
+ get: function() {
1064
+ return DEG2RAD;
1065
+ }
1066
+ });
1067
+ Object.defineProperty(exports, "E", {
1068
+ enumerable: true,
1069
+ get: function() {
1070
+ return E;
1071
+ }
1072
+ });
1073
+ Object.defineProperty(exports, "EPSILON", {
1074
+ enumerable: true,
1075
+ get: function() {
1076
+ return EPSILON;
1077
+ }
1078
+ });
1079
+ Object.defineProperty(exports, "HALF_PI", {
1080
+ enumerable: true,
1081
+ get: function() {
1082
+ return HALF_PI;
1083
+ }
1084
+ });
1085
+ Object.defineProperty(exports, "LN10", {
1086
+ enumerable: true,
1087
+ get: function() {
1088
+ return LN10;
1089
+ }
1090
+ });
1091
+ Object.defineProperty(exports, "LN2", {
1092
+ enumerable: true,
1093
+ get: function() {
1094
+ return LN2;
1095
+ }
1096
+ });
1097
+ Object.defineProperty(exports, "LOG10E", {
1098
+ enumerable: true,
1099
+ get: function() {
1100
+ return LOG10E;
1101
+ }
1102
+ });
1103
+ Object.defineProperty(exports, "LOG2E", {
1104
+ enumerable: true,
1105
+ get: function() {
1106
+ return LOG2E;
1107
+ }
1108
+ });
1109
+ Object.defineProperty(exports, "MAP_3D_MAX_COORD", {
1110
+ enumerable: true,
1111
+ get: function() {
1112
+ return MAP_3D_MAX_COORD;
1113
+ }
1114
+ });
1115
+ Object.defineProperty(exports, "MAP_3D_MIN_COORD", {
1116
+ enumerable: true,
1117
+ get: function() {
1118
+ return MAP_3D_MIN_COORD;
1119
+ }
1120
+ });
1121
+ Object.defineProperty(exports, "Map3D", {
1122
+ enumerable: true,
1123
+ get: function() {
1124
+ return Map3D;
1125
+ }
1126
+ });
1127
+ Object.defineProperty(exports, "PI", {
1128
+ enumerable: true,
1129
+ get: function() {
1130
+ return PI;
1131
+ }
1132
+ });
1133
+ Object.defineProperty(exports, "ParticleSystem2d", {
1134
+ enumerable: true,
1135
+ get: function() {
1136
+ return ParticleSystem2d;
1137
+ }
1138
+ });
1139
+ Object.defineProperty(exports, "QUARTER_PI", {
1140
+ enumerable: true,
1141
+ get: function() {
1142
+ return QUARTER_PI;
1143
+ }
1144
+ });
1145
+ Object.defineProperty(exports, "RAD2DEG", {
1146
+ enumerable: true,
1147
+ get: function() {
1148
+ return RAD2DEG;
1149
+ }
1150
+ });
1151
+ Object.defineProperty(exports, "Random", {
1152
+ enumerable: true,
1153
+ get: function() {
1154
+ return Random;
1155
+ }
1156
+ });
1157
+ Object.defineProperty(exports, "Rng", {
1158
+ enumerable: true,
1159
+ get: function() {
1160
+ return Rng;
1161
+ }
1162
+ });
1163
+ Object.defineProperty(exports, "SQRT1_2", {
1164
+ enumerable: true,
1165
+ get: function() {
1166
+ return SQRT1_2;
1167
+ }
1168
+ });
1169
+ Object.defineProperty(exports, "SQRT2", {
1170
+ enumerable: true,
1171
+ get: function() {
1172
+ return SQRT2;
1173
+ }
1174
+ });
1175
+ Object.defineProperty(exports, "SpatialPartition2d", {
1176
+ enumerable: true,
1177
+ get: function() {
1178
+ return SpatialPartition2d;
1179
+ }
1180
+ });
1181
+ Object.defineProperty(exports, "SpatialPartition3d", {
1182
+ enumerable: true,
1183
+ get: function() {
1184
+ return SpatialPartition3d;
1185
+ }
1186
+ });
1187
+ Object.defineProperty(exports, "TAU", {
1188
+ enumerable: true,
1189
+ get: function() {
1190
+ return TAU;
1191
+ }
1192
+ });
1193
+ Object.defineProperty(exports, "clamp", {
1194
+ enumerable: true,
1195
+ get: function() {
1196
+ return clamp;
1197
+ }
1198
+ });
1199
+ Object.defineProperty(exports, "degrees", {
1200
+ enumerable: true,
1201
+ get: function() {
1202
+ return degrees;
1203
+ }
1204
+ });
1205
+ Object.defineProperty(exports, "distance2d", {
1206
+ enumerable: true,
1207
+ get: function() {
1208
+ return distance2d;
1209
+ }
1210
+ });
1211
+ Object.defineProperty(exports, "distance3d", {
1212
+ enumerable: true,
1213
+ get: function() {
1214
+ return distance3d;
1215
+ }
1216
+ });
1217
+ Object.defineProperty(exports, "fract", {
1218
+ enumerable: true,
1219
+ get: function() {
1220
+ return fract;
1221
+ }
1222
+ });
1223
+ Object.defineProperty(exports, "hash32", {
1224
+ enumerable: true,
1225
+ get: function() {
1226
+ return hash32;
1227
+ }
1228
+ });
1229
+ Object.defineProperty(exports, "hash32mix", {
1230
+ enumerable: true,
1231
+ get: function() {
1232
+ return hash32mix;
1233
+ }
1234
+ });
1235
+ Object.defineProperty(exports, "inverseLerp", {
1236
+ enumerable: true,
1237
+ get: function() {
1238
+ return inverseLerp;
1239
+ }
1240
+ });
1241
+ Object.defineProperty(exports, "lerp", {
1242
+ enumerable: true,
1243
+ get: function() {
1244
+ return lerp;
1245
+ }
1246
+ });
1247
+ Object.defineProperty(exports, "log", {
1248
+ enumerable: true,
1249
+ get: function() {
1250
+ return log;
1251
+ }
1252
+ });
1253
+ Object.defineProperty(exports, "manhattanDistance", {
1254
+ enumerable: true,
1255
+ get: function() {
1256
+ return manhattanDistance;
1257
+ }
1258
+ });
1259
+ Object.defineProperty(exports, "mod", {
1260
+ enumerable: true,
1261
+ get: function() {
1262
+ return mod;
1263
+ }
1264
+ });
1265
+ Object.defineProperty(exports, "nearlyEqual", {
1266
+ enumerable: true,
1267
+ get: function() {
1268
+ return nearlyEqual;
1269
+ }
1270
+ });
1271
+ Object.defineProperty(exports, "normalizeRadians", {
1272
+ enumerable: true,
1273
+ get: function() {
1274
+ return normalizeRadians;
1275
+ }
1276
+ });
1277
+ Object.defineProperty(exports, "radians", {
1278
+ enumerable: true,
1279
+ get: function() {
1280
+ return radians;
1281
+ }
1282
+ });
1283
+ Object.defineProperty(exports, "randomMatrix", {
1284
+ enumerable: true,
1285
+ get: function() {
1286
+ return randomMatrix;
1287
+ }
1288
+ });
1289
+ Object.defineProperty(exports, "rng", {
1290
+ enumerable: true,
1291
+ get: function() {
1292
+ return rng;
1293
+ }
1294
+ });
1295
+ Object.defineProperty(exports, "roundTo", {
1296
+ enumerable: true,
1297
+ get: function() {
1298
+ return roundTo;
1299
+ }
1300
+ });
1301
+ Object.defineProperty(exports, "saturate", {
1302
+ enumerable: true,
1303
+ get: function() {
1304
+ return saturate;
1305
+ }
1306
+ });
1307
+ Object.defineProperty(exports, "smoothstep", {
1308
+ enumerable: true,
1309
+ get: function() {
1310
+ return smoothstep;
1311
+ }
1312
+ });
1313
+ Object.defineProperty(exports, "squaredDistance", {
1314
+ enumerable: true,
1315
+ get: function() {
1316
+ return squaredDistance;
1317
+ }
1318
+ });
1319
+ Object.defineProperty(exports, "wrap", {
1320
+ enumerable: true,
1321
+ get: function() {
1322
+ return wrap;
1323
+ }
1324
+ });