@inglorious/engine 24.5.0 → 24.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -208,17 +208,16 @@ test that inherits from the one before it can only be run in one order.
208
208
 
209
209
  ### The game under test
210
210
 
211
- | | |
212
- | ---------------------------------------------- | ------------------------------------------------------------------------ |
213
- | `game.entity(id)` | one entity, by the name the game knows it by |
214
- | `game.state()` | the lot, for keys and for `Object.keys` |
215
- | `game.pooled(type?)` | the pooled entities in play — drawn from a pool rather than in the state |
216
- | `game.check(condition, description)` | assert, in a failure that says what it was about |
217
- | `game.playedSounds` | the sounds the game reached for, in order |
218
- | `game.notify(event, ...args)` | the one way anything is said to it |
219
- | `game.step(frames)` | run frames |
220
- | `game.advance(seconds)` | run for a length of time |
221
- | `game.press(code)` / `game.hold(code, frames)` | tap a key / hold it down |
211
+ | | |
212
+ | ---------------------------------------------- | ------------------------------------------------ |
213
+ | `game.entity(id)` | one entity, by the name the game knows it by |
214
+ | `game.state()` | the lot, for keys and for `Object.keys` |
215
+ | `game.check(condition, description)` | assert, in a failure that says what it was about |
216
+ | `game.playedSounds` | the sounds the game reached for, in order |
217
+ | `game.notify(event, ...args)` | the one way anything is said to it |
218
+ | `game.step(frames)` | run frames |
219
+ | `game.advance(seconds)` | run for a length of time |
220
+ | `game.press(code)` / `game.hold(code, frames)` | tap a key / hold it down |
222
221
 
223
222
  `advance` is there because a test that waits something out is waiting for a lifetime, and
224
223
  a lifetime is in seconds. Converting that to frames by hand means assuming how many frames
@@ -287,9 +286,9 @@ A renderer checks the entity it draws: `renderText` wants a font size, so a type
287
286
 
288
287
  ## Documentation
289
288
 
