@n3rdw1z4rd/core 0.17.2 → 0.18.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.mjs CHANGED
@@ -1,288 +1,3 @@
1
- var __create = Object.create;
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __getProtoOf = Object.getPrototypeOf;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __esm = (fn, res) => function __init() {
8
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
9
- };
10
- var __commonJS = (cb, mod2) => function __require() {
11
- return mod2 || (0, cb[__getOwnPropNames(cb)[0]])((mod2 = { exports: {} }).exports, mod2), mod2.exports;
12
- };
13
- var __export = (target, all) => {
14
- for (var name in all)
15
- __defProp(target, name, { get: all[name], enumerable: true });
16
- };
17
- var __copyProps = (to, from, except, desc) => {
18
- if (from && typeof from === "object" || typeof from === "function") {
19
- for (let key of __getOwnPropNames(from))
20
- if (!__hasOwnProp.call(to, key) && key !== except)
21
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
22
- }
23
- return to;
24
- };
25
- var __reExport = (target, mod2, secondTarget) => (__copyProps(target, mod2, "default"), secondTarget && __copyProps(secondTarget, mod2, "default"));
26
- var __toESM = (mod2, isNodeMode, target) => (target = mod2 != null ? __create(__getProtoOf(mod2)) : {}, __copyProps(
27
- // If the importer is in node compatibility mode or this is not an ESM
28
- // file that has been converted to a CommonJS file using a Babel-
29
- // compatible transform (i.e. "__esModule" has not been set), then set
30
- // "default" to the CommonJS "module.exports" for node compatibility.
31
- isNodeMode || !mod2 || !mod2.__esModule ? __defProp(target, "default", { value: mod2, enumerable: true }) : target,
32
- mod2
33
- ));
34
-
35
- // src/css/main.css
36
- var init_main = __esm({
37
- "src/css/main.css"() {
38
- }
39
- });
40
-
41
- // src/css/index.ts
42
- var require_css = __commonJS({
43
- "src/css/index.ts"() {
44
- "use strict";
45
- init_main();
46
- }
47
- });
48
-
49
- // src/index.ts
50
- var index_exports = {};
51
- __export(index_exports, {
52
- AStar: () => AStar,
53
- AddThreeComponent: () => AddThreeComponent,
54
- AsteroidMesh: () => AsteroidMesh,
55
- AtlasTextureMaterial: () => AtlasTextureMaterial,
56
- BuildDefaultPalette: () => BuildDefaultPalette,
57
- CanvasRenderer: () => CanvasRenderer,
58
- Clock: () => Clock,
59
- Color: () => Color,
60
- Colors: () => Colors,
61
- CompileShader: () => CompileShader,
62
- CreatePaletteController: () => CreatePaletteController,
63
- CreateProgram: () => CreateProgram,
64
- CreateProgramInfo: () => CreateProgramInfo,
65
- CreateStarfield: () => CreateStarfield,
66
- CreateSubTexture: () => CreateSubTexture,
67
- CreateSystemStar: () => CreateSystemStar,
68
- CreateThreeEntity: () => CreateThreeEntity,
69
- CreateWebGlContext: () => CreateWebGlContext,
70
- CubeSphereGeometry: () => CubeSphereGeometry,
71
- DEFAULT_COLOR: () => DEFAULT_COLOR,
72
- DEFAULT_FONT: () => DEFAULT_FONT,
73
- DEFAULT_FONT_NAME: () => DEFAULT_FONT_NAME,
74
- DEFAULT_FONT_SIZE: () => DEFAULT_FONT_SIZE,
75
- DEFAULT_PIXEL_SIZE: () => DEFAULT_PIXEL_SIZE,
76
- DEFAULT_TEXTALIGN: () => DEFAULT_TEXTALIGN,
77
- DEFAULT_TEXTBASELINE: () => DEFAULT_TEXTBASELINE,
78
- DEG2RAD: () => DEG2RAD,
79
- DOWN: () => DOWN,
80
- Disposable: () => Disposable,
81
- E: () => E,
82
- ECS: () => ECS,
83
- EPSILON: () => EPSILON,
84
- EventQueue: () => EventQueue,
85
- GenerateDoors: () => GenerateDoors,
86
- GenerateEntityId: () => GenerateEntityId,
87
- GenerateRooms: () => GenerateRooms,
88
- GenerateWalls: () => GenerateWalls,
89
- GetProgramLocations: () => GetProgramLocations,
90
- GetThreeComponent: () => GetThreeComponent,
91
- GetUrlParams: () => GetUrlParams,
92
- HALF_PI: () => HALF_PI,
93
- Input: () => Input,
94
- IsThreeEntity: () => IsThreeEntity,
95
- LN10: () => LN10,
96
- LN2: () => LN2,
97
- LOG10E: () => LOG10E,
98
- LOG2E: () => LOG2E,
99
- LoadTexture: () => LoadTexture,
100
- Map2D: () => Map2D,
101
- Map3D: () => Map3D,
102
- Noise: () => Noise,
103
- Observable: () => Observable,
104
- PI: () => PI,
105
- ParticleRenderer: () => ParticleRenderer,
106
- ParticleSystem2d: () => ParticleSystem2d,
107
- ParticleSystem3d: () => ParticleSystem3d,
108
- PoissonDiskSampler: () => PoissonDiskSampler,
109
- QUARTER_PI: () => QUARTER_PI,
110
- RAD2DEG: () => RAD2DEG,
111
- Random: () => Random,
112
- RandomTools: () => RandomTools,
113
- Rectangle: () => Rectangle,
114
- RemoveThreeComponent: () => RemoveThreeComponent,
115
- ResizeWebGlContext: () => ResizeWebGlContext,
116
- SQRT1_2: () => SQRT1_2,
117
- SQRT2: () => SQRT2,
118
- ShaderType: () => ShaderType,
119
- Signal: () => Signal,
120
- SimplexNoise: () => SimplexNoise,
121
- SpatialPartition2d: () => SpatialPartition2d,
122
- SpatialPartition3d: () => SpatialPartition3d,
123
- TAU: () => TAU,
124
- TILE_EMPTY: () => TILE_EMPTY,
125
- TILE_FLOOR: () => TILE_FLOOR,
126
- TILE_PATH: () => TILE_PATH,
127
- TextureAtlas: () => TextureAtlas,
128
- ThreeJsBoilerPlate: () => ThreeJsBoilerPlate,
129
- ThreeJsCameraRig: () => ThreeJsCameraRig,
130
- ThreeJsPlayerController: () => ThreeJsPlayerController,
131
- Tilemap: () => Tilemap,
132
- UP: () => UP,
133
- Vector: () => Vector,
134
- VoxelFaces: () => VoxelFaces,
135
- VoxelMesh: () => VoxelMesh,
136
- WebGlRenderer: () => WebGlRenderer,
137
- WorkerInterface: () => WorkerInterface,
138
- abs: () => abs,
139
- acos: () => acos,
140
- asin: () => asin,
141
- atan: () => atan,
142
- atan2: () => atan2,
143
- cbrt: () => cbrt,
144
- ceil: () => ceil,
145
- clamp: () => clamp,
146
- cos: () => cos,
147
- cosh: () => cosh,
148
- degrees: () => degrees,
149
- distance2d: () => distance2d,
150
- distance3d: () => distance3d,
151
- exp: () => exp,
152
- expm1: () => expm1,
153
- floor: () => floor,
154
- fract: () => fract,
155
- getRedYellowGreenGradientHex: () => getRedYellowGreenGradientHex,
156
- hypot: () => hypot,
157
- hypot2: () => hypot2,
158
- hypot3: () => hypot3,
159
- imul: () => imul,
160
- inverseLerp: () => inverseLerp,
161
- isFinite: () => isFinite,
162
- isInteger: () => isInteger,
163
- isNaN: () => isNaN,
164
- isNullOrUndefined: () => isNullOrUndefined,
165
- isPositiveString: () => isPositiveString,
166
- k2xy: () => k2xy,
167
- k2xyz: () => k2xyz,
168
- lerp: () => lerp,
169
- log: () => log,
170
- log10: () => log10,
171
- log1p: () => log1p,
172
- log2: () => log2,
173
- manhattanDistance: () => manhattanDistance,
174
- map: () => map,
175
- max: () => max,
176
- min: () => min,
177
- mod: () => mod,
178
- nearlyEqual: () => nearlyEqual,
179
- normalizeRadians: () => normalizeRadians,
180
- pow: () => pow,
181
- radians: () => radians,
182
- randomMatrix: () => randomMatrix,
183
- rng: () => rng,
184
- round: () => round,
185
- roundTo: () => roundTo,
186
- saturate: () => saturate,
187
- sign: () => sign,
188
- sin: () => sin,
189
- sinh: () => sinh,
190
- smoothstep: () => smoothstep,
191
- sqrt: () => sqrt,
192
- squaredDistance: () => squaredDistance,
193
- tan: () => tan,
194
- tanh: () => tanh,
195
- trunc: () => trunc,
196
- wrap: () => wrap,
197
- xy2k: () => xy2k,
198
- xyz2k: () => xyz2k
199
- });
200
-
201
- // src/math.ts
202
- var PI = Math.PI;
203
- var TAU = Math.PI * 2;
204
- var HALF_PI = Math.PI / 2;
205
- var QUARTER_PI = Math.PI / 4;
206
- var E = Math.E;
207
- var DEG2RAD = PI / 180;
208
- var RAD2DEG = 180 / PI;
209
- var LN2 = Math.LN2;
210
- var LN10 = Math.LN10;
211
- var LOG2E = Math.LOG2E;
212
- var LOG10E = Math.LOG10E;
213
- var SQRT2 = Math.SQRT2;
214
- var SQRT1_2 = Math.SQRT1_2;
215
- var EPSILON = Number.EPSILON;
216
- var abs = Math.abs;
217
- var min = Math.min;
218
- var max = Math.max;
219
- var floor = Math.floor;
220
- var ceil = Math.ceil;
221
- var round = Math.round;
222
- var trunc = Math.trunc;
223
- var sign = Math.sign;
224
- var sqrt = Math.sqrt;
225
- var cbrt = Math.cbrt;
226
- var pow = Math.pow;
227
- var exp = Math.exp;
228
- var expm1 = Math.expm1;
229
- var log = Math.log;
230
- var log1p = Math.log1p;
231
- var log2 = Math.log2;
232
- var log10 = Math.log10;
233
- var hypot = Math.hypot;
234
- var imul = Math.imul;
235
- var sin = Math.sin;
236
- var cos = Math.cos;
237
- var tan = Math.tan;
238
- var asin = Math.asin;
239
- var acos = Math.acos;
240
- var atan = Math.atan;
241
- var atan2 = Math.atan2;
242
- var sinh = Math.sinh;
243
- var cosh = Math.cosh;
244
- var tanh = Math.tanh;
245
- var clamp = (value, minValue, maxValue) => min(max(value, minValue), maxValue);
246
- var saturate = (value) => clamp(value, 0, 1);
247
- var lerp = (start, end, t) => start + (end - start) * t;
248
- var inverseLerp = (start, end, value) => (value - start) / (end - start);
249
- var map = (value, inMin, inMax, outMin, outMax) => outMin + (value - inMin) * (outMax - outMin) / (inMax - inMin);
250
- var smoothstep = (edge0, edge1, value) => {
251
- const t = saturate((value - edge0) / (edge1 - edge0));
252
- return t * t * (3 - 2 * t);
253
- };
254
- var fract = (value) => value - floor(value);
255
- var mod = (value, divisor) => (value % divisor + divisor) % divisor;
256
- var wrap = (value, minValue, maxValue) => {
257
- const range = maxValue - minValue;
258
- return minValue + mod(value - minValue, range);
259
- };
260
- var radians = (degrees2) => degrees2 * DEG2RAD;
261
- var degrees = (radians2) => radians2 * RAD2DEG;
262
- var normalizeRadians = (radians2) => wrap(radians2, -PI, PI);
263
- var hypot2 = (x, y) => hypot(x, y);
264
- var hypot3 = (x, y, z) => hypot(x, y, z);
265
- var distance2d = (x1, y1, x2, y2) => hypot(x2 - x1, y2 - y1);
266
- var distance3d = (x1, y1, z1, x2, y2, z2) => hypot(
267
- x2 - x1,
268
- y2 - y1,
269
- z2 - z1
270
- );
271
- var squaredDistance = (x1, y1, x2, y2) => {
272
- const dx = x2 - x1;
273
- const dy = y2 - y1;
274
- return dx * dx + dy * dy;
275
- };
276
- var manhattanDistance = (x1, y1, x2, y2) => abs(x2 - x1) + abs(y2 - y1);
277
- var nearlyEqual = (a, b, epsilon = EPSILON) => abs(a - b) <= epsilon;
278
- var roundTo = (value, digits = 0) => {
279
- const factor = 10 ** digits;
280
- return round(value * factor) / factor;
281
- };
282
- var isFinite = Number.isFinite;
283
- var isInteger = Number.isInteger;
284
- var isNaN = Number.isNaN;
285
-
286
1
  // src/astar.ts
