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