@n3rdw1z4rd/core 0.17.2 → 0.18.0

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