287
2
  var DIRECTIONS_4_WAY = [
288
3
  { x: 0, y: -1 },
@@ -292,11 +7,11 @@ var DIRECTIONS_4_WAY = [
292
7
  ];
293
8
  var AStar = class {
294
9
  map;
295
- constructor(map2) {
296
- this.map = map2;
10
+ constructor(map) {
11
+ this.map = map;
297
12
  }
298
13
  _manhattan(a, b) {
299
- return abs(a.x - b.x) + abs(a.y - b.y);
14
+ return Math.abs(a.x - b.x) + Math.abs(a.y - b.y);
300
15
  }
301
16
  _isWalkable(point, walkable = [0]) {
302
17
  const value = this.map.get(point.x, point.y);
@@ -306,7 +21,6 @@ var AStar = class {
306
21
  return `${x},${y}`;
307
22
  }
308
23
  findPath(a, b, params = {}) {
309
- const useAdjacent = true;
310
24
  const walkable = params.walkableValues ?? [0];
311
25
  const openSet = [];
312
26
  const closedSet = /* @__PURE__ */ new Set();
@@ -321,12 +35,10 @@ var AStar = class {
321
35
  nodeMap.set(this._key(a.x, a.y), startNode);
322
36
  const targetKeys = /* @__PURE__ */ new Set();
323
37
  targetKeys.add(this._key(b.x, b.y));
324
- if (useAdjacent) {
325
- for (const dir of DIRECTIONS_4_WAY) {
326
- const nx = b.x + dir.x;
327
- const ny = b.y + dir.y;
328
- targetKeys.add(this._key(nx, ny));
329
- }
38
+ for (const dir of DIRECTIONS_4_WAY) {
39
+ const nx = b.x + dir.x;
40
+ const ny = b.y + dir.y;
41
+ targetKeys.add(this._key(nx, ny));
330
42
  }
331
43
  while (openSet.length > 0) {
332
44
  openSet.sort((a2, b2) => a2.f - b2.f);
@@ -375,6 +87,213 @@ var AStar = class {
375
87
  }
376
88
  };
377
89
 
90
+ // src/math.ts
91
+ var PI = Math.PI;
92
+ var TAU = Math.PI * 2;
93
+ var HALF_PI = Math.PI / 2;
94
+ var QUARTER_PI = Math.PI / 4;
95
+ var E = Math.E;
96
+ var DEG2RAD = PI / 180;
97
+ var RAD2DEG = 180 / PI;
98
+ var LN2 = Math.LN2;
99
+ var LN10 = Math.LN10;
100
+ var LOG2E = Math.LOG2E;
101
+ var LOG10E = Math.LOG10E;
102
+ var SQRT2 = Math.SQRT2;
103
+ var SQRT1_2 = Math.SQRT1_2;
104
+ var EPSILON = Number.EPSILON;
105
+ var clamp = (value, minValue, maxValue) => Math.min(Math.max(value, minValue), maxValue);
106
+ var saturate = (value) => clamp(value, 0, 1);
107
+ var lerp = (start, end, t) => start + (end - start) * t;
108
+ var inverseLerp = (start, end, value) => (value - start) / (end - start);
109
+ var smoothstep = (edge0, edge1, value) => {
110
+ const t = saturate((value - edge0) / (edge1 - edge0));
111
+ return t * t * (3 - 2 * t);
112
+ };
113
+ var fract = (value) => value - Math.floor(value);
114
+ var mod = (value, divisor) => (value % divisor + divisor) % divisor;
115
+ var wrap = (value, minValue, maxValue) => {
116
+ const range = maxValue - minValue;
117
+ return minValue + mod(value - minValue, range);
118
+ };
119
+ var radians = (degrees2) => degrees2 * DEG2RAD;
120
+ var degrees = (radians2) => radians2 * RAD2DEG;
121
+ var normalizeRadians = (radians2) => wrap(radians2, -PI, PI);
122
+ var distance2d = (x1, y1, x2, y2) => Math.hypot(x2 - x1, y2 - y1);
123
+ var distance3d = (x1, y1, z1, x2, y2, z2) => Math.hypot(x2 - x1, y2 - y1, z2 - z1);
124
+ var squaredDistance = (x1, y1, x2, y2) => {
125
+ const dx = x2 - x1;
126
+ const dy = y2 - y1;
127
+ return dx * dx + dy * dy;
128
+ };
129
+ var manhattanDistance = (x1, y1, x2, y2) => Math.abs(x2 - x1) + Math.abs(y2 - y1);
130
+ var nearlyEqual = (a, b, epsilon = EPSILON) => Math.abs(a - b) <= epsilon;
131
+ var roundTo = (value, digits = 0) => {
132
+ const factor = 10 ** digits;
133
+ return Math.round(value * factor) / factor;
134
+ };
135
+ var hash32 = (n) => {
136
+ n |= 0;
137
+ n ^= n >>> 16;
138
+ n = Math.imul(n, 2246822507);
139
+ n ^= n >>> 13;
140
+ n = Math.imul(n, 3266489909);
141
+ n ^= n >>> 16;
142
+ return n >>> 0;
143
+ };
144
+ var hash32mix = (...values) => {
145
+ let n = 0;
146
+ for (const value of values) {
147
+ n ^= value | 0;
148
+ n = hash32(n);
149
+ }
150
+ return n;
151
+ };
152
+
153
+ // src/canvas-renderer.ts
154
+ var DEFAULT_COLOR = "white";
155
+ var DEFAULT_PIXEL_SIZE = 1;
156
+ var DEFAULT_FONT_SIZE = 14;
157
+ var DEFAULT_FONT_NAME = "monospace";
158
+ var DEFAULT_FONT = `${DEFAULT_FONT_SIZE}px ${DEFAULT_FONT_NAME}`;
159
+ var DEFAULT_TEXTALIGN = "left";
160
+ var DEFAULT_TEXTBASELINE = "alphabetic";
161
+ var CanvasRenderer = class {
162
+ context;
163
+ get canvas() {
164
+ return this.context.canvas;
165
+ }
166
+ get width() {
167
+ return this.canvas.width;
168
+ }
169
+ get height() {
170
+ return this.canvas.height;
171
+ }
172
+ constructor(canvas) {
173
+ this.context = (canvas ?? document.createElement("canvas")).getContext("2d");
174
+ this.context.font = DEFAULT_FONT;
175
+ this.context.textAlign = DEFAULT_TEXTALIGN;
176
+ this.context.textBaseline = DEFAULT_TEXTBASELINE;
177
+ }
178
+ resize(width, height) {
179
+ let resized = false;
180
+ width = width ?? this.canvas.parentElement?.clientWidth ?? this.width;
181
+ height = height ?? this.canvas.parentElement?.clientHeight ?? this.height;
182
+ if (this.canvas.width != width || this.canvas.height != height) {
183
+ this.canvas.width = width;
184
+ this.canvas.height = height;
185
+ resized = true;
186
+ }
187
+ return resized;
188
+ }
189
+ clear() {
190
+ this.context.clearRect(0, 0, this.width, this.height);
191
+ }
192
+ drawPath(buildPath, params = {}) {
193
+ this.context.fillStyle = params.color ?? DEFAULT_COLOR;
194
+ this.context.strokeStyle = params.color ?? DEFAULT_COLOR;
195
+ this.context.lineWidth = params.size ?? 1;
196
+ if (params.lineDash) {
197
+ this.context.setLineDash(params.lineDash);
198
+ }
199
+ this.context.beginPath();
200
+ buildPath();
201
+ this.context.stroke();
202
+ if (params.filled) {
203
+ this.context.fill();
204
+ }
205
+ if (params.lineDash) {
206
+ this.context.setLineDash([]);
207
+ }
208
+ }
209
+ drawRect(x, y, width, height, params = {}) {
210
+ x -= width / 2;
211
+ y -= height / 2;
212
+ this.context.fillStyle = params.color ?? DEFAULT_COLOR;
213
+ this.context.strokeStyle = params.color ?? DEFAULT_COLOR;
214
+ this.context.lineWidth = params.size ?? 1;
215
+ if (params.lineDash) {
216
+ this.context.setLineDash(params.lineDash);
217
+ }
218
+ this.context.beginPath();
219
+ this.context.strokeRect(x, y, width, height);
220
+ if (params.filled) {
221
+ this.context.fillRect(x, y, width, height);
222
+ }
223
+ if (params.lineDash) {
224
+ this.context.setLineDash([]);
225
+ }
226
+ }
227
+ drawPixel(x, y, params = {}) {
228
+ const size = Math.abs(params.size || DEFAULT_PIXEL_SIZE);
229
+ this.drawRect(x, y, size, size, {
230
+ ...params,
231
+ filled: true
232
+ });
233
+ }
234
+ drawLine(x1, y1, x2, y2, params = {}) {
235
+ this.context.strokeStyle = params.color ?? DEFAULT_COLOR;
236
+ this.context.lineWidth = params.size ?? 1;
237
+ if (params.lineDash) {
238
+ this.context.setLineDash(params.lineDash);
239
+ }
240
+ this.context.beginPath();
241
+ this.context.moveTo(x1, y1);
242
+ this.context.lineTo(x2, y2);
243
+ this.context.stroke();
244
+ if (params.lineDash) {
245
+ this.context.setLineDash([]);
246
+ }
247
+ }
248
+ drawCircle(x, y, radius, params = {}) {
249
+ this.drawPath(() => {
250
+ this.context.arc(x, y, radius, 0, TAU);
251
+ }, params);
252
+ }
253
+ drawPolygon(x, y, radius, sides, params = {}) {
254
+ sides = Math.floor(clamp(sides, 3, 36));
255
+ this.drawPath(() => {
256
+ for (let i = 0; i < sides; i++) {
257
+ const angle = i / sides * TAU - PI / 2;
258
+ const px = x + Math.cos(angle) * radius;
259
+ const py = y + Math.sin(angle) * radius;
260
+ if (i === 0) {
261
+ this.context.moveTo(px, py);
262
+ } else {
263
+ this.context.lineTo(px, py);
264
+ }
265
+ }
266
+ this.context.closePath();
267
+ }, params);
268
+ }
269
+ drawText(x, y, text, params = {}) {
270
+ this.context.font = params.font ?? `${params.size ?? DEFAULT_FONT_SIZE}px ${params.fontName ?? DEFAULT_FONT_NAME}`;
271
+ this.context.textAlign = params.textAlign ?? DEFAULT_TEXTALIGN;
272
+ this.context.textBaseline = params.textBaseline ?? DEFAULT_TEXTBASELINE;
273
+ this.context.fillStyle = params.color ?? DEFAULT_COLOR;
274
+ this.context.fillText(text, x, y);
275
+ }
276
+ drawSprite(x, y, image, width, height, params = {}) {
277
+ x -= width / 2;
278
+ y -= height / 2;
279
+ if (params.sourceWidth !== void 0 && params.sourceHeight !== void 0) {
280
+ this.context.drawImage(
281
+ image,
282
+ params.sourceX ?? 0,
283
+ params.sourceY ?? 0,
284
+ params.sourceWidth,
285
+ params.sourceHeight,
286
+ x,
287
+ y,
288
+ width,
289
+ height
290
+ );
291
+ } else {
292
+ this.context.drawImage(image, x, y, width, height);
293
+ }
294
+ }
295
+ };
296
+
378
297
  // src/observable.ts
379
298
  var Observable = class {
380
299
  observers = /* @__PURE__ */ new Set();
@@ -403,22 +322,18 @@ var Observable = class {
403
322
  };
404
323
 
405
324
  // src/clock.ts
325
+ var ONE_SECOND = 1e3;
406
326
  var Clock = class {
407
- _startTime = 0;
408
- _time = 0;
409
- _deltaTime = 0;
410
- _frameTime = 0;
411
- _frameCount = 0;
412
327
  _fps = 0;
328
+ _frameCount = 0;
329
+ _frameTime = 0;
413
330
  _isRunning = false;
414
- get time() {
415
- return this._time;
416
- }
417
- get deltaTime() {
418
- return this._deltaTime;
419
- }
331
+ _lastTime = 0;
332
+ onFpsUpdate = new Observable();
333
+ onFrame = new Observable();
334
+ startTime = performance.now();
420
335
  get elapsedTime() {
421
- return performance.now() - this._startTime;
336
+ return performance.now() - this.startTime;
422
337
  }
423
338
  get fps() {
424
339
  return this._fps;
@@ -426,39 +341,207 @@ var Clock = class {
426
341
  get isRunning() {
427
342
  return this._isRunning;
428
343
  }
429
- onFrame = new Observable();
344
+ update(time) {
345
+ const deltaTime = (time - this._lastTime) / ONE_SECOND;
346
+ this._lastTime = time;
347
+ if (this._frameTime + ONE_SECOND >= time) {
348
+ this._frameCount++;
349
+ } else {
350
+ this._frameTime = time;
351
+ this._fps = this._frameCount;
352
+ this._frameCount = 0;
353
+ this.onFpsUpdate.notify(this.fps);
354
+ }
355
+ return deltaTime;
356
+ }
430
357
  start() {
431
358
  if (!this._isRunning) {
432
- this._startTime = performance.now();
433
- this._isRunning = true;
434
- const update = (time) => {
435
- this._deltaTime = (time - this._time) / 1e3;
436
- this._time = time;
437
- if (this._frameTime + 1e3 >= time) {
438
- this._frameCount += 1;
439
- } else {
440
- this._frameTime = time;
441
- this._fps = this._frameCount;
442
- this._frameCount = 0;
443
- }
444
- this.onFrame.notify(this);
445
- if (this._isRunning) {
446
- requestAnimationFrame(update);
447
- }
359
+ const animate = (time) => {
360
+ this.onFrame.notify(this.update(time));
361
+ if (this._isRunning)
362
+ requestAnimationFrame(animate);
448
363
  };
449
- requestAnimationFrame(update);
364
+ this._isRunning = true;
365
+ requestAnimationFrame(animate);
450
366
  }
451
- return this;
452
367
  }
453
368
  stop() {
454
369
  this._isRunning = false;
455
370
  }
456
371
  };
457
372
 
458
- // src/index.ts
459
- __reExport(index_exports, __toESM(require_css()));
373
+ // src/log.ts
374
+ var log_default = console.debug.bind(
375
+ console,
376
+ "%c[dev]",
377
+ "font-weight: bold; color: #888;"
378
+ );
460
379
 
461
- // src/disposable.ts
380
+ // src/color.ts
381
+ var Color = class _Color {
382
+ _hex = "#ffffffff";
383
+ _r = 255;
384
+ _g = 255;
385
+ _b = 255;
386
+ _a = 255;
387
+ get r() {
388
+ return this._r;
389
+ }
390
+ set r(value) {
391
+ this._r = clamp(value, 0, 255);
392
+ this._hex = this._to_hex();
393
+ }
394
+ get g() {
395
+ return this._g;
396
+ }
397
+ set g(value) {
398
+ this._g = clamp(value, 0, 255);
399
+ this._hex = this._to_hex();
400
+ }
401
+ get b() {
402
+ return this._b;
403
+ }
404
+ set b(value) {
405
+ this._b = clamp(value, 0, 255);
406
+ this._hex = this._to_hex();
407
+ }
408
+ get a() {
409
+ return this._a;
410
+ }
411
+ set a(value) {
412
+ this._a = clamp(value, 0, 255);
413
+ this._hex = this._to_hex();
414
+ }
415
+ get hexStr() {
416
+ return this._hex;
417
+ }
418
+ set hexStr(value) {
419
+ if (value.startsWith("#")) {
420
+ [this._r, this._g, this._b, this._a] = this._parse_hex_color_string(value);
421
+ this._hex = value;
422
+ } else {
423
+ log_default(`Color: invalid color string: ${value}. Should be a hexadecimal color string (i.e.: '#ffffff' or '#ffffffff'). Keeping the current color.`);
424
+ }
425
+ }
426
+ get rgba() {
427
+ return [this._r, this._g, this._b, this._a];
428
+ }
429
+ constructor(r = 255, g = 255, b = 255, a = 255) {
430
+ if (typeof r === "string") {
431
+ if (r.startsWith("#")) {
432
+ [r, g, b, a] = this._parse_hex_color_string(r);
433
+ } else {
434
+ log_default(`Color: invalid color string: ${r}. Should be a hexadecimal color string (i.e.: '#ffffff' or '#ffffffff'). Defaulting to opaque white.`);
435
+ r = g = b = a = 255;
436
+ }
437
+ } else {
438
+ [r, g, b, a] = [r, g, b, a].map((n) => _Color._normalize(n));
439
+ }
440
+ this.r = r;
441
+ this.g = g;
442
+ this.b = b;
443
+ this.a = a;
444
+ }
445
+ static _normalize(value) {
446
+ return clamp(0 | (value > 0 && value < 1 ? value * 255 : value), 0, 255);
447
+ }
448
+ _to_hex() {
449
+ 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")}`;
450
+ }
451
+ _parse_hex_color_string(hex) {
452
+ const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})?$/i.exec(hex);
453
+ return result ? [
454
+ parseInt(result[1], 16),
455
+ parseInt(result[2], 16),
456
+ parseInt(result[3], 16),
457
+ result[4] ? parseInt(result[4], 16) : 255
458
+ ] : [255, 255, 255, 255];
459
+ }
460
+ static fromHsv(h, s, v, a = 255) {
461
+ let r = 0;
462
+ let g = 0;
463
+ let b = 0;
464
+ let i = Math.floor(h * 6);
465
+ let f = h * 6 - i;
466
+ let p = v * (1 - s);
467
+ let q = v * (1 - f * s);
468
+ let t = v * (1 - (1 - f) * s);
469
+ switch (i % 6) {
470
+ case 0:
471
+ r = v, g = t, b = p;
472
+ break;
473
+ case 1:
474
+ r = q, g = v, b = p;
475
+ break;
476
+ case 2:
477
+ r = p, g = v, b = t;
478
+ break;
479
+ case 3:
480
+ r = p, g = q, b = v;
481
+ break;
482
+ case 4:
483
+ r = t, g = p, b = v;
484
+ break;
485
+ case 5:
486
+ r = v, g = p, b = q;
487
+ break;
488
+ }
489
+ return new _Color(Math.round(r * 255), Math.round(g * 255), Math.round(b * 255), a);
490
+ }
491
+ static get BLACK() {
492
+ return new _Color(0, 0, 0, 255);
493
+ }
494
+ static get GRAY() {
495
+ return new _Color(128, 128, 128, 255);
496
+ }
497
+ static get WHITE() {
498
+ return new _Color(255, 255, 255, 255);
499
+ }
500
+ static get RED() {
501
+ return new _Color(255, 0, 0, 255);
502
+ }
503
+ static get GREEN() {
504
+ return new _Color(0, 255, 0, 255);
505
+ }
506
+ static get BLUE() {
507
+ return new _Color(0, 0, 255, 255);
508
+ }
509
+ static get YELLOW() {
510
+ return new _Color(255, 255, 0, 255);
511
+ }
512
+ static get ORANGE() {
513
+ return new _Color(255, 128, 0, 255);
514
+ }
515
+ static get PURPLE() {
516
+ return new _Color(128, 0, 128, 255);
517
+ }
518
+ static get CYAN() {
519
+ return new _Color(0, 255, 255, 255);
520
+ }
521
+ static get MAGENTA() {
522
+ return new _Color(255, 0, 255, 255);
523
+ }
524
+ static fromName(name) {
525
+ const element = document.createElement("div");
526
+ element.style.color = name;
527
+ document.body.appendChild(element);
528
+ const computedColor = getComputedStyle(element).color;
529
+ document.body.removeChild(element);
530
+ const rgba = computedColor.match(/\d+/g);
531
+ if (rgba && rgba.length === 4) {
532
+ const [r, g, b, a] = rgba.map(Number);
533
+ return new _Color(r, g, b, a);
534
+ } else {
535
+ log_default(`Color: invalid CSS color name: ${name}. Defaulting to transparent.`);
536
+ return _Color.TRANSPARENT;
537
+ }
538
+ }
539
+ static get TRANSPARENT() {
540
+ return new _Color(0, 0, 0, 0);
541
+ }
542
+ };
543
+
544
+ // src/disposable.ts
462
545
  var Disposable = class {
463
546
  disposers = [];
464
547
  add(disposer) {
@@ -475,7 +558,7 @@ var Disposable = class {
475
558
  import { Heap } from "heap-js";
476
559
 
477
560
  // src/map2d.ts
478
- var DEFAULT_VALUE = -1;
561
+ var DEFAULT_MAP_2D_VALUE = -1;
479
562
  var BASE_2D = 2097152;
480
563
  var OFFSET_2D = 1048576;
481
564
  var Map2D = class {
@@ -487,12 +570,12 @@ var Map2D = class {
487
570
  get size() {
488
571
  return this._data.size;
489
572
  }
490
- constructor(defaultValue = DEFAULT_VALUE) {
573
+ constructor(defaultValue = DEFAULT_MAP_2D_VALUE, mapData) {
491
574
  this.defaultValue = defaultValue;
492
- this._data = /* @__PURE__ */ new Map();
575
+ this._data = mapData ?? /* @__PURE__ */ new Map();
493
576
  }
494
577
  _floor(x, y) {
495
- return [floor(x), floor(y)];
578
+ return [Math.floor(x), Math.floor(y)];
496
579
  }
497
580
  _key(x, y) {
498
581
  const X = x + OFFSET_2D & BASE_2D - 1;
@@ -501,7 +584,7 @@ var Map2D = class {
501
584
  }
502
585
  _pos(key) {
503
586
  const Y = key % BASE_2D;
504
- const X = floor(key / BASE_2D);
587
+ const X = Math.floor(key / BASE_2D);
505
588
  return [X - OFFSET_2D, Y - OFFSET_2D];
506
589
  }
507
590
  clear() {
@@ -521,23 +604,22 @@ var Map2D = class {
521
604
  }
522
605
  }
523
606
  forEach(callback) {
607
+ let i = 0;
524
608
  this._data.forEach((v, key) => {
525
609
  const [x, y] = this._pos(key);
526
- callback(x, y, v);
610
+ callback(x, y, v, i++);
611
+ });
612
+ }
613
+ forEachInArea(x1, y1, x2, y2, callback) {
614
+ this.forEach((x, y, n) => {
615
+ if (x >= x1 && x < x2 && y >= y1 && y < y2) {
616
+ callback(x, y, n);
617
+ }
527
618
  });
528
619
  }
529
620
  };
530
621
 
531
622
  // src/random.ts
532
- var hash32 = (seed) => {
533
- seed |= 0;
534
- seed ^= seed >>> 16;
535
- seed = imul(seed, 2246822507);
536
- seed ^= seed >>> 13;
537
- seed = imul(seed, 3266489909);
538
- seed ^= seed >>> 16;
539
- return seed >>> 0;
540
- };
541
623
  var Random = class _Random {
542
624
  _seed;
543
625
  constructor(seed = Date.now()) {
@@ -549,31 +631,17 @@ var Random = class _Random {
549
631
  set seed(value) {
550
632
  this._seed = value | 0;
551
633
  }
552
- //--------------------------------------------------------------------------
553
- // Internal
554
- //--------------------------------------------------------------------------
555
- static _mix(...values) {
556
- let seed = 0;
557
- for (const value of values) {
558
- seed ^= value | 0;
559
- seed = hash32(seed);
560
- }
561
- return seed;
562
- }
563
- //--------------------------------------------------------------------------
564
- // Stateless
565
- //--------------------------------------------------------------------------
566
634
  static hash(...values) {
567
- return this._mix(...values);
635
+ return hash32mix(...values);
568
636
  }
569
637
  static uint(...values) {
570
- return this._mix(...values);
638
+ return hash32mix(...values);
571
639
  }
572
640
  static float(...values) {
573
- return this._mix(...values) / 4294967296;
641
+ return hash32mix(...values) / 4294967296;
574
642
  }
575
643
  static bool(...values) {
576
- return (this._mix(...values) & 1) !== 0;
644
+ return (hash32mix(...values) & 1) !== 0;
577
645
  }
578
646
  static sign(...values) {
579
647
  return this.bool(...values) ? 1 : -1;
@@ -581,9 +649,6 @@ var Random = class _Random {
581
649
  static angle(...values) {
582
650
  return this.float(...values) * TAU;
583
651
  }
584
- //--------------------------------------------------------------------------
585
- // Stateful
586
- //--------------------------------------------------------------------------
587
652
  uint() {
588
653
  return _Random.uint(this._seed++);
589
654
  }
@@ -602,43 +667,37 @@ var Random = class _Random {
602
667
  };
603
668
 
604
669
  // src/rng.ts
605
- var RandomTools = class {
606
- rng;
670
+ var Rng = class {
671
+ random;
607
672
  get seed() {
608
- return this.rng.seed;
673
+ return this.random.seed;
609
674
  }
610
675
  set seed(seed) {
611
- this.rng.seed = seed;
676
+ this.random.seed = seed;
612
677
  }
613
678
  constructor(seed) {
614
- this.rng = seed instanceof Random ? seed : new Random(seed);
679
+ this.random = seed instanceof Random ? seed : new Random(seed);
615
680
  }
616
- //----------------------------------------------------------------------
617
- // Numbers
618
- //----------------------------------------------------------------------
619
681
  nextFloat() {
620
- return this.rng.float();
682
+ return this.random.float();
621
683
  }
622
684
  nextUint() {
623
- return this.rng.uint();
685
+ return this.random.uint();
624
686
  }
625
- floatRange(min2, max2) {
626
- if (typeof max2 !== "number") {
627
- max2 = min2;
628
- min2 = 0;
687
+ floatRange(min, max) {
688
+ if (typeof max !== "number") {
689
+ max = min;
690
+ min = 0;
629
691
  }
630
- return min2 + this.rng.float() * (max2 - min2);
692
+ return min + this.random.float() * (max - min);
631
693
  }
632
- range(min2, max2) {
633
- if (typeof max2 !== "number") {
634
- max2 = min2;
635
- min2 = 0;
694
+ range(min, max) {
695
+ if (typeof max !== "number") {
696
+ max = min;
697
+ min = 0;
636
698
  }
637
- return floor(this.floatRange(min2, max2));
699
+ return Math.floor(this.floatRange(min, max));
638
700
  }
639
- //----------------------------------------------------------------------
640
- // Collections
641
- //----------------------------------------------------------------------
642
701
  pick(array) {
643
702
  return array[this.range(0, array.length - 1)];
644
703
  }
@@ -654,93 +713,80 @@ var RandomTools = class {
654
713
  return result;
655
714
  }
656
715
  chance(probability) {
657
- return this.rng.float() < probability;
716
+ return this.random.float() < probability;
658
717
  }
659
- //----------------------------------------------------------------------
660
- // Geometry
661
- //----------------------------------------------------------------------
662
718
  vector2() {
663
- const \u03B8 = this.rng.angle();
719
+ const \u03B8 = this.random.angle();
664
720
  return [
665
- cos(\u03B8),
666
- sin(\u03B8)
721
+ Math.cos(\u03B8),
722
+ Math.sin(\u03B8)
667
723
  ];
668
724
  }
669
725
  pointOnCircle(radius = 1) {
670
- const \u03B8 = this.rng.angle();
726
+ const \u03B8 = this.random.angle();
671
727
  return [
672
- radius * cos(\u03B8),
673
- radius * sin(\u03B8)
728
+ radius * Math.cos(\u03B8),
729
+ radius * Math.sin(\u03B8)
674
730
  ];
675
731
  }
676
732
  pointInCircle(radius = 1) {
677
- const \u03B8 = this.rng.angle();
678
- const r = sqrt(this.rng.float()) * radius;
733
+ const \u03B8 = this.random.angle();
734
+ const r = Math.sqrt(this.random.float()) * radius;
679
735
  return [
680
- r * cos(\u03B8),
681
- r * sin(\u03B8)
736
+ r * Math.cos(\u03B8),
737
+ r * Math.sin(\u03B8)
682
738
  ];
683
739
  }
684
740
  pointOnSphere(radius = 1) {
685
- const u = this.rng.float();
686
- const v = this.rng.float();
741
+ const u = this.random.float();
742
+ const v = this.random.float();
687
743
  const \u03B8 = TAU * u;
688
- const \u03C6 = acos(2 * v - 1);
689
- const s = sin(\u03C6);
744
+ const \u03C6 = Math.acos(2 * v - 1);
745
+ const s = Math.sin(\u03C6);
690
746
  return [
691
- radius * s * cos(\u03B8),
692
- radius * s * sin(\u03B8),
693
- radius * cos(\u03C6)
747
+ radius * s * Math.cos(\u03B8),
748
+ radius * s * Math.sin(\u03B8),
749
+ radius * Math.cos(\u03C6)
694
750
  ];
695
751
  }
696
752
  pointInSphere(radius = 1) {
697
- const u = this.rng.float();
698
- const v = this.rng.float();
753
+ const u = this.random.float();
754
+ const v = this.random.float();
699
755
  const \u03B8 = TAU * u;
700
- const \u03C6 = acos(2 * v - 1);
701
- const r = radius * cbrt(this.rng.float());
702
- const s = sin(\u03C6);
756
+ const \u03C6 = Math.acos(2 * v - 1);
757
+ const r = radius * Math.cbrt(this.random.float());
758
+ const s = Math.sin(\u03C6);
703
759
  return [
704
- r * s * cos(\u03B8),
705
- r * s * sin(\u03B8),
706
- r * cos(\u03C6)
760
+ r * s * Math.cos(\u03B8),
761
+ r * s * Math.sin(\u03B8),
762
+ r * Math.cos(\u03C6)
707
763
  ];
708
764
  }
709
- //----------------------------------------------------------------------
710
- // Distributions
711
- //----------------------------------------------------------------------
712
765
  gaussian(mean = 0, standardDeviation = 1) {
713
766
  let u = 0;
714
767
  let v = 0;
715
- while (u === 0) u = this.rng.float();
716
- while (v === 0) v = this.rng.float();
717
- const z = sqrt(-2 * Math.log(u)) * cos(TAU * v);
768
+ while (u === 0) u = this.random.float();
769
+ while (v === 0) v = this.random.float();
770
+ const z = Math.sqrt(-2 * Math.log(u)) * Math.cos(TAU * v);
718
771
  return mean + z * standardDeviation;
719
772
  }
720
- //----------------------------------------------------------------------
721
- // Matrices
722
- //----------------------------------------------------------------------
723
- matrix(rows, columns = rows, min2 = 0, max2 = 1) {
773
+ matrix(rows, columns = rows, min = 0, max = 1) {
724
774
  return Array.from(
725
775
  { length: rows },
726
776
  () => Array.from(
727
777
  { length: columns },
728
- () => this.floatRange(min2, max2)
778
+ () => this.floatRange(min, max)
729
779
  )
730
780
  );
731
781
  }
732
782
  transformMatrix(rows, columns = rows) {
733
783
  return this.matrix(rows, columns, -1, 1);
734
784
  }
785
+ rgb() {
786
+ return [this.range(256), this.range(256), this.range(256)];
787
+ }
735
788
  };
736
- var rng = new RandomTools();
737
-
738
- // src/logger.ts
739
- var logger_default = console.debug.bind(
740
- console,
741
- "%c[dev]",
742
- "font-weight: bold; color: #888;"
743
- );
789
+ var rng = new Rng();
744
790
 
745
791
  // src/vector.ts
746
792
  var Vector = class _Vector {
@@ -807,11 +853,11 @@ var Vector = class _Vector {
807
853
  return Math.acos(Math.min(1, Math.max(-1, theta)));
808
854
  }
809
855
  rotate(radians2) {
810
- const cos2 = Math.cos(radians2);
811
- const sin2 = Math.sin(radians2);
856
+ const cos = Math.cos(radians2);
857
+ const sin = Math.sin(radians2);
812
858
  const { x, y } = this;
813
- this.x = x * cos2 - y * sin2;
814
- this.y = x * sin2 + y * cos2;
859
+ this.x = x * cos - y * sin;
860
+ this.y = x * sin + y * cos;
815
861
  return this;
816
862
  }
817
863
  rotateAround(origin, radians2) {
@@ -967,20 +1013,20 @@ var DIRECTIONS_8_WAY = [
967
1013
  { x: -1, y: 1 }
968
1014
  // down-left
969
1015
  ];
970
- function _plot(map2, data, tile) {
1016
+ function _plot(map, data, tile) {
971
1017
  data.forEach((element) => {
972
1018
  if (element instanceof Rectangle) {
973
1019
  for (let y = 0; y < element.height; y++) {
974
1020
  for (let x = 0; x < element.width; x++) {
975
- map2.set(element.x + x, element.y + y, tile);
1021
+ map.set(element.x + x, element.y + y, tile);
976
1022
  }
977
1023
  }
978
1024
  } else if (Array.isArray(element)) {
979
1025
  element.forEach((point) => {
980
- map2.set(point.x, point.y, tile);
1026
+ map.set(point.x, point.y, tile);
981
1027
  });
982
1028
  } else {
983
- map2.set(element.x, element.y, tile);
1029
+ map.set(element.x, element.y, tile);
984
1030
  }
985
1031
  });
986
1032
  }
@@ -995,10 +1041,10 @@ function _generateRooms(params = {}) {
995
1041
  while (iterations < maxIterations) {
996
1042
  const baseSize = rng.range(minRoomSize, maxRoomSize);
997
1043
  const aspectRatio = 0.75 + rng.gaussian() * 0.5;
998
- const width = min(maxRoomSize, max(minRoomSize, round(baseSize * aspectRatio)));
999
- const height = min(maxRoomSize, max(minRoomSize, round(baseSize / aspectRatio)));
1000
- const x = floor(rng.range(1 + padding, size - width - padding));
1001
- const y = floor(rng.range(1 + padding, size - height - padding));
1044
+ const width = Math.min(maxRoomSize, Math.max(minRoomSize, Math.round(baseSize * aspectRatio)));
1045
+ const height = Math.min(maxRoomSize, Math.max(minRoomSize, Math.round(baseSize / aspectRatio)));
1046
+ const x = Math.floor(rng.range(1 + padding, size - width - padding));
1047
+ const y = Math.floor(rng.range(1 + padding, size - height - padding));
1002
1048
  const room = new Rectangle(x, y, width, height);
1003
1049
  if (!rooms.some((existing) => room.intersects(existing, padding))) {
1004
1050
  rooms.push(room);
@@ -1099,8 +1145,8 @@ function _getShortestPathBetweenRects(rectA, rectB) {
1099
1145
  }
1100
1146
  return { a: paths.a, b: paths.b };
1101
1147
  }
1102
- function _generatePaths(map2, rooms, params = {}) {
1103
- const aStar = new AStar(map2);
1148
+ function _generatePaths(map, rooms, params = {}) {
1149
+ const aStar = new AStar(map);
1104
1150
  const paths = [];
1105
1151
  _generateMST(rooms, params).forEach((rects) => {
1106
1152
  const { a, b } = _getShortestPathBetweenRects(rects.a, rects.b);
@@ -1110,15 +1156,15 @@ function _generatePaths(map2, rooms, params = {}) {
1110
1156
  }
1111
1157
  function GenerateRooms(params = {}) {
1112
1158
  const startTime = Date.now();
1113
- const map2 = params.map ?? new Map2D(TILE_EMPTY);
1159
+ const map = params.map ?? new Map2D(TILE_EMPTY);
1114
1160
  const rooms = _generateRooms(params.rooms);
1115
- _plot(map2, rooms, TILE_FLOOR);
1116
- const paths = _generatePaths(map2, rooms, params.paths);
1117
- _plot(map2, paths, TILE_PATH);
1118
- logger_default("GenerateRooms: done:", Date.now() - startTime, "ms");
1119
- return { map: map2, rooms, paths };
1161
+ _plot(map, rooms, TILE_FLOOR);
1162
+ const paths = _generatePaths(map, rooms, params.paths);
1163
+ _plot(map, paths, TILE_PATH);
1164
+ log_default("GenerateRooms: done:", Date.now() - startTime, "ms");
1165
+ return { map, rooms, paths };
1120
1166
  }
1121
- function GenerateDoors(map2, paths, params = {}) {
1167
+ function GenerateDoors(map, paths, params = {}) {
1122
1168
  const chanceExists = params.chanceExists ?? DEFAULT_DOOR_CHANCE_EXISTS;
1123
1169
  const possibleDoorPoints = [];
1124
1170
  paths.forEach((points) => {
@@ -1129,19 +1175,19 @@ function GenerateDoors(map2, paths, params = {}) {
1129
1175
  });
1130
1176
  const doors = [];
1131
1177
  possibleDoorPoints.forEach((doorPoint) => {
1132
- if (rng.nextFloat() < chanceExists && (map2.get(doorPoint.x, doorPoint.y - 1) === map2.defaultValue && map2.get(doorPoint.x, doorPoint.y + 1) === map2.defaultValue || map2.get(doorPoint.x - 1, doorPoint.y) === map2.defaultValue && map2.get(doorPoint.x + 1, doorPoint.y) === map2.defaultValue)) {
1178
+ if (rng.nextFloat() < 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)) {
1133
1179
  doors.push(doorPoint);
1134
1180
  }
1135
1181
  });
1136
1182
  return doors;
1137
1183
  }
1138
- function GenerateWalls(map2) {
1184
+ function GenerateWalls(map) {
1139
1185
  const walls = [];
1140
- map2.forEach((x, y, _v) => {
1186
+ map.forEach((x, y, _v) => {
1141
1187
  DIRECTIONS_8_WAY.forEach((dir) => {
1142
1188
  const nx = dir.x + x;
1143
1189
  const ny = dir.y + y;
1144
- if (map2.get(nx, ny) === map2.defaultValue) {
1190
+ if (map.get(nx, ny) === map.defaultValue) {
1145
1191
  walls.push({ x: nx, y: ny });
1146
1192
  }
1147
1193
  });
@@ -1150,35 +1196,74 @@ function GenerateWalls(map2) {
1150
1196
  }
1151
1197
 
1152
1198
  // src/ecs.ts
1153
- var ECS = class {
1154
- nextEntityId = 1;
1199
+ var ECS = class _ECS {
1200
+ static #nextEntity = 0;
1155
1201
  components = /* @__PURE__ */ new Map();
1156
1202
  createEntity() {
1157
- return this.nextEntityId++;
1203
+ return _ECS.#nextEntity++;
1158
1204
  }
1159
- addComponent(entity, name, data) {
1160
- if (!this.components.has(name)) {
1161
- this.components.set(name, /* @__PURE__ */ new Map());
1205
+ addComponent(entity, component) {
1206
+ const type = component.constructor;
1207
+ let map = this.components.get(type);
1208
+ if (!map) {
1209
+ map = /* @__PURE__ */ new Map();
1210
+ this.components.set(type, map);
1162
1211
  }
1163
- this.components.get(name).set(entity, data);
1212
+ map.set(entity, component);
1213
+ }
1214
+ getComponent(entity, type) {
1215
+ const map = this.components.get(type);
1216
+ return map?.get(entity);
1164
1217
  }
1165
- getComponent(entity, name) {
1166
- return this.components.get(name)?.get(entity);
1218
+ hasComponent(entity, type) {
1219
+ return this.components.get(type)?.has(entity) ?? false;
1167
1220
  }
1168
- removeComponent(entity, name) {
1169
- this.components.get(name)?.delete(entity);
1221
+ removeComponent(entity, type) {
1222
+ this.components.get(type)?.delete(entity);
1170
1223
  }
1171
- getEntitiesWithComponents(...componentNames) {
1172
- if (componentNames.length === 0) return [];
1173
- const first = this.components.get(componentNames[0]);
1174
- if (!first) return [];
1175
- const result = [];
1176
- for (const entity of first.keys()) {
1177
- if (componentNames.every((name) => this.components.get(name)?.has(entity))) {
1178
- result.push(entity);
1224
+ *query(...types) {
1225
+ if (types.length === 0) {
1226
+ return;
1227
+ }
1228
+ let smallest;
1229
+ const maps = [];
1230
+ for (const type of types) {
1231
+ const map = this.components.get(type);
1232
+ if (!map) {
1233
+ return;
1234
+ }
1235
+ maps.push(map);
1236
+ if (!smallest || map.size < smallest.size) {
1237
+ smallest = map;
1179
1238
  }
1180
1239
  }
1181
- return result;
1240
+ if (!smallest) {
1241
+ return;
1242
+ }
1243
+ for (const entity of smallest.keys()) {
1244
+ const components = [];
1245
+ let matches = true;
1246
+ for (const map of maps) {
1247
+ const component = map.get(entity);
1248
+ if (!component) {
1249
+ matches = false;
1250
+ break;
1251
+ }
1252
+ components.push(component);
1253
+ }
1254
+ if (matches) {
1255
+ yield [entity, ...components];
1256
+ }
1257
+ }
1258
+ }
1259
+ destroyEntity(entity) {
1260
+ for (const map of this.components.values()) {
1261
+ map.delete(entity);
1262
+ }
1263
+ }
1264
+ clear() {
1265
+ this.components.clear();
1266
+ _ECS.#nextEntity = 0;
1182
1267
  }
1183
1268
  };
1184
1269
 
@@ -1202,10 +1287,30 @@ var EventQueue = class {
1202
1287
  }
1203
1288
  };
1204
1289
 
1290
+ // src/emitter.ts
1291
+ var Emitter = class {
1292
+ listeners = /* @__PURE__ */ new Map();
1293
+ constructor() {
1294
+ }
1295
+ on(...eventName) {
1296
+ const listener = eventName.pop();
1297
+ const events = eventName.filter((ev) => typeof ev === "string");
1298
+ events.forEach((event) => {
1299
+ if (!this.listeners.has(event)) {
1300
+ this.listeners.set(event, new Array());
1301
+ }
1302
+ this.listeners.get(event)?.push(listener);
1303
+ });
1304
+ return this;
1305
+ }
1306
+ emit(eventName, ...args) {
1307
+ this.listeners.get(eventName)?.forEach((listener) => listener(...args, eventName));
1308
+ return this;
1309
+ }
1310
+ };
1311
+
1205
1312
  // src/input.ts
1206
- var DOWN = 1;
1207
- var UP = 0;
1208
- var Input = class _Input {
1313
+ var Input = class _Input extends Emitter {
1209
1314
  static _instance;
1210
1315
  static get instance() {
1211
1316
  if (!_Input._instance) {
@@ -1213,79 +1318,153 @@ var Input = class _Input {
1213
1318
  }
1214
1319
  return _Input._instance;
1215
1320
  }
1216
- _keyStates;
1217
- _buttonStates;
1218
- _pointerPosition = new Vector();
1321
+ _keyStates = {};
1322
+ _mouseButtonStates = {};
1323
+ _mousePosition = new Vector();
1324
+ _mousePosition2 = new Vector();
1325
+ get mousePosition() {
1326
+ return this._mousePosition;
1327
+ }
1328
+ get mousePosition2() {
1329
+ return this._mousePosition2;
1330
+ }
1219
1331
  inputThreshold = 200;
1220
- get pointerPosition() {
1221
- return this._pointerPosition.clone();
1222
- }
1223
- // get mouseWorldPosition(): Vector {
1224
- // return new Vector(
1225
- // (this._mousePosition.x / this.canvasWidth) * 2 - 1,
1226
- // -(this._mousePosition.y / this.canvasHeight) * 2 + 1,
1227
- // )
1228
- // }
1229
- onKeyDown = new Observable();
1230
- onKeyUp = new Observable();
1231
- onKeyPressed = new Observable();
1232
- onPointerDown = new Observable();
1233
- onPointerUp = new Observable();
1234
- onPointerPressed = new Observable();
1235
- onPointerMove = new Observable();
1236
- onWheel = new Observable();
1237
1332
  constructor() {
1238
- this._keyStates = /* @__PURE__ */ new Map();
1239
- this._buttonStates = /* @__PURE__ */ new Map();
1240
- window.addEventListener("keydown", (ev) => {
1241
- if (!ev.repeat) {
1242
- this._keyStates.set(ev.code, { state: DOWN, time: ev.timeStamp });
1243
- this.onKeyDown.notify(this, ev);
1244
- }
1245
- });
1246
- window.addEventListener("keyup", (ev) => {
1247
- this._keyStates.set(ev.code, { state: UP, time: ev.timeStamp });
1248
- this.onKeyUp.notify(this, ev);
1249
- const delta = ev.timeStamp - (this._keyStates.get(ev.code)?.time ?? 0);
1250
- if (delta < this.inputThreshold) {
1251
- this.onKeyPressed.notify(this, ev);
1252
- }
1253
- });
1254
- window.addEventListener("pointerdown", (ev) => {
1255
- const code = `Button${ev.button}`;
1256
- if (!this._buttonStates.get(code)) {
1257
- this._buttonStates.set(code, { state: DOWN, time: ev.timeStamp });
1258
- this.onPointerDown.notify(this, ev);
1333
+ super();
1334
+ window.addEventListener("keydown", this._onKeyDown.bind(this));
1335
+ window.addEventListener("keyup", this._onKeyUp.bind(this));
1336
+ window.addEventListener("pointerdown", this._onPointerButtonDown.bind(this));
1337
+ window.addEventListener("pointerup", this._onPointerButtonUp.bind(this));
1338
+ window.addEventListener("mousemove", this._onMouseMove.bind(this));
1339
+ window.addEventListener("wheel", this._onWheel.bind(this));
1340
+ }
1341
+ _getCommonEventProps(event) {
1342
+ const props = {
1343
+ timeStamp: event.timeStamp,
1344
+ altKey: event.altKey,
1345
+ ctrlKey: event.ctrlKey,
1346
+ metaKey: event.metaKey,
1347
+ shiftKey: event.shiftKey,
1348
+ event
1349
+ };
1350
+ return props;
1351
+ }
1352
+ // private _onContextMenu(ev: MouseEvent) {
1353
+ // ev.preventDefault();
1354
+ // this.emit('contextmenu');
1355
+ // return false;
1356
+ // }
1357
+ _onKeyDown(ev) {
1358
+ const props = this._getCommonEventProps(ev);
1359
+ const { code, key } = ev;
1360
+ if (!ev.repeat) {
1361
+ this._keyStates[code] = { state: 1, timeStamp: props.timeStamp };
1362
+ this.emit("key_down", { ...props, code, key });
1363
+ this.emit(`${code.toLowerCase()}_down`, props);
1364
+ }
1365
+ }
1366
+ _onKeyUp(ev) {
1367
+ const props = this._getCommonEventProps(ev);
1368
+ const { code, key } = ev;
1369
+ const deltaStamp = props.timeStamp - (this._keyStates[code]?.timeStamp ?? 0);
1370
+ this._keyStates[code] = { state: 0, timeStamp: props.timeStamp };
1371
+ this.emit("key_up", { ...props, code, key });
1372
+ this.emit(`${code.toLowerCase()}_up`, props);
1373
+ if (deltaStamp < this.inputThreshold) {
1374
+ this.emit("key_pressed", { ...props, code, key });
1375
+ this.emit(`${code.toLowerCase()}_pressed`, props);
1376
+ }
1377
+ }
1378
+ _onPointerButtonDown(ev) {
1379
+ const props = this._getCommonEventProps(ev);
1380
+ const { button } = ev;
1381
+ if (!this._mouseButtonStates[button]?.state) {
1382
+ this._mouseButtonStates[button] = { state: 1, timeStamp: props.timeStamp };
1383
+ switch (ev.pointerType) {
1384
+ case "touch":
1385
+ this.emit("touch_down", { ...props, button });
1386
+ break;
1387
+ default:
1388
+ this.emit("mouse_button_down", { ...props, button });
1389
+ this.emit(`mouse_button${button}_down`, props);
1390
+ break;
1259
1391
  }
1260
- });
1261
- window.addEventListener("pointerup", (ev) => {
1262
- const code = `Button${ev.button}`;
1263
- this._buttonStates.set(code, { state: UP, time: ev.timeStamp });
1264
- this.onPointerUp.notify(this, ev);
1265
- const delta = ev.timeStamp - (this._buttonStates.get(code)?.time ?? 0);
1266
- if (delta < this.inputThreshold) {
1267
- this.onPointerPressed.notify(this, ev);
1392
+ }
1393
+ }
1394
+ _onPointerButtonUp(ev) {
1395
+ const props = this._getCommonEventProps(ev);
1396
+ const { button } = ev;
1397
+ const deltaStamp = props.timeStamp - (this._mouseButtonStates[button]?.timeStamp ?? 0);
1398
+ this._mouseButtonStates[button] = { state: 0, timeStamp: props.timeStamp };
1399
+ switch (ev.pointerType) {
1400
+ case "touch":
1401
+ this.emit("touch_up", { ...props, button });
1402
+ break;
1403
+ default:
1404
+ this.emit("mouse_button_up", { ...props, button });
1405
+ this.emit(`mouse_button${button}_up`, props);
1406
+ break;
1407
+ }
1408
+ if (deltaStamp < this.inputThreshold) {
1409
+ switch (ev.pointerType) {
1410
+ case "touch":
1411
+ this.emit("tapped", { ...props, button });
1412
+ break;
1413
+ default:
1414
+ this.emit("mouse_button_clicked", { ...props, button });
1415
+ this.emit(`mouse_button${button}_clicked`, props);
1416
+ break;
1268
1417
  }
1418
+ }
1419
+ }
1420
+ _onMouseMove(ev) {
1421
+ const props = this._getCommonEventProps(ev);
1422
+ const { buttons, offsetX, offsetY, movementX, movementY } = ev;
1423
+ this._mousePosition = new Vector(offsetX, offsetY);
1424
+ const width = window.innerWidth;
1425
+ const height = window.innerHeight;
1426
+ this._mousePosition2 = new Vector(
1427
+ ev.clientX / width * 2 - 1,
1428
+ -(ev.clientY / height) * 2 + 1
1429
+ );
1430
+ this.emit("mouse_move", {
1431
+ ...props,
1432
+ buttons,
1433
+ x: offsetX,
1434
+ y: offsetY,
1435
+ deltaX: movementX,
1436
+ deltaY: movementY
1269
1437
  });
1270
- window.addEventListener("pointermove", (ev) => {
1271
- this._pointerPosition.x = ev.offsetX;
1272
- this._pointerPosition.y = ev.offsetY;
1273
- this.onPointerMove.notify(this, ev);
1274
- });
1275
- window.addEventListener("wheel", (ev) => {
1276
- this.onWheel.notify(this, ev);
1438
+ }
1439
+ _onWheel(ev) {
1440
+ const props = this._getCommonEventProps(ev);
1441
+ const { deltaX, deltaY, deltaZ } = ev;
1442
+ this.emit("mouse_wheel", {
1443
+ ...props,
1444
+ deltaX,
1445
+ deltaY,
1446
+ deltaZ
1277
1447
  });
1278
1448
  }
1279
- isDown(key) {
1280
- return (this._keyStates.get(key) ?? this._buttonStates.get(key))?.state === 1;
1449
+ isKeyDown(keyCode) {
1450
+ return this._keyStates[keyCode]?.state === 1 ? true : false;
1451
+ }
1452
+ getKeyState(keyCode) {
1453
+ return this._keyStates[keyCode]?.state ?? 0;
1454
+ }
1455
+ isMouseButtonDown(mouseButton) {
1456
+ return this._mouseButtonStates[mouseButton]?.state === 1 ? true : false;
1457
+ }
1458
+ getMouseButtonState(button) {
1459
+ return this._mouseButtonStates[button]?.state ?? 0;
1281
1460
  }
1282
1461
  };
1283
1462
 
1284
1463
  // src/map3d.ts
1285
- var DEFAULT_VALUE2 = -1;
1464
+ var DEFAULT_MAP_3D_VALUE = -1;
1286
1465
  var BASE_3D = 131072;
1287
1466
  var OFFSET_3D = 65536;
1288
- var Map3D = class {
1467
+ var Map3D = class _Map3D {
1289
1468
  defaultValue;
1290
1469
  _data;
1291
1470
  get data() {
@@ -1294,12 +1473,12 @@ var Map3D = class {
1294
1473
  get size() {
1295
1474
  return this._data.size;
1296
1475
  }
1297
- constructor(defaultValue = DEFAULT_VALUE2) {
1476
+ constructor(defaultValue = DEFAULT_MAP_3D_VALUE, mapData) {
1298
1477
  this.defaultValue = defaultValue;
1299
- this._data = /* @__PURE__ */ new Map();
1478
+ this._data = mapData ?? /* @__PURE__ */ new Map();
1300
1479
  }
1301
1480
  _floor(x, y, z) {
1302
- return [floor(x), floor(y), floor(z)];
1481
+ return [Math.floor(x), Math.floor(y), Math.floor(z)];
1303
1482
  }
1304
1483
  _key(x, y, z) {
1305
1484
  const X = x + OFFSET_3D & BASE_3D - 1;
@@ -1309,32 +1488,59 @@ var Map3D = class {
1309
1488
  }
1310
1489
  _pos(key) {
1311
1490
  const Z = key % BASE_3D;
1312
- const Y = floor(key / BASE_3D) % BASE_3D;
1313
- const X = floor(key / (BASE_3D * BASE_3D));
1491
+ const Y = Math.floor(key / BASE_3D) % BASE_3D;
1492
+ const X = Math.floor(key / (BASE_3D * BASE_3D));
1314
1493
  return [X - OFFSET_3D, Y - OFFSET_3D, Z - OFFSET_3D];
1315
1494
  }
1316
1495
  clear() {
1317
1496
  this._data.clear();
1318
1497
  }
1319
- get(x, y, z, defaultValue = this.defaultValue) {
1498
+ get(x, y, z = 0) {
1320
1499
  [x, y, z] = this._floor(x, y, z);
1321
- return this._data.get(this._key(x, y, z)) ?? defaultValue;
1500
+ return this._data.get(this._key(x, y, z)) ?? this.defaultValue;
1322
1501
  }
1323
- set(x, y, z, value = this.defaultValue) {
1502
+ set(x, y, z, n = this.defaultValue) {
1324
1503
  [x, y, z] = this._floor(x, y, z);
1325
1504
  const key = this._key(x, y, z);
1326
- if (value === this.defaultValue) {
1505
+ if (n === this.defaultValue) {
1327
1506
  this._data.delete(key);
1328
1507
  } else {
1329
- this._data.set(key, value);
1508
+ this._data.set(key, n);
1509
+ }
1510
+ }
1511
+ setArea(x1, y1, z1, x2, y2, z2, n) {
1512
+ for (let z = z1; z <= z2; z++) {
1513
+ for (let y = y1; y <= y2; y++) {
1514
+ for (let x = x1; x <= x2; x++) {
1515
+ this.set(x, y, z, n);
1516
+ }
1517
+ }
1330
1518
  }
1331
1519
  }
1332
1520
  forEach(callback) {
1333
- this._data.forEach((v, key) => {
1521
+ this._data.forEach((n, key) => {
1334
1522
  const [x, y, z] = this._pos(key);
1335
- callback(x, y, z, v);
1523
+ callback(x, y, z, n);
1524
+ });
1525
+ }
1526
+ export() {
1527
+ const data = [];
1528
+ this.forEach((x, y, z, n) => {
1529
+ data.push({ x, y, z, n });
1530
+ });
1531
+ return data;
1532
+ }
1533
+ import(data) {
1534
+ this.clear();
1535
+ data.forEach(({ x, y, z, n }) => {
1536
+ this.set(x, y, z, n);
1336
1537
  });
1337
1538
  }
1539
+ static fromMap2D(map2d, defaultValue = DEFAULT_MAP_3D_VALUE) {
1540
+ const map3d = new _Map3D(defaultValue);
1541
+ map2d.forEach((x, y, n) => map3d.set(x, y, 0, n));
1542
+ return map3d;
1543
+ }
1338
1544
  };
1339
1545
 
1340
1546
  // src/misc.ts
@@ -1344,16 +1550,16 @@ function isNullOrUndefined(target) {
1344
1550
  function isPositiveString(target) {
1345
1551
  return target.length > 0;
1346
1552
  }
1347
- var getRedYellowGreenGradientHex = (min2, max2) => {
1348
- if (max2 === void 0) {
1349
- max2 = min2;
1350
- min2 = 0;
1553
+ var getRedYellowGreenGradientHex = (min, max) => {
1554
+ if (max === void 0) {
1555
+ max = min;
1556
+ min = 0;
1351
1557
  }
1352
- if (max2 < 1) {
1353
- max2 = 1;
1558
+ if (max < 1) {
1559
+ max = 1;
1354
1560
  }
1355
- const percent = min2 / max2;
1356
- const index = clamp(floor(percent * 10), 0, 10);
1561
+ const percent = min / max;
1562
+ const index = clamp(Math.floor(percent * 10), 0, 10);
1357
1563
  return [
1358
1564
  "#ff0000",
1359
1565
  "#ff3300",
@@ -1442,167 +1648,57 @@ var Noise = class _Noise {
1442
1648
  }
1443
1649
  };
1444
1650
 
1445
- // src/rendering/color.ts
1446
- var Color = class _Color {
1447
- _hex = "#ffffffff";
1448
- _r = 255;
1449
- _g = 255;
1450
- _b = 255;
1451
- _a = 255;
1452
- get r() {
1453
- return this._r;
1651
+ // src/particle-renderer.ts
1652
+ var ParticleRenderer = class {
1653
+ _screenCanvas;
1654
+ _bufferCanvas;
1655
+ screenContext;
1656
+ bufferContext;
1657
+ get width() {
1658
+ return this._screenCanvas.width;
1454
1659
  }
1455
- set r(value) {
1456
- this._r = clamp(value, 0, 255);
1457
- this._hex = this._to_hex();
1660
+ get height() {
1661
+ return this._screenCanvas.height;
1458
1662
  }
1459
- get g() {
1460
- return this._g;
1461
- }
1462
- set g(value) {
1463
- this._g = clamp(value, 0, 255);
1464
- this._hex = this._to_hex();
1465
- }
1466
- get b() {
1467
- return this._b;
1468
- }
1469
- set b(value) {
1470
- this._b = clamp(value, 0, 255);
1471
- this._hex = this._to_hex();
1472
- }
1473
- get a() {
1474
- return this._a;
1475
- }
1476
- set a(value) {
1477
- this._a = clamp(value, 0, 255);
1478
- this._hex = this._to_hex();
1479
- }
1480
- get hexStr() {
1481
- return this._hex;
1482
- }
1483
- set hexStr(value) {
1484
- if (value.startsWith("#")) {
1485
- [this._r, this._g, this._b, this._a] = this._parse_hex_color_string(value);
1486
- this._hex = value;
1487
- } else {
1488
- logger_default(`Color: invalid color string: ${value}. Should be a hexadecimal color string (i.e.: '#ffffff' or '#ffffffff'). Keeping the current color.`);
1663
+ constructor(canvas) {
1664
+ this._screenCanvas = canvas ?? document.createElement("canvas");
1665
+ this._bufferCanvas = new OffscreenCanvas(this._screenCanvas.width, this._screenCanvas.height);
1666
+ this.screenContext = this._screenCanvas.getContext("2d");
1667
+ this.bufferContext = this._bufferCanvas.getContext("2d");
1668
+ if (!this.screenContext || !this.bufferContext) {
1669
+ throw "Failed to create CanvasRenderingContext2D";
1489
1670
  }
1490
1671
  }
1491
- get rgba() {
1492
- return [this._r, this._g, this._b, this._a];
1493
- }
1494
- constructor(r = 255, g = 255, b = 255, a = 255) {
1495
- if (typeof r === "string") {
1496
- if (r.startsWith("#")) {
1497
- [r, g, b, a] = this._parse_hex_color_string(r);
1498
- } else {
1499
- logger_default(`Color: invalid color string: ${r}. Should be a hexadecimal color string (i.e.: '#ffffff' or '#ffffffff'). Defaulting to opaque white.`);
1500
- r = g = b = a = 255;
1501
- }
1502
- } else {
1503
- [r, g, b, a] = [r, g, b, a].map((n) => _Color._normalize(n));
1672
+ appendTo(target, autoResize = true) {
1673
+ if (this._screenCanvas.parentNode) {
1674
+ this._screenCanvas.parentNode.removeChild(this._screenCanvas);
1504
1675
  }
1505
- this.r = r;
1506
- this.g = g;
1507
- this.b = b;
1508
- this.a = a;
1509
- }
1510
- static _normalize(value) {
1511
- return clamp(0 | (value > 0 && value < 1 ? value * 255 : value), 0, 255);
1512
- }
1513
- _to_hex() {
1514
- 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")}`;
1515
- }
1516
- _parse_hex_color_string(hex) {
1517
- const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})?$/i.exec(hex);
1518
- return result ? [
1519
- parseInt(result[1], 16),
1520
- parseInt(result[2], 16),
1521
- parseInt(result[3], 16),
1522
- result[4] ? parseInt(result[4], 16) : 255
1523
- ] : [255, 255, 255, 255];
1524
- }
1525
- static fromHsv(h, s, v, a = 255) {
1526
- let r = 0;
1527
- let g = 0;
1528
- let b = 0;
1529
- let i = Math.floor(h * 6);
1530
- let f = h * 6 - i;
1531
- let p = v * (1 - s);
1532
- let q = v * (1 - f * s);
1533
- let t = v * (1 - (1 - f) * s);
1534
- switch (i % 6) {
1535
- case 0:
1536
- r = v, g = t, b = p;
1537
- break;
1538
- case 1:
1539
- r = q, g = v, b = p;
1540
- break;
1541
- case 2:
1542
- r = p, g = v, b = t;
1543
- break;
1544
- case 3:
1545
- r = p, g = q, b = v;
1546
- break;
1547
- case 4:
1548
- r = t, g = p, b = v;
1549
- break;
1550
- case 5:
1551
- r = v, g = p, b = q;
1552
- break;
1676
+ target.appendChild(this._screenCanvas);
1677
+ if (autoResize) {
1678
+ this.resize();
1553
1679
  }
1554
- return new _Color(Math.round(r * 255), Math.round(g * 255), Math.round(b * 255), a);
1555
- }
1556
- static get BLACK() {
1557
- return new _Color(0, 0, 0, 255);
1558
- }
1559
- static get GRAY() {
1560
- return new _Color(128, 128, 128, 255);
1561
- }
1562
- static get WHITE() {
1563
- return new _Color(255, 255, 255, 255);
1564
- }
1565
- static get RED() {
1566
- return new _Color(255, 0, 0, 255);
1567
- }
1568
- static get GREEN() {
1569
- return new _Color(0, 255, 0, 255);
1570
- }
1571
- static get BLUE() {
1572
- return new _Color(0, 0, 255, 255);
1573
- }
1574
- static get YELLOW() {
1575
- return new _Color(255, 255, 0, 255);
1576
- }
1577
- static get ORANGE() {
1578
- return new _Color(255, 128, 0, 255);
1579
- }
1580
- static get PURPLE() {
1581
- return new _Color(128, 0, 128, 255);
1582
1680
  }
1583
- static get CYAN() {
1584
- return new _Color(0, 255, 255, 255);
1585
- }
1586
- static get MAGENTA() {
1587
- return new _Color(255, 0, 255, 255);
1588
- }
1589
- static fromName(name) {
1590
- const element = document.createElement("div");
1591
- element.style.color = name;
1592
- document.body.appendChild(element);
1593
- const computedColor = getComputedStyle(element).color;
1594
- document.body.removeChild(element);
1595
- const rgba = computedColor.match(/\d+/g);
1596
- if (rgba && rgba.length === 4) {
1597
- const [r, g, b, a] = rgba.map(Number);
1598
- return new _Color(r, g, b, a);
1599
- } else {
1600
- logger_default(`Color: invalid CSS color name: ${name}. Defaulting to transparent.`);
1601
- return _Color.TRANSPARENT;
1681
+ resize(displayWidth, displayHeight) {
1682
+ const { width, height } = this._screenCanvas.parentElement?.getBoundingClientRect() ?? this._screenCanvas.getBoundingClientRect();
1683
+ displayWidth = 0 | (displayWidth ?? width);
1684
+ displayHeight = 0 | (displayHeight ?? height);
1685
+ if (this._screenCanvas.width !== displayWidth || this._screenCanvas.height !== displayHeight) {
1686
+ this._screenCanvas.width = displayWidth;
1687
+ this._screenCanvas.height = displayHeight;
1688
+ this._bufferCanvas.width = displayWidth;
1689
+ this._bufferCanvas.height = displayHeight;
1690
+ return true;
1602
1691
  }
1692
+ return false;
1603
1693
  }
1604
- static get TRANSPARENT() {
1605
- return new _Color(0, 0, 0, 0);
1694
+ setPixel(x, y, color, size = 2) {
1695
+ this.bufferContext.fillStyle = color.hexStr;
1696
+ this.bufferContext.fillRect(x - size / 2, y - size / 2, size, size);
1697
+ }
1698
+ render() {
1699
+ this.screenContext.clearRect(0, 0, this._screenCanvas.width, this._screenCanvas.height);
1700
+ this.screenContext.drawImage(this._bufferCanvas, 0, 0);
1701
+ this.bufferContext.clearRect(0, 0, this._screenCanvas.width, this._screenCanvas.height);
1606
1702
  }
1607
1703
  };
1608
1704
 
@@ -1693,12 +1789,12 @@ var ParticleSystem2d = class {
1693
1789
  if (r < beta) {
1694
1790
  f = r / beta - 1;
1695
1791
  } else if (beta < r && r < 1) {
1696
- f = a * (1 - abs(2 * r - 1 - beta) / (1 - beta));
1792
+ f = a * (1 - Math.abs(2 * r - 1 - beta) / (1 - beta));
1697
1793
  }
1698
1794
  return f;
1699
1795
  }
1700
1796
  _updateVelocities(deltaTimeSeconds) {
1701
- const frictionFactor = pow(
1797
+ const frictionFactor = Math.pow(
1702
1798
  0.5,
1703
1799
  deltaTimeSeconds / this._frictionHalfLife
1704
1800
  );
@@ -1715,10 +1811,10 @@ var ParticleSystem2d = class {
1715
1811
  if (cell === neighborCell && i === j) continue;
1716
1812
  const p2 = neighborCell[j];
1717
1813
  let rx = p2.x - p1.x;
1718
- if (abs(rx) > 0.5) rx = rx > 0 ? rx - 1 : rx + 1;
1814
+ if (Math.abs(rx) > 0.5) rx = rx > 0 ? rx - 1 : rx + 1;
1719
1815
  let ry = p2.y - p1.y;
1720
- if (abs(ry) > 0.5) ry = ry > 0 ? ry - 1 : ry + 1;
1721
- const d = hypot2(rx, ry);
1816
+ if (Math.abs(ry) > 0.5) ry = ry > 0 ? ry - 1 : ry + 1;
1817
+ const d = Math.hypot(rx, ry);
1722
1818
  if (d > 0 && d < this._range) {
1723
1819
  const f = this._calcForce(
1724
1820
  d / this._range,
@@ -1775,8 +1871,8 @@ var ParticleSystem2d = class {
1775
1871
  function PoissonDiskSampler(width, height, minDist, maxPoints = 30) {
1776
1872
  const k = maxPoints;
1777
1873
  const cellSize = minDist / SQRT2;
1778
- const gridWidth = ceil(width / cellSize);
1779
- const gridHeight = ceil(height / cellSize);
1874
+ const gridWidth = Math.ceil(width / cellSize);
1875
+ const gridHeight = Math.ceil(height / cellSize);
1780
1876
  const grid = Array.from(
1781
1877
  { length: gridWidth },
1782
1878
  () => Array(gridHeight).fill(null)
@@ -1785,8 +1881,8 @@ function PoissonDiskSampler(width, height, minDist, maxPoints = 30) {
1785
1881
  const active = [];
1786
1882
  function gridIndex(p) {
1787
1883
  return {
1788
- i: floor(p.x / cellSize),
1789
- j: floor(p.y / cellSize)
1884
+ i: Math.floor(p.x / cellSize),
1885
+ j: Math.floor(p.y / cellSize)
1790
1886
  };
1791
1887
  }
1792
1888
  function isFarEnough(p) {
@@ -1814,15 +1910,15 @@ function PoissonDiskSampler(width, height, minDist, maxPoints = 30) {
1814
1910
  samples.push(initial);
1815
1911
  active.push(initial);
1816
1912
  while (active.length) {
1817
- const index = floor(rng.range(0, active.length));
1913
+ const index = Math.floor(rng.range(0, active.length));
1818
1914
  const point = active[index];
1819
1915
  let found = false;
1820
1916
  for (let n = 0; n < k; n++) {
1821
1917
  const angle = rng.range(0, PI * 2);
1822
1918
  const dist = rng.range(minDist, 2 * minDist);
1823
1919
  const newPoint = {
1824
- x: point.x + cos(angle) * dist,
1825
- y: point.y + sin(angle) * dist
1920
+ x: point.x + Math.cos(angle) * dist,
1921
+ y: point.y + Math.sin(angle) * dist
1826
1922
  };
1827
1923
  if (newPoint.x >= 0 && newPoint.y >= 0 && newPoint.x < width && newPoint.y < height && isFarEnough(newPoint)) {
1828
1924
  const { i, j } = gridIndex(newPoint);
@@ -1840,273 +1936,320 @@ function PoissonDiskSampler(width, height, minDist, maxPoints = 30) {
1840
1936
  return samples;
1841
1937
  }
1842
1938
 
1843
- // src/rendering/canvas-renderer.ts
1844
- var DEFAULT_COLOR = "white";
1845
- var DEFAULT_PIXEL_SIZE = 1;
1846
- var DEFAULT_FONT_SIZE = 14;
1847
- var DEFAULT_FONT_NAME = "monospace";
1848
- var DEFAULT_FONT = `${DEFAULT_FONT_SIZE}px ${DEFAULT_FONT_NAME}`;
1849
- var DEFAULT_TEXTALIGN = "left";
1850
- var DEFAULT_TEXTBASELINE = "alphabetic";
1851
- var CanvasRenderer = class {
1852
- context;
1853
- get canvas() {
1854
- return this.context.canvas;
1939
+ // src/signal.ts
1940
+ var Signal = class {
1941
+ value;
1942
+ subscribers = /* @__PURE__ */ new Set();
1943
+ constructor(initialValue) {
1944
+ this.value = initialValue;
1855
1945
  }
1856
- get width() {
1857
- return this.canvas.width;
1946
+ get() {
1947
+ return this.value;
1858
1948
  }
1859
- get height() {
1860
- return this.canvas.height;
1949
+ set(value) {
1950
+ if (Object.is(this.value, value)) return;
1951
+ this.value = value;
1952
+ for (const subscriber of [...this.subscribers]) {
1953
+ subscriber(value);
1954
+ }
1861
1955
  }
1862
- constructor(canvas) {
1863
- this.context = (canvas ?? document.createElement("canvas")).getContext("2d");
1864
- this.context.font = DEFAULT_FONT;
1865
- this.context.textAlign = DEFAULT_TEXTALIGN;
1866
- this.context.textBaseline = DEFAULT_TEXTBASELINE;
1956
+ subscribe(subscriber) {
1957
+ this.subscribers.add(subscriber);
1958
+ subscriber(this.value);
1959
+ return () => this.subscribers.delete(subscriber);
1867
1960
  }
1868
- resize(width, height) {
1869
- let resized = false;
1870
- width = width ?? this.canvas.parentElement?.clientWidth ?? this.width;
1871
- height = height ?? this.canvas.parentElement?.clientHeight ?? this.height;
1872
- if (this.canvas.width != width || this.canvas.height != height) {
1873
- this.canvas.width = width;
1874
- this.canvas.height = height;
1875
- resized = true;
1961
+ };
1962
+
1963
+ // src/simplex-noise.ts
1964
+ var SimplexNoise = class {
1965
+ grad3;
1966
+ p;
1967
+ perm;
1968
+ constructor() {
1969
+ this.grad3 = [
1970
+ [1, 1, 0],
1971
+ [-1, 1, 0],
1972
+ [1, -1, 0],
1973
+ [-1, -1, 0],
1974
+ [1, 0, 1],
1975
+ [-1, 0, 1],
1976
+ [1, 0, -1],
1977
+ [-1, 0, -1],
1978
+ [0, 1, 1],
1979
+ [0, -1, 1],
1980
+ [0, 1, -1],
1981
+ [0, -1, -1]
1982
+ ];
1983
+ this.p = [];
1984
+ for (let i = 0; i < 256; i++) {
1985
+ this.p.push(Math.floor(rng.nextFloat() * 256));
1986
+ }
1987
+ this.perm = [];
1988
+ for (let i = 0; i < 512; i++) {
1989
+ this.perm.push(this.p[i & 255]);
1876
1990
  }
1877
- return resized;
1878
- }
1879
- clear() {
1880
- this.context.clearRect(0, 0, this.width, this.height);
1881
1991
  }
1882
- render(callback, camera) {
1883
- camera = camera ?? { x: 0, y: 0, z: 1 };
1884
- this.clear();
1885
- this.context.save();
1886
- this.context.translate(this.width / 2, this.height / 2);
1887
- this.context.scale(camera.z, camera.z);
1888
- this.context.translate(-camera.x, -camera.y);
1889
- callback();
1890
- this.context.restore();
1992
+ dot(g, x, y, z) {
1993
+ return g[0] * x + g[1] * y + (typeof z === "number" ? g[2] * z : 0);
1891
1994
  }
1892
- drawPath(buildPath, params = {}) {
1893
- this.context.fillStyle = params.color ?? DEFAULT_COLOR;
1894
- this.context.strokeStyle = params.color ?? DEFAULT_COLOR;
1895
- this.context.lineWidth = params.size ?? 1;
1896
- if (params.lineDash) {
1897
- this.context.setLineDash(params.lineDash);
1995
+ noise2d(xin, yin) {
1996
+ let n0, n1, n2;
1997
+ const F2 = 0.5 * (Math.sqrt(3) - 1);
1998
+ const s = (xin + yin) * F2;
1999
+ let i = Math.floor(xin + s);
2000
+ let j = Math.floor(yin + s);
2001
+ const G2 = (3 - Math.sqrt(3)) / 6;
2002
+ const t = (i + j) * G2;
2003
+ const X0 = i - t;
2004
+ const Y0 = j - t;
2005
+ const x0 = xin - X0;
2006
+ const y0 = yin - Y0;
2007
+ let i1, j1;
2008
+ if (x0 > y0) {
2009
+ i1 = 1;
2010
+ j1 = 0;
2011
+ } else {
2012
+ i1 = 0;
2013
+ j1 = 1;
1898
2014
  }
1899
- this.context.beginPath();
1900
- buildPath();
1901
- this.context.stroke();
1902
- if (params.filled) {
1903
- this.context.fill();
2015
+ const x1 = x0 - i1 + G2;
2016
+ const y1 = y0 - j1 + G2;
2017
+ const x2 = x0 - 1 + 2 * G2;
2018
+ const y2 = y0 - 1 + 2 * G2;
2019
+ const ii = i & 255;
2020
+ const jj = j & 255;
2021
+ const gi0 = this.perm[ii + this.perm[jj]] % 12;
2022
+ const gi1 = this.perm[ii + i1 + this.perm[jj + j1]] % 12;
2023
+ const gi2 = this.perm[ii + 1 + this.perm[jj + 1]] % 12;
2024
+ let t0 = 0.5 - x0 * x0 - y0 * y0;
2025
+ if (t0 < 0) {
2026
+ n0 = 0;
2027
+ } else {
2028
+ t0 *= t0;
2029
+ n0 = t0 * t0 * this.dot(this.grad3[gi0], x0, y0);
1904
2030
  }
1905
- if (params.lineDash) {
1906
- this.context.setLineDash([]);
2031
+ let t1 = 0.5 - x1 * x1 - y1 * y1;
2032
+ if (t1 < 0) {
2033
+ n1 = 0;
2034
+ } else {
2035
+ t1 *= t1;
2036
+ n1 = t1 * t1 * this.dot(this.grad3[gi1], x1, y1);
1907
2037
  }
2038
+ let t2 = 0.5 - x2 * x2 - y2 * y2;
2039
+ if (t2 < 0) {
2040
+ n2 = 0;
2041
+ } else {
2042
+ t2 *= t2;
2043
+ n2 = t2 * t2 * this.dot(this.grad3[gi2], x2, y2);
2044
+ }
2045
+ return 70 * (n0 + n1 + n2);
1908
2046
  }
1909
- drawRect(x, y, width, height, params = {}) {
1910
- x -= width / 2;
1911
- y -= height / 2;
1912
- this.context.fillStyle = params.color ?? DEFAULT_COLOR;
1913
- this.context.strokeStyle = params.color ?? DEFAULT_COLOR;
1914
- this.context.lineWidth = params.size ?? 1;
1915
- if (params.lineDash) {
1916
- this.context.setLineDash(params.lineDash);
2047
+ noise3d(xin, yin, zin) {
2048
+ let n0, n1, n2, n3;
2049
+ const F3 = 1 / 3;
2050
+ const s = (xin + yin + zin) * F3;
2051
+ const i = Math.floor(xin + s);
2052
+ const j = Math.floor(yin + s);
2053
+ const k = Math.floor(zin + s);
2054
+ const G3 = 1 / 6;
2055
+ const t = (i + j + k) * G3;
2056
+ const X0 = i - t;
2057
+ const Y0 = j - t;
2058
+ const Z0 = k - t;
2059
+ const x0 = xin - X0;
2060
+ const y0 = yin - Y0;
2061
+ const z0 = zin - Z0;
2062
+ let i1, j1, k1;
2063
+ let i2, j2, k2;
2064
+ if (x0 >= y0) {
2065
+ if (y0 >= z0) {
2066
+ i1 = 1;
2067
+ j1 = 0;
2068
+ k1 = 0;
2069
+ i2 = 1;
2070
+ j2 = 1;
2071
+ k2 = 0;
2072
+ } else if (x0 >= z0) {
2073
+ i1 = 1;
2074
+ j1 = 0;
2075
+ k1 = 0;
2076
+ i2 = 1;
2077
+ j2 = 0;
2078
+ k2 = 1;
2079
+ } else {
2080
+ i1 = 0;
2081
+ j1 = 0;
2082
+ k1 = 1;
2083
+ i2 = 1;
2084
+ j2 = 0;
2085
+ k2 = 1;
2086
+ }
2087
+ } else {
2088
+ if (y0 < z0) {
2089
+ i1 = 0;
2090
+ j1 = 0;
2091
+ k1 = 1;
2092
+ i2 = 0;
2093
+ j2 = 1;
2094
+ k2 = 1;
2095
+ } else if (x0 < z0) {
2096
+ i1 = 0;
2097
+ j1 = 1;
2098
+ k1 = 0;
2099
+ i2 = 0;
2100
+ j2 = 1;
2101
+ k2 = 1;
2102
+ } else {
2103
+ i1 = 0;
2104
+ j1 = 1;
2105
+ k1 = 0;
2106
+ i2 = 1;
2107
+ j2 = 1;
2108
+ k2 = 0;
2109
+ }
1917
2110
  }
1918
- this.context.beginPath();
1919
- this.context.strokeRect(x, y, width, height);
1920
- if (params.filled) {
1921
- this.context.fillRect(x, y, width, height);
2111
+ const x1 = x0 - i1 + G3;
2112
+ const y1 = y0 - j1 + G3;
2113
+ const z1 = z0 - k1 + G3;
2114
+ const x2 = x0 - i2 + 2 * G3;
2115
+ const y2 = y0 - j2 + 2 * G3;
2116
+ const z2 = z0 - k2 + 2 * G3;
2117
+ const x3 = x0 - 1 + 3 * G3;
2118
+ const y3 = y0 - 1 + 3 * G3;
2119
+ const z3 = z0 - 1 + 3 * G3;
2120
+ const ii = i & 255;
2121
+ const jj = j & 255;
2122
+ const kk = k & 255;
2123
+ const gi0 = this.perm[ii + this.perm[jj + this.perm[kk]]] % 12;
2124
+ const gi1 = this.perm[ii + i1 + this.perm[jj + j1 + this.perm[kk + k1]]] % 12;
2125
+ const gi2 = this.perm[ii + i2 + this.perm[jj + j2 + this.perm[kk + k2]]] % 12;
2126
+ const gi3 = this.perm[ii + 1 + this.perm[jj + 1 + this.perm[kk + 1]]] % 12;
2127
+ let t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0;
2128
+ if (t0 < 0) {
2129
+ n0 = 0;
2130
+ } else {
2131
+ t0 *= t0;
2132
+ n0 = t0 * t0 * this.dot(this.grad3[gi0], x0, y0, z0);
1922
2133
  }
1923
- if (params.lineDash) {
1924
- this.context.setLineDash([]);
2134
+ let t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1;
2135
+ if (t1 < 0) {
2136
+ n1 = 0;
2137
+ } else {
2138
+ t1 *= t1;
2139
+ n1 = t1 * t1 * this.dot(this.grad3[gi1], x1, y1, z1);
1925
2140
  }
1926
- }
1927
- drawPixel(x, y, params = {}) {
1928
- const size = abs(params.size || DEFAULT_PIXEL_SIZE);
1929
- this.drawRect(x, y, size, size, {
1930
- ...params,
1931
- filled: true
1932
- });
1933
- }
1934
- drawLine(x1, y1, x2, y2, params = {}) {
1935
- this.context.strokeStyle = params.color ?? DEFAULT_COLOR;
1936
- this.context.lineWidth = params.size ?? 1;
1937
- if (params.lineDash) {
1938
- this.context.setLineDash(params.lineDash);
2141
+ let t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2;
2142
+ if (t2 < 0) {
2143
+ n2 = 0;
2144
+ } else {
2145
+ t2 *= t2;
2146
+ n2 = t2 * t2 * this.dot(this.grad3[gi2], x2, y2, z2);
1939
2147
  }
1940
- this.context.beginPath();
1941
- this.context.moveTo(x1, y1);
1942
- this.context.lineTo(x2, y2);
1943
- this.context.stroke();
1944
- if (params.lineDash) {
1945
- this.context.setLineDash([]);
2148
+ let t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3;
2149
+ if (t3 < 0) {
2150
+ n3 = 0;
2151
+ } else {
2152
+ t3 *= t3;
2153
+ n3 = t3 * t3 * this.dot(this.grad3[gi3], x3, y3, z3);
2154
+ }
2155
+ return 32 * (n0 + n1 + n2 + n3);
2156
+ }
2157
+ };
2158
+
2159
+ // src/spatial-partition-3d.ts
2160
+ var SpatialPartition3d = class {
2161
+ cells;
2162
+ cellSize;
2163
+ entities;
2164
+ constructor(cellSize, entities) {
2165
+ this.cellSize = cellSize;
2166
+ this.entities = entities;
2167
+ const gridSize = Math.ceil(1 / cellSize);
2168
+ this.cells = Array.from(
2169
+ { length: gridSize },
2170
+ () => Array.from(
2171
+ { length: gridSize },
2172
+ () => Array.from({ length: gridSize }, () => [])
2173
+ )
2174
+ );
2175
+ for (const entity of this.entities) {
2176
+ this.addEntity(entity);
1946
2177
  }
1947
2178
  }
1948
- drawCircle(x, y, radius, params = {}) {
1949
- this.drawPath(() => {
1950
- this.context.arc(x, y, radius, 0, TAU);
1951
- }, params);
2179
+ getCell(x, y, z) {
2180
+ const cx = Math.floor(x / this.cellSize);
2181
+ const cy = Math.floor(y / this.cellSize);
2182
+ const cz = Math.floor(z / this.cellSize);
2183
+ return this.cells[cz][cy][cx];
1952
2184
  }
1953
- drawPolygon(x, y, radius, sides, params = {}) {
1954
- sides = floor(clamp(sides, 3, 36));
1955
- this.drawPath(() => {
1956
- for (let i = 0; i < sides; i++) {
1957
- const angle = i / sides * TAU - PI / 2;
1958
- const px = x + cos(angle) * radius;
1959
- const py = y + sin(angle) * radius;
1960
- if (i === 0) {
1961
- this.context.moveTo(px, py);
1962
- } else {
1963
- this.context.lineTo(px, py);
2185
+ getCellNeighbors(cx, cy, cz) {
2186
+ const neighbors = [];
2187
+ const gridSize = this.cells.length;
2188
+ for (let dz = -1; dz <= 1; dz++) {
2189
+ for (let dy = -1; dy <= 1; dy++) {
2190
+ for (let dx = -1; dx <= 1; dx++) {
2191
+ let nx = (cx + dx + gridSize) % gridSize;
2192
+ let ny = (cy + dy + gridSize) % gridSize;
2193
+ let nz = (cz + dz + gridSize) % gridSize;
2194
+ neighbors.push(this.cells[nz][ny][nx]);
1964
2195
  }
1965
2196
  }
1966
- this.context.closePath();
1967
- }, params);
2197
+ }
2198
+ return neighbors;
1968
2199
  }
1969
- drawText(x, y, text, params = {}) {
1970
- this.context.font = params.font ?? `${params.size ?? DEFAULT_FONT_SIZE}px ${params.fontName ?? DEFAULT_FONT_NAME}`;
1971
- this.context.textAlign = params.textAlign ?? DEFAULT_TEXTALIGN;
1972
- this.context.textBaseline = params.textBaseline ?? DEFAULT_TEXTBASELINE;
1973
- this.context.fillStyle = params.color ?? DEFAULT_COLOR;
1974
- this.context.fillText(text, x, y);
1975
- }
1976
- drawSprite(x, y, image, width, height, params = {}) {
1977
- x -= width / 2;
1978
- y -= height / 2;
1979
- if (params.sourceWidth !== void 0 && params.sourceHeight !== void 0) {
1980
- this.context.drawImage(
1981
- image,
1982
- params.sourceX ?? 0,
1983
- params.sourceY ?? 0,
1984
- params.sourceWidth,
1985
- params.sourceHeight,
1986
- x,
1987
- y,
1988
- width,
1989
- height
1990
- );
1991
- } else {
1992
- this.context.drawImage(image, x, y, width, height);
1993
- }
2200
+ addEntity(entity) {
2201
+ const cell = this.getCell(entity.x, entity.y, entity.z);
2202
+ cell.push(entity);
1994
2203
  }
1995
2204
  };
1996
2205
 
1997
- // src/rendering/particle-renderer.ts
1998
- var ParticleRenderer = class {
1999
- _screenCanvas;
2000
- _bufferCanvas;
2001
- screenContext;
2002
- bufferContext;
2003
- get width() {
2004
- return this._screenCanvas.width;
2005
- }
2006
- get height() {
2007
- return this._screenCanvas.height;
2008
- }
2009
- constructor(canvas) {
2010
- this._screenCanvas = canvas ?? document.createElement("canvas");
2011
- this._bufferCanvas = new OffscreenCanvas(this._screenCanvas.width, this._screenCanvas.height);
2012
- this.screenContext = this._screenCanvas.getContext("2d");
2013
- this.bufferContext = this._bufferCanvas.getContext("2d");
2014
- if (!this.screenContext || !this.bufferContext) {
2015
- throw "Failed to create CanvasRenderingContext2D";
2016
- }
2017
- }
2018
- appendTo(target, autoResize = true) {
2019
- if (this._screenCanvas.parentNode) {
2020
- this._screenCanvas.parentNode.removeChild(this._screenCanvas);
2021
- }
2022
- target.appendChild(this._screenCanvas);
2023
- if (autoResize) {
2024
- this.resize();
2025
- }
2026
- }
2027
- resize(displayWidth, displayHeight) {
2028
- const { width, height } = this._screenCanvas.parentElement?.getBoundingClientRect() ?? this._screenCanvas.getBoundingClientRect();
2029
- displayWidth = 0 | (displayWidth ?? width);
2030
- displayHeight = 0 | (displayHeight ?? height);
2031
- if (this._screenCanvas.width !== displayWidth || this._screenCanvas.height !== displayHeight) {
2032
- this._screenCanvas.width = displayWidth;
2033
- this._screenCanvas.height = displayHeight;
2034
- this._bufferCanvas.width = displayWidth;
2035
- this._bufferCanvas.height = displayHeight;
2036
- return true;
2206
+ // src/three/asteroid-mesh.ts
2207
+ import { IcosahedronGeometry, Mesh, MeshStandardMaterial } from "three";
2208
+ import { createNoise3D as createNoise3D2 } from "simplex-noise";
2209
+ var AsteroidMesh = class extends Mesh {
2210
+ constructor(options = {}) {
2211
+ const radius = options.radius ?? 1;
2212
+ const detail = options.detail ?? 1;
2213
+ const noiseScale = options.noiseScale ?? 1;
2214
+ const displacement = options.displacement ?? 0.1;
2215
+ const secondaryNoise = options.secondaryNoise ?? false;
2216
+ const color = options.color ?? 8947848;
2217
+ const geometry = new IcosahedronGeometry(radius, detail);
2218
+ const material = new MeshStandardMaterial({ color });
2219
+ super(geometry, material);
2220
+ const noise3d = createNoise3D2(rng.nextFloat);
2221
+ const noise3d2 = secondaryNoise ? createNoise3D2(rng.nextFloat) : null;
2222
+ const position = this.geometry.attributes.position;
2223
+ const vertices = position.array;
2224
+ for (let i = 0; i < vertices.length; i += 3) {
2225
+ const x = vertices[i];
2226
+ const y = vertices[i + 1];
2227
+ const z = vertices[i + 2];
2228
+ const n1 = noise3d(x * noiseScale, y * noiseScale, z * noiseScale);
2229
+ const n2 = secondaryNoise ? 0.5 * noise3d2(x * noiseScale * 2, y * noiseScale * 2, z * noiseScale * 2) : 0;
2230
+ const noiseValue = n1 + n2;
2231
+ const displacementValue = 1 + noiseValue * displacement;
2232
+ vertices[i] = x * displacementValue;
2233
+ vertices[i + 1] = y * displacementValue;
2234
+ vertices[i + 2] = z * displacementValue;
2037
2235
  }
2038
- return false;
2039
- }
2040
- setPixel(x, y, color, size = 2) {
2041
- this.bufferContext.fillStyle = color.hexStr;
2042
- this.bufferContext.fillRect(x - size / 2, y - size / 2, size, size);
2043
- }
2044
- render() {
2045
- this.screenContext.clearRect(0, 0, this._screenCanvas.width, this._screenCanvas.height);
2046
- this.screenContext.drawImage(this._bufferCanvas, 0, 0);
2047
- this.bufferContext.clearRect(0, 0, this._screenCanvas.width, this._screenCanvas.height);
2236
+ position.needsUpdate = true;
2237
+ this.geometry.computeVertexNormals();
2048
2238
  }
2049
2239
  };
2050
2240
 
2051
- // src/rendering/three/cube-sphere-geometry.ts
2052
- import { BoxGeometry, Vector3 } from "three";
2053
- var CubeSphereGeometry = class extends BoxGeometry {
2054
- constructor(size, segments) {
2055
- size = Math.floor(size);
2056
- segments = Math.floor(segments);
2057
- super(size, size, size, segments, segments, segments);
2058
- this.size = size;
2059
- this.segments = segments;
2060
- this._halfSize = this.size / 2;
2061
- const attrPositions = this.attributes.position;
2062
- const position = new Vector3();
2063
- for (let i = 0; i < attrPositions.count; i++) {
2064
- position.fromBufferAttribute(attrPositions, i);
2065
- position.normalize().multiplyScalar(this._halfSize);
2066
- attrPositions.setXYZ(i, position.x, position.y, position.z);
2067
- }
2068
- attrPositions.needsUpdate = true;
2069
- }
2070
- size;
2071
- segments;
2072
- _halfSize;
2073
- applyFractalBrownianMotion(octaves, persistence, scale, amplitude) {
2074
- const attrPositions = this.attributes.position;
2075
- const position = new Vector3();
2076
- for (let i = 0; i < attrPositions.count; i++) {
2077
- position.fromBufferAttribute(attrPositions, i);
2078
- position.normalize().multiplyScalar(this._halfSize);
2079
- const noiseValue = this.fBm(position.x * scale, position.y * scale, position.z * scale, octaves, persistence);
2080
- position.addScaledVector(position.clone().normalize(), noiseValue * amplitude);
2081
- attrPositions.setXYZ(i, position.x, position.y, position.z);
2082
- }
2083
- attrPositions.needsUpdate = true;
2084
- }
2085
- fBm(x, y, z, octaves, persistence) {
2086
- let total = 0;
2087
- let frequency = 1;
2088
- let amplitude = 1;
2089
- let maxValue = 0;
2090
- for (let i = 0; i < octaves; i++) {
2091
- total += Noise.noise3d(x * frequency, y * frequency, z * frequency) * amplitude;
2092
- maxValue += amplitude;
2093
- amplitude *= persistence;
2094
- frequency *= 2;
2095
- }
2096
- return total / maxValue;
2097
- }
2098
- };
2241
+ // src/three/atlas-texture-material.ts
2242
+ import { MeshLambertMaterial, NearestFilter as NearestFilter2 } from "three";
2099
2243
 
2100
- // src/rendering/three/texture-atlas.ts
2101
- import { TextureLoader, MeshLambertMaterial, NearestFilter, RepeatWrapping } from "three";
2244
+ // src/three/texture-utils.ts
2245
+ import { NearestFilter, RepeatWrapping, TextureLoader } from "three";
2102
2246
  function LoadTexture(url) {
2103
2247
  return new Promise((res, rej) => {
2104
2248
  new TextureLoader().load(
2105
2249
  url,
2106
2250
  (texture) => {
2107
- const data = texture.source.data;
2108
- const width = data.width;
2109
- const height = data.height;
2251
+ const width = texture.source.data.width;
2252
+ const height = texture.source.data.height;
2110
2253
  res({ width, height, texture });
2111
2254
  },
2112
2255
  (_ev) => {
@@ -2116,56 +2259,20 @@ function LoadTexture(url) {
2116
2259
  });
2117
2260
  }
2118
2261
  function CreateSubTexture(texture, x, y, w, h) {
2119
- texture = texture.clone();
2120
- texture.magFilter = NearestFilter;
2121
- texture.wrapS = RepeatWrapping;
2122
- const data = texture.source.data;
2123
- const textureWidth = data.width;
2124
- const textureHeight = data.height;
2125
- w /= textureWidth;
2126
- h /= textureHeight;
2127
- x /= textureWidth;
2128
- y = 1 - h - y / textureHeight;
2129
- texture.offset.set(x, y);
2130
- texture.repeat.set(w, h);
2131
- texture.needsUpdate = true;
2132
- return texture;
2262
+ const subTexture = texture.clone();
2263
+ subTexture.magFilter = NearestFilter;
2264
+ subTexture.wrapS = RepeatWrapping;
2265
+ w /= subTexture.width;
2266
+ h /= subTexture.height;
2267
+ x /= subTexture.width;
2268
+ y = 1 - h - y / subTexture.height;
2269
+ subTexture.offset.set(x, y);
2270
+ subTexture.repeat.set(w, h);
2271
+ subTexture.needsUpdate = true;
2272
+ return subTexture;
2133
2273
  }
2134
- var TextureAtlas = class _TextureAtlas extends MeshLambertMaterial {
2135
- constructor(textureData, textureWidth, textureHeight = textureWidth, params) {
2136
- super({
2137
- map: textureData.texture,
2138
- alphaTest: 0.1,
2139
- transparent: true,
2140
- ...params ?? {}
2141
- });
2142
- this.textureData = textureData;
2143
- this.textureWidth = textureWidth;
2144
- this.textureHeight = textureHeight;
2145
- this._uw = this.textureWidth / this.textureData.width;
2146
- this._uh = this.textureHeight / this.textureData.height;
2147
- this.textureData.texture.magFilter = NearestFilter;
2148
- }
2149
- textureData;
2150
- textureWidth;
2151
- textureHeight;
2152
- _uw;
2153
- _uh;
2154
- getUv(voxel, ux, uy) {
2155
- return [
2156
- (voxel + ux) * this._uw,
2157
- 1 - (1 - uy) * this._uh
2158
- ];
2159
- }
2160
- static CreateFromUrl(url, textureWidth, textureHeight = textureWidth, params) {
2161
- return LoadTexture(url).then((textureData) => new _TextureAtlas(
2162
- textureData,
2163
- textureWidth,
2164
- textureHeight,
2165
- params
2166
- ));
2167
- }
2168
- };
2274
+
2275
+ // src/three/atlas-texture-material.ts
2169
2276
  var AtlasTextureMaterial = class _AtlasTextureMaterial extends MeshLambertMaterial {
2170
2277
  textureData;
2171
2278
  tilePixelWidth;
@@ -2184,7 +2291,7 @@ var AtlasTextureMaterial = class _AtlasTextureMaterial extends MeshLambertMateri
2184
2291
  ...materialParams
2185
2292
  });
2186
2293
  this.textureData = textureData;
2187
- this.textureData.texture.magFilter = NearestFilter;
2294
+ this.textureData.texture.magFilter = NearestFilter2;
2188
2295
  this.tilePixelWidth = atlasParams.tilePixelWidth ?? 16;
2189
2296
  this.tilePixelHeight = atlasParams.tilePixelHeight ?? 16;
2190
2297
  this._textureOffsetWidth = atlasParams.tilePixelOffsetWidth ?? 0;
@@ -2222,37 +2329,56 @@ var AtlasTextureMaterial = class _AtlasTextureMaterial extends MeshLambertMateri
2222
2329
  }
2223
2330
  };
2224
2331
 
2225
- // src/rendering/three/threejs-boiler-plate.ts
2226
- init_main();
2227
- import { AmbientLight, BoxGeometry as BoxGeometry2, DirectionalLight, GridHelper, Mesh, MeshLambertMaterial as MeshLambertMaterial2, PlaneGeometry, Raycaster, Scene, Vector2, WebGLRenderer } from "three";
2228
-
2229
- // src/rendering/three/threejs-camera-rig.ts
2332
+ // src/three/camera-rig.ts
2230
2333
  import { PerspectiveCamera, Group } from "three";
2231
- var ThreeJsCameraRig = class extends Group {
2334
+ var DEFAULT_CAMERA_ASPECT = 2;
2335
+ var DEFAULT_CAMERA_DISTANCE = 5;
2336
+ var DEFAULT_CAMERA_FAR = 1e3;
2337
+ var DEFAULT_CAMERA_FOV = 70;
2338
+ var DEFAULT_CAMERA_MAX_DISTANCE = 50;
2339
+ var DEFAULT_CAMERA_MIN_DISTANCE = 1.5;
2340
+ var DEFAULT_CAMERA_NEAR = 0.1;
2341
+ var DEFAULT_GIMBLE_CLAMP_ANGLE = false;
2342
+ var DEFAULT_GIMBLE_MAX_ANGLE = 0;
2343
+ var DEFAULT_GIMBLE_MIN_ANGLE = radians(-90);
2344
+ var DEFAULT_MOUSE_SENSITIVITY = 0.01;
2345
+ var DEFAULT_WHEEL_SENSITIVITY = 0.02;
2346
+ var CameraRig = class extends Group {
2232
2347
  gimbal;
2233
2348
  camera;
2234
- target;
2235
- mouseSensitivity = 0.01;
2236
- wheelSensitivity = 0.02;
2237
- minCameraDistance = 2;
2238
- maxCameraDistance = 100;
2239
- minTiltAngle = degrees(-90);
2240
- maxTiltAngle = degrees(0);
2241
- clampTiltAngle = false;
2349
+ _target;
2350
+ clampTiltAngle = DEFAULT_GIMBLE_CLAMP_ANGLE;
2351
+ maxDistance = DEFAULT_CAMERA_MAX_DISTANCE;
2352
+ maxTiltAngle = DEFAULT_GIMBLE_MAX_ANGLE;
2353
+ minDistance = DEFAULT_CAMERA_MIN_DISTANCE;
2354
+ minTiltAngle = DEFAULT_GIMBLE_MIN_ANGLE;
2355
+ mouseSensitivity = DEFAULT_MOUSE_SENSITIVITY;
2356
+ wheelSensitivity = DEFAULT_WHEEL_SENSITIVITY;
2242
2357
  constructor(params) {
2243
2358
  super();
2244
2359
  this.gimbal = new Group();
2245
2360
  this.add(this.gimbal);
2246
- this.camera = params?.camera ?? new PerspectiveCamera(
2247
- params?.fov ?? 75,
2248
- params?.aspect ?? 2,
2249
- params?.near ?? 0.1,
2250
- params?.far ?? 1e3
2361
+ this.camera = new PerspectiveCamera(
2362
+ params?.fov ?? DEFAULT_CAMERA_FOV,
2363
+ params?.aspect ?? DEFAULT_CAMERA_ASPECT,
2364
+ params?.near ?? DEFAULT_CAMERA_NEAR,
2365
+ params?.far ?? DEFAULT_CAMERA_FAR
2251
2366
  );
2252
2367
  this.gimbal.add(this.camera);
2368
+ this.camera.position.z = DEFAULT_CAMERA_DISTANCE;
2369
+ this.gimbal.rotateX(radians(-45));
2370
+ this.rotateY(radians(45));
2371
+ }
2372
+ setTarget(target) {
2373
+ if (target) {
2374
+ this.rotation.set(0, 0, 0);
2375
+ this.position.set(0, 0, 0);
2376
+ target.add(this);
2377
+ }
2378
+ this._target = target;
2253
2379
  }
2254
2380
  orbit(deltaX, deltaY) {
2255
- (this.target || this).rotateY(-deltaX * this.mouseSensitivity);
2381
+ (this._target ?? this).rotateY(-deltaX * this.mouseSensitivity);
2256
2382
  this.gimbal.rotation.x = this.clampTiltAngle ? clamp(
2257
2383
  this.gimbal.rotation.x + -deltaY * this.mouseSensitivity,
2258
2384
  this.minTiltAngle,
@@ -2262,924 +2388,1103 @@ var ThreeJsCameraRig = class extends Group {
2262
2388
  dolly(deltaY) {
2263
2389
  this.camera.position.z = clamp(
2264
2390
  this.camera.position.z + deltaY * this.wheelSensitivity,
2265
- this.minCameraDistance,
2266
- this.maxCameraDistance
2391
+ this.minDistance,
2392
+ this.maxDistance
2267
2393
  );
2268
2394
  }
2269
2395
  };
2270
2396
 
2271
- // src/rendering/three/threejs-boiler-plate.ts
2272
- var ThreeJsBoilerPlate = class {
2273
- clock = new Clock();
2274
- scene = new Scene();
2275
- input = Input.instance;
2276
- raycaster = new Raycaster();
2277
- renderer;
2278
- cameraRig;
2279
- orbitControls;
2280
- get canvas() {
2281
- return this.renderer.domElement;
2282
- }
2283
- get camera() {
2284
- return this.cameraRig.camera;
2285
- }
2286
- rng = rng;
2287
- constructor(params) {
2288
- rng.seed = params?.seed ?? rng.seed;
2289
- this.renderer = new WebGLRenderer(params?.renderer);
2290
- this.cameraRig = new ThreeJsCameraRig(params?.camera);
2291
- this.scene.add(this.cameraRig);
2292
- if (params?.parentElement) {
2293
- this.appendTo(params.parentElement);
2294
- }
2295
- }
2296
- enableCameraRigControls() {
2297
- this.orbitControls?.dispose();
2298
- this.orbitControls = void 0;
2299
- this.input.onPointerMove.subscribe((_, ev) => {
2300
- if (this.input.isDown("Button0")) {
2301
- this.cameraRig.orbit(ev.movementX, ev.movementY);
2302
- }
2303
- });
2304
- this.input.onWheel.subscribe((_, ev) => this.cameraRig.dolly(ev.deltaY));
2305
- }
2306
- async enableOrbitControls() {
2307
- const { OrbitControls } = await import("three/examples/jsm/Addons.js");
2308
- this.orbitControls = new OrbitControls(this.camera, this.canvas);
2309
- this.orbitControls.minDistance = 0.5;
2310
- this.orbitControls.maxDistance = 100;
2311
- this.orbitControls.update();
2312
- }
2313
- update() {
2314
- this.orbitControls?.update();
2315
- }
2316
- appendTo(htmlElement) {
2317
- if (this.canvas.parentElement) {
2318
- this.canvas.parentElement.removeChild(this.canvas);
2319
- }
2320
- if (htmlElement) {
2321
- htmlElement.appendChild(this.canvas);
2322
- this.resize();
2397
+ // src/three/cube-sphere-geometry.ts
2398
+ import { BoxGeometry, Vector3 } from "three";
2399
+ var CubeSphereGeometry = class extends BoxGeometry {
2400
+ constructor(size, segments) {
2401
+ size = Math.floor(size);
2402
+ segments = Math.floor(segments);
2403
+ super(size, size, size, segments, segments, segments);
2404
+ this.size = size;
2405
+ this.segments = segments;
2406
+ this._halfSize = this.size / 2;
2407
+ const attrPositions = this.attributes.position;
2408
+ const position = new Vector3();
2409
+ for (let i = 0; i < attrPositions.count; i++) {
2410
+ position.fromBufferAttribute(attrPositions, i);
2411
+ position.normalize().multiplyScalar(this._halfSize);
2412
+ attrPositions.setXYZ(i, position.x, position.y, position.z);
2323
2413
  }
2414
+ attrPositions.needsUpdate = true;
2324
2415
  }
2325
- resize(displayWidth, displayHeight) {
2326
- const { width, height } = this.canvas.parentElement?.getBoundingClientRect() ?? this.canvas.getBoundingClientRect();
2327
- displayWidth = 0 | (displayWidth ?? width);
2328
- displayHeight = 0 | (displayHeight ?? height);
2329
- let resized = false;
2330
- if (this.canvas.width !== displayWidth || this.canvas.height !== displayHeight) {
2331
- this.renderer.setSize(displayWidth, displayHeight);
2332
- this.cameraRig.camera.aspect = displayWidth / displayHeight;
2333
- this.cameraRig.camera.updateProjectionMatrix();
2334
- resized = true;
2416
+ size;
2417
+ segments;
2418
+ _halfSize;
2419
+ applyFractalBrownianMotion(octaves, persistence, scale, amplitude) {
2420
+ const attrPositions = this.attributes.position;
2421
+ const position = new Vector3();
2422
+ for (let i = 0; i < attrPositions.count; i++) {
2423
+ position.fromBufferAttribute(attrPositions, i);
2424
+ position.normalize().multiplyScalar(this._halfSize);
2425
+ const noiseValue = this.fBm(position.x * scale, position.y * scale, position.z * scale, octaves, persistence);
2426
+ position.addScaledVector(position.clone().normalize(), noiseValue * amplitude);
2427
+ attrPositions.setXYZ(i, position.x, position.y, position.z);
2335
2428
  }
2336
- return resized;
2429
+ attrPositions.needsUpdate = true;
2337
2430
  }
2338
- setupBasicScene(params = {}) {
2339
- this.camera.position.z = params.cameraDistance ?? 5;
2340
- if (params.ambientLight !== false) this.scene.add(new AmbientLight());
2341
- if (params.directionalLight !== false) this.scene.add(new DirectionalLight());
2342
- if (params.gridHelper !== false) this.scene.add(new GridHelper(100, 100, 16711680));
2343
- if (params.enableControls === true) {
2344
- this.enableCameraRigControls();
2345
- }
2346
- }
2347
- pick() {
2348
- const pickX = this.input.pointerPosition.x / this.renderer.domElement.width * 2 - 1;
2349
- const pickY = -(this.input.pointerPosition.y / this.renderer.domElement.height) * 2 + 1;
2350
- this.raycaster.setFromCamera(new Vector2(pickX, pickY), this.cameraRig.camera);
2351
- const intersected = this.raycaster.intersectObjects(this.scene.children);
2352
- return intersected.length ? intersected[0] : null;
2353
- }
2354
- static CreateCubeMesh(size = 1, color = 16711680) {
2355
- const cubeMesh = new Mesh(
2356
- new BoxGeometry2(size, size, size),
2357
- new MeshLambertMaterial2({ color })
2358
- );
2359
- cubeMesh.name = "CubeMesh";
2360
- return cubeMesh;
2361
- }
2362
- static CreatePlaneMesh(size = 10, segments = 10, color = 16711680) {
2363
- return new Mesh(
2364
- new PlaneGeometry(size, size, segments, segments),
2365
- new MeshLambertMaterial2({ color, wireframe: true })
2366
- );
2431
+ fBm(x, y, z, octaves, persistence) {
2432
+ let total = 0;
2433
+ let frequency = 1;
2434
+ let amplitude = 1;
2435
+ let maxValue = 0;
2436
+ for (let i = 0; i < octaves; i++) {
2437
+ total += Noise.noise3d(x * frequency, y * frequency, z * frequency) * amplitude;
2438
+ maxValue += amplitude;
2439
+ amplitude *= persistence;
2440
+ frequency *= 2;
2441
+ }
2442
+ return total / maxValue;
2367
2443
  }
2368
2444
  };
2369
2445
 
2370
- // src/rendering/three/threejs-player-controller.ts
2371
- import { Group as Group2, Vector3 as Vector32 } from "three";
2372
- var ThreeJsPlayerController = class extends Group2 {
2373
- moveSpeed = 1;
2374
- cameraRig;
2375
- velocity;
2376
- constructor(camera) {
2377
- super();
2378
- this.velocity = new Vector32();
2379
- this.cameraRig = new ThreeJsCameraRig({ camera });
2380
- this.add(this.cameraRig);
2381
- }
2382
- update(deltaTime) {
2383
- if (this.velocity.length()) {
2384
- this.translateOnAxis(this.velocity.normalize(), this.moveSpeed * deltaTime);
2446
+ // src/three/ecs.ts
2447
+ import { Group as Group2 } from "three";
2448
+ var entityCounter = 0;
2449
+ function GenerateEntityId() {
2450
+ return `entity_${entityCounter++}`;
2451
+ }
2452
+ function CreateThreeEntity(obj) {
2453
+ const entity = obj ?? new Group2();
2454
+ entity.userData.entityId = GenerateEntityId();
2455
+ entity.userData.components = {};
2456
+ return entity;
2457
+ }
2458
+ function AddThreeComponent(entity, name, component) {
2459
+ entity.userData.components[name] = component;
2460
+ }
2461
+ function GetThreeComponent(entity, name) {
2462
+ return entity.userData.components[name];
2463
+ }
2464
+ function RemoveThreeComponent(entity, name) {
2465
+ delete entity.userData.components[name];
2466
+ }
2467
+ function IsThreeEntity(obj) {
2468
+ return obj.userData.entityId !== void 0;
2469
+ }
2470
+
2471
+ // src/three/palette-controller.ts
2472
+ import { Color as Color2, Vector3 as Vector32 } from "three";
2473
+ async function CreatePaletteController(parentGui, colorPalette, onChange, folderName = "palette") {
2474
+ const { Controller } = await import("three/examples/jsm/libs/lil-gui.module.min.js");
2475
+ class PaletteControllerImpl extends Controller {
2476
+ $innerDiv;
2477
+ colorButtons = [];
2478
+ colorButtonSize = 20;
2479
+ selectedBorderStyle = "2px dashed black";
2480
+ currentColorIndex = 0;
2481
+ eyedropperButton;
2482
+ colorPalette;
2483
+ _onColorChange;
2484
+ constructor() {
2485
+ const parent = parentGui.addFolder(folderName);
2486
+ super(parent, {}, "", "function");
2487
+ this.colorPalette = colorPalette;
2488
+ this._onColorChange = onChange;
2489
+ this.$widget.style.setProperty("display", "flex");
2490
+ this.$widget.style.setProperty("justify-content", "center");
2491
+ this.$innerDiv = document.createElement("div");
2492
+ this.$innerDiv.style.setProperty("display", "flex");
2493
+ this.$innerDiv.style.setProperty("flex-wrap", "wrap");
2494
+ this.$innerDiv.style.setProperty("width", `${this.colorButtonSize * Math.floor(Math.sqrt(this.colorPalette.length)) + 2}px`);
2495
+ this.$innerDiv.appendChild(this.$name);
2496
+ this.$widget.appendChild(this.$innerDiv);
2497
+ this.colorPalette.forEach((color) => this._createColorButton(color));
2498
+ if (window.EyeDropper) {
2499
+ this.eyedropperButton = parent.add({
2500
+ eyedropper: () => {
2501
+ this.eyedropperButton?.disable(true);
2502
+ new window.EyeDropper().open().then(({ sRGBHex }) => {
2503
+ const i = this.findClosestColorMatchIndex(sRGBHex);
2504
+ this.setSelectedColor(i);
2505
+ this._onColorChange?.(i);
2506
+ }).finally(() => this.eyedropperButton?.disable(false)).catch(() => {
2507
+ });
2508
+ }
2509
+ }, "eyedropper").name("findClosestColor");
2510
+ }
2511
+ this.name("");
2512
+ this.updateDisplay();
2513
+ }
2514
+ _onColorButtonClicked(i, button) {
2515
+ if (button === 0) {
2516
+ this.setSelectedColor(i);
2517
+ this._onColorChange?.(i);
2518
+ this.colorButtons[i].blur();
2519
+ } else if (button === 2 && window.EyeDropper) {
2520
+ new window.EyeDropper().open().then(({ sRGBHex }) => {
2521
+ this.colorPalette[i] = sRGBHex;
2522
+ this.colorButtons[i].setAttribute("title", `${sRGBHex}`);
2523
+ this.colorButtons[i].style.setProperty("background", sRGBHex);
2524
+ this.setSelectedColor(i);
2525
+ this._onColorChange?.(i);
2526
+ this.colorButtons[i].blur();
2527
+ }).finally(() => this.eyedropperButton?.disable(false)).catch(() => {
2528
+ });
2529
+ }
2530
+ }
2531
+ _createColorButton(color) {
2532
+ const i = this.colorButtons.length;
2533
+ const colorButton = document.createElement("div");
2534
+ colorButton.setAttribute("id", `colorButton${i}`);
2535
+ colorButton.setAttribute("title", `${color}`);
2536
+ colorButton.style.setProperty("width", `${this.colorButtonSize}px`);
2537
+ colorButton.style.setProperty("height", `${this.colorButtonSize}px`);
2538
+ colorButton.style.setProperty("background", color);
2539
+ colorButton.addEventListener("pointerup", (ev) => this._onColorButtonClicked(i, ev.button));
2540
+ this.colorButtons.push(colorButton);
2541
+ this.$innerDiv.appendChild(colorButton);
2542
+ }
2543
+ updatePaletteColors() {
2544
+ this.colorPalette.forEach((color, i) => {
2545
+ if (i < this.colorButtons.length) {
2546
+ this.colorButtons[i].setAttribute("title", `${color}`);
2547
+ this.colorButtons[i].style.setProperty("background", color);
2548
+ } else {
2549
+ this._createColorButton(color);
2550
+ }
2551
+ });
2552
+ }
2553
+ setSelectedColor(colorIndex = 0) {
2554
+ this.colorButtons[this.currentColorIndex].style.removeProperty("border");
2555
+ this.currentColorIndex = clamp(colorIndex, 0, this.colorPalette.length);
2556
+ this.colorButtons[this.currentColorIndex].style.setProperty("border", this.selectedBorderStyle);
2557
+ }
2558
+ findClosestColorMatchIndex(color) {
2559
+ const pickedColor = new Color2(color);
2560
+ const pickedVector = new Vector32().setFromColor(pickedColor);
2561
+ const list = [];
2562
+ this.colorPalette.forEach((paletteColorString, i) => {
2563
+ const paletteColor = new Color2(paletteColorString);
2564
+ const paletteVector = new Vector32().setFromColor(paletteColor);
2565
+ const d = paletteVector.distanceTo(pickedVector);
2566
+ list.push({ i, d });
2567
+ });
2568
+ list.sort((a, b) => a.d - b.d);
2569
+ const closest = list.shift();
2570
+ return closest?.i ?? 0;
2385
2571
  }
2386
2572
  }
2387
- };
2573
+ return new PaletteControllerImpl();
2574
+ }
2388
2575
 
2389
- // src/rendering/three/voxel-mesh.ts
2390
- import { BufferAttribute, BufferGeometry, Color as Color2, Mesh as Mesh2 } from "three";
2391
- var VoxelMesh = class extends Mesh2 {
2392
- type = "VoxelMesh";
2393
- width;
2394
- depth;
2395
- height;
2396
- colorPalette;
2397
- voxels;
2398
- needsGeometryUpdate = true;
2399
- constructor(width, depth, height, material, name) {
2576
+ // src/three/particle-system-3d.ts
2577
+ import { BufferGeometry, Float32BufferAttribute, Group as Group3, Points, ShaderMaterial, Vector3 as Vector33 } from "three";
2578
+ var vertexShader = `
2579
+ uniform float pointSize;
2580
+
2581
+ varying vec4 vColor;
2582
+
2583
+ void main() {
2584
+ vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);
2585
+
2586
+ gl_Position = projectionMatrix * mvPosition;
2587
+ gl_PointSize = pointSize;
2588
+
2589
+ vColor = color;
2590
+ }`;
2591
+ var fragmentShader = `
2592
+ varying vec4 vColor;
2593
+
2594
+ void main() {
2595
+ gl_FragColor = vColor;
2596
+ }`;
2597
+ var Colors = [
2598
+ [1, 0, 0, 1],
2599
+ // red
2600
+ [0, 1, 0, 1],
2601
+ // green,
2602
+ [0, 0, 1, 1],
2603
+ // blue,
2604
+ [1, 1, 0, 1],
2605
+ // yellow,
2606
+ [1, 0, 1, 1]
2607
+ // magenta,
2608
+ ];
2609
+ var ParticleSystem3d = class extends Group3 {
2610
+ particleCount = 1e3;
2611
+ _geometry;
2612
+ _particles = [];
2613
+ _frictionHalfLife = 0.04;
2614
+ _range = 0.2;
2615
+ _rangeFactor = 0.1;
2616
+ _attractionMatrix;
2617
+ _spatialPartition;
2618
+ constructor() {
2400
2619
  super();
2401
- this.width = width;
2402
- this.depth = depth;
2403
- this.height = height;
2404
- this.material = material;
2405
- this.material.vertexColors = true;
2406
- this.name = name ?? "VoxelMesh";
2407
- this.colorPalette = BuildDefaultPalette();
2408
- this.voxels = /* @__PURE__ */ new Map();
2409
- this.geometry = new BufferGeometry();
2410
- this.updateGeometry();
2411
- }
2412
- _xyz2k(x, y, z) {
2413
- x = Math.abs(Math.floor(x));
2414
- y = Math.abs(Math.floor(y));
2415
- z = Math.abs(Math.floor(z));
2416
- return `${x},${y},${z}`;
2417
- }
2418
- _k2xyz(k) {
2419
- const [x, y, z] = k.split(",").map((s) => parseInt(s));
2420
- return { x, y, z };
2421
- }
2422
- get(x, y, z) {
2423
- let n = -1;
2424
- if (x >= 0 && y >= 0 && z >= 0 && x < this.width && y < this.height && z < this.depth) {
2425
- n = this.voxels.get(this._xyz2k(x, y, z)) ?? -1;
2620
+ const uniforms = {
2621
+ pointSize: { value: 4 }
2622
+ };
2623
+ this.position.x = -0.5;
2624
+ this.position.y = -0.5;
2625
+ this.position.z = -0.5;
2626
+ this._geometry = new BufferGeometry();
2627
+ this._geometry.setAttribute("position", new Float32BufferAttribute([], 3));
2628
+ this._geometry.setAttribute("color", new Float32BufferAttribute([], 4));
2629
+ const material = new ShaderMaterial({
2630
+ uniforms,
2631
+ vertexShader,
2632
+ fragmentShader,
2633
+ depthTest: true,
2634
+ depthWrite: false,
2635
+ vertexColors: true
2636
+ });
2637
+ const pointsMesh = new Points(this._geometry, material);
2638
+ this.add(pointsMesh);
2639
+ for (let i = 0; i < this.particleCount; i++) {
2640
+ this._particles.push({
2641
+ x: rng.nextFloat(),
2642
+ y: rng.nextFloat(),
2643
+ z: rng.nextFloat(),
2644
+ vx: 0,
2645
+ vy: 0,
2646
+ vz: 0,
2647
+ color: rng.range(Colors.length)
2648
+ });
2426
2649
  }
2427
- return n;
2650
+ this._attractionMatrix = randomMatrix(Colors.length);
2651
+ this._spatialPartition = new SpatialPartition3d(this._range, this._particles);
2428
2652
  }
2429
- set(x, y, z, n) {
2430
- if (x >= 0 && y >= 0 && z >= 0 && x < this.width && y < this.height && z < this.depth) {
2431
- if (n === void 0) this.voxels.delete(this._xyz2k(x, y, z));
2432
- else this.voxels.set(this._xyz2k(x, y, z), n);
2433
- this.needsGeometryUpdate = true;
2653
+ _calcForce(r, a, beta = 0.3) {
2654
+ let f = 0;
2655
+ if (r < beta) {
2656
+ f = r / beta - 1;
2657
+ } else if (beta < r && r < 1) {
2658
+ f = a * (1 - Math.abs(2 * r - 1 - beta) / (1 - beta));
2434
2659
  }
2660
+ return f;
2435
2661
  }
2436
- clearVoxels() {
2437
- this.voxels.clear();
2438
- }
2439
- setSize(width, depth, height) {
2440
- this.forEachVoxel((x, y, z) => {
2441
- if (x >= width || y >= height || z >= depth) this.set(x, y, z);
2442
- });
2443
- this.width = width;
2444
- this.depth = depth;
2445
- this.height = height;
2446
- this.needsGeometryUpdate = true;
2447
- }
2448
- forEachVoxel(callback) {
2449
- this.voxels.forEach((n, k) => {
2450
- const { x, y, z } = this._k2xyz(k);
2451
- callback(x, y, z, n);
2452
- });
2662
+ _updateVelocities(dt) {
2663
+ const frictionFactor = Math.pow(
2664
+ 0.5,
2665
+ dt / this._frictionHalfLife
2666
+ );
2667
+ for (let z = 0; z < this._spatialPartition.cells.length; z++) {
2668
+ for (let y = 0; y < this._spatialPartition.cells[z].length; y++) {
2669
+ for (let x = 0; x < this._spatialPartition.cells[z][y].length; x++) {
2670
+ const cell = this._spatialPartition.cells[z][y][x];
2671
+ for (let i = 0; i < cell.length; i++) {
2672
+ let fx = 0, fy = 0, fz = 0;
2673
+ const p1 = cell[i];
2674
+ const neighbors = this._spatialPartition.getCellNeighbors(x, y, z);
2675
+ for (const neighborCell of neighbors) {
2676
+ for (let j = 0; j < neighborCell.length; j++) {
2677
+ if (cell === neighborCell && i === j) continue;
2678
+ const p2 = neighborCell[j];
2679
+ let dx = p2.x - p1.x;
2680
+ let dy = p2.y - p1.y;
2681
+ let dz = p2.z - p1.z;
2682
+ if (Math.abs(dx) > 0.5) dx = dx > 0 ? dx - 1 : dx + 1;
2683
+ if (Math.abs(dy) > 0.5) dy = dy > 0 ? dy - 1 : dy + 1;
2684
+ if (Math.abs(dz) > 0.5) dz = dz > 0 ? dz - 1 : dz + 1;
2685
+ const dist = Math.hypot(dx, dy, dz);
2686
+ if (dist > 0 && dist < this._range) {
2687
+ const f = this._calcForce(dist / this._range, this._attractionMatrix[p1.color][p2.color]);
2688
+ fx += dx / dist * f;
2689
+ fy += dy / dist * f;
2690
+ fz += dz / dist * f;
2691
+ }
2692
+ }
2693
+ }
2694
+ fx *= this._range * this._rangeFactor;
2695
+ fy *= this._range * this._rangeFactor;
2696
+ fz *= this._range * this._rangeFactor;
2697
+ p1.vx *= frictionFactor;
2698
+ p1.vy *= frictionFactor;
2699
+ p1.vz *= frictionFactor;
2700
+ p1.vx += fx;
2701
+ p1.vy += fy;
2702
+ p1.vz += fz;
2703
+ }
2704
+ }
2705
+ }
2706
+ }
2453
2707
  }
2454
- importVoxelData(voxelData) {
2455
- this.clearVoxels();
2456
- this.name = voxelData.name;
2457
- this.setSize(voxelData.width, voxelData.depth, voxelData.height);
2458
- voxelData.palette.forEach((color, i) => {
2459
- if (i < this.colorPalette.length) {
2460
- this.colorPalette[i] = color;
2461
- } else {
2462
- this.colorPalette.push(color);
2708
+ _updatePositions(dt) {
2709
+ for (let i = 0; i < this._particles.length; i++) {
2710
+ const particle = this._particles[i];
2711
+ const oldCell = this._spatialPartition.getCell(particle.x, particle.y, particle.z);
2712
+ particle.x += particle.vx * dt;
2713
+ particle.y += particle.vy * dt;
2714
+ particle.z += particle.vz * dt;
2715
+ if (particle.x < 0) particle.x = (particle.x + 1) % 1;
2716
+ if (particle.x > 1) particle.x = particle.x % 1;
2717
+ if (particle.y < 0) particle.y = (particle.y + 1) % 1;
2718
+ if (particle.y > 1) particle.y = particle.y % 1;
2719
+ if (particle.z < 0) particle.z = (particle.z + 1) % 1;
2720
+ if (particle.z > 1) particle.z = particle.z % 1;
2721
+ const newCell = this._spatialPartition.getCell(particle.x, particle.y, particle.z);
2722
+ if (newCell !== oldCell) {
2723
+ const index = oldCell.indexOf(particle);
2724
+ if (index !== -1) {
2725
+ oldCell.splice(index, 1);
2726
+ }
2727
+ newCell.push(particle);
2463
2728
  }
2729
+ }
2730
+ }
2731
+ _sortParticles(camera) {
2732
+ this._particles.sort((a, b) => {
2733
+ const d1 = camera.position.distanceTo(new Vector33(a.x, a.y, a.z));
2734
+ const d2 = camera.position.distanceTo(new Vector33(b.x, b.y, b.z));
2735
+ return d1 > d2 ? -1 : d1 > d1 ? 1 : 0;
2464
2736
  });
2465
- voxelData.voxels.forEach((voxel) => {
2466
- const { x, y, z, color } = voxel;
2467
- this.set(x, y, z, color);
2468
- });
2469
- this.updateGeometry();
2470
2737
  }
2471
- updateGeometry() {
2472
- if (this.needsGeometryUpdate) {
2473
- const positions = [];
2474
- const normals = [];
2475
- const colors2 = [];
2476
- const indices = [];
2477
- this.forEachVoxel((x, y, z, n) => {
2478
- VoxelFaces.forEach((faces) => {
2479
- const [dx, dy, dz] = faces[0];
2480
- const neighborVoxel = this.get(x + dx, y + dy, z + dz);
2481
- if (neighborVoxel < 0) {
2482
- const positionIndex = positions.length / 3;
2483
- faces.forEach((face) => {
2484
- const [nx, ny, nz, px, py, pz] = face;
2485
- positions.push(x + px, y + py, z + pz);
2486
- normals.push(nx, ny, nz);
2487
- const { r, g, b } = new Color2(this.colorPalette[n]);
2488
- colors2.push(r, g, b, 1);
2489
- });
2490
- indices.push(
2491
- positionIndex,
2492
- positionIndex + 1,
2493
- positionIndex + 2,
2494
- positionIndex + 2,
2495
- positionIndex + 1,
2496
- positionIndex + 3
2497
- );
2498
- }
2499
- });
2500
- });
2501
- this.geometry.setAttribute("position", new BufferAttribute(new Float32Array(positions), 3));
2502
- this.geometry.setAttribute("normal", new BufferAttribute(new Float32Array(normals), 3));
2503
- this.geometry.setAttribute("color", new BufferAttribute(new Float32Array(colors2), 4));
2504
- this.geometry.setIndex(indices);
2505
- this.geometry.computeBoundingSphere();
2506
- this.updateMatrixWorld();
2738
+ _updateGeometry() {
2739
+ const positions = [];
2740
+ const colors2 = [];
2741
+ for (const particle of this._particles) {
2742
+ positions.push(
2743
+ particle.x,
2744
+ particle.y,
2745
+ particle.z
2746
+ );
2747
+ colors2.push(
2748
+ Colors[particle.color][0],
2749
+ Colors[particle.color][1],
2750
+ Colors[particle.color][2],
2751
+ Colors[particle.color][3]
2752
+ );
2507
2753
  }
2508
- this.needsGeometryUpdate = false;
2754
+ this._geometry.setAttribute("position", new Float32BufferAttribute(positions, 3));
2755
+ this._geometry.setAttribute("color", new Float32BufferAttribute(colors2, 4));
2756
+ this._geometry.attributes.position.needsUpdate = true;
2509
2757
  }
2510
- exportData() {
2511
- const voxelData = {
2512
- name: this.name,
2513
- width: this.width,
2514
- depth: this.depth,
2515
- height: this.height,
2516
- palette: [...this.colorPalette],
2517
- voxels: []
2518
- };
2519
- this.forEachVoxel((x, y, z, color) => {
2520
- voxelData.voxels.push({ x, y, z, color });
2521
- });
2522
- return voxelData;
2758
+ update(camera, dt) {
2759
+ this._updateVelocities(dt);
2760
+ this._updatePositions(dt);
2761
+ this._sortParticles(camera);
2762
+ this._updateGeometry();
2523
2763
  }
2524
2764
  };
2525
- var VoxelFaces = [
2526
- // [nx, ny, nz, px, py, pz]
2527
- [
2528
- //left
2529
- [-1, 0, 0, 0, 1, 0],
2530
- [-1, 0, 0, 0, 0, 0],
2531
- [-1, 0, 0, 0, 1, 1],
2532
- [-1, 0, 0, 0, 0, 1]
2533
- ],
2534
- [
2535
- //right
2536
- [1, 0, 0, 1, 1, 1],
2537
- [1, 0, 0, 1, 0, 1],
2538
- [1, 0, 0, 1, 1, 0],
2539
- [1, 0, 0, 1, 0, 0]
2540
- ],
2541
- [
2542
- //bottom
2543
- [0, -1, 0, 1, 0, 1],
2544
- [0, -1, 0, 0, 0, 1],
2545
- [0, -1, 0, 1, 0, 0],
2546
- [0, -1, 0, 0, 0, 0]
2547
- ],
2548
- [
2549
- //top
2550
- [0, 1, 0, 0, 1, 1],
2551
- [0, 1, 0, 1, 1, 1],
2552
- [0, 1, 0, 0, 1, 0],
2553
- [0, 1, 0, 1, 1, 0]
2554
- ],
2555
- [
2556
- //back
2557
- [0, 0, -1, 1, 0, 0],
2558
- [0, 0, -1, 0, 0, 0],
2559
- [0, 0, -1, 1, 1, 0],
2560
- [0, 0, -1, 0, 1, 0]
2561
- ],
2562
- [
2563
- //front
2564
- [0, 0, 1, 0, 0, 1],
2565
- [0, 0, 1, 1, 0, 1],
2566
- [0, 0, 1, 0, 1, 1],
2567
- [0, 0, 1, 1, 1, 1]
2568
- ]
2569
- ];
2570
- function BuildDefaultPalette(palette) {
2571
- palette = palette ?? Colors.rgb48;
2572
- const grayscale = [];
2573
- const count = 16;
2765
+
2766
+ // src/three/renderer.ts
2767
+ import { WebGLRenderer } from "three";
2768
+ var Renderer = class extends WebGLRenderer {
2769
+ get width() {
2770
+ return this.domElement.width;
2771
+ }
2772
+ get height() {
2773
+ return this.domElement.height;
2774
+ }
2775
+ get aspectRatio() {
2776
+ return this.width / this.height;
2777
+ }
2778
+ constructor(parameters) {
2779
+ super(parameters);
2780
+ this.setPixelRatio(window.devicePixelRatio);
2781
+ }
2782
+ resize(width, height) {
2783
+ let resized = false;
2784
+ width = width ?? this.domElement.parentElement?.clientWidth ?? this.width;
2785
+ height = height ?? this.domElement.parentElement?.clientHeight ?? this.height;
2786
+ if (this.width !== width || this.height !== height) {
2787
+ this.setSize(width, height);
2788
+ resized = true;
2789
+ }
2790
+ return resized;
2791
+ }
2792
+ };
2793
+
2794
+ // src/three/starfield.ts
2795
+ import { BufferAttribute, BufferGeometry as BufferGeometry2, Group as Group4, Mesh as Mesh2, MeshBasicMaterial, PointLight, Points as Points2, PointsMaterial, SphereGeometry, Vector3 as Vector34 } from "three";
2796
+ function CreateStarfield(radius = 1e3, count = 5e3, color = 16777215) {
2797
+ const geometry = new BufferGeometry2();
2798
+ const positions = new Float32Array(count * 3);
2574
2799
  for (let i = 0; i < count; i++) {
2575
- const grey = Math.floor(i / count * 255);
2576
- grayscale.push(`rgb(${grey}, ${grey}, ${grey})`);
2800
+ const theta = rng.nextFloat() * Math.PI * 2;
2801
+ const phi = Math.acos(rng.nextFloat() * 2 - 1);
2802
+ const x = radius * Math.sin(phi) * Math.cos(theta);
2803
+ const y = radius * Math.sin(phi) * Math.sin(theta);
2804
+ const z = radius * Math.cos(phi);
2805
+ positions.set([x, y, z], i * 3);
2577
2806
  }
2578
- return [...palette, ...grayscale];
2807
+ geometry.setAttribute("position", new BufferAttribute(positions, 3));
2808
+ const material = new PointsMaterial({
2809
+ color,
2810
+ size: 5,
2811
+ sizeAttenuation: true,
2812
+ transparent: true,
2813
+ opacity: 0.9
2814
+ });
2815
+ const stars = new Points2(geometry, material);
2816
+ stars.name = "Starfield";
2817
+ return stars;
2818
+ }
2819
+ function CreateSystemStar(position) {
2820
+ const star = new Group4();
2821
+ const starPos = position ?? new Vector34();
2822
+ const starGeo = new SphereGeometry(50, 32, 32);
2823
+ const starMat = new MeshBasicMaterial({ color: 16768426 });
2824
+ const starMesh = new Mesh2(starGeo, starMat);
2825
+ starMesh.position.copy(starPos);
2826
+ star.add(starMesh);
2827
+ const starLight = new PointLight(16777215, 10, 0, 0);
2828
+ starLight.position.copy(starPos);
2829
+ star.add(starLight);
2830
+ return star;
2579
2831
  }
2580
- var Colors = {
2581
- rgb12: [
2582
- "#FF0000",
2583
- "#FF8800",
2584
- "#FFFF00",
2585
- "#88FF00",
2586
- "#00FF00",
2587
- "#00FF88",
2588
- "#00FFFF",
2589
- "#0088FF",
2590
- "#0000FF",
2591
- "#8800FF",
2592
- "#FF00FF",
2593
- "#FF0080"
2594
- ],
2595
- rgb24: [
2596
- "#FF0000",
2597
- "#FF4000",
2598
- "#FF8000",
2599
- "#FFBF00",
2600
- "#FFFF00",
2601
- "#CCFF00",
2602
- "#80FF00",
2603
- "#40FF00",
2604
- "#00FF00",
2605
- "#00FF40",
2606
- "#00FF80",
2607
- "#00FFCC",
2608
- "#00FFFF",
2609
- "#00CCFF",
2610
- "#0080FF",
2611
- "#0040FF",
2612
- "#0000FF",
2613
- "#4000FF",
2614
- "#8000FF",
2615
- "#CC00FF",
2616
- "#FF00FF",
2617
- "#FF00CC",
2618
- "#FF0080",
2619
- "#FF0040"
2620
- ],
2621
- rgb48: [
2622
- "#FF0000",
2623
- "#FF2000",
2624
- "#FF4000",
2625
- "#FF6000",
2626
- "#FF8000",
2627
- "#FFAA00",
2628
- "#FFCC00",
2629
- "#FFEE00",
2630
- "#FFFF00",
2631
- "#DDFF00",
2632
- "#CCFF00",
2633
- "#AAFF00",
2634
- "#80FF00",
2635
- "#60FF00",
2636
- "#40FF00",
2637
- "#20FF00",
2638
- "#00FF00",
2639
- "#00FF20",
2640
- "#00FF40",
2641
- "#00FF60",
2642
- "#00FF80",
2643
- "#00FFAA",
2644
- "#00FFCC",
2645
- "#00FFDD",
2646
- "#00FFFF",
2647
- "#00DDFF",
2648
- "#00CCFF",
2649
- "#0099FF",
2650
- "#0080FF",
2651
- "#0060FF",
2652
- "#0040FF",
2653
- "#0020FF",
2654
- "#0000FF",
2655
- "#2000FF",
2656
- "#4000FF",
2657
- "#6000FF",
2658
- "#8000FF",
2659
- "#AA00FF",
2660
- "#CC00FF",
2661
- "#DD00FF",
2662
- "#FF00FF",
2663
- "#FF00EE",
2664
- "#FF00CC",
2665
- "#FF00AA",
2666
- "#FF0080",
2667
- "#FF0060",
2668
- "#FF0040",
2669
- "#FF0020"
2670
- ],
2671
- rgb64: [
2672
- "#000000",
2673
- "#000055",
2674
- "#0000AA",
2675
- "#0000FF",
2676
- "#005500",
2677
- "#005555",
2678
- "#0055AA",
2679
- "#0055FF",
2680
- "#00AA00",
2681
- "#00AA55",
2682
- "#00AAAA",
2683
- "#00AAFF",
2684
- "#00FF00",
2685
- "#00FF55",
2686
- "#00FFAA",
2687
- "#00FFFF",
2688
- "#550000",
2689
- "#550055",
2690
- "#5500AA",
2691
- "#5500FF",
2692
- "#555500",
2693
- "#555555",
2694
- "#5555AA",
2695
- "#5555FF",
2696
- "#55AA00",
2697
- "#55AA55",
2698
- "#55AAAA",
2699
- "#55AAFF",
2700
- "#55FF00",
2701
- "#55FF55",
2702
- "#55FFAA",
2703
- "#55FFFF",
2704
- "#AA0000",
2705
- "#AA0055",
2706
- "#AA00AA",
2707
- "#AA00FF",
2708
- "#AA5500",
2709
- "#AA5555",
2710
- "#AA55AA",
2711
- "#AA55FF",
2712
- "#AAAA00",
2713
- "#AAAA55",
2714
- "#AAAAAA",
2715
- "#AAAAFF",
2716
- "#AAFF00",
2717
- "#AAFF55",
2718
- "#AAFFAA",
2719
- "#AAFFFF",
2720
- "#FF0000",
2721
- "#FF0055",
2722
- "#FF00AA",
2723
- "#FF00FF",
2724
- "#FF5500",
2725
- "#FF5555",
2726
- "#FF55AA",
2727
- "#FF55FF",
2728
- "#FFAA00",
2729
- "#FFAA55",
2730
- "#FFAAAA",
2731
- "#FFAAFF",
2732
- "#FFFF00",
2733
- "#FFFF55",
2734
- "#FFFFAA",
2735
- "#FFFFFF"
2736
- ]
2737
- };
2738
-
2739
- // src/rendering/three/particle-system-3d.ts
2740
- import { BufferGeometry as BufferGeometry2, Float32BufferAttribute, Group as Group3, Points, ShaderMaterial, Vector3 as Vector33 } from "three";
2741
2832
 
2742
- // src/spatial-partition-3d.ts
2743
- var SpatialPartition3d = class {
2744
- cells;
2745
- cellSize;
2746
- entities;
2747
- constructor(cellSize, entities) {
2748
- this.cellSize = cellSize;
2749
- this.entities = entities;
2750
- const gridSize = Math.ceil(1 / cellSize);
2751
- this.cells = Array.from(
2752
- { length: gridSize },
2753
- () => Array.from(
2754
- { length: gridSize },
2755
- () => Array.from({ length: gridSize }, () => [])
2756
- )
2757
- );
2758
- for (const entity of this.entities) {
2759
- this.addEntity(entity);
2760
- }
2761
- }
2762
- getCell(x, y, z) {
2763
- const cx = Math.floor(x / this.cellSize);
2764
- const cy = Math.floor(y / this.cellSize);
2765
- const cz = Math.floor(z / this.cellSize);
2766
- return this.cells[cz][cy][cx];
2833
+ // src/three/texture-atlas.ts
2834
+ import { MeshLambertMaterial as MeshLambertMaterial2, NearestFilter as NearestFilter3 } from "three";
2835
+ var TextureAtlas = class _TextureAtlas extends MeshLambertMaterial2 {
2836
+ constructor(textureData, textureWidth, textureHeight = textureWidth, params) {
2837
+ super({
2838
+ map: textureData.texture,
2839
+ alphaTest: 0.1,
2840
+ transparent: true,
2841
+ ...params ?? {}
2842
+ });
2843
+ this.textureData = textureData;
2844
+ this.textureWidth = textureWidth;
2845
+ this.textureHeight = textureHeight;
2846
+ this._uw = this.textureWidth / this.textureData.width;
2847
+ this._uh = this.textureHeight / this.textureData.height;
2848
+ this.textureData.texture.magFilter = NearestFilter3;
2767
2849
  }
2768
- getCellNeighbors(cx, cy, cz) {
2769
- const neighbors = [];
2770
- const gridSize = this.cells.length;
2771
- for (let dz = -1; dz <= 1; dz++) {
2772
- for (let dy = -1; dy <= 1; dy++) {
2773
- for (let dx = -1; dx <= 1; dx++) {
2774
- let nx = (cx + dx + gridSize) % gridSize;
2775
- let ny = (cy + dy + gridSize) % gridSize;
2776
- let nz = (cz + dz + gridSize) % gridSize;
2777
- neighbors.push(this.cells[nz][ny][nx]);
2778
- }
2779
- }
2780
- }
2781
- return neighbors;
2850
+ textureData;
2851
+ textureWidth;
2852
+ textureHeight;
2853
+ _uw;
2854
+ _uh;
2855
+ getUv(voxel, ux, uy) {
2856
+ return [
2857
+ (voxel + ux) * this._uw,
2858
+ 1 - (1 - uy) * this._uh
2859
+ ];
2782
2860
  }
2783
- addEntity(entity) {
2784
- const cell = this.getCell(entity.x, entity.y, entity.z);
2785
- cell.push(entity);
2861
+ static CreateFromUrl(url, textureWidth, textureHeight = textureWidth, params) {
2862
+ return LoadTexture(url).then((textureData) => new _TextureAtlas(
2863
+ textureData,
2864
+ textureWidth,
2865
+ textureHeight,
2866
+ params
2867
+ ));
2786
2868
  }
2787
2869
  };
2788
2870
 
2789
- // src/rendering/three/particle-system-3d.ts
2790
- var vertexShader = `
2791
- uniform float pointSize;
2792
-
2793
- varying vec4 vColor;
2794
-
2795
- void main() {
2796
- vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);
2797
-
2798
- gl_Position = projectionMatrix * mvPosition;
2799
- gl_PointSize = pointSize;
2800
-
2801
- vColor = color;
2802
- }`;
2803
- var fragmentShader = `
2804
- varying vec4 vColor;
2805
-
2806
- void main() {
2807
- gl_FragColor = vColor;
2808
- }`;
2809
- var Colors2 = [
2810
- [1, 0, 0, 1],
2811
- // red
2812
- [0, 1, 0, 1],
2813
- // green,
2814
- [0, 0, 1, 1],
2815
- // blue,
2816
- [1, 1, 0, 1],
2817
- // yellow,
2818
- [1, 0, 1, 1]
2819
- // magenta,
2820
- ];
2821
- var ParticleSystem3d = class extends Group3 {
2822
- particleCount = 1e3;
2823
- _geometry;
2824
- _particles = [];
2825
- _frictionHalfLife = 0.04;
2826
- _range = 0.2;
2827
- _rangeFactor = 0.1;
2828
- _attractionMatrix;
2829
- _spatialPartition;
2830
- constructor() {
2871
+ // src/three/threejs-camera-rig.ts
2872
+ import { PerspectiveCamera as PerspectiveCamera3, Group as Group5 } from "three";
2873
+ var ThreeJsCameraRig = class extends Group5 {
2874
+ gimbal;
2875
+ camera;
2876
+ target;
2877
+ mouseSensitivity = 0.01;
2878
+ wheelSensitivity = 0.02;
2879
+ minCameraDistance = 2;
2880
+ maxCameraDistance = 100;
2881
+ minTiltAngle = degrees(-90);
2882
+ maxTiltAngle = degrees(0);
2883
+ clampTiltAngle = false;
2884
+ constructor(params) {
2831
2885
  super();
2832
- const uniforms = {
2833
- pointSize: { value: 4 }
2834
- };
2835
- this.position.x = -0.5;
2836
- this.position.y = -0.5;
2837
- this.position.z = -0.5;
2838
- this._geometry = new BufferGeometry2();
2839
- this._geometry.setAttribute("position", new Float32BufferAttribute([], 3));
2840
- this._geometry.setAttribute("color", new Float32BufferAttribute([], 4));
2841
- const material = new ShaderMaterial({
2842
- uniforms,
2843
- vertexShader,
2844
- fragmentShader,
2845
- depthTest: true,
2846
- depthWrite: false,
2847
- vertexColors: true
2848
- });
2849
- const pointsMesh = new Points(this._geometry, material);
2850
- this.add(pointsMesh);
2851
- for (let i = 0; i < this.particleCount; i++) {
2852
- this._particles.push({
2853
- x: rng.nextFloat(),
2854
- y: rng.nextFloat(),
2855
- z: rng.nextFloat(),
2856
- vx: 0,
2857
- vy: 0,
2858
- vz: 0,
2859
- color: rng.range(Colors2.length)
2860
- });
2861
- }
2862
- this._attractionMatrix = randomMatrix(Colors2.length);
2863
- this._spatialPartition = new SpatialPartition3d(this._range, this._particles);
2886
+ this.gimbal = new Group5();
2887
+ this.add(this.gimbal);
2888
+ this.camera = params?.camera ?? new PerspectiveCamera3(
2889
+ params?.fov ?? 75,
2890
+ params?.aspect ?? 2,
2891
+ params?.near ?? 0.1,
2892
+ params?.far ?? 1e3
2893
+ );
2894
+ this.gimbal.add(this.camera);
2864
2895
  }
2865
- _calcForce(r, a, beta = 0.3) {
2866
- let f = 0;
2867
- if (r < beta) {
2868
- f = r / beta - 1;
2869
- } else if (beta < r && r < 1) {
2870
- f = a * (1 - Math.abs(2 * r - 1 - beta) / (1 - beta));
2871
- }
2872
- return f;
2896
+ orbit(deltaX, deltaY) {
2897
+ (this.target || this).rotateY(-deltaX * this.mouseSensitivity);
2898
+ this.gimbal.rotation.x = this.clampTiltAngle ? clamp(
2899
+ this.gimbal.rotation.x + -deltaY * this.mouseSensitivity,
2900
+ this.minTiltAngle,
2901
+ this.maxTiltAngle
2902
+ ) : this.gimbal.rotation.x + -deltaY * this.mouseSensitivity;
2873
2903
  }
2874
- _updateVelocities(dt) {
2875
- const frictionFactor = Math.pow(
2876
- 0.5,
2877
- dt / this._frictionHalfLife
2904
+ dolly(deltaY) {
2905
+ this.camera.position.z = clamp(
2906
+ this.camera.position.z + deltaY * this.wheelSensitivity,
2907
+ this.minCameraDistance,
2908
+ this.maxCameraDistance
2878
2909
  );
2879
- for (let z = 0; z < this._spatialPartition.cells.length; z++) {
2880
- for (let y = 0; y < this._spatialPartition.cells[z].length; y++) {
2881
- for (let x = 0; x < this._spatialPartition.cells[z][y].length; x++) {
2882
- const cell = this._spatialPartition.cells[z][y][x];
2883
- for (let i = 0; i < cell.length; i++) {
2884
- let fx = 0, fy = 0, fz = 0;
2885
- const p1 = cell[i];
2886
- const neighbors = this._spatialPartition.getCellNeighbors(x, y, z);
2887
- for (const neighborCell of neighbors) {
2888
- for (let j = 0; j < neighborCell.length; j++) {
2889
- if (cell === neighborCell && i === j) continue;
2890
- const p2 = neighborCell[j];
2891
- let dx = p2.x - p1.x;
2892
- let dy = p2.y - p1.y;
2893
- let dz = p2.z - p1.z;
2894
- if (Math.abs(dx) > 0.5) dx = dx > 0 ? dx - 1 : dx + 1;
2895
- if (Math.abs(dy) > 0.5) dy = dy > 0 ? dy - 1 : dy + 1;
2896
- if (Math.abs(dz) > 0.5) dz = dz > 0 ? dz - 1 : dz + 1;
2897
- const dist = Math.hypot(dx, dy, dz);
2898
- if (dist > 0 && dist < this._range) {
2899
- const f = this._calcForce(dist / this._range, this._attractionMatrix[p1.color][p2.color]);
2900
- fx += dx / dist * f;
2901
- fy += dy / dist * f;
2902
- fz += dz / dist * f;
2903
- }
2904
- }
2905
- }
2906
- fx *= this._range * this._rangeFactor;
2907
- fy *= this._range * this._rangeFactor;
2908
- fz *= this._range * this._rangeFactor;
2909
- p1.vx *= frictionFactor;
2910
- p1.vy *= frictionFactor;
2911
- p1.vz *= frictionFactor;
2912
- p1.vx += fx;
2913
- p1.vy += fy;
2914
- p1.vz += fz;
2915
- }
2916
- }
2917
- }
2918
- }
2919
2910
  }
2920
- _updatePositions(dt) {
2921
- for (let i = 0; i < this._particles.length; i++) {
2922
- const particle = this._particles[i];
2923
- const oldCell = this._spatialPartition.getCell(particle.x, particle.y, particle.z);
2924
- particle.x += particle.vx * dt;
2925
- particle.y += particle.vy * dt;
2926
- particle.z += particle.vz * dt;
2927
- if (particle.x < 0) particle.x = (particle.x + 1) % 1;
2928
- if (particle.x > 1) particle.x = particle.x % 1;
2929
- if (particle.y < 0) particle.y = (particle.y + 1) % 1;
2930
- if (particle.y > 1) particle.y = particle.y % 1;
2931
- if (particle.z < 0) particle.z = (particle.z + 1) % 1;
2932
- if (particle.z > 1) particle.z = particle.z % 1;
2933
- const newCell = this._spatialPartition.getCell(particle.x, particle.y, particle.z);
2934
- if (newCell !== oldCell) {
2935
- const index = oldCell.indexOf(particle);
2936
- if (index !== -1) {
2937
- oldCell.splice(index, 1);
2938
- }
2939
- newCell.push(particle);
2940
- }
2911
+ };
2912
+
2913
+ // src/three/threejs-player-controller.ts
2914
+ import { Group as Group6, Vector3 as Vector35 } from "three";
2915
+ var ThreeJsPlayerController = class extends Group6 {
2916
+ moveSpeed = 1;
2917
+ cameraRig;
2918
+ velocity;
2919
+ constructor(camera) {
2920
+ super();
2921
+ this.velocity = new Vector35();
2922
+ this.cameraRig = new ThreeJsCameraRig({ camera });
2923
+ this.add(this.cameraRig);
2924
+ }
2925
+ update(deltaTime) {
2926
+ if (this.velocity.length()) {
2927
+ this.translateOnAxis(this.velocity.normalize(), this.moveSpeed * deltaTime);
2941
2928
  }
2942
2929
  }
2943
- _sortParticles(camera) {
2944
- this._particles.sort((a, b) => {
2945
- const d1 = camera.position.distanceTo(new Vector33(a.x, a.y, a.z));
2946
- const d2 = camera.position.distanceTo(new Vector33(b.x, b.y, b.z));
2947
- return d1 > d2 ? -1 : d1 > d1 ? 1 : 0;
2930
+ };
2931
+
2932
+ // src/three/voxel-geometry.ts
2933
+ import { BufferGeometry as BufferGeometry3, Float32BufferAttribute as Float32BufferAttribute2 } from "three";
2934
+ var VoxelGeometry = class extends BufferGeometry3 {
2935
+ type = "VoxelGeometry";
2936
+ voxels = new Map3D();
2937
+ voxelBuildParams = {};
2938
+ updateGeometry(params) {
2939
+ BuildVoxelGeometry(this.voxels, {
2940
+ ...params ?? this.voxelBuildParams,
2941
+ voxelGeometry: this
2948
2942
  });
2949
2943
  }
2950
- _updateGeometry() {
2951
- const positions = [];
2952
- const colors2 = [];
2953
- for (const particle of this._particles) {
2944
+ };
2945
+ function BuildVoxelGeometry(voxelMap, params) {
2946
+ const includeHiddenFaces = params.includeHiddenFaces ?? false;
2947
+ const smoothNormals = params.smoothNormals ?? false;
2948
+ const palette = params.palette ?? [];
2949
+ const positions = [];
2950
+ const normals = [];
2951
+ const colors2 = [];
2952
+ const indices = [];
2953
+ function pushColor(hex) {
2954
+ colors2.push(
2955
+ (hex >> 16 & 255) / 255,
2956
+ (hex >> 8 & 255) / 255,
2957
+ (hex & 255) / 255
2958
+ );
2959
+ }
2960
+ function emitFace(face, x, y, z, color) {
2961
+ const index = positions.length / 3;
2962
+ const vertices = face.vertices;
2963
+ for (let i = 0; i < vertices.length; i += 3) {
2954
2964
  positions.push(
2955
- particle.x,
2956
- particle.y,
2957
- particle.z
2965
+ x + vertices[i],
2966
+ y + vertices[i + 1],
2967
+ z + vertices[i + 2]
2958
2968
  );
2959
- colors2.push(
2960
- Colors2[particle.color][0],
2961
- Colors2[particle.color][1],
2962
- Colors2[particle.color][2],
2963
- Colors2[particle.color][3]
2969
+ normals.push(
2970
+ face.normal[0],
2971
+ face.normal[1],
2972
+ face.normal[2]
2964
2973
  );
2965
- }
2966
- this._geometry.setAttribute("position", new Float32BufferAttribute(positions, 3));
2967
- this._geometry.setAttribute("color", new Float32BufferAttribute(colors2, 4));
2968
- this._geometry.attributes.position.needsUpdate = true;
2974
+ pushColor(color);
2975
+ }
2976
+ indices.push(
2977
+ index,
2978
+ index + 1,
2979
+ index + 2,
2980
+ index,
2981
+ index + 2,
2982
+ index + 3
2983
+ );
2969
2984
  }
2970
- update(camera, dt) {
2971
- this._updateVelocities(dt);
2972
- this._updatePositions(dt);
2973
- this._sortParticles(camera);
2974
- this._updateGeometry();
2985
+ function randomColor() {
2986
+ return rng.range(256 ** 3);
2975
2987
  }
2976
- };
2977
-
2978
- // src/rendering/three/asteroid-mesh.ts
2979
- import { IcosahedronGeometry, Mesh as Mesh3, MeshStandardMaterial as MeshStandardMaterial2 } from "three";
2980
- import { createNoise3D as createNoise3D2 } from "simplex-noise";
2981
- var AsteroidMesh = class extends Mesh3 {
2982
- constructor(options = {}) {
2983
- const radius = options.radius ?? 1;
2984
- const detail = options.detail ?? 1;
2985
- const noiseScale = options.noiseScale ?? 1;
2986
- const displacement = options.displacement ?? 0.1;
2987
- const secondaryNoise = options.secondaryNoise ?? false;
2988
- const color = options.color ?? 8947848;
2989
- const geometry = new IcosahedronGeometry(radius, detail);
2990
- const material = new MeshStandardMaterial2({ color });
2991
- super(geometry, material);
2992
- const noise3d = createNoise3D2(rng.rng.float);
2993
- const noise3d2 = secondaryNoise ? createNoise3D2(rng.rng.float) : null;
2994
- const position = this.geometry.attributes.position;
2995
- const vertices = position.array;
2996
- for (let i = 0; i < vertices.length; i += 3) {
2997
- const x = vertices[i];
2998
- const y = vertices[i + 1];
2999
- const z = vertices[i + 2];
3000
- const n1 = noise3d(x * noiseScale, y * noiseScale, z * noiseScale);
3001
- const n2 = secondaryNoise ? 0.5 * noise3d2(x * noiseScale * 2, y * noiseScale * 2, z * noiseScale * 2) : 0;
3002
- const noiseValue = n1 + n2;
3003
- const displacementValue = 1 + noiseValue * displacement;
3004
- vertices[i] = x * displacementValue;
3005
- vertices[i + 1] = y * displacementValue;
3006
- vertices[i + 2] = z * displacementValue;
2988
+ voxelMap.forEach((x, y, z, n) => {
2989
+ const color = palette[n] ?? randomColor();
2990
+ for (const face of VOXEL_FACES) {
2991
+ const neighbor = voxelMap.get(
2992
+ x + face.normal[0],
2993
+ y + face.normal[1],
2994
+ z + face.normal[2]
2995
+ );
2996
+ if (neighbor !== voxelMap.defaultValue && !includeHiddenFaces) continue;
2997
+ emitFace(face, x, y, z, color);
3007
2998
  }
3008
- position.needsUpdate = true;
3009
- this.geometry.computeVertexNormals();
3010
- }
3011
- };
3012
-
3013
- // src/rendering/three/starfield.ts
3014
- import { BufferAttribute as BufferAttribute2, BufferGeometry as BufferGeometry3, Group as Group4, Mesh as Mesh4, MeshBasicMaterial as MeshBasicMaterial2, PointLight, Points as Points2, PointsMaterial, SphereGeometry, Vector3 as Vector34 } from "three";
3015
- function CreateStarfield(radius = 1e3, count = 5e3, color = 16777215) {
3016
- const geometry = new BufferGeometry3();
3017
- const positions = new Float32Array(count * 3);
3018
- for (let i = 0; i < count; i++) {
3019
- const theta = rng.nextFloat() * Math.PI * 2;
3020
- const phi = Math.acos(rng.nextFloat() * 2 - 1);
3021
- const x = radius * Math.sin(phi) * Math.cos(theta);
3022
- const y = radius * Math.sin(phi) * Math.sin(theta);
3023
- const z = radius * Math.cos(phi);
3024
- positions.set([x, y, z], i * 3);
3025
- }
3026
- geometry.setAttribute("position", new BufferAttribute2(positions, 3));
3027
- const material = new PointsMaterial({
3028
- color,
3029
- size: 5,
3030
- sizeAttenuation: true,
3031
- transparent: true,
3032
- opacity: 0.9
3033
2999
  });
3034
- const stars = new Points2(geometry, material);
3035
- stars.name = "Starfield";
3036
- return stars;
3037
- }
3038
- function CreateSystemStar(position) {
3039
- const star = new Group4();
3040
- const starPos = position ?? new Vector34();
3041
- const starGeo = new SphereGeometry(50, 32, 32);
3042
- const starMat = new MeshBasicMaterial2({ color: 16768426 });
3043
- const starMesh = new Mesh4(starGeo, starMat);
3044
- starMesh.position.copy(starPos);
3045
- star.add(starMesh);
3046
- const starLight = new PointLight(16777215, 10, 0, 0);
3047
- starLight.position.copy(starPos);
3048
- star.add(starLight);
3049
- return star;
3000
+ const geometry = params.voxelGeometry ?? new VoxelGeometry();
3001
+ geometry.setAttribute("position", new Float32BufferAttribute2(positions, 3));
3002
+ geometry.setAttribute("normal", new Float32BufferAttribute2(normals, 3));
3003
+ geometry.setAttribute("color", new Float32BufferAttribute2(colors2, 3));
3004
+ geometry.setIndex(indices);
3005
+ if (smoothNormals) geometry.computeVertexNormals();
3006
+ geometry.computeBoundingBox();
3007
+ geometry.computeBoundingSphere();
3008
+ return geometry;
3050
3009
  }
3010
+ var VOXEL_FACES = [
3011
+ // +X
3012
+ {
3013
+ normal: [1, 0, 0],
3014
+ vertices: [
3015
+ 1,
3016
+ 0,
3017
+ 0,
3018
+ 1,
3019
+ 1,
3020
+ 0,
3021
+ 1,
3022
+ 1,
3023
+ 1,
3024
+ 1,
3025
+ 0,
3026
+ 1
3027
+ ]
3028
+ },
3029
+ // -X
3030
+ {
3031
+ normal: [-1, 0, 0],
3032
+ vertices: [
3033
+ 0,
3034
+ 0,
3035
+ 1,
3036
+ 0,
3037
+ 1,
3038
+ 1,
3039
+ 0,
3040
+ 1,
3041
+ 0,
3042
+ 0,
3043
+ 0,
3044
+ 0
3045
+ ]
3046
+ },
3047
+ // +Y
3048
+ {
3049
+ normal: [0, 1, 0],
3050
+ vertices: [
3051
+ 0,
3052
+ 1,
3053
+ 0,
3054
+ 0,
3055
+ 1,
3056
+ 1,
3057
+ 1,
3058
+ 1,
3059
+ 1,
3060
+ 1,
3061
+ 1,
3062
+ 0
3063
+ ]
3064
+ },
3065
+ // -Y
3066
+ {
3067
+ normal: [0, -1, 0],
3068
+ vertices: [
3069
+ 1,
3070
+ 0,
3071
+ 0,
3072
+ 1,
3073
+ 0,
3074
+ 1,
3075
+ 0,
3076
+ 0,
3077
+ 1,
3078
+ 0,
3079
+ 0,
3080
+ 0
3081
+ ]
3082
+ },
3083
+ // +Z
3084
+ {
3085
+ normal: [0, 0, 1],
3086
+ vertices: [
3087
+ 1,
3088
+ 0,
3089
+ 1,
3090
+ 1,
3091
+ 1,
3092
+ 1,
3093
+ 0,
3094
+ 1,
3095
+ 1,
3096
+ 0,
3097
+ 0,
3098
+ 1
3099
+ ]
3100
+ },
3101
+ // -Z
3102
+ {
3103
+ normal: [0, 0, -1],
3104
+ vertices: [
3105
+ 0,
3106
+ 0,
3107
+ 0,
3108
+ 0,
3109
+ 1,
3110
+ 0,
3111
+ 1,
3112
+ 1,
3113
+ 0,
3114
+ 1,
3115
+ 0,
3116
+ 0
3117
+ ]
3118
+ }
3119
+ ];
3051
3120
 
3052
- // src/rendering/three/palette-controller.ts
3053
- import { Color as Color3, Vector3 as Vector35 } from "three";
3054
- async function CreatePaletteController(parentGui, colorPalette, onChange, folderName = "palette") {
3055
- const { Controller } = await import("three/examples/jsm/libs/lil-gui.module.min.js");
3056
- class PaletteControllerImpl extends Controller {
3057
- $innerDiv;
3058
- colorButtons = [];
3059
- colorButtonSize = 20;
3060
- selectedBorderStyle = "2px dashed black";
3061
- currentColorIndex = 0;
3062
- eyedropperButton;
3063
- colorPalette;
3064
- _onColorChange;
3065
- constructor() {
3066
- const parent = parentGui.addFolder(folderName);
3067
- super(parent, {}, "", "function");
3068
- this.colorPalette = colorPalette;
3069
- this._onColorChange = onChange;
3070
- this.$widget.style.setProperty("display", "flex");
3071
- this.$widget.style.setProperty("justify-content", "center");
3072
- this.$innerDiv = document.createElement("div");
3073
- this.$innerDiv.style.setProperty("display", "flex");
3074
- this.$innerDiv.style.setProperty("flex-wrap", "wrap");
3075
- this.$innerDiv.style.setProperty("width", `${this.colorButtonSize * Math.floor(Math.sqrt(this.colorPalette.length)) + 2}px`);
3076
- this.$innerDiv.appendChild(this.$name);
3077
- this.$widget.appendChild(this.$innerDiv);
3078
- this.colorPalette.forEach((color) => this._createColorButton(color));
3079
- if (window.EyeDropper) {
3080
- this.eyedropperButton = parent.add({
3081
- eyedropper: () => {
3082
- this.eyedropperButton?.disable(true);
3083
- new window.EyeDropper().open().then(({ sRGBHex }) => {
3084
- const i = this.findClosestColorMatchIndex(sRGBHex);
3085
- this.setSelectedColor(i);
3086
- this._onColorChange?.(i);
3087
- }).finally(() => this.eyedropperButton?.disable(false)).catch(() => {
3121
+ // src/three/voxel-mesh.ts
3122
+ import { BufferAttribute as BufferAttribute2, BufferGeometry as BufferGeometry4, Color as Color3, Mesh as Mesh3 } from "three";
3123
+ var VoxelMesh = class extends Mesh3 {
3124
+ type = "VoxelMesh";
3125
+ width;
3126
+ depth;
3127
+ height;
3128
+ colorPalette;
3129
+ voxels;
3130
+ needsGeometryUpdate = true;
3131
+ constructor(width, depth, height, material, name) {
3132
+ super();
3133
+ this.width = width;
3134
+ this.depth = depth;
3135
+ this.height = height;
3136
+ this.material = material;
3137
+ this.material.vertexColors = true;
3138
+ this.name = name ?? "VoxelMesh";
3139
+ this.colorPalette = BuildDefaultPalette();
3140
+ this.voxels = /* @__PURE__ */ new Map();
3141
+ this.geometry = new BufferGeometry4();
3142
+ this.updateGeometry();
3143
+ }
3144
+ _xyz2k(x, y, z) {
3145
+ x = Math.abs(Math.floor(x));
3146
+ y = Math.abs(Math.floor(y));
3147
+ z = Math.abs(Math.floor(z));
3148
+ return `${x},${y},${z}`;
3149
+ }
3150
+ _k2xyz(k) {
3151
+ const [x, y, z] = k.split(",").map((s) => parseInt(s));
3152
+ return { x, y, z };
3153
+ }
3154
+ get(x, y, z) {
3155
+ let n = -1;
3156
+ if (x >= 0 && y >= 0 && z >= 0 && x < this.width && y < this.height && z < this.depth) {
3157
+ n = this.voxels.get(this._xyz2k(x, y, z)) ?? -1;
3158
+ }
3159
+ return n;
3160
+ }
3161
+ set(x, y, z, n) {
3162
+ if (x >= 0 && y >= 0 && z >= 0 && x < this.width && y < this.height && z < this.depth) {
3163
+ if (n === void 0) this.voxels.delete(this._xyz2k(x, y, z));
3164
+ else this.voxels.set(this._xyz2k(x, y, z), n);
3165
+ this.needsGeometryUpdate = true;
3166
+ }
3167
+ }
3168
+ clearVoxels() {
3169
+ this.voxels.clear();
3170
+ }
3171
+ setSize(width, depth, height) {
3172
+ this.forEachVoxel((x, y, z) => {
3173
+ if (x >= width || y >= height || z >= depth) this.set(x, y, z);
3174
+ });
3175
+ this.width = width;
3176
+ this.depth = depth;
3177
+ this.height = height;
3178
+ this.needsGeometryUpdate = true;
3179
+ }
3180
+ forEachVoxel(callback) {
3181
+ this.voxels.forEach((n, k) => {
3182
+ const { x, y, z } = this._k2xyz(k);
3183
+ callback(x, y, z, n);
3184
+ });
3185
+ }
3186
+ importVoxelData(voxelData) {
3187
+ this.clearVoxels();
3188
+ this.name = voxelData.name;
3189
+ this.setSize(voxelData.width, voxelData.depth, voxelData.height);
3190
+ voxelData.palette.forEach((color, i) => {
3191
+ if (i < this.colorPalette.length) {
3192
+ this.colorPalette[i] = color;
3193
+ } else {
3194
+ this.colorPalette.push(color);
3195
+ }
3196
+ });
3197
+ voxelData.voxels.forEach((voxel) => {
3198
+ const { x, y, z, color } = voxel;
3199
+ this.set(x, y, z, color);
3200
+ });
3201
+ this.updateGeometry();
3202
+ }
3203
+ updateGeometry() {
3204
+ if (this.needsGeometryUpdate) {
3205
+ const positions = [];
3206
+ const normals = [];
3207
+ const colors2 = [];
3208
+ const indices = [];
3209
+ this.forEachVoxel((x, y, z, n) => {
3210
+ VoxelFaces.forEach((faces) => {
3211
+ const [dx, dy, dz] = faces[0];
3212
+ const neighborVoxel = this.get(x + dx, y + dy, z + dz);
3213
+ if (neighborVoxel < 0) {
3214
+ const positionIndex = positions.length / 3;
3215
+ faces.forEach((face) => {
3216
+ const [nx, ny, nz, px, py, pz] = face;
3217
+ positions.push(x + px, y + py, z + pz);
3218
+ normals.push(nx, ny, nz);
3219
+ const { r, g, b } = new Color3(this.colorPalette[n]);
3220
+ colors2.push(r, g, b, 1);
3088
3221
  });
3222
+ indices.push(
3223
+ positionIndex,
3224
+ positionIndex + 1,
3225
+ positionIndex + 2,
3226
+ positionIndex + 2,
3227
+ positionIndex + 1,
3228
+ positionIndex + 3
3229
+ );
3089
3230
  }
3090
- }, "eyedropper").name("findClosestColor");
3091
- }
3092
- this.name("");
3093
- this.updateDisplay();
3094
- }
3095
- _onColorButtonClicked(i, button) {
3096
- if (button === 0) {
3097
- this.setSelectedColor(i);
3098
- this._onColorChange?.(i);
3099
- this.colorButtons[i].blur();
3100
- } else if (button === 2 && window.EyeDropper) {
3101
- new window.EyeDropper().open().then(({ sRGBHex }) => {
3102
- this.colorPalette[i] = sRGBHex;
3103
- this.colorButtons[i].setAttribute("title", `${sRGBHex}`);
3104
- this.colorButtons[i].style.setProperty("background", sRGBHex);
3105
- this.setSelectedColor(i);
3106
- this._onColorChange?.(i);
3107
- this.colorButtons[i].blur();
3108
- }).finally(() => this.eyedropperButton?.disable(false)).catch(() => {
3109
3231
  });
3110
- }
3111
- }
3112
- _createColorButton(color) {
3113
- const i = this.colorButtons.length;
3114
- const colorButton = document.createElement("div");
3115
- colorButton.setAttribute("id", `colorButton${i}`);
3116
- colorButton.setAttribute("title", `${color}`);
3117
- colorButton.style.setProperty("width", `${this.colorButtonSize}px`);
3118
- colorButton.style.setProperty("height", `${this.colorButtonSize}px`);
3119
- colorButton.style.setProperty("background", color);
3120
- colorButton.addEventListener("pointerup", (ev) => this._onColorButtonClicked(i, ev.button));
3121
- this.colorButtons.push(colorButton);
3122
- this.$innerDiv.appendChild(colorButton);
3123
- }
3124
- updatePaletteColors() {
3125
- this.colorPalette.forEach((color, i) => {
3126
- if (i < this.colorButtons.length) {
3127
- this.colorButtons[i].setAttribute("title", `${color}`);
3128
- this.colorButtons[i].style.setProperty("background", color);
3129
- } else {
3130
- this._createColorButton(color);
3131
- }
3132
3232
  });
3233
+ this.geometry.setAttribute("position", new BufferAttribute2(new Float32Array(positions), 3));
3234
+ this.geometry.setAttribute("normal", new BufferAttribute2(new Float32Array(normals), 3));
3235
+ this.geometry.setAttribute("color", new BufferAttribute2(new Float32Array(colors2), 4));
3236
+ this.geometry.setIndex(indices);
3237
+ this.geometry.computeBoundingSphere();
3238
+ this.updateMatrixWorld();
3133
3239
  }
3134
- setSelectedColor(colorIndex = 0) {
3135
- this.colorButtons[this.currentColorIndex].style.removeProperty("border");
3136
- this.currentColorIndex = clamp(colorIndex, 0, this.colorPalette.length);
3137
- this.colorButtons[this.currentColorIndex].style.setProperty("border", this.selectedBorderStyle);
3138
- }
3139
- findClosestColorMatchIndex(color) {
3140
- const pickedColor = new Color3(color);
3141
- const pickedVector = new Vector35().setFromColor(pickedColor);
3142
- const list = [];
3143
- this.colorPalette.forEach((paletteColorString, i) => {
3144
- const paletteColor = new Color3(paletteColorString);
3145
- const paletteVector = new Vector35().setFromColor(paletteColor);
3146
- const d = paletteVector.distanceTo(pickedVector);
3147
- list.push({ i, d });
3148
- });
3149
- list.sort((a, b) => a.d - b.d);
3150
- const closest = list.shift();
3151
- return closest?.i ?? 0;
3152
- }
3240
+ this.needsGeometryUpdate = false;
3153
3241
  }
3154
- return new PaletteControllerImpl();
3155
- }
3156
-
3157
- // src/rendering/three/ecs.ts
3158
- import { Group as Group5 } from "three";
3159
- var entityCounter = 0;
3160
- function GenerateEntityId() {
3161
- return `entity_${entityCounter++}`;
3162
- }
3163
- function CreateThreeEntity(obj) {
3164
- const entity = obj ?? new Group5();
3165
- entity.userData.entityId = GenerateEntityId();
3166
- entity.userData.components = {};
3167
- return entity;
3168
- }
3169
- function AddThreeComponent(entity, name, component) {
3170
- entity.userData.components[name] = component;
3171
- }
3172
- function GetThreeComponent(entity, name) {
3173
- return entity.userData.components[name];
3174
- }
3175
- function RemoveThreeComponent(entity, name) {
3176
- delete entity.userData.components[name];
3177
- }
3178
- function IsThreeEntity(obj) {
3179
- return obj.userData.entityId !== void 0;
3242
+ exportData() {
3243
+ const voxelData = {
3244
+ name: this.name,
3245
+ width: this.width,
3246
+ depth: this.depth,
3247
+ height: this.height,
3248
+ palette: [...this.colorPalette],
3249
+ voxels: []
3250
+ };
3251
+ this.forEachVoxel((x, y, z, color) => {
3252
+ voxelData.voxels.push({ x, y, z, color });
3253
+ });
3254
+ return voxelData;
3255
+ }
3256
+ };
3257
+ var VoxelFaces = [
3258
+ // [nx, ny, nz, px, py, pz]
3259
+ [
3260
+ //left
3261
+ [-1, 0, 0, 0, 1, 0],
3262
+ [-1, 0, 0, 0, 0, 0],
3263
+ [-1, 0, 0, 0, 1, 1],
3264
+ [-1, 0, 0, 0, 0, 1]
3265
+ ],
3266
+ [
3267
+ //right
3268
+ [1, 0, 0, 1, 1, 1],
3269
+ [1, 0, 0, 1, 0, 1],
3270
+ [1, 0, 0, 1, 1, 0],
3271
+ [1, 0, 0, 1, 0, 0]
3272
+ ],
3273
+ [
3274
+ //bottom
3275
+ [0, -1, 0, 1, 0, 1],
3276
+ [0, -1, 0, 0, 0, 1],
3277
+ [0, -1, 0, 1, 0, 0],
3278
+ [0, -1, 0, 0, 0, 0]
3279
+ ],
3280
+ [
3281
+ //top
3282
+ [0, 1, 0, 0, 1, 1],
3283
+ [0, 1, 0, 1, 1, 1],
3284
+ [0, 1, 0, 0, 1, 0],
3285
+ [0, 1, 0, 1, 1, 0]
3286
+ ],
3287
+ [
3288
+ //back
3289
+ [0, 0, -1, 1, 0, 0],
3290
+ [0, 0, -1, 0, 0, 0],
3291
+ [0, 0, -1, 1, 1, 0],
3292
+ [0, 0, -1, 0, 1, 0]
3293
+ ],
3294
+ [
3295
+ //front
3296
+ [0, 0, 1, 0, 0, 1],
3297
+ [0, 0, 1, 1, 0, 1],
3298
+ [0, 0, 1, 0, 1, 1],
3299
+ [0, 0, 1, 1, 1, 1]
3300
+ ]
3301
+ ];
3302
+ function BuildDefaultPalette(palette) {
3303
+ palette = palette ?? Colors2.rgb48;
3304
+ const grayscale = [];
3305
+ const count = 16;
3306
+ for (let i = 0; i < count; i++) {
3307
+ const grey = Math.floor(i / count * 255);
3308
+ grayscale.push(`rgb(${grey}, ${grey}, ${grey})`);
3309
+ }
3310
+ return [...palette, ...grayscale];
3180
3311
  }
3312
+ var Colors2 = {
3313
+ rgb12: [
3314
+ "#FF0000",
3315
+ "#FF8800",
3316
+ "#FFFF00",
3317
+ "#88FF00",
3318
+ "#00FF00",
3319
+ "#00FF88",
3320
+ "#00FFFF",
3321
+ "#0088FF",
3322
+ "#0000FF",
3323
+ "#8800FF",
3324
+ "#FF00FF",
3325
+ "#FF0080"
3326
+ ],
3327
+ rgb24: [
3328
+ "#FF0000",
3329
+ "#FF4000",
3330
+ "#FF8000",
3331
+ "#FFBF00",
3332
+ "#FFFF00",
3333
+ "#CCFF00",
3334
+ "#80FF00",
3335
+ "#40FF00",
3336
+ "#00FF00",
3337
+ "#00FF40",
3338
+ "#00FF80",
3339
+ "#00FFCC",
3340
+ "#00FFFF",
3341
+ "#00CCFF",
3342
+ "#0080FF",
3343
+ "#0040FF",
3344
+ "#0000FF",
3345
+ "#4000FF",
3346
+ "#8000FF",
3347
+ "#CC00FF",
3348
+ "#FF00FF",
3349
+ "#FF00CC",
3350
+ "#FF0080",
3351
+ "#FF0040"
3352
+ ],
3353
+ rgb48: [
3354
+ "#FF0000",
3355
+ "#FF2000",
3356
+ "#FF4000",
3357
+ "#FF6000",
3358
+ "#FF8000",
3359
+ "#FFAA00",
3360
+ "#FFCC00",
3361
+ "#FFEE00",
3362
+ "#FFFF00",
3363
+ "#DDFF00",
3364
+ "#CCFF00",
3365
+ "#AAFF00",
3366
+ "#80FF00",
3367
+ "#60FF00",
3368
+ "#40FF00",
3369
+ "#20FF00",
3370
+ "#00FF00",
3371
+ "#00FF20",
3372
+ "#00FF40",
3373
+ "#00FF60",
3374
+ "#00FF80",
3375
+ "#00FFAA",
3376
+ "#00FFCC",
3377
+ "#00FFDD",
3378
+ "#00FFFF",
3379
+ "#00DDFF",
3380
+ "#00CCFF",
3381
+ "#0099FF",
3382
+ "#0080FF",
3383
+ "#0060FF",
3384
+ "#0040FF",
3385
+ "#0020FF",
3386
+ "#0000FF",
3387
+ "#2000FF",
3388
+ "#4000FF",
3389
+ "#6000FF",
3390
+ "#8000FF",
3391
+ "#AA00FF",
3392
+ "#CC00FF",
3393
+ "#DD00FF",
3394
+ "#FF00FF",
3395
+ "#FF00EE",
3396
+ "#FF00CC",
3397
+ "#FF00AA",
3398
+ "#FF0080",
3399
+ "#FF0060",
3400
+ "#FF0040",
3401
+ "#FF0020"
3402
+ ],
3403
+ rgb64: [
3404
+ "#000000",
3405
+ "#000055",
3406
+ "#0000AA",
3407
+ "#0000FF",
3408
+ "#005500",
3409
+ "#005555",
3410
+ "#0055AA",
3411
+ "#0055FF",
3412
+ "#00AA00",
3413
+ "#00AA55",
3414
+ "#00AAAA",
3415
+ "#00AAFF",
3416
+ "#00FF00",
3417
+ "#00FF55",
3418
+ "#00FFAA",
3419
+ "#00FFFF",
3420
+ "#550000",
3421
+ "#550055",
3422
+ "#5500AA",
3423
+ "#5500FF",
3424
+ "#555500",
3425
+ "#555555",
3426
+ "#5555AA",
3427
+ "#5555FF",
3428
+ "#55AA00",
3429
+ "#55AA55",
3430
+ "#55AAAA",
3431
+ "#55AAFF",
3432
+ "#55FF00",
3433
+ "#55FF55",
3434
+ "#55FFAA",
3435
+ "#55FFFF",
3436
+ "#AA0000",
3437
+ "#AA0055",
3438
+ "#AA00AA",
3439
+ "#AA00FF",
3440
+ "#AA5500",
3441
+ "#AA5555",
3442
+ "#AA55AA",
3443
+ "#AA55FF",
3444
+ "#AAAA00",
3445
+ "#AAAA55",
3446
+ "#AAAAAA",
3447
+ "#AAAAFF",
3448
+ "#AAFF00",
3449
+ "#AAFF55",
3450
+ "#AAFFAA",
3451
+ "#AAFFFF",
3452
+ "#FF0000",
3453
+ "#FF0055",
3454
+ "#FF00AA",
3455
+ "#FF00FF",
3456
+ "#FF5500",
3457
+ "#FF5555",
3458
+ "#FF55AA",
3459
+ "#FF55FF",
3460
+ "#FFAA00",
3461
+ "#FFAA55",
3462
+ "#FFAAAA",
3463
+ "#FFAAFF",
3464
+ "#FFFF00",
3465
+ "#FFFF55",
3466
+ "#FFFFAA",
3467
+ "#FFFFFF"
3468
+ ]
3469
+ };
3470
+
3471
+ // src/tilemap.ts
3472
+ var Tilemap = class {
3473
+ map = /* @__PURE__ */ new Map();
3474
+ _key(x, y) {
3475
+ x = Math.floor(x);
3476
+ y = Math.floor(y);
3477
+ return `${x}x${y}`;
3478
+ }
3479
+ get(x, y) {
3480
+ return this.map.get(this._key(x, y));
3481
+ }
3482
+ set(x, y, v) {
3483
+ this.map.set(this._key(x, y), v);
3484
+ }
3485
+ };
3181
3486
 
3182
- // src/rendering/webgl.ts
3487
+ // src/webgl.ts
3183
3488
  var ShaderType = ((ShaderType2) => {
3184
3489
  ShaderType2[ShaderType2["VERTEX"] = WebGL2RenderingContext.VERTEX_SHADER] = "VERTEX";
3185
3490
  ShaderType2[ShaderType2["FRAGMENT"] = WebGL2RenderingContext.FRAGMENT_SHADER] = "FRAGMENT";
@@ -3251,7 +3556,7 @@ function CreateProgramInfo(gl, vertexShaderSource, fragmentShaderSource) {
3251
3556
  return { program, ...locations };
3252
3557
  }
3253
3558
 
3254
- // src/rendering/webgl-renderer.ts
3559
+ // src/webgl-renderer.ts
3255
3560
  var WebGlRenderer = class {
3256
3561
  gl;
3257
3562
  programInfo;
@@ -3295,242 +3600,6 @@ var WebGlRenderer = class {
3295
3600
  }
3296
3601
  };
3297
3602
 
3298
- // src/signal.ts
3299
- var Signal = class {
3300
- value;
3301
- subscribers = /* @__PURE__ */ new Set();
3302
- constructor(initialValue) {
3303
- this.value = initialValue;
3304
- }
3305
- get() {
3306
- return this.value;
3307
- }
3308
- set(value) {
3309
- if (Object.is(this.value, value)) return;
3310
- this.value = value;
3311
- for (const subscriber of [...this.subscribers]) {
3312
- subscriber(value);
3313
- }
3314
- }
3315
- subscribe(subscriber) {
3316
- this.subscribers.add(subscriber);
3317
- subscriber(this.value);
3318
- return () => this.subscribers.delete(subscriber);
3319
- }
3320
- };
3321
-
3322
- // src/simplex-noise.ts
3323
- var SimplexNoise = class {
3324
- grad3;
3325
- p;
3326
- perm;
3327
- constructor() {
3328
- this.grad3 = [
3329
- [1, 1, 0],
3330
- [-1, 1, 0],
3331
- [1, -1, 0],
3332
- [-1, -1, 0],
3333
- [1, 0, 1],
3334
- [-1, 0, 1],
3335
- [1, 0, -1],
3336
- [-1, 0, -1],
3337
- [0, 1, 1],
3338
- [0, -1, 1],
3339
- [0, 1, -1],
3340
- [0, -1, -1]
3341
- ];
3342
- this.p = [];
3343
- for (let i = 0; i < 256; i++) {
3344
- this.p.push(Math.floor(rng.nextFloat() * 256));
3345
- }
3346
- this.perm = [];
3347
- for (let i = 0; i < 512; i++) {
3348
- this.perm.push(this.p[i & 255]);
3349
- }
3350
- }
3351
- dot(g, x, y, z) {
3352
- return g[0] * x + g[1] * y + (typeof z === "number" ? g[2] * z : 0);
3353
- }
3354
- noise2d(xin, yin) {
3355
- let n0, n1, n2;
3356
- const F2 = 0.5 * (Math.sqrt(3) - 1);
3357
- const s = (xin + yin) * F2;
3358
- let i = Math.floor(xin + s);
3359
- let j = Math.floor(yin + s);
3360
- const G2 = (3 - Math.sqrt(3)) / 6;
3361
- const t = (i + j) * G2;
3362
- const X0 = i - t;
3363
- const Y0 = j - t;
3364
- const x0 = xin - X0;
3365
- const y0 = yin - Y0;
3366
- let i1, j1;
3367
- if (x0 > y0) {
3368
- i1 = 1;
3369
- j1 = 0;
3370
- } else {
3371
- i1 = 0;
3372
- j1 = 1;
3373
- }
3374
- const x1 = x0 - i1 + G2;
3375
- const y1 = y0 - j1 + G2;
3376
- const x2 = x0 - 1 + 2 * G2;
3377
- const y2 = y0 - 1 + 2 * G2;
3378
- const ii = i & 255;
3379
- const jj = j & 255;
3380
- const gi0 = this.perm[ii + this.perm[jj]] % 12;
3381
- const gi1 = this.perm[ii + i1 + this.perm[jj + j1]] % 12;
3382
- const gi2 = this.perm[ii + 1 + this.perm[jj + 1]] % 12;
3383
- let t0 = 0.5 - x0 * x0 - y0 * y0;
3384
- if (t0 < 0) {
3385
- n0 = 0;
3386
- } else {
3387
- t0 *= t0;
3388
- n0 = t0 * t0 * this.dot(this.grad3[gi0], x0, y0);
3389
- }
3390
- let t1 = 0.5 - x1 * x1 - y1 * y1;
3391
- if (t1 < 0) {
3392
- n1 = 0;
3393
- } else {
3394
- t1 *= t1;
3395
- n1 = t1 * t1 * this.dot(this.grad3[gi1], x1, y1);
3396
- }
3397
- let t2 = 0.5 - x2 * x2 - y2 * y2;
3398
- if (t2 < 0) {
3399
- n2 = 0;
3400
- } else {
3401
- t2 *= t2;
3402
- n2 = t2 * t2 * this.dot(this.grad3[gi2], x2, y2);
3403
- }
3404
- return 70 * (n0 + n1 + n2);
3405
- }
3406
- noise3d(xin, yin, zin) {
3407
- let n0, n1, n2, n3;
3408
- const F3 = 1 / 3;
3409
- const s = (xin + yin + zin) * F3;
3410
- const i = Math.floor(xin + s);
3411
- const j = Math.floor(yin + s);
3412
- const k = Math.floor(zin + s);
3413
- const G3 = 1 / 6;
3414
- const t = (i + j + k) * G3;
3415
- const X0 = i - t;
3416
- const Y0 = j - t;
3417
- const Z0 = k - t;
3418
- const x0 = xin - X0;
3419
- const y0 = yin - Y0;
3420
- const z0 = zin - Z0;
3421
- let i1, j1, k1;
3422
- let i2, j2, k2;
3423
- if (x0 >= y0) {
3424
- if (y0 >= z0) {
3425
- i1 = 1;
3426
- j1 = 0;
3427
- k1 = 0;
3428
- i2 = 1;
3429
- j2 = 1;
3430
- k2 = 0;
3431
- } else if (x0 >= z0) {
3432
- i1 = 1;
3433
- j1 = 0;
3434
- k1 = 0;
3435
- i2 = 1;
3436
- j2 = 0;
3437
- k2 = 1;
3438
- } else {
3439
- i1 = 0;
3440
- j1 = 0;
3441
- k1 = 1;
3442
- i2 = 1;
3443
- j2 = 0;
3444
- k2 = 1;
3445
- }
3446
- } else {
3447
- if (y0 < z0) {
3448
- i1 = 0;
3449
- j1 = 0;
3450
- k1 = 1;
3451
- i2 = 0;
3452
- j2 = 1;
3453
- k2 = 1;
3454
- } else if (x0 < z0) {
3455
- i1 = 0;
3456
- j1 = 1;
3457
- k1 = 0;
3458
- i2 = 0;
3459
- j2 = 1;
3460
- k2 = 1;
3461
- } else {
3462
- i1 = 0;
3463
- j1 = 1;
3464
- k1 = 0;
3465
- i2 = 1;
3466
- j2 = 1;
3467
- k2 = 0;
3468
- }
3469
- }
3470
- const x1 = x0 - i1 + G3;
3471
- const y1 = y0 - j1 + G3;
3472
- const z1 = z0 - k1 + G3;
3473
- const x2 = x0 - i2 + 2 * G3;
3474
- const y2 = y0 - j2 + 2 * G3;
3475
- const z2 = z0 - k2 + 2 * G3;
3476
- const x3 = x0 - 1 + 3 * G3;
3477
- const y3 = y0 - 1 + 3 * G3;
3478
- const z3 = z0 - 1 + 3 * G3;
3479
- const ii = i & 255;
3480
- const jj = j & 255;
3481
- const kk = k & 255;
3482
- const gi0 = this.perm[ii + this.perm[jj + this.perm[kk]]] % 12;
3483
- const gi1 = this.perm[ii + i1 + this.perm[jj + j1 + this.perm[kk + k1]]] % 12;
3484
- const gi2 = this.perm[ii + i2 + this.perm[jj + j2 + this.perm[kk + k2]]] % 12;
3485
- const gi3 = this.perm[ii + 1 + this.perm[jj + 1 + this.perm[kk + 1]]] % 12;
3486
- let t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0;
3487
- if (t0 < 0) {
3488
- n0 = 0;
3489
- } else {
3490
- t0 *= t0;
3491
- n0 = t0 * t0 * this.dot(this.grad3[gi0], x0, y0, z0);
3492
- }
3493
- let t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1;
3494
- if (t1 < 0) {
3495
- n1 = 0;
3496
- } else {
3497
- t1 *= t1;
3498
- n1 = t1 * t1 * this.dot(this.grad3[gi1], x1, y1, z1);
3499
- }
3500
- let t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2;
3501
- if (t2 < 0) {
3502
- n2 = 0;
3503
- } else {
3504
- t2 *= t2;
3505
- n2 = t2 * t2 * this.dot(this.grad3[gi2], x2, y2, z2);
3506
- }
3507
- let t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3;
3508
- if (t3 < 0) {
3509
- n3 = 0;
3510
- } else {
3511
- t3 *= t3;
3512
- n3 = t3 * t3 * this.dot(this.grad3[gi3], x3, y3, z3);
3513
- }
3514
- return 32 * (n0 + n1 + n2 + n3);
3515
- }
3516
- };
3517
-
3518
- // src/tilemap.ts
3519
- var Tilemap = class {
3520
- map = /* @__PURE__ */ new Map();
3521
- _key(x, y) {
3522
- x = floor(x);
3523
- y = floor(y);
3524
- return `${x}x${y}`;
3525
- }
3526
- get(x, y) {
3527
- return this.map.get(this._key(x, y));
3528
- }
3529
- set(x, y, v) {
3530
- this.map.set(this._key(x, y), v);
3531
- }
3532
- };
3533
-
3534
3603
  // src/worker-interface.ts
3535
3604
  var WorkerInterface = class {
3536
3605
  _worker;
@@ -3538,8 +3607,8 @@ var WorkerInterface = class {
3538
3607
  onMessage = new Observable();
3539
3608
  constructor(url) {
3540
3609
  this._worker = new Worker(url, { type: "module" });
3541
- this._worker.onerror = (error) => this.onError.notify(this, error);
3542
- this._worker.onmessage = (message) => this.onMessage.notify(this, message);
3610
+ this._worker.onerror = (error) => this.onError.notify(error);
3611
+ this._worker.onmessage = (message) => this.onMessage.notify(message);
3543
3612
  }
3544
3613
  postMessage(message, options) {
3545
3614
  this._worker.postMessage(message, options);
@@ -3554,10 +3623,12 @@ export {
3554
3623
  AsteroidMesh,
3555
3624
  AtlasTextureMaterial,
3556
3625
  BuildDefaultPalette,
3626
+ BuildVoxelGeometry,
3627
+ CameraRig,
3557
3628
  CanvasRenderer,
3558
3629
  Clock,
3559
3630
  Color,
3560
- Colors,
3631
+ Colors2 as Colors,
3561
3632
  CompileShader,
3562
3633
  CreatePaletteController,
3563
3634
  CreateProgram,
@@ -3572,11 +3643,12 @@ export {
3572
3643
  DEFAULT_FONT,
3573
3644
  DEFAULT_FONT_NAME,
3574
3645
  DEFAULT_FONT_SIZE,
3646
+ DEFAULT_MAP_2D_VALUE,
3647
+ DEFAULT_MAP_3D_VALUE,
3575
3648
  DEFAULT_PIXEL_SIZE,
3576
3649
  DEFAULT_TEXTALIGN,
3577
3650
  DEFAULT_TEXTBASELINE,
3578
3651
  DEG2RAD,
3579
- DOWN,
3580
3652
  Disposable,
3581
3653
  E,
3582
3654
  ECS,
@@ -3600,6 +3672,7 @@ export {
3600
3672
  Map2D,
3601
3673
  Map3D,
3602
3674
  Noise,
3675
+ ONE_SECOND,
3603
3676
  Observable,
3604
3677
  PI,
3605
3678
  ParticleRenderer,
@@ -3609,10 +3682,11 @@ export {
3609
3682
  QUARTER_PI,
3610
3683
  RAD2DEG,
3611
3684
  Random,
3612
- RandomTools,
3613
3685
  Rectangle,
3614
3686
  RemoveThreeComponent,
3687
+ Renderer,
3615
3688
  ResizeWebGlContext,
3689
+ Rng,
3616
3690
  SQRT1_2,
3617
3691
  SQRT2,
3618
3692
  ShaderType,
@@ -3625,74 +3699,41 @@ export {
3625
3699
  TILE_FLOOR,
3626
3700
  TILE_PATH,
3627
3701
  TextureAtlas,
3628
- ThreeJsBoilerPlate,
3629
3702
  ThreeJsCameraRig,
3630
3703
  ThreeJsPlayerController,
3631
3704
  Tilemap,
3632
- UP,
3705
+ VOXEL_FACES,
3633
3706
  Vector,
3634
3707
  VoxelFaces,
3708
+ VoxelGeometry,
3635
3709
  VoxelMesh,
3636
3710
  WebGlRenderer,
3637
3711
  WorkerInterface,
3638
- abs,
3639
- acos,
3640
- asin,
3641
- atan,
3642
- atan2,
3643
- cbrt,
3644
- ceil,
3645
3712
  clamp,
3646
- cos,
3647
- cosh,
3648
3713
  degrees,
3649
3714
  distance2d,
3650
3715
  distance3d,
3651
- exp,
3652
- expm1,
3653
- floor,
3654
3716
  fract,
3655
3717
  getRedYellowGreenGradientHex,
3656
- hypot,
3657
- hypot2,
3658
- hypot3,
3659
- imul,
3718
+ hash32,
3719
+ hash32mix,
3660
3720
  inverseLerp,
3661
- isFinite,
3662
- isInteger,
3663
- isNaN,
3664
3721
  isNullOrUndefined,
3665
3722
  isPositiveString,
3666
3723
  k2xy,
3667
3724
  k2xyz,
3668
3725
  lerp,
3669
- log,
3670
- log10,
3671
- log1p,
3672
- log2,
3673
3726
  manhattanDistance,
3674
- map,
3675
- max,
3676
- min,
3677
3727
  mod,
3678
3728
  nearlyEqual,
3679
3729
  normalizeRadians,
3680
- pow,
3681
3730
  radians,
3682
3731
  randomMatrix,
3683
3732
  rng,
3684
- round,
3685
3733
  roundTo,
3686
3734
  saturate,
3687
- sign,
3688
- sin,
3689
- sinh,
3690
3735
  smoothstep,
3691
- sqrt,
3692
3736
  squaredDistance,
3693
- tan,
3694
- tanh,
3695
- trunc,
3696
3737
  wrap,
3697
3738
  xy2k,
3698
3739
  xyz2k