@n3rdw1z4rd/core 0.17.2 → 0.18.1

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