290
- The best way to get started is with the official documentation, which includes a **[Quick Start Guide](https://inglorious-engine.vercel.app/?path=/docs/quick-start--docs)**.
289
+ The best way to get started is with the official documentation, which includes a **[Quick Start Guide](https://inglorious.dev/engine/?path=/docs/quick-start--docs)**.
291
290
 
292
- Full documentation is available at: **[https://inglorious-engine.vercel.app/](https://inglorious-engine.vercel.app/)**
291
+ Full documentation is available at: **[https://inglorious.dev/engine/](https://inglorious.dev/engine/)**
293
292
 
294
293
  ## Why Functional Programming?
295
294
 
@@ -357,7 +356,7 @@ This engine is the product of countless hours of coding, smartly paired with AI
357
356
 
358
357
  Now, let's talk performance. The critique often has two parts: garbage collection (GC) pressure from immutability, and cache performance compared to modern engines.
359
358
 
360
- 1. **Garbage Collection**: The concern is that creating new objects on every state change will flood the GC. This is mitigated by **structural sharing** (via Mutative). We don't deep-clone the state; only the changed data paths create new objects. For the most extreme cases (e.g., a bullet hell), the engine provides a dedicated **entity pooling system** as a pragmatic escape hatch, eliminating GC pressure in performance hotspots.
359
+ 1. **Garbage Collection**: The concern is that creating new objects on every state change will flood the GC. This is mitigated by **structural sharing** (via Mutative). We don't deep-clone the state; only the changed data paths create new objects. For the most extreme cases (thousands of particles, a swarm), a crowd is kept in one entity as a pool of typed arrays (`@inglorious/utils/data-structures/pool.js`): nothing is allocated per member, and the engine's particles work this way.
361
360
 
362
361
  2. **Cache Performance & ECS**: The other critique is that modern engines like Unity or Godot use an Entity-Component-System (ECS) architecture to avoid deep object graphs (`player.inventory.getItem()`) and achieve better cache performance. **This is absolutely correct!** Those engines solve this problem very well.
363
362
 
@@ -375,7 +374,7 @@ This is a frequent point of confusion, so let's clarify. The engine uses [Data-D
375
374
 
376
375
  - **Data-Oriented Design (DOD)**: This is a lower-level implementation strategy focused on CPU cache performance, common in ECS architectures. It involves organizing data in contiguous memory blocks (e.g., an array of all positions, an array of all velocities) to minimize cache misses during iteration.
377
376
 
378
- This engine does **not** implement a strict DOD memory layout. However, by centralizing all entities into a single, flat object, we get a pragmatic, "almost-DOD" benefit. We leverage the JavaScript engine's highly optimized internal object layout, which is significantly more cache-friendly than chasing pointers through a deeply nested OOP graph.
377
+ This engine does **not** impose a DOD memory layout on every entity. By centralizing all entities into a single, flat object, we get a pragmatic, "almost-DOD" benefit; and where it really counts, a crowd kept as a pool of typed arrays (one per property) is a true struct-of-arrays layout. We leverage the JavaScript engine's highly optimized internal object layout, which is significantly more cache-friendly than chasing pointers through a deeply nested OOP graph.
379
378
 
380
379
  **"Functional programming is just painful to read and write."**
381
380
 
@@ -410,7 +409,7 @@ True, disciplined developers favor composition in any paradigm. The difference i
410
409
 
411
410
  This critique usually misunderstands how modern immutability works. The engine uses structural sharing (via Mutative), which means we're not deep-copying the entire game state on every change. It's incredibly efficient.
412
411
 
413
- That said, we're pragmatic. For performance-critical scenarios like a bullet hell with thousands of short-lived objects, we provide an **entity pooling** system as an escape hatch. But for 99% of game logic, we believe the massive benefits of a predictable, testable, and debuggable state (hello, time-travel debugging!) are a worthwhile trade-off for a negligible performance cost.
412
+ That said, we're pragmatic. For performance-critical scenarios like thousands of short-lived particles, the crowd is kept in one entity as a pool of typed arrays rather than as thousands of entities. But for 99% of game logic, we believe the massive benefits of a predictable, testable, and debuggable state (hello, time-travel debugging!) are a worthwhile trade-off for a negligible performance cost.
414
413
 
415
414
  **"My favorite OOP engine can do all this too!"**
416
415
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inglorious/engine",
3
- "version": "24.5.0",
3
+ "version": "24.8.0",
4
4
  "description": "A JavaScript game engine written with global state, immutability, and pure functions in mind. Have fun(ctional programming) with it!",
5
5
  "author": "Matteo Antony Mistretta <antony.mistretta@gmail.com> (https://ingloriouscoderz.it)",
6
6
  "license": "MIT",
@@ -9,7 +9,7 @@
9
9
  "url": "git+https://github.com/IngloriousCoderz/inglorious-forge.git",
10
10
  "directory": "packages/engine"
11
11
  },
12
- "homepage": "https://inglorious-engine.vercel.app/",
12
+ "homepage": "https://inglorious.dev/engine/",
13
13
  "bugs": {
14
14
  "url": "https://github.com/IngloriousCoderz/inglorious-forge/issues"
15
15
  },
@@ -41,18 +41,18 @@
41
41
  },
42
42
  "sideEffects": false,
43
43
  "dependencies": {
44
- "@inglorious/utils": "^5.6.0"
44
+ "@inglorious/utils": "^5.8.0"
45
45
  },
46
46
  "peerDependencies": {
47
- "@inglorious/store": "^12.9.5",
48
- "vitest": "^5.1.1"
47
+ "@inglorious/store": "^12.9.6",
48
+ "vitest": "^5.1.2"
49
49
  },
50
50
  "devDependencies": {
51
51
  "@inglorious/eslint-config": "1.2.2",
52
52
  "prettier": "^3.10.1",
53
53
  "typescript": "~7.0.2",
54
54
  "vite": "^8.3.8",
55
- "vitest": "^5.1.1"
55
+ "vitest": "^5.1.2"
56
56
  },
57
57
  "engines": {
58
58
  "node": ">= 26"
@@ -1,120 +1,233 @@
1
+ import {
2
+ addTo,
3
+ createPool,
4
+ removeFrom,
5
+ } from "@inglorious/utils/data-structures/pool.js"
1
6
  import { random } from "@inglorious/utils/math/rng.js"
2
7
  import { v } from "@inglorious/utils/v.js"
3
- import {
4
- multiply,
5
- negate,
6
- randomVector,
7
- sum,
8
- } from "@inglorious/utils/vector.js"
9
8
 
10
- const FIRST_INDEX = 0
9
+ const DEFAULT_ID = "particles"
10
+ const DEFAULT_CAPACITY = 1024
11
+ const PARTICLES_TYPE = "Particles"
11
12
  const SINGLE = 1
12
13
  const OPAQUE = 1
13
- const NO_LAYER = 0
14
- const NO_SPREAD = 0
15
- const NO_DEPTH = 0
16
- const NO_TIME = 0
17
14
  const WHOLE = 1
18
- const DEFAULT_SIZE = 1
19
- const PARTICLE_TYPE = "Particle"
15
+ const NO_TIME = 0
16
+ const NOTHING = 0
17
+ const NOT_FOUND = -1
18
+ const FIRST = 0
19
+ const AXIS_X = 0
20
+ const AXIS_Y = 1
21
+ const AXIS_Z = 2
20
22
 
21
- const DEFAULT_SIZE_VECTOR = () => v(DEFAULT_SIZE, DEFAULT_SIZE, NO_DEPTH)
22
- const NO_SPREAD_VECTOR = () => v(NO_SPREAD, NO_SPREAD, NO_SPREAD)
23
+ /**
24
+ * What each particle holds: where it is, how it moves, how long it lives and how it
25
+ * looks. One typed array per property, so a frame walks a few arrays instead of
26
+ * thousands of entities. `tint` is the index of the particle's colour in the entity's
27
+ * `tints`.
28
+ */
29
+ const SCHEMA = {
30
+ x: Float64Array,
31
+ y: Float64Array,
32
+ z: Float64Array,
33
+ vx: Float64Array,
34
+ vy: Float64Array,
35
+ vz: Float64Array,
36
+ ax: Float64Array,
37
+ ay: Float64Array,
38
+ az: Float64Array,
39
+ age: Float64Array,
40
+ life: Float64Array,
41
+ opacity: Float64Array,
42
+ tint: Uint16Array,
43
+ }
23
44
 
24
45
  /**
25
- * A single particle: it drifts under an acceleration and fades out over its
26
- * lifetime, then hands itself back to the pool.
46
+ * An entity holding a crowd of particles: debris, sparks, smoke. The particles are not
47
+ * entities of their own but a pool (`@inglorious/utils/data-structures/pool.js`) in
48
+ * `entity.particles`, read as `entity.particles.x[i]` for `i` up to
49
+ * `entity.particles.count`.
27
50
  *
28
- * Pair it with whatever draws the particle, which is usually `renderImage` or
29
- * `renderRectangle`:
51
+ * What every particle shares -- `image`, `size`, `layer` -- is said once, on the
52
+ * entity. A burst says where its particles start, how they move, how long they last
53
+ * and their colour. A different look is a different particles entity, with its own id.
30
54
  *
31
55
  * @example
32
56
  * ```js
33
- * types: { Particle: [{ render: renderImage }, particle()] }
57
+ * types: { Particles: [{ render: renderParticles }, particles()] },
58
+ * entities: {
59
+ * debris: createParticles({
60
+ * id: "debris",
61
+ * size: v(8, 8, 0),
62
+ * layer: 0.5,
63
+ * image: { id: "particle", imageSize: [8, 8] },
64
+ * }),
65
+ * }
34
66
  * ```
67
+ *
68
+ * @param {Object} [options]
69
+ * @param {string} [options.id="particles"] - Where bursts are sent.
70
+ * @param {number} [options.capacity=1024] - The most particles alive at once: a burst
71
+ * past it emits only those that fit.
72
+ * @returns {Object} The entity, of type `Particles` unless `type` says otherwise. Any
73
+ * other option (`image`, `size`, `layer`...) is kept on it for the renderer.
35
74
  */
36
- export function particle() {
75
+ export function createParticles({
76
+ id = DEFAULT_ID,
77
+ capacity = DEFAULT_CAPACITY,
78
+ ...rest
79
+ } = {}) {
37
80
  return {
38
- update(entity, dt, api) {
39
- entity.age += dt
81
+ id,
82
+ type: PARTICLES_TYPE,
83
+ position: v(NOTHING, NOTHING, NOTHING),
84
+ particles: createPool(capacity, SCHEMA),
85
+ tints: [],
86
+ ...rest,
87
+ }
88
+ }
40
89
 
41
- if (entity.age >= entity.life) {
42
- api.notify("despawn", entity)
43
- return
44
- }
90
+ /**
91
+ * The behaviour of a particles entity: each particle drifts under its acceleration and
92
+ * fades out over its lifetime, then leaves the pool; a `particlesBurst` event adds new
93
+ * ones (see `emitBurst`).
94
+ *
95
+ * Pair it with `renderParticles` from `@inglorious/renderer-2d/particles.js`.
96
+ */
97
+ export function particles() {
98
+ return {
99
+ update(entity, dt) {
100
+ const pool = entity.particles
45
101
 
46
- entity.velocity = sum(entity.velocity, multiply(entity.acceleration, dt))
47
- entity.position = sum(entity.position, multiply(entity.velocity, dt))
102
+ // From last to first: a removed particle's place is taken by the last one,
103
+ // which has already moved this frame.
104
+ for (let index = pool.count - SINGLE; index >= FIRST; index--) {
105
+ pool.age[index] += dt
106
+ if (pool.age[index] >= pool.life[index]) {
107
+ removeFrom(pool, index)
108
+ continue
109
+ }
48
110
 
49
- const spent = entity.age / entity.life
50
- entity.opacity = entity.startOpacity * (WHOLE - spent)
111
+ pool.vx[index] += pool.ax[index] * dt
112
+ pool.vy[index] += pool.ay[index] * dt
113
+ pool.vz[index] += pool.az[index] * dt
114
+ pool.x[index] += pool.vx[index] * dt
115
+ pool.y[index] += pool.vy[index] * dt
116
+ pool.z[index] += pool.vz[index] * dt
117
+ }
118
+ },
119
+
120
+ particlesBurst(entity, params) {
121
+ burst(entity, params)
51
122
  },
52
123
  }
53
124
  }
54
125
 
55
126
  /**
56
- * Emits a burst of particles, pooled like any other entity.
127
+ * Sends a burst of particles to a particles entity.
57
128
  *
58
- * Each particle picks its own lifetime, its own acceleration and its own place
59
- * in the emission box, so one call reads as a burst rather than a grid.
129
+ * Each particle picks its own lifetime, its own acceleration and its own place in the
130
+ * emission box, so one call reads as a burst rather than a grid.
60
131
  *
61
- * `acceleration` is a pair of vectors, and each particle's acceleration is drawn
62
- * per axis between them: the low end is where a component starts, the high end
63
- * where it can reach. `spread` is the half-extent of the box particles are
64
- * emitted in, so `[5, 5, 0]` emits within five of the position on each axis.
132
+ * `acceleration` is a pair of vectors, and each particle's acceleration is drawn per
133
+ * axis between them: the low end is where a component starts, the high end where it
134
+ * can reach. `spread` is the half-extent of the box particles are emitted in, so
135
+ * `[5, 5, 0]` emits within five of the position on each axis.
65
136
  *
66
137
  * @example
67
138
  * ```js
68
139
  * // Debris falling away from something that was hit.
69
140
  * emitBurst(api, {
141
+ * into: "debris",
70
142
  * count: 64,
71
143
  * position: v(100, 100, 0),
72
- * size: v(2, 2, 0),
73
144
  * lifetime: [0.5, 1],
74
145
  * tint: "rgb(99, 155, 255)",
75
146
  * acceleration: [v(-15, -80, 0), v(15, 0, 0)],
76
147
  * spread: v(5, 5, 0),
77
- * layer: LAYER_PARTICLES,
78
- * image: { id: "particle", imageSize: [2, 2] },
79
148
  * })
80
149
  * ```
150
+ *
151
+ * @param {Object} api
152
+ * @param {Object} params - `into` is the id of the particles entity ("particles"); the
153
+ * rest is as for `burst`.
81
154
  */
82
- export function emitBurst(api, params) {
155
+ export function emitBurst(api, { into = DEFAULT_ID, ...params }) {
156
+ api.notify(`#${into}:particlesBurst`, params)
157
+ }
158
+
159
+ /**
160
+ * Adds a burst's particles to the pool, as many as fit: what `particlesBurst` does,
161
+ * for whoever holds the entity already.
162
+ *
163
+ * @param {Object} entity - A particles entity, from `createParticles`.
164
+ * @param {Object} params
165
+ * @param {number} [params.count=1]
166
+ * @param {number[]} [params.position] - Where the burst is centred.
167
+ * @param {number[]} [params.spread] - The half-extent of the box particles start in.
168
+ * @param {number[]} [params.velocity] - Every particle's starting velocity (at rest).
169
+ * @param {number[][]} [params.acceleration] - Low and high ends, drawn per axis.
170
+ * @param {number[]} [params.lifetime=[1, 1]] - The shortest and longest life, in seconds.
171
+ * @param {number} [params.opacity=1] - How opaque particles start.
172
+ * @param {string} [params.tint] - Their colour.
173
+ */
174
+ export function burst(entity, params) {
83
175
  const {
84
176
  count = SINGLE,
85
- type = PARTICLE_TYPE,
86
- size = DEFAULT_SIZE_VECTOR(),
87
177
  lifetime = [WHOLE, WHOLE],
88
178
  acceleration,
89
- spread = NO_SPREAD_VECTOR(),
179
+ spread,
90
180
  velocity,
91
181
  opacity = OPAQUE,
92
- layer = NO_LAYER,
93
- image,
94
182
  tint,
95
- position = v(NO_SPREAD, NO_SPREAD, NO_DEPTH),
183
+ position,
96
184
  } = params
185
+ const pool = entity.particles
186
+ const [x = NOTHING, y = NOTHING, z = NOTHING] = position ?? []
187
+ const [spreadX = NOTHING, spreadY = NOTHING, spreadZ = NOTHING] = spread ?? []
188
+ const [vx = NOTHING, vy = NOTHING, vz = NOTHING] = velocity ?? []
189
+ const [low = [], high = []] = acceleration ?? []
190
+ const tintIndex = tintOf(entity, tint)
97
191
 
98
- const [low, high] = acceleration ?? []
192
+ for (let emitted = 0; emitted < count; emitted++) {
193
+ const index = addTo(pool)
194
+ if (index === NOT_FOUND) return
99
195
 
100
- for (let index = FIRST_INDEX; index < count; index++) {
101
- api.notify("spawn", {
102
- type,
103
- layer,
104
- size,
105
- image,
106
- tint,
107
- age: NO_TIME,
108
- life: random(...lifetime),
109
- startOpacity: opacity,
110
- opacity,
111
- position: within(position, spread),
112
- velocity: velocity ?? v(NO_SPREAD, NO_SPREAD, NO_DEPTH),
113
- acceleration: randomVector(low, high),
114
- })
196
+ pool.x[index] = x + random(-spreadX, spreadX)
197
+ pool.y[index] = y + random(-spreadY, spreadY)
198
+ pool.z[index] = z + random(-spreadZ, spreadZ)
199
+ pool.vx[index] = vx
200
+ pool.vy[index] = vy
201
+ pool.vz[index] = vz
202
+ pool.ax[index] = between(low, high, AXIS_X)
203
+ pool.ay[index] = between(low, high, AXIS_Y)
204
+ pool.az[index] = between(low, high, AXIS_Z)
205
+ pool.age[index] = NO_TIME
206
+ pool.life[index] = random(...lifetime)
207
+ pool.opacity[index] = opacity
208
+ pool.tint[index] = tintIndex
115
209
  }
116
210
  }
117
211
 
118
- function within(centre, spread) {
119
- return sum(centre, randomVector(negate(spread), spread))
212
+ /**
213
+ * How opaque a particle is now: it fades from the opacity it was emitted at to nothing
214
+ * over its lifetime.
215
+ * @param {Object} pool - `entity.particles`.
216
+ * @param {number} index
217
+ * @returns {number}
218
+ */
219
+ export function particleOpacity(pool, index) {
220
+ return pool.opacity[index] * (WHOLE - pool.age[index] / pool.life[index])
221
+ }
222
+
223
+ function between(low, high, axis) {
224
+ return random(low[axis] ?? NOTHING, high[axis] ?? NOTHING)
225
+ }
226
+
227
+ /** Where a colour sits in the entity's `tints`, added the first time it is used. */
228
+ function tintOf(entity, tint) {
229
+ const found = entity.tints.indexOf(tint)
230
+ if (found !== NOT_FOUND) return found
231
+ entity.tints.push(tint)
232
+ return entity.tints.length - SINGLE
120
233
  }
@@ -0,0 +1,172 @@
1
+ import {
2
+ createRecorder,
3
+ isSession,
4
+ } from "@inglorious/utils/data-structures/recorder.js"
5
+ import { saveJSON } from "@inglorious/utils/files.js"
6
+
7
+ const NO_TURNS = 0
8
+ const STAMP_START = 0
9
+ const STAMP_LENGTH = 19 // "2026-12-01T13:42:32", to the second
10
+
11
+ // One recorder per entity: kept outside the state, which the store copies on every
12
+ // event, while a recording grows all game long.
13
+ const recorders = new Map()
14
+
15
+ /**
16
+ * Records an entity that holds a deterministic simulation, turned on `tick` (see the
17
+ * `ticks` system), and plays a recording back: runs with what the player did at each
18
+ * turn (see `createRecorder`). Put it last in the type's behaviors, so it wraps the
19
+ * `tick` and the events that start a run.
20
+ *
21
+ * What the simulation is stays the game's, told through the options:
22
+ *
23
+ * - `turn(entity)`: the simulation's turn, or null while there is no simulation. A
24
+ * `tick` that leaves the turn as it was (the game held it still) records nothing.
25
+ * - `state(entity)`: the simulation's state, whose fingerprint tells whether a replay
26
+ * ended where the recording did.
27
+ * - `about(entity)`: what it takes to start the simulation again, as plain data.
28
+ * - `input(entity)`: what the player did before this turn, read before `tick`; null
29
+ * for nothing.
30
+ * - `useInput(entity, input)`: puts a recorded input in place of the player's before
31
+ * `tick`; `undefined` where nothing was done.
32
+ * - `replayRun(entity, about)`: starts the simulation of a recorded run.
33
+ * - `startsRun`: the events after which a new run starts (a level started again, a
34
+ * new seed); the one before ends where it was. Ignored while replaying, so a replay
35
+ * is not knocked off its runs. `create` always starts one.
36
+ *
37
+ * It handles `saveRecording` (the session so far, downloaded as a JSON file),
38
+ * `replayLoad` (a session to play back, typically a file dropped on the page: see
39
+ * `onDroppedJSON` and `engine.notify`; on success it notifies `replayStart`, for the
40
+ * game to leave its menus) and `replayStop`. While replaying, `entity.replay` is
41
+ * `{ run, runs, diverged, over }`, else null; once `over`, `tick` holds the simulation
42
+ * still, and the player's input is still replaced by none.
43
+ *
44
+ * @param {Object} options
45
+ * @param {(entity: Object) => number | null} options.turn
46
+ * @param {(entity: Object) => *} options.state
47
+ * @param {(entity: Object) => *} options.about
48
+ * @param {(entity: Object) => *} options.input
49
+ * @param {(entity: Object, input: *) => void} options.useInput
50
+ * @param {(entity: Object, about: *) => void} options.replayRun
51
+ * @param {string[]} [options.startsRun] - Events that start a new run, besides `create`.
52
+ * @param {(session: Object) => boolean} [options.isPlayable] - Whether the game can play a session's runs (its levels still exist).
53
+ * @param {string} [options.format] - What the recordings are; a session of another format is refused.
54
+ * @param {string} [options.build] - Which build of the game made them.
55
+ * @param {string} [options.name] - The start of a saved file's name, followed by the time.
56
+ * @returns {Function} The behavior.
57
+ */
58
+ export function recorded({
59
+ turn,
60
+ state,
61
+ about,
62
+ input,
63
+ useInput,
64
+ replayRun,
65
+ startsRun = [],
66
+ isPlayable = () => true,
67
+ format = "recording",
68
+ build,
69
+ name = format,
70
+ }) {
71
+ const recorderOf = (entity) => recorders.get(entity.id)
72
+
73
+ /** Ends the run being recorded where the simulation is. */
74
+ function close(entity) {
75
+ recorderOf(entity).close(turn(entity) ?? NO_TURNS, state(entity))
76
+ }
77
+
78
+ /** Starts recording a run, if there is a simulation to record. */
79
+ function open(entity) {
80
+ if (turn(entity) != null) recorderOf(entity).open(about(entity))
81
+ }
82
+
83
+ function play(entity, run) {
84
+ replayRun(entity, run.about)
85
+ entity.replay = recorderOf(entity).progress()
86
+ }
87
+
88
+ return (type) => {
89
+ const runStarters = Object.fromEntries(
90
+ startsRun.map((event) => [
91
+ event,
92
+ (entity, payload, api) => {
93
+ if (entity.replay) return
94
+ close(entity)
95
+ type[event]?.(entity, payload, api)
96
+ open(entity)
97
+ },
98
+ ]),
99
+ )
100
+
101
+ return {
102
+ ...runStarters,
103
+
104
+ create(entity, payload, api) {
105
+ recorders.set(entity.id, createRecorder({ format, build }))
106
+ entity.replay = null
107
+ type.create?.(entity, payload, api)
108
+ open(entity)
109
+ },
110
+
111
+ tick(entity, dt, api) {
112
+ if (entity.replay?.over) {
113
+ useInput(entity, undefined) // the player's input is dropped, not saved up
114
+ return
115
+ }
116
+
117
+ const before = turn(entity)
118
+ if (before == null) {
119
+ type.tick?.(entity, dt, api)
120
+ return
121
+ }
122
+
123
+ const recorder = recorderOf(entity)
124
+ const done = entity.replay ? null : input(entity)
125
+ if (entity.replay) useInput(entity, recorder.input(before))
126
+
127
+ type.tick?.(entity, dt, api)
128
+
129
+ const after = turn(entity)
130
+ if (after === before) return
131
+ if (!entity.replay) {
132
+ recorder.record(before, done)
133
+ return
134
+ }
135
+
136
+ if (after < recorder.replayed().ticks) return
137
+ const next = recorder.finish(state(entity))
138
+ if (next) play(entity, next)
139
+ else entity.replay = { ...recorder.progress(), over: true }
140
+ },
141
+
142
+ saveRecording(entity, payload, api) {
143
+ type.saveRecording?.(entity, payload, api)
144
+ const session = recorderOf(entity).session(
145
+ turn(entity) ?? NO_TURNS,
146
+ state(entity),
147
+ )
148
+ const stamp = session.recordedAt
149
+ .slice(STAMP_START, STAMP_LENGTH)
150
+ .replaceAll(":", "-")
151
+ saveJSON(`${name}-${stamp}.json`, session)
152
+ },
153
+
154
+ replayLoad(entity, session, api) {
155
+ type.replayLoad?.(entity, session, api)
156
+ if (!isSession(session, format) || !isPlayable(session)) {
157
+ console.warn(`Not a ${format} this game can play back`)
158
+ return
159
+ }
160
+ close(entity)
161
+ play(entity, recorderOf(entity).load(session))
162
+ api.notify("replayStart")
163
+ },
164
+
165
+ replayStop(entity, payload, api) {
166
+ type.replayStop?.(entity, payload, api)
167
+ recorderOf(entity).stop()
168
+ entity.replay = null
169
+ },
170
+ }
171
+ }
172
+ }
@@ -17,7 +17,6 @@ import { game } from "../behaviors/game.js"
17
17
  import { images } from "../behaviors/images.js"
18
18
  import { coreEvents } from "./core-events.js"
19
19
  import { Loop } from "./loops/index.js"
20
- import { entityPoolMiddleware } from "./middlewares/entity-pool/entity-pool-middleware.js"
21
20
  import { assertTypesAreDeclared } from "./types.js"
22
21
 
23
22
  /**
@@ -64,8 +63,6 @@ export class Engine {
64
63
 
65
64
  const middlewares = []
66
65
 
67
- middlewares.push(entityPoolMiddleware())
68
-
69
66
  const multiplayer = this._config.entities.game?.multiplayer
70
67
  if (multiplayer) {
71
68
  middlewares.push(
@@ -127,6 +124,18 @@ export class Engine {
127
124
  return this._store.getState()
128
125
  }
129
126
 
127
+ /**
128
+ * Tells the game something from outside it, as its own entities would with
129
+ * `api.notify`: a file dropped on the page, a message from the host. The event is
130
+ * handled in the next frame, with the others.
131
+ *
132
+ * @param {string} type - The event.
133
+ * @param {*} [payload] - What comes with it.
134
+ */
135
+ notify(type, payload) {
136
+ this._store.notify(type, payload)
137
+ }
138
+
130
139
  /**
131
140
  * Updates the game state.
132
141
  *
package/src/test.js CHANGED
@@ -66,21 +66,6 @@ export function createGame(gameConfig, extendWith = {}) {
66
66
  entity: (id) => engine._store.getEntity(id),
67
67
  state: () => engine._store.getState(),
68
68
 
69
- /**
70
- * The pooled entities of a type that are in play right now.
71
- *
72
- * Pooled entities live outside the store's state -- they are drawn from a pool and put
73
- * back rather than being added and removed -- so one is not read by looking up an id.
74
- *
75
- * @param {string} [typeName] - Which type of pooled entity to answer with.
76
- * @returns {Object[]} The entities currently in play.
77
- */
78
- pooled(typeName) {
79
- const active = engine._store.extras.getAllActivePoolEntities()
80
-
81
- return typeName ? active.filter(({ type }) => type === typeName) : active
82
- },
83
-
84
69
  /** The one way anything is said to the game. */
85
70
  notify(event, ...args) {
86
71
  engine._store.notify(event, ...args)
@@ -1,44 +1,89 @@
1
+ import type { Pool } from "@inglorious/utils/data-structures/pool.js"
1
2
  import type { Vector3 } from "@inglorious/utils/vector.js"
2
3
 
3
- import type { Entity, GameApi, UpdateHandler } from "../index"
4
+ import type { Entity, GameApi } from "../index"
4
5
 
5
- export interface ParticleEntity extends Entity {
6
- position: Vector3
7
- velocity: Vector3
8
- acceleration: Vector3
6
+ /** Each particle's properties, one typed array each, in `entity.particles`. */
7
+ export type ParticlesPool = Pool<{
8
+ x: Float64ArrayConstructor
9
+ y: Float64ArrayConstructor
10
+ z: Float64ArrayConstructor
11
+ vx: Float64ArrayConstructor
12
+ vy: Float64ArrayConstructor
13
+ vz: Float64ArrayConstructor
14
+ ax: Float64ArrayConstructor
15
+ ay: Float64ArrayConstructor
16
+ az: Float64ArrayConstructor
9
17
  /** Seconds since it was emitted. */
10
- age: number
18
+ age: Float64ArrayConstructor
11
19
  /** Seconds it lasts. */
12
- life: number
13
- startOpacity: number
14
- opacity: number
20
+ life: Float64ArrayConstructor
21
+ /** How opaque it was emitted. */
22
+ opacity: Float64ArrayConstructor
23
+ /** Its colour's place in the entity's `tints`. */
24
+ tint: Uint16ArrayConstructor
25
+ }>
26
+
27
+ /** An entity holding a crowd of particles that share its look. */
28
+ export interface ParticlesEntity extends Entity {
29
+ position: Vector3
30
+ particles: ParticlesPool
31
+ /** The colours bursts used, each once. */
32
+ tints: (string | undefined)[]
33
+ /** Drawn for each particle, tinted; a square of `size` without one. */
34
+ image?: unknown
35
+ size?: Vector3
36
+ layer?: number
15
37
  }
16
38
 
17
- /** Drifts and fades over its life, then despawns. */
18
- export function particle(): {
19
- update: UpdateHandler<ParticleEntity>
39
+ export interface ParticlesOptions {
40
+ /** Where bursts are sent. Defaults to `"particles"`. */
41
+ id?: string
42
+ /** The most particles alive at once. Defaults to 1024. */
43
+ capacity?: number
44
+ type?: string
45
+ image?: unknown
46
+ size?: Vector3
47
+ layer?: number
48
+ [key: string]: unknown
20
49
  }
21
50
 
51
+ /** A particles entity with an empty pool. */
52
+ export function createParticles(options?: ParticlesOptions): ParticlesEntity
53
+
22
54
  export interface BurstParams {
23
55
  /** Defaults to 1. */
24
56
  count?: number
25
- /** Defaults to `"Particle"`. */
26
- type?: string
27
- size?: Vector3
28
57
  /** The shortest and longest a particle lasts, in seconds. Defaults to 1. */
29
58
  lifetime?: readonly [number, number]
30
59
  /** Each particle's acceleration is drawn between these, axis by axis. */
31
- acceleration?: readonly [Vector3, Vector3]
60
+ acceleration?: readonly [
61
+ Vector3 | readonly number[],
62
+ Vector3 | readonly number[],
63
+ ]
32
64
  /** The half-extent of the box particles are emitted in. */
33
- spread?: Vector3
34
- velocity?: Vector3
35
- /** Defaults to 1. */
65
+ spread?: Vector3 | readonly number[]
66
+ velocity?: Vector3 | readonly number[]
67
+ /** How opaque particles start. Defaults to 1. */
36
68
  opacity?: number
37
- layer?: number
38
- image?: unknown
39
69
  tint?: string
40
- position?: Vector3
70
+ position?: Vector3 | readonly number[]
71
+ }
72
+
73
+ /** Moves and fades the particles, and adds those of a `particlesBurst`. */
74
+ export function particles(): {
75
+ update: (entity: ParticlesEntity, dt: number) => void
76
+ particlesBurst: (entity: ParticlesEntity, params: BurstParams) => void
41
77
  }
42
78
 
43
- /** Spawns a burst of pooled particles. */
44
- export function emitBurst(api: GameApi, params: BurstParams): void
79
+ /** Sends a burst to the particles entity `into` names (`"particles"`). */
80
+ export function emitBurst(
81
+ api: GameApi,
82
+ params: BurstParams & { into?: string },
83
+ ): void
84
+
85
+ /** Adds a burst's particles to an entity's pool, as many as fit. */
86
+ export function burst(entity: ParticlesEntity, params: BurstParams): void
87
+
88
+ /** How opaque a particle is now, fading over its life. */
89
+ export function particleOpacity(pool: ParticlesPool, index: number): number
@@ -0,0 +1,59 @@
1
+ import type {
2
+ RecordedSession,
3
+ ReplayProgress,
4
+ } from "@inglorious/utils/data-structures/recorder"
5
+
6
+ import type { Decorator, Entity, Handler } from "../index"
7
+
8
+ export interface RecordedEntity extends Entity {
9
+ /** Where a replay is, and whether it is over; null when not replaying. */
10
+ replay?: (ReplayProgress & { over?: boolean }) | null
11
+ }
12
+
13
+ export interface RecordedOptions<
14
+ TEntity extends RecordedEntity = RecordedEntity,
15
+ About = unknown,
16
+ Input = unknown,
17
+ > {
18
+ /** The simulation's turn, or null while there is none. */
19
+ turn(entity: TEntity): number | null
20
+ /** The simulation's state, fingerprinted where a run ends. */
21
+ state(entity: TEntity): unknown
22
+ /** What it takes to start the simulation again. */
23
+ about(entity: TEntity): About
24
+ /** What the player did before this turn; null for nothing. */
25
+ input(entity: TEntity): Input | null
26
+ /** Puts a recorded input in place of the player's; undefined where nothing was done. */
27
+ useInput(entity: TEntity, input: Input | undefined): void
28
+ /** Starts the simulation of a recorded run. */
29
+ replayRun(entity: TEntity, about: About): void
30
+ /** Events after which a new run starts, besides `create`. */
31
+ startsRun?: string[]
32
+ /** Whether the game can play a session's runs. */
33
+ isPlayable?(session: RecordedSession<About, Input>): boolean
34
+ format?: string
35
+ build?: string
36
+ /** The start of a saved file's name. */
37
+ name?: string
38
+ }
39
+
40
+ /**
41
+ * Records an entity holding a deterministic simulation turned on `tick`, and plays
42
+ * recordings back. Put it last in the type's behaviors.
43
+ */
44
+ export function recorded<
45
+ TEntity extends RecordedEntity = RecordedEntity,
46
+ About = unknown,
47
+ Input = unknown,
48
+ >(
49
+ options: RecordedOptions<TEntity, About, Input>,
50
+ ): Decorator<
51
+ // and a handler for each of `startsRun`
52
+ Record<string, Handler<TEntity, unknown>> & {
53
+ create: Handler<TEntity, unknown>
54
+ tick: Handler<TEntity, number>
55
+ saveRecording: Handler<TEntity, unknown>
56
+ replayLoad: Handler<TEntity, RecordedSession<About, Input>>
57
+ replayStop: Handler<TEntity, unknown>
58
+ }
59
+ >
@@ -23,6 +23,9 @@ export class Engine {
23
23
  /** The entities as they are now. */
24
24
  getState(): EntitiesState
25
25
 
26
+ /** Tells the game something from outside it; handled in the next frame. */
27
+ notify(type: string, payload?: unknown): void
28
+
26
29
  /** Runs a frame, `dt` seconds after the last one. */
27
30
  update(dt: number): void
28
31
  }
package/types/index.d.ts CHANGED
@@ -74,25 +74,11 @@ export interface GameEntity extends BaseEntity {
74
74
  multiplayer?: MultiplayerMiddlewareConfig
75
75
  }
76
76
 
77
- /** The api the engine hands every handler: the store's, and the entity pools'. */
78
- export interface GameApi<
77
+ /** The api the engine hands every handler: the store's. */
78
+ export type GameApi<
79
79
  TEntity extends BaseEntity = BaseEntity,
80
80
  TState extends EntitiesState<TEntity> = EntitiesState<TEntity>,
81
- > extends Api<TEntity, TState> {
82
- /** The pooled entities in play, from `spawn`. */
83
- getAllActivePoolEntities: () => Stored<Entity>[]
84
- /** The first entity that collides with `entity`, pooled ones included. */
85
- findCollision: (
86
- entity: Entity,
87
- entities?: Record<string, Entity>,
88
- collisionGroup?: string,
89
- ) => Stored<Entity> | undefined
90
- /** How many entities each pool holds, in `devMode`. */
91
- getEntityPoolsStats?: () => Record<
92
- string,
93
- { active: number; inactive: number }
94
- >
95
- }
81
+ > = Api<TEntity, TState>
96
82
 
97
83
  /** An event handler: the entity, the event's payload and the api. */
98
84
  export type EventHandler<
package/types/test.d.ts CHANGED
@@ -11,10 +11,6 @@ export interface TestGame {
11
11
  /** One entity, by id, typed as `TEntity`. */
12
12
  entity<TEntity extends BaseEntity = Entity>(id: string): Stored<TEntity>
13
13
  state(): EntitiesState
14
- /** The pooled entities in play, of one type or all. */
15
- pooled<TEntity extends BaseEntity = Entity>(
16
- typeName?: string,
17
- ): Stored<TEntity>[]
18
14
  notify(event: string, payload?: unknown): this
19
15
  /** Runs frames. Defaults to one. */
20
16
  step(frames?: number): this
@@ -1,68 +0,0 @@
1
- import { createApi } from "@inglorious/store/api.js"
2
- import { EventMap } from "@inglorious/store/event-map.js"
3
-
4
- import { findCollision } from "../../../collision/detection.js"
5
- import { EntityPools } from "./entity-pools.js"
6
-
7
- export function entityPoolMiddleware() {
8
- return (store) => {
9
- const pools = new EntityPools()
10
- const eventMap = new EventMap()
11
-
12
- store.extras ??= {}
13
- store.extras.getAllActivePoolEntities = () => pools.getAllActiveEntities()
14
-
15
- store.extras.findCollision = (
16
- entity,
17
- entities = store.getState(),
18
- collisionGroup,
19
- ) =>
20
- findCollision(
21
- entity,
22
- { ...entities, ...pools.getAllActiveEntitiesById() },
23
- collisionGroup,
24
- )
25
-
26
- const game = store.getState().game
27
- if (game.devMode) {
28
- store.extras.getEntityPoolsStats = () => pools.getStats()
29
- }
30
-
31
- const api = createApi(store)
32
-
33
- const next = store.dispatch
34
- store.dispatch = (event) => {
35
- switch (event.type) {
36
- case "spawn": {
37
- const entity = pools.acquire(event.payload)
38
- const type = store.getType(entity.type)
39
- eventMap.addEntity(entity.id, type, entity.type)
40
- break
41
- }
42
-
43
- case "despawn": {
44
- const entity = pools.recycle(event.payload)
45
- const type = store.getType(entity.type)
46
- eventMap.removeEntity(entity.id, type, entity.type)
47
- break
48
- }
49
-
50
- default: {
51
- const entityIds = eventMap.getEntitiesForEvent(event.type)
52
- for (const id of entityIds) {
53
- const entity = pools.activeEntitiesById.get(id)
54
- if (!entity) continue
55
-
56
- const type = store.getType(entity.type)
57
- const handle = type[event.type]
58
- handle?.(entity, event.payload, api)
59
- }
60
- }
61
- }
62
-
63
- return next(event)
64
- }
65
-
66
- return store
67
- }
68
- }
@@ -1,40 +0,0 @@
1
- const INITIAL_ID = 0
2
- const NOT_FOUND = -1
3
- const ITEMS_TO_REMOVE = 1
4
-
5
- export class EntityPool {
6
- _activeEntities = []
7
- _inactiveEntities = []
8
- _nextId = INITIAL_ID
9
-
10
- populate(factory, count) {
11
- for (let i = 0; i < count; i++) {
12
- this._activeEntities.push(factory())
13
- }
14
- }
15
-
16
- acquire(props) {
17
- const entity = this._inactiveEntities.pop() || {
18
- id: `entity-${this._nextId++}`,
19
- }
20
- Object.assign(entity, props)
21
- this._activeEntities.push(entity)
22
- return entity
23
- }
24
-
25
- recycle(entity) {
26
- const index = this._activeEntities.indexOf(entity)
27
- if (index !== NOT_FOUND) {
28
- const [entity] = this._activeEntities.splice(index, ITEMS_TO_REMOVE)
29
- this._inactiveEntities.push(entity)
30
- }
31
- return entity
32
- }
33
-
34
- getStats() {
35
- return {
36
- active: this._activeEntities.length,
37
- inactive: this._inactiveEntities.length,
38
- }
39
- }
40
- }
@@ -1,46 +0,0 @@
1
- import { EntityPool } from "./entity-pool.js"
2
-
3
- export class EntityPools {
4
- _pools = new Map()
5
- _activeEntitiesById = new Map()
6
-
7
- get activeEntitiesById() {
8
- return this._activeEntitiesById
9
- }
10
-
11
- getAllActiveEntitiesById() {
12
- return Object.fromEntries(this._activeEntitiesById)
13
- }
14
-
15
- acquire(props) {
16
- this.lazyInit(props)
17
- const entity = this._pools.get(props.type).acquire(props)
18
- this._activeEntitiesById.set(entity.id, entity)
19
- return entity
20
- }
21
-
22
- recycle(props) {
23
- this.lazyInit(props)
24
- const entity = this._pools.get(props.type).recycle(props)
25
- this._activeEntitiesById.delete(entity.id)
26
- return entity
27
- }
28
-
29
- getStats() {
30
- const stats = {}
31
- for (const [type, pool] of this._pools.entries()) {
32
- stats[type] = pool.getStats()
33
- }
34
- return stats
35
- }
36
-
37
- lazyInit(entity) {
38
- if (!this._pools.get(entity.type)) {
39
- this._pools.set(entity.type, new EntityPool())
40
- }
41
- }
42
-
43
- getAllActiveEntities() {
44
- return Array.from(this._activeEntitiesById.values())
45
- }
46
- }
@@ -1,4 +0,0 @@
1
- import type { Middleware } from "@inglorious/store"
2
-
3
- /** Handles `spawn` and `despawn` with entity pools, and adds them to the api. */
4
- export function entityPoolMiddleware(): Middleware
@@ -1,9 +0,0 @@
1
- import type { BaseEntity } from "@inglorious/store"
2
-
3
- /** Recycles entities of one type rather than making new ones. */
4
- export class EntityPool<TEntity extends BaseEntity = BaseEntity> {
5
- populate(factory: () => TEntity, count: number): void
6
- acquire(props: TEntity): TEntity & { id: string }
7
- recycle(entity: TEntity): TEntity
8
- getStats(): { active: number; inactive: number }
9
- }
@@ -1,12 +0,0 @@
1
- import type { BaseEntity } from "@inglorious/store"
2
-
3
- /** An entity pool per type. */
4
- export class EntityPools<TEntity extends BaseEntity = BaseEntity> {
5
- readonly activeEntitiesById: Map<string, TEntity & { id: string }>
6
- getAllActiveEntitiesById(): Record<string, TEntity & { id: string }>
7
- acquire(props: TEntity): TEntity & { id: string }
8
- recycle(props: TEntity): TEntity
9
- getStats(): Record<string, { active: number; inactive: number }>
10
- lazyInit(entity: TEntity): void
11
- getAllActiveEntities(): (TEntity & { id: string })[]
12
- }