@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
@@ -0,0 +1,142 @@
1
+ import { XY } from "./types.js";
2
+ import { Map2D } from "./map2d.js";
3
+ import { Rectangle } from "./rectangle.js";
4
+ //#region src/dungeon-generator.d.ts
5
+ /**
6
+ * Two rooms to be joined by a corridor.
7
+ *
8
+ * @property a first room
9
+ * @property b second room
10
+ * @category Pathfinding & Procedural
11
+ */
12
+ export type RectPair = {
13
+ a: Rectangle;
14
+ b: Rectangle;
15
+ };
16
+ /**
17
+ * Two tiles, e.g. the closest edge tiles of two rooms.
18
+ *
19
+ * @property a first point
20
+ * @property b second point
21
+ * @category Pathfinding & Procedural
22
+ */
23
+ export type PointPair = {
24
+ a: XY;
25
+ b: XY;
26
+ };
27
+ /**
28
+ * Room placement options for {@link GenerateRooms}.
29
+ *
30
+ * @category Pathfinding & Procedural
31
+ */
32
+ export interface RoomsParams {
33
+ /** level width and height in tiles, default 64 */
34
+ size?: number;
35
+ /** smallest room side in tiles, default 3 */
36
+ minSize?: number;
37
+ /** largest room side in tiles, default 9 */
38
+ maxSize?: number;
39
+ /** spacing kept around each room and from the level edge in tiles, default 1 */
40
+ padding?: number;
41
+ /** stop after this many consecutive failed placements, default 1000 */
42
+ maxIterations?: number;
43
+ }
44
+ /**
45
+ * Corridor options for {@link GenerateRooms}.
46
+ *
47
+ * @category Pathfinding & Procedural
48
+ */
49
+ export interface PathsParams {
50
+ /** number of shortest unused room connections considered as extra (loop) corridors, default 0 */
51
+ extraPaths?: number;
52
+ /** chance (0-1) that each considered extra connection is added, default 0.1 */
53
+ extraPathDensity?: number;
54
+ /** tile values corridors may be carved through, default: the map's default value (empty space) */
55
+ walkableValues?: number[];
56
+ }
57
+ /**
58
+ * Options for {@link GenerateDoors}.
59
+ *
60
+ * @category Pathfinding & Procedural
61
+ */
62
+ export interface DoorsParams {
63
+ /** chance (0-1) that a door is placed at each eligible corridor end, default 0.5 */
64
+ chanceExists?: number;
65
+ }
66
+ /**
67
+ * Options for {@link GenerateRooms}.
68
+ *
69
+ * @category Pathfinding & Procedural
70
+ */
71
+ export interface GenerateRoomsParams {
72
+ /** map to draw into, default a new {@link Map2D} filled with {@link TILE_EMPTY} */
73
+ map?: Map2D;
74
+ /** room placement options */
75
+ rooms?: RoomsParams;
76
+ /** corridor options */
77
+ paths?: PathsParams;
78
+ }
79
+ /**
80
+ * Tile value for empty (unused) space.
81
+ *
82
+ * @category Pathfinding & Procedural
83
+ */
84
+ export declare const TILE_EMPTY = 0;
85
+ /**
86
+ * Tile value for room floor.
87
+ *
88
+ * @category Pathfinding & Procedural
89
+ */
90
+ export declare const TILE_FLOOR = 1;
91
+ /**
92
+ * Tile value for corridor floor.
93
+ *
94
+ * @category Pathfinding & Procedural
95
+ */
96
+ export declare const TILE_PATH = 2;
97
+ /**
98
+ * Generates a dungeon level: scatters non-overlapping rectangular rooms, joins them with a minimum
99
+ * spanning tree of A* corridors (plus optional extra ones) and plots both into the map as
100
+ * {@link TILE_FLOOR} and {@link TILE_PATH}.
101
+ *
102
+ * Rooms are placed at random until {@link RoomsParams.maxIterations} placements in a row fail.
103
+ * Corridors are carved only through {@link PathsParams.walkableValues} tiles; each runs from next to
104
+ * one room's edge to next to the other's, and is empty if no route exists. Randomness comes from the
105
+ * shared {@link rng}, so set `rng.seed` first for a reproducible level. Logs its duration.
106
+ *
107
+ * ```ts
108
+ * rng.seed = 1234;
109
+ * const { map, rooms, paths } = GenerateRooms({ rooms: { size: 48 } });
110
+ * const doors = GenerateDoors(map, paths);
111
+ * const walls = GenerateWalls(map);
112
+ * ```
113
+ *
114
+ * @category Pathfinding & Procedural
115
+ */
116
+ export declare function GenerateRooms(params?: GenerateRoomsParams): {
117
+ /** the given map (modified) or a new one */
118
+ map: Map2D;
119
+ /** the placed rooms */
120
+ rooms: Rectangle[];
121
+ /** one tile list per corridor */
122
+ paths: XY[][];
123
+ };
124
+ /**
125
+ * Picks door tiles from the two end tiles of each corridor (corridors shorter than 2 tiles are
126
+ * skipped). An end qualifies when both its up/down or both its left/right neighbours hold the map's
127
+ * default value, i.e. it sits in a 1-wide gap; each qualifying end becomes a door with probability
128
+ * {@link DoorsParams.chanceExists}, using the shared {@link rng}. Does not modify the map.
129
+ *
130
+ * @param paths corridors as returned by {@link GenerateRooms}
131
+ * @returns the door tiles
132
+ * @category Pathfinding & Procedural
133
+ */
134
+ export declare function GenerateDoors(map: Map2D, paths: XY[][], params?: DoorsParams): XY[];
135
+ /**
136
+ * Returns every tile holding the map's default value that touches (8-way) a non-default tile, each
137
+ * once: the walls around all rooms and corridors. Does not modify the map.
138
+ *
139
+ * @category Pathfinding & Procedural
140
+ */
141
+ export declare function GenerateWalls(map: Map2D): XY[];
142
+ //#endregion
@@ -0,0 +1,288 @@
1
+ import { distance2d, squaredDistance } from "./math.js";
2
+ import { findPath } from "./astar.js";
3
+ import { log } from "./log.js";
4
+ import { Map2D } from "./map2d.js";
5
+ import { rng } from "./rng.js";
6
+ import { Rectangle } from "./rectangle.js";
7
+ import { Heap } from "heap-js";
8
+ //#region src/dungeon-generator.ts
9
+ /**
10
+ * Tile value for empty (unused) space.
11
+ *
12
+ * @category Pathfinding & Procedural
13
+ */
14
+ const TILE_EMPTY = 0;
15
+ /**
16
+ * Tile value for room floor.
17
+ *
18
+ * @category Pathfinding & Procedural
19
+ */
20
+ const TILE_FLOOR = 1;
21
+ /**
22
+ * Tile value for corridor floor.
23
+ *
24
+ * @category Pathfinding & Procedural
25
+ */
26
+ const TILE_PATH = 2;
27
+ const DEFAULT_LEVEL_SIZE = 64;
28
+ const DEFAULT_ROOM_MIN_SIZE = 3;
29
+ const DEFAULT_ROOM_MAX_SIZE = 9;
30
+ const DEFAULT_ROOM_PADDING = 1;
31
+ const DEFAULT_ROOM_MAX_ITERATIONS = 1e3;
32
+ const DEFAULT_PATH_EXTRA_PATHS = 0;
33
+ const DEFAULT_PATH_EXTRA_PATH_DENSITY = .1;
34
+ const DEFAULT_DOOR_CHANCE_EXISTS = .5;
35
+ const DIRECTIONS_8_WAY = [
36
+ {
37
+ x: -1,
38
+ y: 0
39
+ },
40
+ {
41
+ x: -1,
42
+ y: -1
43
+ },
44
+ {
45
+ x: 0,
46
+ y: -1
47
+ },
48
+ {
49
+ x: 1,
50
+ y: -1
51
+ },
52
+ {
53
+ x: 1,
54
+ y: 0
55
+ },
56
+ {
57
+ x: 1,
58
+ y: 1
59
+ },
60
+ {
61
+ x: 0,
62
+ y: 1
63
+ },
64
+ {
65
+ x: -1,
66
+ y: 1
67
+ }
68
+ ];
69
+ function _plot(map, data, tile) {
70
+ data.forEach((element) => {
71
+ if (element instanceof Rectangle) for (let y = 0; y < element.height; y++) for (let x = 0; x < element.width; x++) map.set(element.x + x, element.y + y, tile);
72
+ else if (Array.isArray(element)) element.forEach((point) => {
73
+ map.set(point.x, point.y, tile);
74
+ });
75
+ else map.set(element.x, element.y, tile);
76
+ });
77
+ }
78
+ function _generateRooms(params = {}) {
79
+ const size = params.size ?? DEFAULT_LEVEL_SIZE;
80
+ const minRoomSize = params.minSize ?? DEFAULT_ROOM_MIN_SIZE;
81
+ const maxRoomSize = params.maxSize ?? DEFAULT_ROOM_MAX_SIZE;
82
+ const padding = params.padding ?? DEFAULT_ROOM_PADDING;
83
+ const maxIterations = params.maxIterations ?? DEFAULT_ROOM_MAX_ITERATIONS;
84
+ const rooms = [];
85
+ let iterations = 0;
86
+ while (iterations < maxIterations) {
87
+ const baseSize = rng.range(minRoomSize, maxRoomSize);
88
+ const aspectRatio = .75 + rng.gaussian() * .5;
89
+ const width = Math.min(maxRoomSize, Math.max(minRoomSize, Math.round(baseSize * aspectRatio)));
90
+ const height = Math.min(maxRoomSize, Math.max(minRoomSize, Math.round(baseSize / aspectRatio)));
91
+ const x = rng.range(1 + padding, size - width - padding);
92
+ const y = rng.range(1 + padding, size - height - padding);
93
+ const room = new Rectangle(x, y, width, height);
94
+ if (!rooms.some((existing) => room.intersects(existing, padding * 2))) {
95
+ rooms.push(room);
96
+ iterations = 0;
97
+ } else iterations += 1;
98
+ }
99
+ return rooms;
100
+ }
101
+ function _generateMST(rooms, params = {}) {
102
+ const extraPathLevels = params.extraPaths ?? DEFAULT_PATH_EXTRA_PATHS;
103
+ const extraPathDensity = params.extraPathDensity ?? DEFAULT_PATH_EXTRA_PATH_DENSITY;
104
+ const mst = [];
105
+ const extraPaths = [];
106
+ if (rooms.length < 2) return [];
107
+ const visited = /* @__PURE__ */ new Set();
108
+ const heap = new Heap((a, b) => a.cost - b.cost);
109
+ visited.add(0);
110
+ const zeroCenter = rooms[0].center();
111
+ for (let i = 1; i < rooms.length; i++) {
112
+ const iCenter = rooms[i].center();
113
+ heap.push({
114
+ from: 0,
115
+ to: i,
116
+ cost: squaredDistance(zeroCenter.x, zeroCenter.y, iCenter.x, iCenter.y)
117
+ });
118
+ }
119
+ while (visited.size < rooms.length) {
120
+ let edge = heap.pop();
121
+ while (edge && visited.has(edge.to)) edge = heap.pop();
122
+ if (!edge) break;
123
+ const { from, to } = edge;
124
+ visited.add(to);
125
+ mst.push({
126
+ a: rooms[from],
127
+ b: rooms[to]
128
+ });
129
+ const toCenter = rooms[to].center();
130
+ for (let i = 0; i < rooms.length; i++) if (!visited.has(i)) {
131
+ const iCenter = rooms[i].center();
132
+ heap.push({
133
+ from: to,
134
+ to: i,
135
+ cost: squaredDistance(toCenter.x, toCenter.y, iCenter.x, iCenter.y)
136
+ });
137
+ }
138
+ }
139
+ const remainingEdges = heap.toArray().sort((a, b) => a.cost - b.cost);
140
+ for (let i = 0; i < extraPathLevels && i < remainingEdges.length; i++) {
141
+ const e = remainingEdges[i];
142
+ if (rng.nextFloat() < extraPathDensity) extraPaths.push({
143
+ a: rooms[e.from],
144
+ b: rooms[e.to]
145
+ });
146
+ }
147
+ return mst.concat(extraPaths);
148
+ }
149
+ function _getRectEdgePoints(rect) {
150
+ const points = [];
151
+ const x2 = rect.x + rect.width - 1;
152
+ const y2 = rect.y + rect.height - 1;
153
+ for (let x1 = rect.x; x1 <= x2; x1++) {
154
+ points.push({
155
+ x: x1,
156
+ y: rect.y
157
+ });
158
+ points.push({
159
+ x: x1,
160
+ y: y2
161
+ });
162
+ }
163
+ for (let y1 = rect.y; y1 <= y2; y1++) {
164
+ points.push({
165
+ x: rect.x,
166
+ y: y1
167
+ });
168
+ points.push({
169
+ x: x2,
170
+ y: y1
171
+ });
172
+ }
173
+ return points;
174
+ }
175
+ function _getShortestPathBetweenRects(rectA, rectB) {
176
+ const edgeA = _getRectEdgePoints(rectA);
177
+ const edgeB = _getRectEdgePoints(rectB);
178
+ let paths = {
179
+ a: edgeA[0],
180
+ b: edgeB[0],
181
+ distance: Infinity
182
+ };
183
+ for (const a of edgeA) for (const b of edgeB) {
184
+ const d = distance2d(a.x, a.y, b.x, b.y);
185
+ if (d < paths.distance) paths = {
186
+ a,
187
+ b,
188
+ distance: d
189
+ };
190
+ }
191
+ return {
192
+ a: paths.a,
193
+ b: paths.b
194
+ };
195
+ }
196
+ function _generatePaths(map, rooms, params = {}) {
197
+ const walkable = params.walkableValues ?? [map.defaultValue];
198
+ const cost = (x, y) => walkable.includes(map.get(x, y)) ? 1 : Infinity;
199
+ const paths = [];
200
+ _generateMST(rooms, params).forEach((rects) => {
201
+ const { a, b } = _getShortestPathBetweenRects(rects.a, rects.b);
202
+ paths.push(findPath(a, b, cost, {
203
+ adjacent: true,
204
+ maxNodes: Infinity
205
+ }));
206
+ });
207
+ return paths;
208
+ }
209
+ /**
210
+ * Generates a dungeon level: scatters non-overlapping rectangular rooms, joins them with a minimum
211
+ * spanning tree of A* corridors (plus optional extra ones) and plots both into the map as
212
+ * {@link TILE_FLOOR} and {@link TILE_PATH}.
213
+ *
214
+ * Rooms are placed at random until {@link RoomsParams.maxIterations} placements in a row fail.
215
+ * Corridors are carved only through {@link PathsParams.walkableValues} tiles; each runs from next to
216
+ * one room's edge to next to the other's, and is empty if no route exists. Randomness comes from the
217
+ * shared {@link rng}, so set `rng.seed` first for a reproducible level. Logs its duration.
218
+ *
219
+ * ```ts
220
+ * rng.seed = 1234;
221
+ * const { map, rooms, paths } = GenerateRooms({ rooms: { size: 48 } });
222
+ * const doors = GenerateDoors(map, paths);
223
+ * const walls = GenerateWalls(map);
224
+ * ```
225
+ *
226
+ * @category Pathfinding & Procedural
227
+ */
228
+ function GenerateRooms(params = {}) {
229
+ const startTime = Date.now();
230
+ const map = params.map ?? new Map2D(0);
231
+ const rooms = _generateRooms(params.rooms);
232
+ _plot(map, rooms, 1);
233
+ const paths = _generatePaths(map, rooms, params.paths);
234
+ _plot(map, paths, 2);
235
+ log("GenerateRooms: done:", Date.now() - startTime, "ms");
236
+ return {
237
+ map,
238
+ rooms,
239
+ paths
240
+ };
241
+ }
242
+ /**
243
+ * Picks door tiles from the two end tiles of each corridor (corridors shorter than 2 tiles are
244
+ * skipped). An end qualifies when both its up/down or both its left/right neighbours hold the map's
245
+ * default value, i.e. it sits in a 1-wide gap; each qualifying end becomes a door with probability
246
+ * {@link DoorsParams.chanceExists}, using the shared {@link rng}. Does not modify the map.
247
+ *
248
+ * @param paths corridors as returned by {@link GenerateRooms}
249
+ * @returns the door tiles
250
+ * @category Pathfinding & Procedural
251
+ */
252
+ function GenerateDoors(map, paths, params = {}) {
253
+ const chanceExists = params.chanceExists ?? DEFAULT_DOOR_CHANCE_EXISTS;
254
+ const possibleDoorPoints = [];
255
+ paths.forEach((points) => {
256
+ if (points.length > 1) {
257
+ possibleDoorPoints.push(points[0]);
258
+ possibleDoorPoints.push(points[points.length - 1]);
259
+ }
260
+ });
261
+ const doors = [];
262
+ possibleDoorPoints.forEach((doorPoint) => {
263
+ 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)) doors.push(doorPoint);
264
+ });
265
+ return doors;
266
+ }
267
+ /**
268
+ * Returns every tile holding the map's default value that touches (8-way) a non-default tile, each
269
+ * once: the walls around all rooms and corridors. Does not modify the map.
270
+ *
271
+ * @category Pathfinding & Procedural
272
+ */
273
+ function GenerateWalls(map) {
274
+ const walls = /* @__PURE__ */ new Map();
275
+ map.forEach((x, y, _v) => {
276
+ DIRECTIONS_8_WAY.forEach((dir) => {
277
+ const nx = dir.x + x;
278
+ const ny = dir.y + y;
279
+ if (map.get(nx, ny) === map.defaultValue) walls.set(`${nx},${ny}`, {
280
+ x: nx,
281
+ y: ny
282
+ });
283
+ });
284
+ });
285
+ return [...walls.values()];
286
+ }
287
+ //#endregion
288
+ export { GenerateDoors, GenerateRooms, GenerateWalls, TILE_EMPTY, TILE_FLOOR, TILE_PATH };
package/dist/ecs.d.ts ADDED
@@ -0,0 +1,87 @@
1
+ //#region src/ecs.d.ts
2
+ /**
3
+ * An entity id: a plain integer handed out by {@link ECS.createEntity}.
4
+ *
5
+ * @category ECS
6
+ */
7
+ export type Entity = number;
8
+ /**
9
+ * Any object used as a component. Components are stored by their constructor, so each entity holds
10
+ * at most one component per class.
11
+ *
12
+ * @category ECS
13
+ */
14
+ export type Component = object;
15
+ /**
16
+ * A component class; used as the key for lookups and queries.
17
+ *
18
+ * @category ECS
19
+ */
20
+ export type ComponentType<T extends Component = Component> = new (...args: any[]) => T;
21
+ /**
22
+ * The component instances for a tuple of component types, as yielded by {@link ECS.query}.
23
+ *
24
+ * @category ECS
25
+ */
26
+ export type ComponentInstances<T extends readonly ComponentType[]> = { [K in keyof T]: T[K] extends ComponentType<infer U> ? U : never; };
27
+ /**
28
+ * A function run once per frame with the elapsed time. Not used by {@link ECS} itself; a convention
29
+ * for callers that keep their own system list.
30
+ *
31
+ * @category ECS
32
+ */
33
+ export type System = (deltaTime: number) => void;
34
+ /**
35
+ * A minimal entity-component store. Entities are integers; components are class instances stored
36
+ * per class, and {@link ECS.query} iterates the entities that have every requested component.
37
+ *
38
+ * ```ts
39
+ * class Position { constructor(public x = 0, public y = 0) {} }
40
+ * class Velocity { constructor(public x = 0, public y = 0) {} }
41
+ *
42
+ * const world = new ECS();
43
+ * const e = world.createEntity();
44
+ * world.addComponent(e, new Position());
45
+ * world.addComponent(e, new Velocity(1, 0));
46
+ *
47
+ * for (const [entity, pos, vel] of world.query(Position, Velocity)) {
48
+ * pos.x += vel.x;
49
+ * }
50
+ * ```
51
+ *
52
+ * @category ECS
53
+ */
54
+ export declare class ECS {
55
+ #private;
56
+ private readonly components;
57
+ /** Returns a new entity id (0, 1, 2, ...). Ids are never reused until {@link ECS.clear}. */
58
+ createEntity(): Entity;
59
+ /**
60
+ * Attaches `component` to `entity`, keyed by `component.constructor`; replaces any existing
61
+ * component of the same class.
62
+ */
63
+ addComponent<T extends Component>(entity: Entity, component: T): void;
64
+ /** The entity's component of class `type`, or `undefined` if it has none. */
65
+ getComponent<T extends Component>(entity: Entity, type: ComponentType<T>): T | undefined;
66
+ /** Whether the entity has a component of class `type`. */
67
+ hasComponent<T extends Component>(entity: Entity, type: ComponentType<T>): boolean;
68
+ /** Removes the entity's component of class `type`, if any. */
69
+ removeComponent<T extends Component>(entity: Entity, type: ComponentType<T>): void;
70
+ /**
71
+ * Iterates `[entity, ...components]` for every entity that has all of `types`, with the
72
+ * components in the same order as `types`. Yields nothing when `types` is empty or any type has
73
+ * never been added. Order follows insertion into the least-populated component type.
74
+ */
75
+ query<T extends readonly ComponentType[]>(...types: T): IterableIterator<[Entity, ...ComponentInstances<T>]>;
76
+ /** Removes all of the entity's components. The id is not recycled. */
77
+ destroyEntity(entity: Entity): void;
78
+ /** Removes every component and resets entity ids to start from 0 again. */
79
+ clear(): void;
80
+ }
81
+ /**
82
+ * A shared {@link ECS} instance.
83
+ *
84
+ * @category ECS
85
+ */
86
+ export declare const ecs: ECS;
87
+ //#endregion
package/dist/ecs.js ADDED
@@ -0,0 +1,101 @@
1
+ //#region src/ecs.ts
2
+ /**
3
+ * A minimal entity-component store. Entities are integers; components are class instances stored
4
+ * per class, and {@link ECS.query} iterates the entities that have every requested component.
5
+ *
6
+ * ```ts
7
+ * class Position { constructor(public x = 0, public y = 0) {} }
8
+ * class Velocity { constructor(public x = 0, public y = 0) {} }
9
+ *
10
+ * const world = new ECS();
11
+ * const e = world.createEntity();
12
+ * world.addComponent(e, new Position());
13
+ * world.addComponent(e, new Velocity(1, 0));
14
+ *
15
+ * for (const [entity, pos, vel] of world.query(Position, Velocity)) {
16
+ * pos.x += vel.x;
17
+ * }
18
+ * ```
19
+ *
20
+ * @category ECS
21
+ */
22
+ var ECS = class {
23
+ #nextEntity = 0;
24
+ components = /* @__PURE__ */ new Map();
25
+ /** Returns a new entity id (0, 1, 2, ...). Ids are never reused until {@link ECS.clear}. */
26
+ createEntity() {
27
+ return this.#nextEntity++;
28
+ }
29
+ /**
30
+ * Attaches `component` to `entity`, keyed by `component.constructor`; replaces any existing
31
+ * component of the same class.
32
+ */
33
+ addComponent(entity, component) {
34
+ const type = component.constructor;
35
+ let map = this.components.get(type);
36
+ if (!map) {
37
+ map = /* @__PURE__ */ new Map();
38
+ this.components.set(type, map);
39
+ }
40
+ map.set(entity, component);
41
+ }
42
+ /** The entity's component of class `type`, or `undefined` if it has none. */
43
+ getComponent(entity, type) {
44
+ return this.components.get(type)?.get(entity);
45
+ }
46
+ /** Whether the entity has a component of class `type`. */
47
+ hasComponent(entity, type) {
48
+ return this.components.get(type)?.has(entity) ?? false;
49
+ }
50
+ /** Removes the entity's component of class `type`, if any. */
51
+ removeComponent(entity, type) {
52
+ this.components.get(type)?.delete(entity);
53
+ }
54
+ /**
55
+ * Iterates `[entity, ...components]` for every entity that has all of `types`, with the
56
+ * components in the same order as `types`. Yields nothing when `types` is empty or any type has
57
+ * never been added. Order follows insertion into the least-populated component type.
58
+ */
59
+ *query(...types) {
60
+ if (types.length === 0) return;
61
+ let smallest;
62
+ const maps = [];
63
+ for (const type of types) {
64
+ const map = this.components.get(type);
65
+ if (!map) return;
66
+ maps.push(map);
67
+ if (!smallest || map.size < smallest.size) smallest = map;
68
+ }
69
+ if (!smallest) return;
70
+ for (const entity of smallest.keys()) {
71
+ const components = [];
72
+ let matches = true;
73
+ for (const map of maps) {
74
+ const component = map.get(entity);
75
+ if (!component) {
76
+ matches = false;
77
+ break;
78
+ }
79
+ components.push(component);
80
+ }
81
+ if (matches) yield [entity, ...components];
82
+ }
83
+ }
84
+ /** Removes all of the entity's components. The id is not recycled. */
85
+ destroyEntity(entity) {
86
+ for (const map of this.components.values()) map.delete(entity);
87
+ }
88
+ /** Removes every component and resets entity ids to start from 0 again. */
89
+ clear() {
90
+ this.components.clear();
91
+ this.#nextEntity = 0;
92
+ }
93
+ };
94
+ /**
95
+ * A shared {@link ECS} instance.
96
+ *
97
+ * @category ECS
98
+ */
99
+ const ecs = new ECS();
100
+ //#endregion
101
+ export { ECS, ecs };
@@ -0,0 +1,40 @@
1
+ //#region src/emitter.d.ts
2
+ /**
3
+ * An {@link Emitter} listener: called with the emitted arguments, followed by the event name.
4
+ *
5
+ * @category Events & Timing
6
+ */
7
+ export type Listener = (...args: any[]) => void;
8
+ /**
9
+ * A string-keyed event emitter. Listeners get the emitted arguments followed by the event name,
10
+ * so one listener can tell apart the events it was added to.
11
+ *
12
+ * ```ts
13
+ * const events = new Emitter();
14
+ *
15
+ * events.on('hit', 'miss', (target, eventName) => console.log(eventName, target));
16
+ * events.emit('hit', enemy); // logs 'hit', enemy
17
+ * ```
18
+ *
19
+ * @category Events & Timing
20
+ */
21
+ export declare class Emitter {
22
+ private listeners;
23
+ constructor();
24
+ /**
25
+ * Adds a listener (the last argument) to one or more event names (the arguments before it).
26
+ * Adding the same listener twice makes it fire twice. Returns `this` for chaining.
27
+ */
28
+ on<T extends string[]>(...eventName: [...T, Listener]): this;
29
+ /**
30
+ * Calls the listeners of `eventName` in the order they were added, with `args` followed by
31
+ * `eventName`. Returns `this` for chaining.
32
+ */
33
+ emit(eventName: string, ...args: any[]): this;
34
+ /**
35
+ * Removes `listener` from `eventName` (one registration of it, if it was added more than
36
+ * once), or every listener of `eventName` when `listener` is left out. Returns `this`.
37
+ */
38
+ off(eventName: string, listener?: Listener): this;
39
+ }
40
+ //#endregion