@n3rdw1z4rd/core 0.10.0 → 0.13.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.
package/dist/index.js CHANGED
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __export = (target, all) => {
7
9
  for (var name in all)
@@ -15,52 +17,209 @@ var __copyProps = (to, from, except, desc) => {
15
17
  }
16
18
  return to;
17
19
  };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
18
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
29
 
20
30
  // src/index.ts
21
31
  var index_exports = {};
22
32
  __export(index_exports, {
33
+ AStar: () => AStar,
34
+ AddThreeComponent: () => AddThreeComponent,
35
+ AsteroidMesh: () => AsteroidMesh,
36
+ AtlasTextureMaterial: () => AtlasTextureMaterial,
37
+ BuildDefaultPalette: () => BuildDefaultPalette,
23
38
  CanvasRenderer: () => CanvasRenderer,
24
39
  Clock: () => Clock,
25
40
  ClockStats: () => ClockStats,
41
+ Color: () => Color,
42
+ Colors: () => Colors,
26
43
  CompileShader: () => CompileShader,
44
+ CreatePaletteController: () => CreatePaletteController,
27
45
  CreateProgram: () => CreateProgram,
28
46
  CreateProgramInfo: () => CreateProgramInfo,
47
+ CreateStarfield: () => CreateStarfield,
48
+ CreateSubTexture: () => CreateSubTexture,
49
+ CreateSystemStar: () => CreateSystemStar,
50
+ CreateThreeEntity: () => CreateThreeEntity,
29
51
  CreateWebGlContext: () => CreateWebGlContext,
30
52
  CubeSphereGeometry: () => CubeSphereGeometry,
31
53
  ECS: () => ECS,
32
54
  Emitter: () => Emitter,
55
+ EventBus: () => EventBus,
56
+ GenerateDoors: () => GenerateDoors,
57
+ GenerateEntityId: () => GenerateEntityId,
58
+ GenerateRooms: () => GenerateRooms,
59
+ GenerateWalls: () => GenerateWalls,
33
60
  GetProgramLocations: () => GetProgramLocations,
61
+ GetThreeComponent: () => GetThreeComponent,
34
62
  GlobalEmitter: () => GlobalEmitter,
35
63
  Input: () => Input,
64
+ IsThreeEntity: () => IsThreeEntity,
36
65
  LoadTexture: () => LoadTexture,
66
+ Map2D: () => Map2D,
67
+ Map3D: () => Map3D,
37
68
  Noise: () => Noise,
69
+ PI: () => PI,
70
+ ParticleSystem2d: () => ParticleSystem2d,
71
+ ParticleSystem3d: () => ParticleSystem3d,
72
+ PoissonDiskSampler: () => PoissonDiskSampler,
73
+ Rectangle: () => Rectangle,
74
+ RemoveThreeComponent: () => RemoveThreeComponent,
75
+ Renderer: () => Renderer,
38
76
  ResizeWebGlContext: () => ResizeWebGlContext,
39
77
  Rng: () => Rng,
40
78
  ShaderType: () => ShaderType,
41
79
  SimplexNoise: () => SimplexNoise,
80
+ SpatialPartition2d: () => SpatialPartition2d,
81
+ SpatialPartition3d: () => SpatialPartition3d,
82
+ TILE_EMPTY: () => TILE_EMPTY,
83
+ TILE_FLOOR: () => TILE_FLOOR,
84
+ TILE_PATH: () => TILE_PATH,
42
85
  TextureAtlas: () => TextureAtlas,
43
86
  ThreeJsBoilerPlate: () => ThreeJsBoilerPlate,
44
87
  ThreeJsCameraRig: () => ThreeJsCameraRig,
45
88
  ThreeJsPlayerController: () => ThreeJsPlayerController,
46
- VoxelGeometry: () => VoxelGeometry,
89
+ Tilemap: () => Tilemap,
90
+ Vector: () => Vector,
91
+ VoxelFaces: () => VoxelFaces,
92
+ VoxelMesh: () => VoxelMesh,
47
93
  WebGlRenderer: () => WebGlRenderer,
94
+ WorkerInterface: () => WorkerInterface,
95
+ abs: () => abs,
96
+ ceil: () => ceil,
48
97
  clamp: () => clamp,
98
+ cos: () => cos,
49
99
  deg2rad: () => deg2rad,
100
+ distance: () => distance,
101
+ eventBus: () => eventBus,
102
+ floor: () => floor,
50
103
  getRedYellowGreenGradientHex: () => getRedYellowGreenGradientHex,
104
+ hypot2: () => hypot2,
105
+ hypot3: () => hypot3,
106
+ imul: () => imul,
51
107
  isNullOrUndefined: () => isNullOrUndefined,
52
- key2xyz: () => key2xyz,
53
108
  lerp: () => lerp,
54
109
  log: () => log,
55
110
  logdev: () => logdev,
56
111
  logerr: () => logerr,
57
112
  loginf: () => loginf,
58
113
  logwrn: () => logwrn,
114
+ manhattanDistance: () => manhattanDistance,
115
+ max: () => max,
116
+ min: () => min,
117
+ pow: () => pow,
59
118
  rng: () => rng,
60
- xyz2key: () => xyz2key
119
+ round: () => round,
120
+ roundTo: () => roundTo,
121
+ sin: () => sin,
122
+ sqrt: () => sqrt,
123
+ squaredDistance: () => squaredDistance
61
124
  });
62
125
  module.exports = __toCommonJS(index_exports);
63
126
 
127
+ // src/astar.ts
128
+ var DIRECTIONS_4_WAY = [
129
+ { x: 0, y: -1 },
130
+ { x: 1, y: 0 },
131
+ { x: 0, y: 1 },
132
+ { x: -1, y: 0 }
133
+ ];
134
+ var AStar = class {
135
+ map;
136
+ constructor(map) {
137
+ this.map = map;
138
+ }
139
+ _manhattan(a, b) {
140
+ return Math.abs(a.x - b.x) + Math.abs(a.y - b.y);
141
+ }
142
+ _isWalkable(point, walkable = [0]) {
143
+ const value = this.map.get(point.x, point.y);
144
+ return walkable.includes(value);
145
+ }
146
+ _key(x, y) {
147
+ return `${x},${y}`;
148
+ }
149
+ // NOTE: ported as-is from rogue-craft. useAdjacent is currently hard-coded
150
+ // to true below - the original had a known unresolved bug where setting it
151
+ // to false via params caused an infinite loop, so that path is disabled
152
+ // rather than exposed broken.
153
+ findPath(a, b, params = {}) {
154
+ const useAdjacent = true;
155
+ const walkable = params.walkableValues ?? [0];
156
+ const openSet = [];
157
+ const closedSet = /* @__PURE__ */ new Set();
158
+ const nodeMap = /* @__PURE__ */ new Map();
159
+ const startNode = {
160
+ pos: a,
161
+ g: 0,
162
+ h: this._manhattan(a, b),
163
+ f: this._manhattan(a, b)
164
+ };
165
+ openSet.push(startNode);
166
+ nodeMap.set(this._key(a.x, a.y), startNode);
167
+ const targetKeys = /* @__PURE__ */ new Set();
168
+ targetKeys.add(this._key(b.x, b.y));
169
+ if (useAdjacent) {
170
+ for (const dir of DIRECTIONS_4_WAY) {
171
+ const nx = b.x + dir.x;
172
+ const ny = b.y + dir.y;
173
+ targetKeys.add(this._key(nx, ny));
174
+ }
175
+ }
176
+ while (openSet.length > 0) {
177
+ openSet.sort((a2, b2) => a2.f - b2.f);
178
+ const current = openSet.shift();
179
+ const currentKey = this._key(current.pos.x, current.pos.y);
180
+ if (targetKeys.has(currentKey)) {
181
+ const path = [];
182
+ let curr = current;
183
+ while (curr) {
184
+ path.push(curr.pos);
185
+ curr = curr.parent;
186
+ }
187
+ path.pop();
188
+ return path.reverse();
189
+ }
190
+ closedSet.add(currentKey);
191
+ for (const dir of DIRECTIONS_4_WAY) {
192
+ const neighborPos = {
193
+ x: current.pos.x + dir.x,
194
+ y: current.pos.y + dir.y
195
+ };
196
+ const key = this._key(neighborPos.x, neighborPos.y);
197
+ if (!this._isWalkable(neighborPos, walkable) || closedSet.has(key)) {
198
+ continue;
199
+ }
200
+ const g = current.g + 1;
201
+ let neighbor = nodeMap.get(key);
202
+ if (!neighbor) {
203
+ neighbor = {
204
+ pos: neighborPos,
205
+ g,
206
+ h: this._manhattan(neighborPos, b),
207
+ f: g + this._manhattan(neighborPos, b),
208
+ parent: current
209
+ };
210
+ nodeMap.set(key, neighbor);
211
+ openSet.push(neighbor);
212
+ } else if (g < neighbor.g) {
213
+ neighbor.g = g;
214
+ neighbor.f = g + neighbor.h;
215
+ neighbor.parent = current;
216
+ }
217
+ }
218
+ }
219
+ return [];
220
+ }
221
+ };
222
+
64
223
  // src/clock-stats.ts
