@n3rdw1z4rd/core 0.17.1 → 0.18.0

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