65
224
  var ClockStats = class {
66
225
  divElement;
@@ -194,6 +353,767 @@ var loginf = console.log.bind(console, "%c[inf]", "font-weight: bold;");
194
353
  var logwrn = console.log.bind(console, "%c[wrn]", "font-weight: bold; color: orange;");
195
354
  var logerr = console.log.bind(console, "%c[err]", "font-weight: bold; color: red;");
196
355
 
356
+ // src/math.ts
357
+ var DEG2RAD = 0.01745329;
358
+ var PI = 3.141592653589793;
359
+ var TWO_PI = PI * 2;
360
+ var HALF_PI = PI / 2;
361
+ function abs(n) {
362
+ return n < 0 ? -n : n;
363
+ }
364
+ function min(a, b) {
365
+ return a < b ? a : b;
366
+ }
367
+ function max(a, b) {
368
+ return a > b ? a : b;
369
+ }
370
+ function floor(n) {
371
+ const t = n | 0;
372
+ return n < 0 && t !== n ? t - 1 : t;
373
+ }
374
+ function ceil(n) {
375
+ const t = n | 0;
376
+ return n > 0 && t !== n ? t + 1 : t;
377
+ }
378
+ function round(n) {
379
+ return floor(n + 0.5);
380
+ }
381
+ function sqrt(n) {
382
+ return n ** 0.5;
383
+ }
384
+ function pow(base, exp) {
385
+ return base ** exp;
386
+ }
387
+ function hypot2(x, y) {
388
+ return (x * x + y * y) ** 0.5;
389
+ }
390
+ function hypot3(x, y, z) {
391
+ return (x * x + y * y + z * z) ** 0.5;
392
+ }
393
+ function imul(a, b) {
394
+ b |= 0;
395
+ let result = (a & 4194303) * b;
396
+ if (a & 4290772992) result += (a & 4290772992) * b | 0;
397
+ return result | 0;
398
+ }
399
+ function wrapAngle(n) {
400
+ n = n % TWO_PI;
401
+ if (n > PI) n -= TWO_PI;
402
+ else if (n < -PI) n += TWO_PI;
403
+ return n;
404
+ }
405
+ function sinSeries(n) {
406
+ const n2 = n * n;
407
+ return n * (1 + n2 * (-1 / 6 + n2 * (1 / 120 + n2 * (-1 / 5040 + n2 * (1 / 362880 + n2 * (-1 / 39916800))))));
408
+ }
409
+ function cosSeries(n) {
410
+ const n2 = n * n;
411
+ return 1 + n2 * (-1 / 2 + n2 * (1 / 24 + n2 * (-1 / 720 + n2 * (1 / 40320 + n2 * (-1 / 3628800)))));
412
+ }
413
+ function reduceAngle(n) {
414
+ let x = wrapAngle(n);
415
+ let sinSign = 1;
416
+ if (x < 0) {
417
+ x = -x;
418
+ sinSign = -1;
419
+ }
420
+ let cosSign = 1;
421
+ if (x > HALF_PI) {
422
+ x = PI - x;
423
+ cosSign = -1;
424
+ }
425
+ return [x, sinSign, cosSign];
426
+ }
427
+ function sin(n) {
428
+ const [x, sinSign] = reduceAngle(n);
429
+ return sinSign * sinSeries(x);
430
+ }
431
+ function cos(n) {
432
+ const [x, , cosSign] = reduceAngle(n);
433
+ return cosSign * cosSeries(x);
434
+ }
435
+ function clamp(value, lo, hi) {
436
+ return max(lo, min(hi, value));
437
+ }
438
+ function deg2rad(value) {
439
+ return value * DEG2RAD;
440
+ }
441
+ function lerp(start, end, scale) {
442
+ return start * (1 - scale) + end * scale;
443
+ }
444
+ function distance(x1, y1, x2, y2) {
445
+ return hypot2(x2 - x1, y2 - y1);
446
+ }
447
+ function squaredDistance(x1, y1, x2, y2) {
448
+ const dx = x1 - x2;
449
+ const dy = y1 - y2;
450
+ return dx * dx + dy * dy;
451
+ }
452
+ function manhattanDistance(x1, y1, x2, y2) {
453
+ return abs(x1 - x2) + abs(y1 - y2);
454
+ }
455
+ function roundTo(value, digits, base = 10) {
456
+ const p = pow(base, digits);
457
+ return round(value * p) / p;
458
+ }
459
+
460
+ // src/color.ts
461
+ var Color = class _Color {
462
+ _hex = "#ffffffff";
463
+ _r = 255;
464
+ _g = 255;
465
+ _b = 255;
466
+ _a = 255;
467
+ get r() {
468
+ return this._r;
469
+ }
470
+ set r(value) {
471
+ this._r = clamp(value, 0, 255);
472
+ this._hex = this._to_hex();
473
+ }
474
+ get g() {
475
+ return this._g;
476
+ }
477
+ set g(value) {
478
+ this._g = clamp(value, 0, 255);
479
+ this._hex = this._to_hex();
480
+ }
481
+ get b() {
482
+ return this._b;
483
+ }
484
+ set b(value) {
485
+ this._b = clamp(value, 0, 255);
486
+ this._hex = this._to_hex();
487
+ }
488
+ get a() {
489
+ return this._a;
490
+ }
491
+ set a(value) {
492
+ this._a = clamp(value, 0, 255);
493
+ this._hex = this._to_hex();
494
+ }
495
+ get hexStr() {
496
+ return this._hex;
497
+ }
498
+ set hexStr(value) {
499
+ if (value.startsWith("#")) {
500
+ [this._r, this._g, this._b, this._a] = this._parse_hex_color_string(value);
501
+ this._hex = value;
502
+ } else {
503
+ logwrn(`Color: invalid color string: ${value}. Should be a hexadecimal color string (i.e.: '#ffffff' or '#ffffffff'). Keeping the current color.`);
504
+ }
505
+ }
506
+ get rgba() {
507
+ return [this._r, this._g, this._b, this._a];
508
+ }
509
+ constructor(r = 255, g = 255, b = 255, a = 255) {
510
+ if (typeof r === "string") {
511
+ if (r.startsWith("#")) {
512
+ [r, g, b, a] = this._parse_hex_color_string(r);
513
+ } else {
514
+ logwrn(`Color: invalid color string: ${r}. Should be a hexadecimal color string (i.e.: '#ffffff' or '#ffffffff'). Defaulting to opaque white.`);
515
+ r = g = b = a = 255;
516
+ }
517
+ } else {
518
+ [r, g, b, a] = [r, g, b, a].map((n) => _Color._normalize(n));
519
+ }
520
+ this.r = r;
521
+ this.g = g;
522
+ this.b = b;
523
+ this.a = a;
524
+ }
525
+ static _normalize(value) {
526
+ return clamp(0 | (value > 0 && value < 1 ? value * 255 : value), 0, 255);
527
+ }
528
+ _to_hex() {
529
+ 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")}`;
530
+ }
531
+ _parse_hex_color_string(hex) {
532
+ const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})?$/i.exec(hex);
533
+ return result ? [
534
+ parseInt(result[1], 16),
535
+ parseInt(result[2], 16),
536
+ parseInt(result[3], 16),
537
+ result[4] ? parseInt(result[4], 16) : 255
538
+ ] : [255, 255, 255, 255];
539
+ }
540
+ static fromHsv(h, s, v, a = 255) {
541
+ let r = 0;
542
+ let g = 0;
543
+ let b = 0;
544
+ let i = Math.floor(h * 6);
545
+ let f = h * 6 - i;
546
+ let p = v * (1 - s);
547
+ let q = v * (1 - f * s);
548
+ let t = v * (1 - (1 - f) * s);
549
+ switch (i % 6) {
550
+ case 0:
551
+ r = v, g = t, b = p;
552
+ break;
553
+ case 1:
554
+ r = q, g = v, b = p;
555
+ break;
556
+ case 2:
557
+ r = p, g = v, b = t;
558
+ break;
559
+ case 3:
560
+ r = p, g = q, b = v;
561
+ break;
562
+ case 4:
563
+ r = t, g = p, b = v;
564
+ break;
565
+ case 5:
566
+ r = v, g = p, b = q;
567
+ break;
568
+ }
569
+ return new _Color(Math.round(r * 255), Math.round(g * 255), Math.round(b * 255), a);
570
+ }
571
+ static get BLACK() {
572
+ return new _Color(0, 0, 0, 255);
573
+ }
574
+ static get GRAY() {
575
+ return new _Color(128, 128, 128, 255);
576
+ }
577
+ static get WHITE() {
578
+ return new _Color(255, 255, 255, 255);
579
+ }
580
+ static get RED() {
581
+ return new _Color(255, 0, 0, 255);
582
+ }
583
+ static get GREEN() {
584
+ return new _Color(0, 255, 0, 255);
585
+ }
586
+ static get BLUE() {
587
+ return new _Color(0, 0, 255, 255);
588
+ }
589
+ static get YELLOW() {
590
+ return new _Color(255, 255, 0, 255);
591
+ }
592
+ static get ORANGE() {
593
+ return new _Color(255, 128, 0, 255);
594
+ }
595
+ static get PURPLE() {
596
+ return new _Color(128, 0, 128, 255);
597
+ }
598
+ static get CYAN() {
599
+ return new _Color(0, 255, 255, 255);
600
+ }
601
+ static get MAGENTA() {
602
+ return new _Color(255, 0, 255, 255);
603
+ }
604
+ static fromName(name) {
605
+ const element = document.createElement("div");
606
+ element.style.color = name;
607
+ document.body.appendChild(element);
608
+ const computedColor = getComputedStyle(element).color;
609
+ document.body.removeChild(element);
610
+ const rgba = computedColor.match(/\d+/g);
611
+ if (rgba && rgba.length === 4) {
612
+ const [r, g, b, a] = rgba.map(Number);
613
+ return new _Color(r, g, b, a);
614
+ } else {
615
+ logwrn(`Color: invalid CSS color name: ${name}. Defaulting to transparent.`);
616
+ return _Color.TRANSPARENT;
617
+ }
618
+ }
619
+ static get TRANSPARENT() {
620
+ return new _Color(0, 0, 0, 0);
621
+ }
622
+ };
623
+
624
+ // src/dungeon-generator.ts
625
+ var import_heap_js = require("heap-js");
626
+
627
+ // src/map2d.ts
628
+ var DEFAULT_VALUE = -1;
629
+ var Map2D = class {
630
+ defaultValue;
631
+ _data;
632
+ get size() {
633
+ return this._data.size;
634
+ }
635
+ constructor(defaultValue = DEFAULT_VALUE) {
636
+ this.defaultValue = defaultValue;
637
+ this._data = /* @__PURE__ */ new Map();
638
+ }
639
+ _floor(x, y) {
640
+ return [floor(x), floor(y)];
641
+ }
642
+ _key(x, y) {
643
+ return `${x},${y}`;
644
+ }
645
+ _pos(key) {
646
+ return key.split(",").map((v) => parseInt(v));
647
+ }
648
+ clear() {
649
+ this._data.clear();
650
+ }
651
+ get(x, y, defaultValue = this.defaultValue) {
652
+ [x, y] = this._floor(x, y);
653
+ return this._data.get(this._key(x, y)) ?? defaultValue;
654
+ }
655
+ set(x, y, value = this.defaultValue) {
656
+ [x, y] = this._floor(x, y);
657
+ const key = this._key(x, y);
658
+ if (value === this.defaultValue) {
659
+ this._data.delete(key);
660
+ } else {
661
+ this._data.set(key, value);
662
+ }
663
+ }
664
+ forEach(callback) {
665
+ this._data.forEach((v, key) => {
666
+ const [x, y] = this._pos(key);
667
+ callback(x, y, v);
668
+ });
669
+ }
670
+ };
671
+
672
+ // src/vector.ts
673
+ var Vector = class _Vector {
674
+ x;
675
+ y;
676
+ constructor(x = 0, y = 0) {
677
+ this.x = x;
678
+ this.y = y;
679
+ }
680
+ clone() {
681
+ return new _Vector(this.x, this.y);
682
+ }
683
+ distanceTo(that) {
684
+ return distance(
685
+ this.x,
686
+ this.y,
687
+ that.x,
688
+ that.y
689
+ );
690
+ }
691
+ floored() {
692
+ return new _Vector(
693
+ Math.floor(this.x),
694
+ Math.floor(this.y)
695
+ );
696
+ }
697
+ plus(x, y) {
698
+ if (x instanceof _Vector) {
699
+ y = x.y;
700
+ x = x.x;
701
+ } else if (y === void 0) {
702
+ y = x;
703
+ }
704
+ this.x += x;
705
+ this.y += y;
706
+ return this;
707
+ }
708
+ minus(x, y) {
709
+ if (x instanceof _Vector) {
710
+ y = x.y;
711
+ x = x.x;
712
+ } else if (y === void 0) {
713
+ y = x;
714
+ }
715
+ this.x -= x;
716
+ this.y -= y;
717
+ return this;
718
+ }
719
+ times(x, y) {
720
+ if (x instanceof _Vector) {
721
+ y = x.y;
722
+ x = x.x;
723
+ } else if (y === void 0) {
724
+ y = x;
725
+ }
726
+ this.x *= x;
727
+ this.y *= y;
728
+ return this;
729
+ }
730
+ dividedBy(x, y) {
731
+ if (x instanceof _Vector) {
732
+ y = x.y;
733
+ x = x.x;
734
+ } else if (y === void 0) {
735
+ y = x;
736
+ }
737
+ this.x /= x || 1;
738
+ this.y /= y || 1;
739
+ return this;
740
+ }
741
+ static get NORTH() {
742
+ return new _Vector(0, -1);
743
+ }
744
+ static get SOUTH() {
745
+ return new _Vector(0, 1);
746
+ }
747
+ static get EAST() {
748
+ return new _Vector(1, 0);
749
+ }
750
+ static get WEST() {
751
+ return new _Vector(-1, 0);
752
+ }
753
+ };
754
+
755
+ // src/rectangle.ts
756
+ var Rectangle = class _Rectangle {
757
+ x;
758
+ y;
759
+ width;
760
+ height;
761
+ constructor(x = 0, y = 0, width = 1, height = 1) {
762
+ this.x = x;
763
+ this.y = y;
764
+ this.width = width;
765
+ this.height = height;
766
+ }
767
+ area() {
768
+ return this.width * this.height;
769
+ }
770
+ contains(target, padding = 0) {
771
+ return target instanceof Vector ? target.x >= this.x - padding && target.x <= this.x + this.width + padding && target.y >= this.y - padding && target.y <= this.y + this.height + padding : target.x >= this.x + padding && target.y >= this.y + padding && target.x + target.width <= this.x + this.width - padding && target.y + target.height <= this.y + this.height - padding;
772
+ }
773
+ intersects(other, padding = 0) {
774
+ return !(other.x - padding > this.x + this.width + padding || other.x + other.width + padding < this.x - padding || other.y - padding > this.y + this.height + padding || other.y + other.height + padding < this.y - padding);
775
+ }
776
+ center() {
777
+ return new Vector(
778
+ this.x + this.width / 2,
779
+ this.y + this.height / 2
780
+ );
781
+ }
782
+ distanceTo(other) {
783
+ return this.center().distanceTo(other.center());
784
+ }
785
+ clone() {
786
+ return new _Rectangle(this.x, this.y, this.width, this.height);
787
+ }
788
+ equals(other) {
789
+ return this.x === other.x && this.y === other.y && this.width === other.width && this.height === other.height;
790
+ }
791
+ grow(padding) {
792
+ return new _Rectangle(
793
+ this.x - padding,
794
+ this.y - padding,
795
+ this.width + padding * 2,
796
+ this.height + padding * 2
797
+ );
798
+ }
799
+ vectorInside(vec, padding = 0) {
800
+ return vec.x >= this.x - padding && vec.x <= this.x + this.width + padding && vec.y >= this.y - padding && vec.y <= this.y + this.height + padding;
801
+ }
802
+ };
803
+
804
+ // src/rng.ts
805
+ var Rng = class {
806
+ __seed;
807
+ _seed;
808
+ _uid_characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
809
+ constructor() {
810
+ this._seed = Date.now();
811
+ this.__seed = this._seed;
812
+ this._uid_characters = this.shuffle(this._uid_characters);
813
+ this.seed = this.nexti;
814
+ }
815
+ get seed() {
816
+ return this._seed;
817
+ }
818
+ set seed(value) {
819
+ this._seed = value;
820
+ this.__seed = this._seed;
821
+ }
822
+ get startingSeed() {
823
+ return this.__seed;
824
+ }
825
+ get nextf() {
826
+ this._seed |= 0;
827
+ this._seed = this._seed + 2654435769 | 0;
828
+ let t = this._seed ^ this._seed >>> 16;
829
+ t = imul(t, 569420461);
830
+ t = t ^ t >>> 15;
831
+ t = imul(t, 1935289751);
832
+ return ((t = t ^ t >>> 15) >>> 0) / 4294967296;
833
+ }
834
+ get nexti() {
835
+ return this.nextf * Number.MAX_SAFE_INTEGER | 0;
836
+ }
837
+ // NOTE: as of the core/apparatus consolidation, range(min, max) treats
838
+ // max as EXCLUSIVE (previous published versions of this package treated
839
+ // it as inclusive - if you're upgrading from an older @n3rdw1z4rd/core,
840
+ // range(0, 10) now returns [0, 10) instead of [0, 10]).
841
+ range(min2, max2) {
842
+ if (max2 === void 0) {
843
+ max2 = min2;
844
+ min2 = 0;
845
+ }
846
+ return min2 + this.nextf * (max2 - min2) | 0;
847
+ }
848
+ randomUnitVector() {
849
+ const theta = this.nextf * 2 * PI;
850
+ return [cos(theta), sin(theta)];
851
+ }
852
+ // Box-Muller-ish gaussian sample, mean 0.5 stddev 1/6 (so ~99.7% of
853
+ // samples land in [0, 1]). Uses native Math.log since a pure natural-log
854
+ // implementation isn't part of math.ts yet.
855
+ parkMillerNormal() {
856
+ const mean = 1 / 2;
857
+ const stddev = 1 / 6;
858
+ let u = 0;
859
+ let v = 0;
860
+ while (u === 0) u = this.nextf;
861
+ while (v === 0) v = this.nextf;
862
+ const n = sqrt(-2 * Math.log(u)) * cos(2 * PI * v);
863
+ return n * stddev + mean;
864
+ }
865
+ choose(...args) {
866
+ if (args.length === 1) {
867
+ if (Array.isArray(args[0])) {
868
+ return args[0][this.range(args[0].length - 1)];
869
+ } else if (typeof args[0] === "string") {
870
+ return args[0].charAt(this.range(args[0].length - 1));
871
+ } else {
872
+ return args[0];
873
+ }
874
+ } else {
875
+ return args[this.range(args.length - 1)];
876
+ }
877
+ }
878
+ shuffle(value) {
879
+ if (Array.isArray(value)) {
880
+ return value.sort(() => 0.5 - this.nextf);
881
+ } else {
882
+ return value.split("").sort(() => 0.5 - this.nextf).join("");
883
+ }
884
+ }
885
+ uid(length = 16) {
886
+ const uid = [];
887
+ for (let i = 0; i < length; i++) uid.push(this.choose(this._uid_characters));
888
+ return uid.join("");
889
+ }
890
+ randomMatrix(size) {
891
+ const rows = [];
892
+ for (let i = 0; i < size; i++) {
893
+ const row = [];
894
+ for (let j = 0; j < size; j++) {
895
+ row.push(this.nextf * 2 - 1);
896
+ }
897
+ rows.push(row);
898
+ }
899
+ return rows;
900
+ }
901
+ };
902
+ var rng = new Rng();
903
+
904
+ // src/dungeon-generator.ts
905
+ var TILE_EMPTY = 0;
906
+ var TILE_FLOOR = 1;
907
+ var TILE_PATH = 2;
908
+ var DEFAULT_LEVEL_SIZE = 64;
909
+ var DEFAULT_ROOM_MIN_SIZE = 3;
910
+ var DEFAULT_ROOM_MAX_SIZE = 9;
911
+ var DEFAULT_ROOM_PADDING = 1;
912
+ var DEFAULT_ROOM_MAX_ITERATIONS = 1e3;
913
+ var DEFAULT_PATH_TIMEOUT = 1e4;
914
+ var DEFAULT_PATH_EXTRA_PATHS = 0;
915
+ var DEFAULT_PATH_EXTRA_PATH_DENSITY = 0.1;
916
+ var DEFAULT_DOOR_CHANCE_EXISTS = 0.5;
917
+ var DIRECTIONS_8_WAY = [
918
+ { x: -1, y: 0 },
919
+ // left
920
+ { x: -1, y: -1 },
921
+ // left-up
922
+ { x: 0, y: -1 },
923
+ // up
924
+ { x: 1, y: -1 },
925
+ // up-right
926
+ { x: 1, y: 0 },
927
+ // right
928
+ { x: 1, y: 1 },
929
+ // right-down
930
+ { x: 0, y: 1 },
931
+ // down
932
+ { x: -1, y: 1 }
933
+ // down-left
934
+ ];
935
+ function _plot(map, data, tile) {
936
+ data.forEach((element) => {
937
+ if (element instanceof Rectangle) {
938
+ for (let y = 0; y < element.height; y++) {
939
+ for (let x = 0; x < element.width; x++) {
940
+ map.set(element.x + x, element.y + y, tile);
941
+ }
942
+ }
943
+ } else if (Array.isArray(element)) {
944
+ element.forEach((point) => {
945
+ map.set(point.x, point.y, tile);
946
+ });
947
+ } else {
948
+ map.set(element.x, element.y, tile);
949
+ }
950
+ });
951
+ }
952
+ function _generateRooms(params = {}) {
953
+ const size = params.size ?? DEFAULT_LEVEL_SIZE;
954
+ const minRoomSize = params.minSize ?? DEFAULT_ROOM_MIN_SIZE;
955
+ const maxRoomSize = params.maxSize ?? DEFAULT_ROOM_MAX_SIZE;
956
+ const padding = params.padding ?? DEFAULT_ROOM_PADDING;
957
+ const maxIterations = params.maxIterations ?? DEFAULT_ROOM_MAX_ITERATIONS;
958
+ const rooms = [];
959
+ let iterations = 0;
960
+ while (iterations < maxIterations) {
961
+ const baseSize = rng.range(minRoomSize, maxRoomSize);
962
+ const aspectRatio = 0.75 + rng.parkMillerNormal() * 0.5;
963
+ const width = Math.min(maxRoomSize, Math.max(minRoomSize, Math.round(baseSize * aspectRatio)));
964
+ const height = Math.min(maxRoomSize, Math.max(minRoomSize, Math.round(baseSize / aspectRatio)));
965
+ const x = Math.floor(rng.range(1 + padding, size - width - padding));
966
+ const y = Math.floor(rng.range(1 + padding, size - height - padding));
967
+ const room = new Rectangle(x, y, width, height);
968
+ if (!rooms.some((existing) => room.intersects(existing, padding))) {
969
+ rooms.push(room);
970
+ iterations = 0;
971
+ } else {
972
+ iterations += 1;
973
+ }
974
+ }
975
+ return rooms;
976
+ }
977
+ function _generateMST(rooms, params = {}) {
978
+ const timeout = params.timeout ?? DEFAULT_PATH_TIMEOUT;
979
+ const extraPathLevels = params.extraPaths ?? DEFAULT_PATH_EXTRA_PATHS;
980
+ const extraPathDensity = params.extraPathDensity ?? DEFAULT_PATH_EXTRA_PATH_DENSITY;
981
+ const startTime = Date.now();
982
+ const mst = [];
983
+ const extraPaths = [];
984
+ const visited = /* @__PURE__ */ new Set();
985
+ const heap = new import_heap_js.Heap((a, b) => a.cost - b.cost);
986
+ visited.add(0);
987
+ const zeroCenter = rooms[0].center();
988
+ for (let i = 1; i < rooms.length; i++) {
989
+ const iCenter = rooms[i].center();
990
+ heap.push({
991
+ from: 0,
992
+ to: i,
993
+ cost: squaredDistance(
994
+ zeroCenter.x,
995
+ zeroCenter.y,
996
+ iCenter.x,
997
+ iCenter.y
998
+ )
999
+ });
1000
+ }
1001
+ while (visited.size < rooms.length && Date.now() - startTime < timeout) {
1002
+ let edge = heap.pop();
1003
+ while (edge && visited.has(edge.to)) {
1004
+ edge = heap.pop();
1005
+ }
1006
+ if (!edge) break;
1007
+ const { from, to } = edge;
1008
+ visited.add(to);
1009
+ mst.push({ a: rooms[from], b: rooms[to] });
1010
+ const toCenter = rooms[to].center();
1011
+ for (let i = 0; i < rooms.length; i++) {
1012
+ if (!visited.has(i)) {
1013
+ const iCenter = rooms[i].center();
1014
+ heap.push({
1015
+ from: to,
1016
+ to: i,
1017
+ cost: squaredDistance(
1018
+ toCenter.x,
1019
+ toCenter.y,
1020
+ iCenter.x,
1021
+ iCenter.y
1022
+ )
1023
+ });
1024
+ }
1025
+ }
1026
+ }
1027
+ const remainingEdges = heap.toArray().sort((a, b) => a.cost - b.cost);
1028
+ for (let i = 0; i < extraPathLevels && i < remainingEdges.length; i++) {
1029
+ const e = remainingEdges[i];
1030
+ if (rng.nextf < extraPathDensity) {
1031
+ extraPaths.push({
1032
+ a: rooms[e.from],
1033
+ b: rooms[e.to]
1034
+ });
1035
+ }
1036
+ }
1037
+ return mst.concat(extraPaths);
1038
+ }
1039
+ function _getRectEdgePoints(rect) {
1040
+ const points = [];
1041
+ const x2 = rect.x + rect.width - 1;
1042
+ const y2 = rect.y + rect.height - 1;
1043
+ for (let x1 = rect.x; x1 < x2; x1++) {
1044
+ points.push({ x: x1, y: rect.y });
1045
+ points.push({ x: x1, y: y2 });
1046
+ }
1047
+ for (let y1 = rect.y; y1 < y2; y1++) {
1048
+ points.push({ x: rect.x, y: y1 });
1049
+ points.push({ x: x2, y: y1 });
1050
+ }
1051
+ return points;
1052
+ }
1053
+ function _getShortestPathBetweenRects(rectA, rectB) {
1054
+ const edgeA = _getRectEdgePoints(rectA);
1055
+ const edgeB = _getRectEdgePoints(rectB);
1056
+ let paths = { a: edgeA[0], b: edgeB[0], distance: Infinity };
1057
+ for (const a of edgeA) {
1058
+ for (const b of edgeB) {
1059
+ const d = distance(a.x, a.y, b.x, b.y);
1060
+ if (d < paths.distance) {
1061
+ paths = { a, b, distance: d };
1062
+ }
1063
+ }
1064
+ }
1065
+ return { a: paths.a, b: paths.b };
1066
+ }
1067
+ function _generatePaths(map, rooms, params = {}) {
1068
+ const aStar = new AStar(map);
1069
+ const paths = [];
1070
+ _generateMST(rooms, params).forEach((rects) => {
1071
+ const { a, b } = _getShortestPathBetweenRects(rects.a, rects.b);
1072
+ paths.push(aStar.findPath(a, b, params.astarFindPathParams));
1073
+ });
1074
+ return paths;
1075
+ }
1076
+ function GenerateRooms(params = {}) {
1077
+ const startTime = Date.now();
1078
+ const map = params.map ?? new Map2D(TILE_EMPTY);
1079
+ const rooms = _generateRooms(params.rooms);
1080
+ _plot(map, rooms, TILE_FLOOR);
1081
+ const paths = _generatePaths(map, rooms, params.paths);
1082
+ _plot(map, paths, TILE_PATH);
1083
+ log("GenerateRooms: done:", Date.now() - startTime, "ms");
1084
+ return { map, rooms, paths };
1085
+ }
1086
+ function GenerateDoors(map, paths, params = {}) {
1087
+ const chanceExists = params.chanceExists ?? DEFAULT_DOOR_CHANCE_EXISTS;
1088
+ const possibleDoorPoints = [];
1089
+ paths.forEach((points) => {
1090
+ if (points.length > 1) {
1091
+ possibleDoorPoints.push(points[0]);
1092
+ possibleDoorPoints.push(points[points.length - 1]);
1093
+ }
1094
+ });
1095
+ const doors = [];
1096
+ possibleDoorPoints.forEach((doorPoint) => {
1097
+ if (rng.nextf < chanceExists && (map.get(doorPoint.x, doorPoint.y - 1) === map.defaultValue && map.get(doorPoint.x, doorPoint.y + 1) === map.defaultValue || map.get(doorPoint.x - 1, doorPoint.y) === map.defaultValue && map.get(doorPoint.x + 1, doorPoint.y) === map.defaultValue)) {
1098
+ doors.push(doorPoint);
1099
+ }
1100
+ });
1101
+ return doors;
1102
+ }
1103
+ function GenerateWalls(map) {
1104
+ const walls = [];
1105
+ map.forEach((x, y, _v) => {
1106
+ DIRECTIONS_8_WAY.forEach((dir) => {
1107
+ const nx = dir.x + x;
1108
+ const ny = dir.y + y;
1109
+ if (map.get(nx, ny) === map.defaultValue) {
1110
+ walls.push({ x: nx, y: ny });
1111
+ }
1112
+ });
1113
+ });
1114
+ return walls;
1115
+ }
1116
+
197
1117
  // src/ecs.ts
198
1118
  var ECS = class _ECS {
199
1119
  _globals = /* @__PURE__ */ new Map();
@@ -434,8 +1354,25 @@ var Emitter = class {
434
1354
  this.listeners.get(eventName)?.forEach((listener) => listener(...args, eventName));
435
1355
  return this;
436
1356
  }
1357
+ clear(eventName) {
1358
+ if (eventName) {
1359
+ this.listeners.delete(eventName);
1360
+ } else {
1361
+ this.listeners.clear();
1362
+ }
1363
+ return this;
1364
+ }
437
1365
  };
438
1366
  var GlobalEmitter = new Emitter();
1367
+ var EventBus = class extends EventTarget {
1368
+ emit(type, detail) {
1369
+ this.dispatchEvent(new CustomEvent(type, { detail }));
1370
+ }
1371
+ on(type, cb) {
1372
+ this.addEventListener(type, cb);
1373
+ }
1374
+ };
1375
+ var eventBus = new EventBus();
439
1376
 
440
1377
  // src/input.ts
441
1378
  var import_gl_matrix = require("gl-matrix");
@@ -560,132 +1497,82 @@ var Input = class extends Emitter {
560
1497
  }
561
1498
  };
562
1499
 
563
- // src/math.ts
564
- var DEG2RAD = 0.01745329;
565
- function clamp(value, min, max) {
566
- return Math.max(min, Math.min(max, value));
567
- }
568
- function deg2rad(value) {
569
- return value * DEG2RAD;
570
- }
571
- function lerp(start, end, scale) {
572
- return start * (1 - scale) + end * scale;
573
- }
574
-
575
- // src/misc.ts
576
- function isNullOrUndefined(target) {
577
- return target === null || target === void 0;
578
- }
579
- var getRedYellowGreenGradientHex = (min, max) => {
580
- if (max === void 0) {
581
- max = min;
582
- min = 0;
1500
+ // src/map3d.ts
1501
+ var DEFAULT_VALUE2 = -1;
1502
+ var Map3D = class {
1503
+ defaultValue;
1504
+ _data;
1505
+ get data() {
1506
+ return this._data;
583
1507
  }
584
- if (max < 1) {
585
- max = 1;
1508
+ constructor(defaultValue = DEFAULT_VALUE2) {
1509
+ this.defaultValue = defaultValue;
1510
+ this._data = /* @__PURE__ */ new Map();
586
1511
  }
587
- const percent = min / max;
588
- const index = clamp(Math.floor(percent * 10), 0, 10);
589
- return [
590
- "#ff0000",
591
- "#ff3300",
592
- "#ff6600",
593
- "#ff9900",
594
- "#ffcc00",
595
- "#ffff00",
596
- "#ccff00",
597
- "#99ff00",
598
- "#66ff00",
599
- "#33ff00",
600
- "#00ff00"
601
- ][index];
602
- };
603
-
604
- // src/noise.ts
605
- var import_simplex_noise = require("simplex-noise");
606
-
607
- // src/rng.ts
608
- var import_gl_matrix2 = require("gl-matrix");
609
- var Rng = class {
610
- _seed = Date.now();
611
- _uid_characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
612
- constructor() {
613
- this._uid_characters = this.shuffle(this._uid_characters);
614
- this.seed = this.nexti;
1512
+ _floor(x, y, z) {
1513
+ return [floor(x), floor(y), floor(z)];
615
1514
  }
616
- get seed() {
617
- return this._seed;
1515
+ _key(x, y, z) {
1516
+ return `${x},${y},${z}`;
618
1517
  }
619
- set seed(value) {
620
- this._seed = value;
1518
+ _pos(key) {
1519
+ return key.split(",").map((v) => parseInt(v));
621
1520
  }
622
- get nextf() {
623
- this._seed |= 0;
624
- this._seed = this._seed + 2654435769 | 0;
625
- let t = this._seed ^ this._seed >>> 16;
626
- t = Math.imul(t, 569420461);
627
- t = t ^ t >>> 15;
628
- t = Math.imul(t, 1935289751);
629
- return ((t = t ^ t >>> 15) >>> 0) / 4294967296;
630
- }
631
- get nexti() {
632
- return this.nextf * Number.MAX_SAFE_INTEGER | 0;
633
- }
634
- range(min, max) {
635
- if (max === void 0) {
636
- if (min !== 0) {
637
- max = min;
638
- min = 0;
639
- } else {
640
- max = Number.MAX_SAFE_INTEGER;
641
- }
642
- }
643
- return this.nextf * (max - min + 1) + min | 0;
644
- }
645
- choose(...args) {
646
- if (args.length === 1) {
647
- if (Array.isArray(args[0])) {
648
- return args[0][this.range(args[0].length - 1)];
649
- } else if (typeof args[0] === "string") {
650
- return args[0].charAt(this.range(args[0].length - 1));
651
- } else {
652
- return args[0];
653
- }
654
- } else {
655
- return args[this.range(args.length - 1)];
656
- }
657
- }
658
- shuffle(value) {
659
- if (Array.isArray(value)) {
660
- return value.sort(() => 0.5 - this.nextf);
661
- } else {
662
- return value.split("").sort(() => 0.5 - this.nextf).join("");
663
- }
664
- }
665
- uid(length = 16) {
666
- const uid = [];
667
- for (let i = 0; i < length; i++) uid.push(this.choose(this._uid_characters));
668
- return uid.join("");
1521
+ clear() {
1522
+ this._data.clear();
669
1523
  }
670
- randomMatrix(size) {
671
- const rows = [];
672
- for (let i = 0; i < size; i++) {
673
- const row = [];
674
- for (let j = 0; j < size; j++) {
675
- row.push(this.nextf * 2 - 1);
676
- }
677
- rows.push(row);
1524
+ get(x, y, z, defaultValue = this.defaultValue) {
1525
+ [x, y, z] = this._floor(x, y, z);
1526
+ return this._data.get(this._key(x, y, z)) ?? defaultValue;
1527
+ }
1528
+ set(x, y, z, value = this.defaultValue) {
1529
+ [x, y, z] = this._floor(x, y, z);
1530
+ const key = this._key(x, y, z);
1531
+ if (value === this.defaultValue) {
1532
+ this._data.delete(key);
1533
+ } else {
1534
+ this._data.set(key, value);
678
1535
  }
679
- return rows;
680
1536
  }
681
- randomUnitVector() {
682
- const theta = rng.nextf * 2 * Math.PI;
683
- return import_gl_matrix2.vec2.fromValues(Math.cos(theta), Math.sin(theta));
1537
+ forEach(callback) {
1538
+ this._data.forEach((v, key) => {
1539
+ const [x, y, z] = this._pos(key);
1540
+ callback(x, y, z, v);
1541
+ });
684
1542
  }
685
1543
  };
686
- var rng = new Rng();
1544
+
1545
+ // src/misc.ts
1546
+ function isNullOrUndefined(target) {
1547
+ return target === null || target === void 0;
1548
+ }
1549
+ var getRedYellowGreenGradientHex = (min2, max2) => {
1550
+ if (max2 === void 0) {
1551
+ max2 = min2;
1552
+ min2 = 0;
1553
+ }
1554
+ if (max2 < 1) {
1555
+ max2 = 1;
1556
+ }
1557
+ const percent = min2 / max2;
1558
+ const index = clamp(Math.floor(percent * 10), 0, 10);
1559
+ return [
1560
+ "#ff0000",
1561
+ "#ff3300",
1562
+ "#ff6600",
1563
+ "#ff9900",
1564
+ "#ffcc00",
1565
+ "#ffff00",
1566
+ "#ccff00",
1567
+ "#99ff00",
1568
+ "#66ff00",
1569
+ "#33ff00",
1570
+ "#00ff00"
1571
+ ][index];
1572
+ };
687
1573
 
688
1574
  // src/noise.ts
1575
+ var import_simplex_noise = require("simplex-noise");
689
1576
  var Noise = class _Noise {
690
1577
  static _n2d;
691
1578
  static _n3d;
@@ -745,8 +1632,285 @@ var Noise = class _Noise {
745
1632
  }
746
1633
  };
747
1634
 
1635
+ // src/particle-renderer.ts
1636
+ var Renderer = class {
1637
+ _screenCanvas;
1638
+ _bufferCanvas;
1639
+ screenContext;
1640
+ bufferContext;
1641
+ get width() {
1642
+ return this._screenCanvas.width;
1643
+ }
1644
+ get height() {
1645
+ return this._screenCanvas.height;
1646
+ }
1647
+ constructor(canvas) {
1648
+ this._screenCanvas = canvas ?? document.createElement("canvas");
1649
+ this._bufferCanvas = new OffscreenCanvas(this._screenCanvas.width, this._screenCanvas.height);
1650
+ this.screenContext = this._screenCanvas.getContext("2d");
1651
+ this.bufferContext = this._bufferCanvas.getContext("2d");
1652
+ if (!this.screenContext || !this.bufferContext) {
1653
+ throw "Failed to create CanvasRenderingContext2D";
1654
+ }
1655
+ }
1656
+ appendTo(target, autoResize = true) {
1657
+ if (this._screenCanvas.parentNode) {
1658
+ this._screenCanvas.parentNode.removeChild(this._screenCanvas);
1659
+ }
1660
+ target.appendChild(this._screenCanvas);
1661
+ if (autoResize) {
1662
+ this.resize();
1663
+ }
1664
+ }
1665
+ resize(displayWidth, displayHeight) {
1666
+ const { width, height } = this._screenCanvas.parentElement?.getBoundingClientRect() ?? this._screenCanvas.getBoundingClientRect();
1667
+ displayWidth = 0 | (displayWidth ?? width);
1668
+ displayHeight = 0 | (displayHeight ?? height);
1669
+ if (this._screenCanvas.width !== displayWidth || this._screenCanvas.height !== displayHeight) {
1670
+ this._screenCanvas.width = displayWidth;
1671
+ this._screenCanvas.height = displayHeight;
1672
+ this._bufferCanvas.width = displayWidth;
1673
+ this._bufferCanvas.height = displayHeight;
1674
+ return true;
1675
+ }
1676
+ return false;
1677
+ }
1678
+ setPixel(x, y, color, size = 2) {
1679
+ this.bufferContext.fillStyle = color.hexStr;
1680
+ this.bufferContext.fillRect(x - size / 2, y - size / 2, size, size);
1681
+ }
1682
+ render() {
1683
+ this.screenContext.clearRect(0, 0, this._screenCanvas.width, this._screenCanvas.height);
1684
+ this.screenContext.drawImage(this._bufferCanvas, 0, 0);
1685
+ this.bufferContext.clearRect(0, 0, this._screenCanvas.width, this._screenCanvas.height);
1686
+ }
1687
+ };
1688
+
1689
+ // src/spatial-partition-2d.ts
1690
+ var SpatialPartition2d = class {
1691
+ cells;
1692
+ cellSize;
1693
+ entities;
1694
+ constructor(cellSize, entities) {
1695
+ this.cellSize = cellSize;
1696
+ this.entities = entities;
1697
+ this.cells = Array.from(
1698
+ { length: Math.ceil(1 / cellSize) },
1699
+ () => Array.from({ length: Math.ceil(1 / cellSize) }, () => [])
1700
+ );
1701
+ for (const entity of this.entities) {
1702
+ this.addEntity(entity);
1703
+ }
1704
+ }
1705
+ addEntity(entity) {
1706
+ const cell = this.getCell(entity.x, entity.y);
1707
+ cell.push(entity);
1708
+ }
1709
+ getCell(x, y) {
1710
+ const cellX = Math.floor(x / this.cellSize);
1711
+ const cellY = Math.floor(y / this.cellSize);
1712
+ return this.cells[cellY][cellX];
1713
+ }
1714
+ getCellNeighbors(x, y) {
1715
+ const neighbors = [];
1716
+ for (let dy = -1; dy <= 1; dy++) {
1717
+ for (let dx = -1; dx <= 1; dx++) {
1718
+ let nx = x + dx;
1719
+ let ny = y + dy;
1720
+ if (nx < 0) nx = this.cells[0].length - 1;
1721
+ else if (nx >= this.cells[0].length) nx = 0;
1722
+ if (ny < 0) ny = this.cells.length - 1;
1723
+ else if (ny >= this.cells.length) ny = 0;
1724
+ neighbors.push(this.cells[ny][nx]);
1725
+ }
1726
+ }
1727
+ return neighbors;
1728
+ }
1729
+ };
1730
+
1731
+ // src/particle-system-2d.ts
1732
+ var colors = [
1733
+ Color.RED,
1734
+ Color.GREEN,
1735
+ Color.BLUE,
1736
+ Color.YELLOW,
1737
+ Color.MAGENTA
1738
+ ];
1739
+ var ParticleSystem2d = class {
1740
+ particleCount = 2e3;
1741
+ _particleSize = 2;
1742
+ _frictionHalfLife = 0.04;
1743
+ _range = 0.1;
1744
+ _rangeFactor = 0.1;
1745
+ _attractionMatrix = rng.randomMatrix(colors.length);
1746
+ _particles = [];
1747
+ _spatialPartition;
1748
+ constructor() {
1749
+ for (let i = 0; i < this.particleCount; i++) {
1750
+ this._particles.push({
1751
+ x: rng.nextf,
1752
+ y: rng.nextf,
1753
+ vx: 0,
1754
+ vy: 0,
1755
+ color: rng.range(colors.length)
1756
+ });
1757
+ }
1758
+ this._spatialPartition = new SpatialPartition2d(this._range, this._particles);
1759
+ }
1760
+ _calcForce(r, a, beta = 0.3) {
1761
+ let f = 0;
1762
+ if (r < beta) {
1763
+ f = r / beta - 1;
1764
+ } else if (beta < r && r < 1) {
1765
+ f = a * (1 - Math.abs(2 * r - 1 - beta) / (1 - beta));
1766
+ }
1767
+ return f;
1768
+ }
1769
+ _updateVelocities(deltaTimeSeconds) {
1770
+ const frictionFactor = Math.pow(
1771
+ 0.5,
1772
+ deltaTimeSeconds / this._frictionHalfLife
1773
+ );
1774
+ for (let y = 0; y < this._spatialPartition.cells.length; y++) {
1775
+ for (let x = 0; x < this._spatialPartition.cells[y].length; x++) {
1776
+ const cell = this._spatialPartition.cells[y][x];
1777
+ for (let i = 0; i < cell.length; i++) {
1778
+ let fx = 0;
1779
+ let fy = 0;
1780
+ const p1 = cell[i];
1781
+ const neighborCells = this._spatialPartition.getCellNeighbors(x, y);
1782
+ for (const neighborCell of neighborCells) {
1783
+ for (let j = 0; j < neighborCell.length; j++) {
1784
+ if (cell === neighborCell && i === j) continue;
1785
+ const p2 = neighborCell[j];
1786
+ let rx = p2.x - p1.x;
1787
+ if (Math.abs(rx) > 0.5) rx = rx > 0 ? rx - 1 : rx + 1;
1788
+ let ry = p2.y - p1.y;
1789
+ if (Math.abs(ry) > 0.5) ry = ry > 0 ? ry - 1 : ry + 1;
1790
+ const d = Math.hypot(rx, ry);
1791
+ if (d > 0 && d < this._range) {
1792
+ const f = this._calcForce(
1793
+ d / this._range,
1794
+ this._attractionMatrix[p1.color][p2.color]
1795
+ );
1796
+ fx += rx / d * f;
1797
+ fy += ry / d * f;
1798
+ }
1799
+ }
1800
+ }
1801
+ fx *= this._range * this._rangeFactor;
1802
+ fy *= this._range * this._rangeFactor;
1803
+ p1.vx *= frictionFactor;
1804
+ p1.vy *= frictionFactor;
1805
+ p1.vx += fx;
1806
+ p1.vy += fy;
1807
+ }
1808
+ }
1809
+ }
1810
+ }
1811
+ _updatePositions(deltaTimeSeconds, renderer) {
1812
+ for (let i = 0; i < this.particleCount; i++) {
1813
+ const particle = this._particles[i];
1814
+ const oldCell = this._spatialPartition.getCell(particle.x, particle.y);
1815
+ particle.x += particle.vx * deltaTimeSeconds;
1816
+ particle.y += particle.vy * deltaTimeSeconds;
1817
+ if (particle.x < 0) particle.x = 1 + particle.x % 1;
1818
+ if (particle.x > 1) particle.x = particle.x % 1;
1819
+ if (particle.y < 0) particle.y = 1 + particle.y % 1;
1820
+ if (particle.y > 1) particle.y = particle.y % 1;
1821
+ renderer.setPixel(
1822
+ particle.x * renderer.width,
1823
+ particle.y * renderer.height,
1824
+ colors[particle.color],
1825
+ this._particleSize
1826
+ );
1827
+ const newCell = this._spatialPartition.getCell(particle.x, particle.y);
1828
+ if (newCell !== oldCell) {
1829
+ const index = oldCell.indexOf(particle);
1830
+ if (index !== -1) {
1831
+ oldCell.splice(index, 1);
1832
+ }
1833
+ newCell.push(particle);
1834
+ }
1835
+ }
1836
+ }
1837
+ update(renderer, dt) {
1838
+ this._updateVelocities(dt);
1839
+ this._updatePositions(dt, renderer);
1840
+ }
1841
+ };
1842
+
1843
+ // src/poisson-disk-sampler.ts
1844
+ function PoissonDiskSampler(width, height, minDist, maxPoints = 30) {
1845
+ const k = maxPoints;
1846
+ const cellSize = minDist / Math.SQRT2;
1847
+ const gridWidth = Math.ceil(width / cellSize);
1848
+ const gridHeight = Math.ceil(height / cellSize);
1849
+ const grid = Array.from(
1850
+ { length: gridWidth },
1851
+ () => Array(gridHeight).fill(null)
1852
+ );
1853
+ const samples = [];
1854
+ const active = [];
1855
+ function gridIndex(p) {
1856
+ return {
1857
+ i: Math.floor(p.x / cellSize),
1858
+ j: Math.floor(p.y / cellSize)
1859
+ };
1860
+ }
1861
+ function isFarEnough(p) {
1862
+ const { i, j } = gridIndex(p);
1863
+ for (let x = i - 2; x <= i + 2; x++) {
1864
+ for (let y = j - 2; y <= j + 2; y++) {
1865
+ if (x < 0 || y < 0 || x >= gridWidth || y >= gridHeight) continue;
1866
+ const neighbor = grid[x][y];
1867
+ if (!neighbor) continue;
1868
+ const dx = neighbor.x - p.x;
1869
+ const dy = neighbor.y - p.y;
1870
+ if (dx * dx + dy * dy < minDist * minDist) {
1871
+ return false;
1872
+ }
1873
+ }
1874
+ }
1875
+ return true;
1876
+ }
1877
+ const initial = {
1878
+ x: rng.range(0, width),
1879
+ y: rng.range(0, height)
1880
+ };
1881
+ const { i: i0, j: j0 } = gridIndex(initial);
1882
+ grid[i0][j0] = initial;
1883
+ samples.push(initial);
1884
+ active.push(initial);
1885
+ while (active.length) {
1886
+ const index = Math.floor(rng.range(0, active.length));
1887
+ const point = active[index];
1888
+ let found = false;
1889
+ for (let n = 0; n < k; n++) {
1890
+ const angle = rng.range(0, Math.PI * 2);
1891
+ const dist = rng.range(minDist, 2 * minDist);
1892
+ const newPoint = {
1893
+ x: point.x + Math.cos(angle) * dist,
1894
+ y: point.y + Math.sin(angle) * dist
1895
+ };
1896
+ if (newPoint.x >= 0 && newPoint.y >= 0 && newPoint.x < width && newPoint.y < height && isFarEnough(newPoint)) {
1897
+ const { i, j } = gridIndex(newPoint);
1898
+ grid[i][j] = newPoint;
1899
+ samples.push(newPoint);
1900
+ active.push(newPoint);
1901
+ found = true;
1902
+ break;
1903
+ }
1904
+ }
1905
+ if (!found) {
1906
+ active.splice(index, 1);
1907
+ }
1908
+ }
1909
+ return samples;
1910
+ }
1911
+
748
1912
  // src/renderer/canvas-renderer.ts
749
- var import_gl_matrix3 = require("gl-matrix");
1913
+ var import_gl_matrix2 = require("gl-matrix");
750
1914
  var CanvasRenderer = class {
751
1915
  ctx;
752
1916
  clearColor = "#000000";
@@ -761,7 +1925,7 @@ var CanvasRenderer = class {
761
1925
  return this.ctx?.canvas.height ?? 0;
762
1926
  }
763
1927
  get center() {
764
- return import_gl_matrix3.vec2.fromValues(this.width / 2, this.height / 2);
1928
+ return import_gl_matrix2.vec2.fromValues(this.width / 2, this.height / 2);
765
1929
  }
766
1930
  constructor(canvas) {
767
1931
  this.ctx = (canvas ?? document.createElement("canvas")).getContext("2d");
@@ -892,16 +2056,16 @@ function CompileShader(gl, type, source) {
892
2056
  }
893
2057
  return shader;
894
2058
  }
895
- function CreateProgram(gl, vertexShader, fragmentShader) {
896
- if (typeof vertexShader === "string") {
897
- vertexShader = CompileShader(gl, ShaderType.VERTEX, vertexShader);
2059
+ function CreateProgram(gl, vertexShader2, fragmentShader2) {
2060
+ if (typeof vertexShader2 === "string") {
2061
+ vertexShader2 = CompileShader(gl, ShaderType.VERTEX, vertexShader2);
898
2062
  }
899
- if (typeof fragmentShader === "string") {
900
- fragmentShader = CompileShader(gl, ShaderType.FRAGMENT, fragmentShader);
2063
+ if (typeof fragmentShader2 === "string") {
2064
+ fragmentShader2 = CompileShader(gl, ShaderType.FRAGMENT, fragmentShader2);
901
2065
  }
902
2066
  const program = gl.createProgram();
903
- gl.attachShader(program, vertexShader);
904
- gl.attachShader(program, fragmentShader);
2067
+ gl.attachShader(program, vertexShader2);
2068
+ gl.attachShader(program, fragmentShader2);
905
2069
  gl.linkProgram(program);
906
2070
  if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
907
2071
  throw `CreateProgram: failed to link program: ${gl.getProgramInfoLog(program)}`;
@@ -1174,6 +2338,69 @@ var SimplexNoise = class {
1174
2338
  }
1175
2339
  };
1176
2340
 
2341
+ // src/spatial-partition-3d.ts
2342
+ var SpatialPartition3d = class {
2343
+ cells;
2344
+ cellSize;
2345
+ entities;
2346
+ constructor(cellSize, entities) {
2347
+ this.cellSize = cellSize;
2348
+ this.entities = entities;
2349
+ const gridSize = Math.ceil(1 / cellSize);
2350
+ this.cells = Array.from(
2351
+ { length: gridSize },
2352
+ () => Array.from(
2353
+ { length: gridSize },
2354
+ () => Array.from({ length: gridSize }, () => [])
2355
+ )
2356
+ );
2357
+ for (const entity of this.entities) {
2358
+ this.addEntity(entity);
2359
+ }
2360
+ }
2361
+ getCell(x, y, z) {
2362
+ const cx = Math.floor(x / this.cellSize);
2363
+ const cy = Math.floor(y / this.cellSize);
2364
+ const cz = Math.floor(z / this.cellSize);
2365
+ return this.cells[cz][cy][cx];
2366
+ }
2367
+ getCellNeighbors(cx, cy, cz) {
2368
+ const neighbors = [];
2369
+ const gridSize = this.cells.length;
2370
+ for (let dz = -1; dz <= 1; dz++) {
2371
+ for (let dy = -1; dy <= 1; dy++) {
2372
+ for (let dx = -1; dx <= 1; dx++) {
2373
+ let nx = (cx + dx + gridSize) % gridSize;
2374
+ let ny = (cy + dy + gridSize) % gridSize;
2375
+ let nz = (cz + dz + gridSize) % gridSize;
2376
+ neighbors.push(this.cells[nz][ny][nx]);
2377
+ }
2378
+ }
2379
+ }
2380
+ return neighbors;
2381
+ }
2382
+ addEntity(entity) {
2383
+ const cell = this.getCell(entity.x, entity.y, entity.z);
2384
+ cell.push(entity);
2385
+ }
2386
+ };
2387
+
2388
+ // src/tilemap.ts
2389
+ var Tilemap = class {
2390
+ map = /* @__PURE__ */ new Map();
2391
+ _key(x, y) {
2392
+ x = floor(x);
2393
+ y = floor(y);
2394
+ return `${x}x${y}`;
2395
+ }
2396
+ get(x, y) {
2397
+ return this.map.get(this._key(x, y));
2398
+ }
2399
+ set(x, y, v) {
2400
+ this.map.set(this._key(x, y), v);
2401
+ }
2402
+ };
2403
+
1177
2404
  // src/three/cube-sphere-geometry.ts
1178
2405
  var import_three = require("three");
1179
2406
  var CubeSphereGeometry = class extends import_three.BoxGeometry {
@@ -1193,6 +2420,8 @@ var CubeSphereGeometry = class extends import_three.BoxGeometry {
1193
2420
  }
1194
2421
  attrPositions.needsUpdate = true;
1195
2422
  }
2423
+ size;
2424
+ segments;
1196
2425
  _halfSize;
1197
2426
  applyFractalBrownianMotion(octaves, persistence, scale, amplitude) {
1198
2427
  const attrPositions = this.attributes.position;
@@ -1222,15 +2451,16 @@ var CubeSphereGeometry = class extends import_three.BoxGeometry {
1222
2451
  };
1223
2452
 
1224
2453
  // src/three/texture-atlas.ts
1225
- var import_gl_matrix4 = require("gl-matrix");
2454
+ var import_gl_matrix3 = require("gl-matrix");
1226
2455
  var import_three2 = require("three");
1227
2456
  function LoadTexture(url) {
1228
2457
  return new Promise((res, rej) => {
1229
2458
  new import_three2.TextureLoader().load(
1230
2459
  url,
1231
2460
  (texture) => {
1232
- const width = texture.source.data.width;
1233
- const height = texture.source.data.height;
2461
+ const data = texture.source.data;
2462
+ const width = data.width;
2463
+ const height = data.height;
1234
2464
  res({ width, height, texture });
1235
2465
  },
1236
2466
  (_ev) => {
@@ -1239,6 +2469,22 @@ function LoadTexture(url) {
1239
2469
  );
1240
2470
  });
1241
2471
  }
2472
+ function CreateSubTexture(texture, x, y, w, h) {
2473
+ texture = texture.clone();
2474
+ texture.magFilter = import_three2.NearestFilter;
2475
+ texture.wrapS = import_three2.RepeatWrapping;
2476
+ const data = texture.source.data;
2477
+ const textureWidth = data.width;
2478
+ const textureHeight = data.height;
2479
+ w /= textureWidth;
2480
+ h /= textureHeight;
2481
+ x /= textureWidth;
2482
+ y = 1 - h - y / textureHeight;
2483
+ texture.offset.set(x, y);
2484
+ texture.repeat.set(w, h);
2485
+ texture.needsUpdate = true;
2486
+ return texture;
2487
+ }
1242
2488
  var TextureAtlas = class _TextureAtlas extends import_three2.MeshLambertMaterial {
1243
2489
  constructor(textureData, textureWidth, textureHeight = textureWidth, params) {
1244
2490
  super({
@@ -1254,10 +2500,13 @@ var TextureAtlas = class _TextureAtlas extends import_three2.MeshLambertMaterial
1254
2500
  this._uh = this.textureHeight / this.textureData.height;
1255
2501
  this.textureData.texture.magFilter = import_three2.NearestFilter;
1256
2502
  }
2503
+ textureData;
2504
+ textureWidth;
2505
+ textureHeight;
1257
2506
  _uw;
1258
2507
  _uh;
1259
2508
  getUv(voxel, ux, uy) {
1260
- return import_gl_matrix4.vec2.fromValues(
2509
+ return import_gl_matrix3.vec2.fromValues(
1261
2510
  (voxel + ux) * this._uw,
1262
2511
  1 - (1 - uy) * this._uh
1263
2512
  );
@@ -1271,6 +2520,61 @@ var TextureAtlas = class _TextureAtlas extends import_three2.MeshLambertMaterial
1271
2520
  ));
1272
2521
  }
1273
2522
  };
2523
+ var AtlasTextureMaterial = class _AtlasTextureMaterial extends import_three2.MeshLambertMaterial {
2524
+ textureData;
2525
+ tilePixelWidth;
2526
+ tilePixelHeight;
2527
+ _tileCount;
2528
+ _uvWidth;
2529
+ _uvHeight;
2530
+ _textureOffsetWidth;
2531
+ _textureOffsetHeight;
2532
+ constructor(textureData, atlasParams = {}, materialParams = {}) {
2533
+ super({
2534
+ map: textureData.texture,
2535
+ alphaTest: 0.1,
2536
+ transparent: true,
2537
+ name: "AtlasTextureMaterial",
2538
+ ...materialParams
2539
+ });
2540
+ this.textureData = textureData;
2541
+ this.textureData.texture.magFilter = import_three2.NearestFilter;
2542
+ this.tilePixelWidth = atlasParams.tilePixelWidth ?? 16;
2543
+ this.tilePixelHeight = atlasParams.tilePixelHeight ?? 16;
2544
+ this._textureOffsetWidth = atlasParams.tilePixelOffsetWidth ?? 0;
2545
+ this._textureOffsetHeight = atlasParams.tilePixelOffsetHeight ?? 0;
2546
+ this._tileCount = Math.floor(this.textureData.width / this.tilePixelWidth);
2547
+ this._uvWidth = this.tilePixelWidth / (this.textureData.width - this._textureOffsetWidth);
2548
+ this._uvHeight = this.tilePixelHeight / (this.textureData.height - this._textureOffsetHeight);
2549
+ }
2550
+ getTileUVs(tileIndex, vertexIndex) {
2551
+ const col = tileIndex % this._tileCount;
2552
+ const row = Math.floor(tileIndex / this._tileCount);
2553
+ const baseU = this._textureOffsetWidth / this.textureData.width + col * this._uvWidth;
2554
+ const baseV = this._textureOffsetHeight / this.textureData.height + row * this._uvHeight;
2555
+ const uvCorners = [
2556
+ [0, 0],
2557
+ // bottom-left
2558
+ [1, 0],
2559
+ // bottom-right
2560
+ [0, 1],
2561
+ // top-left
2562
+ [1, 1]
2563
+ // top-right
2564
+ ];
2565
+ const [u, v] = uvCorners[vertexIndex];
2566
+ const uvx = baseU + u * this._uvWidth;
2567
+ const uvy = 1 - (baseV + v * this._uvHeight);
2568
+ return [uvx, uvy];
2569
+ }
2570
+ static fromUrl(url, atlasParams = {}, materialParams = {}) {
2571
+ return LoadTexture(url).then((textureData) => new _AtlasTextureMaterial(
2572
+ textureData,
2573
+ atlasParams,
2574
+ materialParams
2575
+ ));
2576
+ }
2577
+ };
1274
2578
 
1275
2579
  // src/three/threejs-boiler-plate.ts
1276
2580
  var import_three4 = require("three");
@@ -1292,7 +2596,7 @@ var ThreeJsCameraRig = class extends import_three3.Group {
1292
2596
  super();
1293
2597
  this.gimbal = new import_three3.Group();
1294
2598
  this.add(this.gimbal);
1295
- this.camera = new import_three3.PerspectiveCamera(
2599
+ this.camera = params?.camera ?? new import_three3.PerspectiveCamera(
1296
2600
  params?.fov ?? 75,
1297
2601
  params?.aspect ?? 2,
1298
2602
  params?.near ?? 0.1,
@@ -1325,6 +2629,7 @@ var ThreeJsBoilerPlate = class {
1325
2629
  raycaster = new import_three4.Raycaster();
1326
2630
  renderer;
1327
2631
  cameraRig;
2632
+ orbitControls;
1328
2633
  get canvas() {
1329
2634
  return this.renderer.domElement;
1330
2635
  }
@@ -1337,14 +2642,38 @@ var ThreeJsBoilerPlate = class {
1337
2642
  this.renderer = new import_three4.WebGLRenderer(params?.renderer);
1338
2643
  this.cameraRig = new ThreeJsCameraRig(params?.camera);
1339
2644
  this.scene.add(this.cameraRig);
1340
- GlobalEmitter.on("mouse_move", ({ deltaX, deltaY }) => {
2645
+ if (params?.parentElement) {
2646
+ this.appendTo(params.parentElement);
2647
+ }
2648
+ }
2649
+ // Mutually exclusive with enableOrbitControls() - pick one. Gives you
2650
+ // manual orbit()/dolly() with tilt clamping and target-following, driven
2651
+ // by this.input's mouse events.
2652
+ enableCameraRigControls() {
2653
+ this.orbitControls?.dispose();
2654
+ this.orbitControls = void 0;
2655
+ this.input.on("mouse_move", ({ deltaX, deltaY }) => {
1341
2656
  if (this.input.isMouseButtonDown(0)) {
1342
2657
  this.cameraRig.orbit(deltaX, deltaY);
1343
2658
  }
1344
2659
  }).on("mouse_wheel", ({ deltaY }) => this.cameraRig.dolly(deltaY));
1345
- if (params?.parentElement) {
1346
- this.appendTo(params.parentElement);
1347
- }
2660
+ }
2661
+ // Mutually exclusive with enableCameraRigControls() - pick one. Uses
2662
+ // Three's own OrbitControls instead of the hand-rolled rig math; call
2663
+ // update() once per frame in your render loop while this is active.
2664
+ // Async because OrbitControls only ships as an ESM-only addon module -
2665
+ // a dynamic import avoids forcing this whole package (built as both
2666
+ // CJS and ESM) to statically import an ESM-only file.
2667
+ async enableOrbitControls() {
2668
+ const { OrbitControls } = await import("three/examples/jsm/Addons.js");
2669
+ this.orbitControls = new OrbitControls(this.camera, this.canvas);
2670
+ this.orbitControls.minDistance = 0.5;
2671
+ this.orbitControls.maxDistance = 100;
2672
+ this.orbitControls.update();
2673
+ }
2674
+ // Call once per frame if enableOrbitControls() is active - no-op otherwise.
2675
+ update() {
2676
+ this.orbitControls?.update();
1348
2677
  }
1349
2678
  appendTo(htmlElement) {
1350
2679
  if (this.canvas.parentElement) {
@@ -1373,6 +2702,9 @@ var ThreeJsBoilerPlate = class {
1373
2702
  if (params.ambientLight !== false) this.scene.add(new import_three4.AmbientLight());
1374
2703
  if (params.directionalLight !== false) this.scene.add(new import_three4.DirectionalLight());
1375
2704
  if (params.gridHelper !== false) this.scene.add(new import_three4.GridHelper(100, 100, 16711680));
2705
+ if (params.enableControls === true) {
2706
+ this.enableCameraRigControls();
2707
+ }
1376
2708
  }
1377
2709
  pick() {
1378
2710
  const pickX = this.input.mousePosition[0] / this.renderer.domElement.width * 2 - 1;
@@ -1406,7 +2738,7 @@ var ThreeJsPlayerController = class extends import_three5.Group {
1406
2738
  constructor(camera) {
1407
2739
  super();
1408
2740
  this.velocity = new import_three5.Vector3();
1409
- this.cameraRig = new ThreeJsCameraRig(camera);
2741
+ this.cameraRig = new ThreeJsCameraRig({ camera });
1410
2742
  this.add(this.cameraRig);
1411
2743
  }
1412
2744
  update(deltaTime) {
@@ -1416,93 +2748,106 @@ var ThreeJsPlayerController = class extends import_three5.Group {
1416
2748
  }
1417
2749
  };
1418
2750
 
1419
- // src/three/voxel-geometry.ts
2751
+ // src/three/voxel-mesh.ts
1420
2752
  var import_three6 = require("three");
1421
- var import_gl_matrix5 = require("gl-matrix");
1422
- function xyz2key(x, y, z) {
1423
- return `${x},${y},${z}`;
1424
- }
1425
- function key2xyz(key) {
1426
- return key.split(",").map((v) => parseFloat(v));
1427
- }
1428
- var VoxelGeometry = class extends import_three6.BufferGeometry {
1429
- _voxels = /* @__PURE__ */ new Map();
1430
- colors = [
1431
- [1, 0, 0, 1],
1432
- // Red
1433
- [0, 1, 0, 1],
1434
- // Green
1435
- [0, 0, 1, 1]
1436
- // Blue
1437
- ];
1438
- constructor() {
2753
+ var VoxelMesh = class extends import_three6.Mesh {
2754
+ type = "VoxelMesh";
2755
+ width;
2756
+ depth;
2757
+ height;
2758
+ colorPalette;
2759
+ voxels;
2760
+ needsGeometryUpdate = true;
2761
+ constructor(width, depth, height, material, name) {
1439
2762
  super();
1440
- const size = 1;
1441
- for (let x = -size; x <= size; x++) {
1442
- for (let y = -size; y <= size; y++) {
1443
- for (let z = -size; z <= size; z++) {
1444
- this._voxels.set(xyz2key(x, y, z), 2);
1445
- }
1446
- }
1447
- }
2763
+ this.width = width;
2764
+ this.depth = depth;
2765
+ this.height = height;
2766
+ this.material = material;
2767
+ this.material.vertexColors = true;
2768
+ this.name = name ?? "VoxelMesh";
2769
+ this.colorPalette = BuildDefaultPalette();
2770
+ this.voxels = /* @__PURE__ */ new Map();
2771
+ this.geometry = new import_three6.BufferGeometry();
1448
2772
  this.updateGeometry();
1449
2773
  }
2774
+ _xyz2k(x, y, z) {
2775
+ x = Math.abs(Math.floor(x));
2776
+ y = Math.abs(Math.floor(y));
2777
+ z = Math.abs(Math.floor(z));
2778
+ return `${x},${y},${z}`;
2779
+ }
2780
+ _k2xyz(k) {
2781
+ const [x, y, z] = k.split(",").map((s) => parseInt(s));
2782
+ return { x, y, z };
2783
+ }
1450
2784
  get(x, y, z) {
1451
- return this._voxels.get(xyz2key(x, y, z));
1452
- }
1453
- set(x, y, z, value) {
1454
- this._voxels.set(xyz2key(x, y, z), value);
1455
- }
1456
- getVoxelCoordsFromFaceIndex(faceIndex, size, height) {
1457
- const facePerVoxel = 6;
1458
- const triangleIndex = Math.floor(faceIndex / 2);
1459
- const voxelIndex = Math.floor(triangleIndex / facePerVoxel);
1460
- const x = voxelIndex % size;
1461
- const y = Math.floor(voxelIndex / size % height);
1462
- const z = Math.floor(voxelIndex / (size * height));
1463
- return import_gl_matrix5.vec3.fromValues(x, y, z);
1464
- }
1465
- // public changeVoxelColor(faceIndex: number, newColor: THREE.Color) {
1466
- // const colorAttr = voxelMesh.geometry.getAttribute("color") as THREE.BufferAttribute;
1467
- // if (!colorAttr) return; // Ensure the color attribute exists
1468
- // const colors = colorAttr.array as Float32Array;
1469
- // // Each face has 3 vertices, each vertex has 4 components (RGBA)
1470
- // const vertexIndex = faceIndex * 3 * 4; // Multiply by 4 because each vertex has RGBA
1471
- // for (let i = 0; i < 3; i++) { // Update all three vertices of the face
1472
- // colors[vertexIndex + i * 4] = newColor.r;
1473
- // colors[vertexIndex + i * 4 + 1] = newColor.g;
1474
- // colors[vertexIndex + i * 4 + 2] = newColor.b;
1475
- // colors[vertexIndex + i * 4 + 3] = 1; // Ensure full opacity
1476
- // }
1477
- // colorAttr.needsUpdate = true; // Tell Three.js to update the buffer
1478
- // }
2785
+ let n = -1;
2786
+ if (x >= 0 && y >= 0 && z >= 0 && x < this.width && y < this.height && z < this.depth) {
2787
+ n = this.voxels.get(this._xyz2k(x, y, z)) ?? -1;
2788
+ }
2789
+ return n;
2790
+ }
2791
+ set(x, y, z, n) {
2792
+ if (x >= 0 && y >= 0 && z >= 0 && x < this.width && y < this.height && z < this.depth) {
2793
+ if (n === void 0) this.voxels.delete(this._xyz2k(x, y, z));
2794
+ else this.voxels.set(this._xyz2k(x, y, z), n);
2795
+ this.needsGeometryUpdate = true;
2796
+ }
2797
+ }
2798
+ clearVoxels() {
2799
+ this.voxels.clear();
2800
+ }
2801
+ setSize(width, depth, height) {
2802
+ this.forEachVoxel((x, y, z) => {
2803
+ if (x >= width || y >= height || z >= depth) this.set(x, y, z);
2804
+ });
2805
+ this.width = width;
2806
+ this.depth = depth;
2807
+ this.height = height;
2808
+ this.needsGeometryUpdate = true;
2809
+ }
2810
+ forEachVoxel(callback) {
2811
+ this.voxels.forEach((n, k) => {
2812
+ const { x, y, z } = this._k2xyz(k);
2813
+ callback(x, y, z, n);
2814
+ });
2815
+ }
2816
+ importVoxelData(voxelData) {
2817
+ this.clearVoxels();
2818
+ this.name = voxelData.name;
2819
+ this.setSize(voxelData.width, voxelData.depth, voxelData.height);
2820
+ voxelData.palette.forEach((color, i) => {
2821
+ if (i < this.colorPalette.length) {
2822
+ this.colorPalette[i] = color;
2823
+ } else {
2824
+ this.colorPalette.push(color);
2825
+ }
2826
+ });
2827
+ voxelData.voxels.forEach((voxel) => {
2828
+ const { x, y, z, color } = voxel;
2829
+ this.set(x, y, z, color);
2830
+ });
2831
+ this.updateGeometry();
2832
+ }
1479
2833
  updateGeometry() {
1480
- const positions = [];
1481
- const normals = [];
1482
- const colors = [];
1483
- const indices = [];
1484
- let needsUpdate = false;
1485
- this._voxels.forEach((voxel, key) => {
1486
- if (voxel) {
1487
- const [x, y, z] = key2xyz(key);
2834
+ if (this.needsGeometryUpdate) {
2835
+ const positions = [];
2836
+ const normals = [];
2837
+ const colors2 = [];
2838
+ const indices = [];
2839
+ this.forEachVoxel((x, y, z, n) => {
1488
2840
  VoxelFaces.forEach((faces) => {
1489
2841
  const [dx, dy, dz] = faces[0];
1490
- const neighborVoxel = this.get(x + dx, y + dy, z + dz) ?? 0;
1491
- if (!neighborVoxel) {
2842
+ const neighborVoxel = this.get(x + dx, y + dy, z + dz);
2843
+ if (neighborVoxel < 0) {
1492
2844
  const positionIndex = positions.length / 3;
1493
- faces.forEach((faceVerts) => {
1494
- const [
1495
- nx,
1496
- ny,
1497
- nz,
1498
- px,
1499
- py,
1500
- pz
1501
- /*ux, uy*/
1502
- ] = faceVerts;
2845
+ faces.forEach((face) => {
2846
+ const [nx, ny, nz, px, py, pz] = face;
1503
2847
  positions.push(x + px, y + py, z + pz);
1504
2848
  normals.push(nx, ny, nz);
1505
- colors.push(...this.colors[voxel - 1]);
2849
+ const { r, g, b } = new import_three6.Color(this.colorPalette[n]);
2850
+ colors2.push(r, g, b, 1);
1506
2851
  });
1507
2852
  indices.push(
1508
2853
  positionIndex,
@@ -1512,106 +2857,748 @@ var VoxelGeometry = class extends import_three6.BufferGeometry {
1512
2857
  positionIndex + 1,
1513
2858
  positionIndex + 3
1514
2859
  );
1515
- needsUpdate = true;
1516
2860
  }
1517
2861
  });
1518
- this.setAttribute("position", new import_three6.BufferAttribute(new Float32Array(positions), 3));
1519
- this.setAttribute("normal", new import_three6.BufferAttribute(new Float32Array(normals), 3));
1520
- this.setAttribute("color", new import_three6.BufferAttribute(new Float32Array(colors), 4));
1521
- this.setIndex(indices);
1522
- }
1523
- });
1524
- if (needsUpdate) {
1525
- this.attributes.position.needsUpdate = true;
1526
- this.computeVertexNormals();
2862
+ });
2863
+ this.geometry.setAttribute("position", new import_three6.BufferAttribute(new Float32Array(positions), 3));
2864
+ this.geometry.setAttribute("normal", new import_three6.BufferAttribute(new Float32Array(normals), 3));
2865
+ this.geometry.setAttribute("color", new import_three6.BufferAttribute(new Float32Array(colors2), 4));
2866
+ this.geometry.setIndex(indices);
2867
+ this.geometry.computeBoundingSphere();
2868
+ this.updateMatrixWorld();
1527
2869
  }
2870
+ this.needsGeometryUpdate = false;
2871
+ }
2872
+ exportData() {
2873
+ const voxelData = {
2874
+ name: this.name,
2875
+ width: this.width,
2876
+ depth: this.depth,
2877
+ height: this.height,
2878
+ palette: [...this.colorPalette],
2879
+ voxels: []
2880
+ };
2881
+ this.forEachVoxel((x, y, z, color) => {
2882
+ voxelData.voxels.push({ x, y, z, color });
2883
+ });
2884
+ return voxelData;
1528
2885
  }
1529
2886
  };
1530
- var lo = -0.5;
1531
- var hi = 0.5;
1532
2887
  var VoxelFaces = [
1533
- // [nx, ny, nz, px, py, pz, ux, uy]
2888
+ // [nx, ny, nz, px, py, pz]
1534
2889
  [
1535
2890
  //left
1536
- [-1, 0, 0, lo, hi, lo, 0, 1],
1537
- [-1, 0, 0, lo, lo, lo, 0, 0],
1538
- [-1, 0, 0, lo, hi, hi, 1, 1],
1539
- [-1, 0, 0, lo, lo, hi, 1, 0]
2891
+ [-1, 0, 0, 0, 1, 0],
2892
+ [-1, 0, 0, 0, 0, 0],
2893
+ [-1, 0, 0, 0, 1, 1],
2894
+ [-1, 0, 0, 0, 0, 1]
1540
2895
  ],
1541
2896
  [
1542
2897
  //right
1543
- [1, 0, 0, hi, hi, hi, 0, 1],
1544
- [1, 0, 0, hi, lo, hi, 0, 0],
1545
- [1, 0, 0, hi, hi, lo, 1, 1],
1546
- [1, 0, 0, hi, lo, lo, 1, 0]
2898
+ [1, 0, 0, 1, 1, 1],
2899
+ [1, 0, 0, 1, 0, 1],
2900
+ [1, 0, 0, 1, 1, 0],
2901
+ [1, 0, 0, 1, 0, 0]
1547
2902
  ],
1548
2903
  [
1549
2904
  //bottom
1550
- [0, -1, 0, hi, lo, hi, 1, 0],
1551
- [0, -1, 0, lo, lo, hi, 0, 0],
1552
- [0, -1, 0, hi, lo, lo, 1, 1],
1553
- [0, -1, 0, lo, lo, lo, 0, 1]
2905
+ [0, -1, 0, 1, 0, 1],
2906
+ [0, -1, 0, 0, 0, 1],
2907
+ [0, -1, 0, 1, 0, 0],
2908
+ [0, -1, 0, 0, 0, 0]
1554
2909
  ],
1555
2910
  [
1556
2911
  //top
1557
- [0, 1, 0, lo, hi, hi, 1, 1],
1558
- [0, 1, 0, hi, hi, hi, 0, 1],
1559
- [0, 1, 0, lo, hi, lo, 1, 0],
1560
- [0, 1, 0, hi, hi, lo, 0, 0]
2912
+ [0, 1, 0, 0, 1, 1],
2913
+ [0, 1, 0, 1, 1, 1],
2914
+ [0, 1, 0, 0, 1, 0],
2915
+ [0, 1, 0, 1, 1, 0]
1561
2916
  ],
1562
2917
  [
1563
2918
  //back
1564
- [0, 0, -1, hi, lo, lo, 0, 0],
1565
- [0, 0, -1, lo, lo, lo, 1, 0],
1566
- [0, 0, -1, hi, hi, lo, 0, 1],
1567
- [0, 0, -1, lo, hi, lo, 1, 1]
2919
+ [0, 0, -1, 1, 0, 0],
2920
+ [0, 0, -1, 0, 0, 0],
2921
+ [0, 0, -1, 1, 1, 0],
2922
+ [0, 0, -1, 0, 1, 0]
1568
2923
  ],
1569
2924
  [
1570
2925
  //front
1571
- [0, 0, 1, lo, lo, hi, 0, 0],
1572
- [0, 0, 1, hi, lo, hi, 1, 0],
1573
- [0, 0, 1, lo, hi, hi, 0, 1],
1574
- [0, 0, 1, hi, hi, hi, 1, 1]
2926
+ [0, 0, 1, 0, 0, 1],
2927
+ [0, 0, 1, 1, 0, 1],
2928
+ [0, 0, 1, 0, 1, 1],
2929
+ [0, 0, 1, 1, 1, 1]
1575
2930
  ]
1576
2931
  ];
2932
+ function BuildDefaultPalette(palette) {
2933
+ palette = palette ?? Colors.rgb48;
2934
+ const grayscale = [];
2935
+ const count = 16;
2936
+ for (let i = 0; i < count; i++) {
2937
+ const grey = Math.floor(i / count * 255);
2938
+ grayscale.push(`rgb(${grey}, ${grey}, ${grey})`);
2939
+ }
2940
+ return [...palette, ...grayscale];
2941
+ }
2942
+ var Colors = {
2943
+ rgb12: [
2944
+ "#FF0000",
2945
+ "#FF8800",
2946
+ "#FFFF00",
2947
+ "#88FF00",
2948
+ "#00FF00",
2949
+ "#00FF88",
2950
+ "#00FFFF",
2951
+ "#0088FF",
2952
+ "#0000FF",
2953
+ "#8800FF",
2954
+ "#FF00FF",
2955
+ "#FF0080"
2956
+ ],
2957
+ rgb24: [
2958
+ "#FF0000",
2959
+ "#FF4000",
2960
+ "#FF8000",
2961
+ "#FFBF00",
2962
+ "#FFFF00",
2963
+ "#CCFF00",
2964
+ "#80FF00",
2965
+ "#40FF00",
2966
+ "#00FF00",
2967
+ "#00FF40",
2968
+ "#00FF80",
2969
+ "#00FFCC",
2970
+ "#00FFFF",
2971
+ "#00CCFF",
2972
+ "#0080FF",
2973
+ "#0040FF",
2974
+ "#0000FF",
2975
+ "#4000FF",
2976
+ "#8000FF",
2977
+ "#CC00FF",
2978
+ "#FF00FF",
2979
+ "#FF00CC",
2980
+ "#FF0080",
2981
+ "#FF0040"
2982
+ ],
2983
+ rgb48: [
2984
+ "#FF0000",
2985
+ "#FF2000",
2986
+ "#FF4000",
2987
+ "#FF6000",
2988
+ "#FF8000",
2989
+ "#FFAA00",
2990
+ "#FFCC00",
2991
+ "#FFEE00",
2992
+ "#FFFF00",
2993
+ "#DDFF00",
2994
+ "#CCFF00",
2995
+ "#AAFF00",
2996
+ "#80FF00",
2997
+ "#60FF00",
2998
+ "#40FF00",
2999
+ "#20FF00",
3000
+ "#00FF00",
3001
+ "#00FF20",
3002
+ "#00FF40",
3003
+ "#00FF60",
3004
+ "#00FF80",
3005
+ "#00FFAA",
3006
+ "#00FFCC",
3007
+ "#00FFDD",
3008
+ "#00FFFF",
3009
+ "#00DDFF",
3010
+ "#00CCFF",
3011
+ "#0099FF",
3012
+ "#0080FF",
3013
+ "#0060FF",
3014
+ "#0040FF",
3015
+ "#0020FF",
3016
+ "#0000FF",
3017
+ "#2000FF",
3018
+ "#4000FF",
3019
+ "#6000FF",
3020
+ "#8000FF",
3021
+ "#AA00FF",
3022
+ "#CC00FF",
3023
+ "#DD00FF",
3024
+ "#FF00FF",
3025
+ "#FF00EE",
3026
+ "#FF00CC",
3027
+ "#FF00AA",
3028
+ "#FF0080",
3029
+ "#FF0060",
3030
+ "#FF0040",
3031
+ "#FF0020"
3032
+ ],
3033
+ rgb64: [
3034
+ "#000000",
3035
+ "#000055",
3036
+ "#0000AA",
3037
+ "#0000FF",
3038
+ "#005500",
3039
+ "#005555",
3040
+ "#0055AA",
3041
+ "#0055FF",
3042
+ "#00AA00",
3043
+ "#00AA55",
3044
+ "#00AAAA",
3045
+ "#00AAFF",
3046
+ "#00FF00",
3047
+ "#00FF55",
3048
+ "#00FFAA",
3049
+ "#00FFFF",
3050
+ "#550000",
3051
+ "#550055",
3052
+ "#5500AA",
3053
+ "#5500FF",
3054
+ "#555500",
3055
+ "#555555",
3056
+ "#5555AA",
3057
+ "#5555FF",
3058
+ "#55AA00",
3059
+ "#55AA55",
3060
+ "#55AAAA",
3061
+ "#55AAFF",
3062
+ "#55FF00",
3063
+ "#55FF55",
3064
+ "#55FFAA",
3065
+ "#55FFFF",
3066
+ "#AA0000",
3067
+ "#AA0055",
3068
+ "#AA00AA",
3069
+ "#AA00FF",
3070
+ "#AA5500",
3071
+ "#AA5555",
3072
+ "#AA55AA",
3073
+ "#AA55FF",
3074
+ "#AAAA00",
3075
+ "#AAAA55",
3076
+ "#AAAAAA",
3077
+ "#AAAAFF",
3078
+ "#AAFF00",
3079
+ "#AAFF55",
3080
+ "#AAFFAA",
3081
+ "#AAFFFF",
3082
+ "#FF0000",
3083
+ "#FF0055",
3084
+ "#FF00AA",
3085
+ "#FF00FF",
3086
+ "#FF5500",
3087
+ "#FF5555",
3088
+ "#FF55AA",
3089
+ "#FF55FF",
3090
+ "#FFAA00",
3091
+ "#FFAA55",
3092
+ "#FFAAAA",
3093
+ "#FFAAFF",
3094
+ "#FFFF00",
3095
+ "#FFFF55",
3096
+ "#FFFFAA",
3097
+ "#FFFFFF"
3098
+ ]
3099
+ };
3100
+
3101
+ // src/three/particle-system-3d.ts
3102
+ var import_three7 = require("three");
3103
+ var vertexShader = `
3104
+ uniform float pointSize;
3105
+
3106
+ varying vec4 vColor;
3107
+
3108
+ void main() {
3109
+ vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);
3110
+
3111
+ gl_Position = projectionMatrix * mvPosition;
3112
+ gl_PointSize = pointSize;
3113
+
3114
+ vColor = color;
3115
+ }`;
3116
+ var fragmentShader = `
3117
+ varying vec4 vColor;
3118
+
3119
+ void main() {
3120
+ gl_FragColor = vColor;
3121
+ }`;
3122
+ var Colors2 = [
3123
+ [1, 0, 0, 1],
3124
+ // red
3125
+ [0, 1, 0, 1],
3126
+ // green,
3127
+ [0, 0, 1, 1],
3128
+ // blue,
3129
+ [1, 1, 0, 1],
3130
+ // yellow,
3131
+ [1, 0, 1, 1]
3132
+ // magenta,
3133
+ ];
3134
+ var ParticleSystem3d = class extends import_three7.Group {
3135
+ particleCount = 1e3;
3136
+ _geometry;
3137
+ _particles = [];
3138
+ _frictionHalfLife = 0.04;
3139
+ _range = 0.2;
3140
+ _rangeFactor = 0.1;
3141
+ _attractionMatrix;
3142
+ _spatialPartition;
3143
+ constructor() {
3144
+ super();
3145
+ const uniforms = {
3146
+ pointSize: { value: 4 }
3147
+ };
3148
+ this.position.x = -0.5;
3149
+ this.position.y = -0.5;
3150
+ this.position.z = -0.5;
3151
+ this._geometry = new import_three7.BufferGeometry();
3152
+ this._geometry.setAttribute("position", new import_three7.Float32BufferAttribute([], 3));
3153
+ this._geometry.setAttribute("color", new import_three7.Float32BufferAttribute([], 4));
3154
+ const material = new import_three7.ShaderMaterial({
3155
+ uniforms,
3156
+ vertexShader,
3157
+ fragmentShader,
3158
+ depthTest: true,
3159
+ depthWrite: false,
3160
+ vertexColors: true
3161
+ });
3162
+ const pointsMesh = new import_three7.Points(this._geometry, material);
3163
+ this.add(pointsMesh);
3164
+ for (let i = 0; i < this.particleCount; i++) {
3165
+ this._particles.push({
3166
+ x: rng.nextf,
3167
+ y: rng.nextf,
3168
+ z: rng.nextf,
3169
+ vx: 0,
3170
+ vy: 0,
3171
+ vz: 0,
3172
+ color: rng.range(Colors2.length)
3173
+ });
3174
+ }
3175
+ this._attractionMatrix = rng.randomMatrix(Colors2.length);
3176
+ this._spatialPartition = new SpatialPartition3d(this._range, this._particles);
3177
+ }
3178
+ _calcForce(r, a, beta = 0.3) {
3179
+ let f = 0;
3180
+ if (r < beta) {
3181
+ f = r / beta - 1;
3182
+ } else if (beta < r && r < 1) {
3183
+ f = a * (1 - Math.abs(2 * r - 1 - beta) / (1 - beta));
3184
+ }
3185
+ return f;
3186
+ }
3187
+ _updateVelocities(dt) {
3188
+ const frictionFactor = Math.pow(
3189
+ 0.5,
3190
+ dt / this._frictionHalfLife
3191
+ );
3192
+ for (let z = 0; z < this._spatialPartition.cells.length; z++) {
3193
+ for (let y = 0; y < this._spatialPartition.cells[z].length; y++) {
3194
+ for (let x = 0; x < this._spatialPartition.cells[z][y].length; x++) {
3195
+ const cell = this._spatialPartition.cells[z][y][x];
3196
+ for (let i = 0; i < cell.length; i++) {
3197
+ let fx = 0, fy = 0, fz = 0;
3198
+ const p1 = cell[i];
3199
+ const neighbors = this._spatialPartition.getCellNeighbors(x, y, z);
3200
+ for (const neighborCell of neighbors) {
3201
+ for (let j = 0; j < neighborCell.length; j++) {
3202
+ if (cell === neighborCell && i === j) continue;
3203
+ const p2 = neighborCell[j];
3204
+ let dx = p2.x - p1.x;
3205
+ let dy = p2.y - p1.y;
3206
+ let dz = p2.z - p1.z;
3207
+ if (Math.abs(dx) > 0.5) dx = dx > 0 ? dx - 1 : dx + 1;
3208
+ if (Math.abs(dy) > 0.5) dy = dy > 0 ? dy - 1 : dy + 1;
3209
+ if (Math.abs(dz) > 0.5) dz = dz > 0 ? dz - 1 : dz + 1;
3210
+ const dist = Math.hypot(dx, dy, dz);
3211
+ if (dist > 0 && dist < this._range) {
3212
+ const f = this._calcForce(dist / this._range, this._attractionMatrix[p1.color][p2.color]);
3213
+ fx += dx / dist * f;
3214
+ fy += dy / dist * f;
3215
+ fz += dz / dist * f;
3216
+ }
3217
+ }
3218
+ }
3219
+ fx *= this._range * this._rangeFactor;
3220
+ fy *= this._range * this._rangeFactor;
3221
+ fz *= this._range * this._rangeFactor;
3222
+ p1.vx *= frictionFactor;
3223
+ p1.vy *= frictionFactor;
3224
+ p1.vz *= frictionFactor;
3225
+ p1.vx += fx;
3226
+ p1.vy += fy;
3227
+ p1.vz += fz;
3228
+ }
3229
+ }
3230
+ }
3231
+ }
3232
+ }
3233
+ _updatePositions(dt) {
3234
+ for (let i = 0; i < this._particles.length; i++) {
3235
+ const particle = this._particles[i];
3236
+ const oldCell = this._spatialPartition.getCell(particle.x, particle.y, particle.z);
3237
+ particle.x += particle.vx * dt;
3238
+ particle.y += particle.vy * dt;
3239
+ particle.z += particle.vz * dt;
3240
+ if (particle.x < 0) particle.x = (particle.x + 1) % 1;
3241
+ if (particle.x > 1) particle.x = particle.x % 1;
3242
+ if (particle.y < 0) particle.y = (particle.y + 1) % 1;
3243
+ if (particle.y > 1) particle.y = particle.y % 1;
3244
+ if (particle.z < 0) particle.z = (particle.z + 1) % 1;
3245
+ if (particle.z > 1) particle.z = particle.z % 1;
3246
+ const newCell = this._spatialPartition.getCell(particle.x, particle.y, particle.z);
3247
+ if (newCell !== oldCell) {
3248
+ const index = oldCell.indexOf(particle);
3249
+ if (index !== -1) {
3250
+ oldCell.splice(index, 1);
3251
+ }
3252
+ newCell.push(particle);
3253
+ }
3254
+ }
3255
+ }
3256
+ _sortParticles(camera) {
3257
+ this._particles.sort((a, b) => {
3258
+ const d1 = camera.position.distanceTo(new import_three7.Vector3(a.x, a.y, a.z));
3259
+ const d2 = camera.position.distanceTo(new import_three7.Vector3(b.x, b.y, b.z));
3260
+ return d1 > d2 ? -1 : d1 > d1 ? 1 : 0;
3261
+ });
3262
+ }
3263
+ _updateGeometry() {
3264
+ const positions = [];
3265
+ const colors2 = [];
3266
+ for (const particle of this._particles) {
3267
+ positions.push(
3268
+ particle.x,
3269
+ particle.y,
3270
+ particle.z
3271
+ );
3272
+ colors2.push(
3273
+ Colors2[particle.color][0],
3274
+ Colors2[particle.color][1],
3275
+ Colors2[particle.color][2],
3276
+ Colors2[particle.color][3]
3277
+ );
3278
+ }
3279
+ this._geometry.setAttribute("position", new import_three7.Float32BufferAttribute(positions, 3));
3280
+ this._geometry.setAttribute("color", new import_three7.Float32BufferAttribute(colors2, 4));
3281
+ this._geometry.attributes.position.needsUpdate = true;
3282
+ }
3283
+ update(camera, dt) {
3284
+ this._updateVelocities(dt);
3285
+ this._updatePositions(dt);
3286
+ this._sortParticles(camera);
3287
+ this._updateGeometry();
3288
+ }
3289
+ };
3290
+
3291
+ // src/three/asteroid-mesh.ts
3292
+ var import_three8 = require("three");
3293
+ var import_simplex_noise2 = require("simplex-noise");
3294
+ var AsteroidMesh = class extends import_three8.Mesh {
3295
+ constructor(options = {}) {
3296
+ const radius = options.radius ?? 1;
3297
+ const detail = options.detail ?? 1;
3298
+ const noiseScale = options.noiseScale ?? 1;
3299
+ const displacement = options.displacement ?? 0.1;
3300
+ const secondaryNoise = options.secondaryNoise ?? false;
3301
+ const color = options.color ?? 8947848;
3302
+ const geometry = new import_three8.IcosahedronGeometry(radius, detail);
3303
+ const material = new import_three8.MeshStandardMaterial({ color });
3304
+ super(geometry, material);
3305
+ const noise3d = (0, import_simplex_noise2.createNoise3D)(() => rng.nextf);
3306
+ const noise3d2 = secondaryNoise ? (0, import_simplex_noise2.createNoise3D)(() => rng.nextf) : null;
3307
+ const position = this.geometry.attributes.position;
3308
+ const vertices = position.array;
3309
+ for (let i = 0; i < vertices.length; i += 3) {
3310
+ const x = vertices[i];
3311
+ const y = vertices[i + 1];
3312
+ const z = vertices[i + 2];
3313
+ const n1 = noise3d(x * noiseScale, y * noiseScale, z * noiseScale);
3314
+ const n2 = secondaryNoise ? 0.5 * noise3d2(x * noiseScale * 2, y * noiseScale * 2, z * noiseScale * 2) : 0;
3315
+ const noiseValue = n1 + n2;
3316
+ const displacementValue = 1 + noiseValue * displacement;
3317
+ vertices[i] = x * displacementValue;
3318
+ vertices[i + 1] = y * displacementValue;
3319
+ vertices[i + 2] = z * displacementValue;
3320
+ }
3321
+ position.needsUpdate = true;
3322
+ this.geometry.computeVertexNormals();
3323
+ }
3324
+ };
3325
+
3326
+ // src/three/starfield.ts
3327
+ var import_three9 = require("three");
3328
+ function CreateStarfield(radius = 1e3, count = 5e3, color = 16777215) {
3329
+ const geometry = new import_three9.BufferGeometry();
3330
+ const positions = new Float32Array(count * 3);
3331
+ for (let i = 0; i < count; i++) {
3332
+ const theta = rng.nextf * Math.PI * 2;
3333
+ const phi = Math.acos(rng.nextf * 2 - 1);
3334
+ const x = radius * Math.sin(phi) * Math.cos(theta);
3335
+ const y = radius * Math.sin(phi) * Math.sin(theta);
3336
+ const z = radius * Math.cos(phi);
3337
+ positions.set([x, y, z], i * 3);
3338
+ }
3339
+ geometry.setAttribute("position", new import_three9.BufferAttribute(positions, 3));
3340
+ const material = new import_three9.PointsMaterial({
3341
+ color,
3342
+ size: 5,
3343
+ sizeAttenuation: true,
3344
+ transparent: true,
3345
+ opacity: 0.9
3346
+ });
3347
+ const stars = new import_three9.Points(geometry, material);
3348
+ stars.name = "Starfield";
3349
+ return stars;
3350
+ }
3351
+ function CreateSystemStar(position) {
3352
+ const star = new import_three9.Group();
3353
+ const starPos = position ?? new import_three9.Vector3();
3354
+ const starGeo = new import_three9.SphereGeometry(50, 32, 32);
3355
+ const starMat = new import_three9.MeshBasicMaterial({ color: 16768426 });
3356
+ const starMesh = new import_three9.Mesh(starGeo, starMat);
3357
+ starMesh.position.copy(starPos);
3358
+ star.add(starMesh);
3359
+ const starLight = new import_three9.PointLight(16777215, 10, 0, 0);
3360
+ starLight.position.copy(starPos);
3361
+ star.add(starLight);
3362
+ return star;
3363
+ }
3364
+
3365
+ // src/three/palette-controller.ts
3366
+ var import_three10 = require("three");
3367
+ async function CreatePaletteController(parentGui, colorPalette, onChange, folderName = "palette") {
3368
+ const { Controller } = await import("three/examples/jsm/libs/lil-gui.module.min.js");
3369
+ class PaletteControllerImpl extends Controller {
3370
+ $innerDiv;
3371
+ colorButtons = [];
3372
+ colorButtonSize = 20;
3373
+ selectedBorderStyle = "2px dashed black";
3374
+ currentColorIndex = 0;
3375
+ eyedropperButton;
3376
+ colorPalette;
3377
+ _onColorChange;
3378
+ constructor() {
3379
+ const parent = parentGui.addFolder(folderName);
3380
+ super(parent, {}, "", "function");
3381
+ this.colorPalette = colorPalette;
3382
+ this._onColorChange = onChange;
3383
+ this.$widget.style.setProperty("display", "flex");
3384
+ this.$widget.style.setProperty("justify-content", "center");
3385
+ this.$innerDiv = document.createElement("div");
3386
+ this.$innerDiv.style.setProperty("display", "flex");
3387
+ this.$innerDiv.style.setProperty("flex-wrap", "wrap");
3388
+ this.$innerDiv.style.setProperty("width", `${this.colorButtonSize * Math.floor(Math.sqrt(this.colorPalette.length)) + 2}px`);
3389
+ this.$innerDiv.appendChild(this.$name);
3390
+ this.$widget.appendChild(this.$innerDiv);
3391
+ this.colorPalette.forEach((color) => this._createColorButton(color));
3392
+ if (window.EyeDropper) {
3393
+ this.eyedropperButton = parent.add({
3394
+ eyedropper: () => {
3395
+ this.eyedropperButton?.disable(true);
3396
+ new window.EyeDropper().open().then(({ sRGBHex }) => {
3397
+ const i = this.findClosestColorMatchIndex(sRGBHex);
3398
+ this.setSelectedColor(i);
3399
+ this._onColorChange?.(i);
3400
+ }).finally(() => this.eyedropperButton?.disable(false)).catch(() => {
3401
+ });
3402
+ }
3403
+ }, "eyedropper").name("findClosestColor");
3404
+ }
3405
+ this.name("");
3406
+ this.updateDisplay();
3407
+ }
3408
+ _onColorButtonClicked(i, button) {
3409
+ if (button === 0) {
3410
+ this.setSelectedColor(i);
3411
+ this._onColorChange?.(i);
3412
+ this.colorButtons[i].blur();
3413
+ } else if (button === 2 && window.EyeDropper) {
3414
+ new window.EyeDropper().open().then(({ sRGBHex }) => {
3415
+ this.colorPalette[i] = sRGBHex;
3416
+ this.colorButtons[i].setAttribute("title", `${sRGBHex}`);
3417
+ this.colorButtons[i].style.setProperty("background", sRGBHex);
3418
+ this.setSelectedColor(i);
3419
+ this._onColorChange?.(i);
3420
+ this.colorButtons[i].blur();
3421
+ }).finally(() => this.eyedropperButton?.disable(false)).catch(() => {
3422
+ });
3423
+ }
3424
+ }
3425
+ _createColorButton(color) {
3426
+ const i = this.colorButtons.length;
3427
+ const colorButton = document.createElement("div");
3428
+ colorButton.setAttribute("id", `colorButton${i}`);
3429
+ colorButton.setAttribute("title", `${color}`);
3430
+ colorButton.style.setProperty("width", `${this.colorButtonSize}px`);
3431
+ colorButton.style.setProperty("height", `${this.colorButtonSize}px`);
3432
+ colorButton.style.setProperty("background", color);
3433
+ colorButton.addEventListener("pointerup", (ev) => this._onColorButtonClicked(i, ev.button));
3434
+ this.colorButtons.push(colorButton);
3435
+ this.$innerDiv.appendChild(colorButton);
3436
+ }
3437
+ updatePaletteColors() {
3438
+ this.colorPalette.forEach((color, i) => {
3439
+ if (i < this.colorButtons.length) {
3440
+ this.colorButtons[i].setAttribute("title", `${color}`);
3441
+ this.colorButtons[i].style.setProperty("background", color);
3442
+ } else {
3443
+ this._createColorButton(color);
3444
+ }
3445
+ });
3446
+ }
3447
+ setSelectedColor(colorIndex = 0) {
3448
+ this.colorButtons[this.currentColorIndex].style.removeProperty("border");
3449
+ this.currentColorIndex = clamp(colorIndex, 0, this.colorPalette.length);
3450
+ this.colorButtons[this.currentColorIndex].style.setProperty("border", this.selectedBorderStyle);
3451
+ }
3452
+ findClosestColorMatchIndex(color) {
3453
+ const pickedColor = new import_three10.Color(color);
3454
+ const pickedVector = new import_three10.Vector3().setFromColor(pickedColor);
3455
+ const list = [];
3456
+ this.colorPalette.forEach((paletteColorString, i) => {
3457
+ const paletteColor = new import_three10.Color(paletteColorString);
3458
+ const paletteVector = new import_three10.Vector3().setFromColor(paletteColor);
3459
+ const d = paletteVector.distanceTo(pickedVector);
3460
+ list.push({ i, d });
3461
+ });
3462
+ list.sort((a, b) => a.d - b.d);
3463
+ const closest = list.shift();
3464
+ return closest?.i ?? 0;
3465
+ }
3466
+ }
3467
+ return new PaletteControllerImpl();
3468
+ }
3469
+
3470
+ // src/three/ecs.ts
3471
+ var import_three11 = require("three");
3472
+ var entityCounter = 0;
3473
+ function GenerateEntityId() {
3474
+ return `entity_${entityCounter++}`;
3475
+ }
3476
+ function CreateThreeEntity(obj) {
3477
+ const entity = obj ?? new import_three11.Group();
3478
+ entity.userData.entityId = GenerateEntityId();
3479
+ entity.userData.components = {};
3480
+ return entity;
3481
+ }
3482
+ function AddThreeComponent(entity, name, component) {
3483
+ entity.userData.components[name] = component;
3484
+ }
3485
+ function GetThreeComponent(entity, name) {
3486
+ return entity.userData.components[name];
3487
+ }
3488
+ function RemoveThreeComponent(entity, name) {
3489
+ delete entity.userData.components[name];
3490
+ }
3491
+ function IsThreeEntity(obj) {
3492
+ return obj.userData.entityId !== void 0;
3493
+ }
3494
+
3495
+ // src/worker-interface.ts
3496
+ var WorkerInterface = class extends Emitter {
3497
+ _worker;
3498
+ constructor(url) {
3499
+ super();
3500
+ this._worker = new Worker(url, { type: "module" });
3501
+ this._worker.onerror = (error) => this.emit("error", error);
3502
+ this._worker.onmessage = (message) => this.emit("message", message);
3503
+ }
3504
+ postMessage(message, options) {
3505
+ this._worker.postMessage(message, options);
3506
+ }
3507
+ terminate() {
3508
+ this._worker.terminate();
3509
+ }
3510
+ };
1577
3511
  // Annotate the CommonJS export names for ESM import in node:
1578
3512
  0 && (module.exports = {
3513
+ AStar,
3514
+ AddThreeComponent,
3515
+ AsteroidMesh,
3516
+ AtlasTextureMaterial,
3517
+ BuildDefaultPalette,
1579
3518
  CanvasRenderer,
1580
3519
  Clock,
1581
3520
  ClockStats,
3521
+ Color,
3522
+ Colors,
1582
3523
  CompileShader,
3524
+ CreatePaletteController,
1583
3525
  CreateProgram,
1584
3526
  CreateProgramInfo,
3527
+ CreateStarfield,
3528
+ CreateSubTexture,
3529
+ CreateSystemStar,
3530
+ CreateThreeEntity,
1585
3531
  CreateWebGlContext,
1586
3532
  CubeSphereGeometry,
1587
3533
  ECS,
1588
3534
  Emitter,
3535
+ EventBus,
3536
+ GenerateDoors,
3537
+ GenerateEntityId,
3538
+ GenerateRooms,
3539
+ GenerateWalls,
1589
3540
  GetProgramLocations,
3541
+ GetThreeComponent,
1590
3542
  GlobalEmitter,
1591
3543
  Input,
3544
+ IsThreeEntity,
1592
3545
  LoadTexture,
3546
+ Map2D,
3547
+ Map3D,
1593
3548
  Noise,
3549
+ PI,
3550
+ ParticleSystem2d,
3551
+ ParticleSystem3d,
3552
+ PoissonDiskSampler,
3553
+ Rectangle,
3554
+ RemoveThreeComponent,
3555
+ Renderer,
1594
3556
  ResizeWebGlContext,
1595
3557
  Rng,
1596
3558
  ShaderType,
1597
3559
  SimplexNoise,
3560
+ SpatialPartition2d,
3561
+ SpatialPartition3d,
3562
+ TILE_EMPTY,
3563
+ TILE_FLOOR,
3564
+ TILE_PATH,
1598
3565
  TextureAtlas,
1599
3566
  ThreeJsBoilerPlate,
1600
3567
  ThreeJsCameraRig,
1601
3568
  ThreeJsPlayerController,
1602
- VoxelGeometry,
3569
+ Tilemap,
3570
+ Vector,
3571
+ VoxelFaces,
3572
+ VoxelMesh,
1603
3573
  WebGlRenderer,
3574
+ WorkerInterface,
3575
+ abs,
3576
+ ceil,
1604
3577
  clamp,
3578
+ cos,
1605
3579
  deg2rad,
3580
+ distance,
3581
+ eventBus,
3582
+ floor,
1606
3583
  getRedYellowGreenGradientHex,
3584
+ hypot2,
3585
+ hypot3,
3586
+ imul,
1607
3587
  isNullOrUndefined,
1608
- key2xyz,
1609
3588
  lerp,
1610
3589
  log,
1611
3590
  logdev,
1612
3591
  logerr,
1613
3592
  loginf,
1614
3593
  logwrn,
3594
+ manhattanDistance,
3595
+ max,
3596
+ min,
3597
+ pow,
1615
3598
  rng,
1616
- xyz2key
3599
+ round,
3600
+ roundTo,
3601
+ sin,
3602
+ sqrt,
3603
+ squaredDistance
1617
3604
  });