@inglorious/engine 24.13.0 → 24.15.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
@@ -136,20 +136,21 @@ both at once, which is the difference between moving the thing and moving its ou
136
136
 
137
137
  ### Pausing
138
138
 
139
- `api.notify("pause")` stops the store handing out `update` events, and `notify("resume")` starts it again. `pauseToggle` sends whichever of the two is due, for a single key or button (`Space: "pauseToggle"`); a state that does more on it, such as playing a sound, answers it itself:
139
+ `api.notify("pause")` stops the store handing out `update` events, and `notify("resume")` starts it again. `pauseToggle` sends whichever of the two is due, for a single key or button (`Space: "pauseToggle"`). Whatever else should happen on pausing answers `pause` itself, such as a sound from the Audio entity:
140
140
 
141
141
  ```javascript
142
- fsm({
143
- play: {
144
- pauseToggle(entity, _, api) {
145
- api.notify("soundPlay", "pause")
146
- api.notify(entity.paused ? "resume" : "pause")
142
+ import { playSound } from "@inglorious/engine/behaviors/audio.js"
143
+
144
+ const types = {
145
+ Audio: {
146
+ pause(entity) {
147
+ playSound(entity, "pause")
147
148
  },
148
149
  },
149
- })
150
+ }
150
151
  ```
151
152
 
152
- The game entity already keeps a readable `paused` flag, which is what that handler reads. Because `update` is never called while halted, a moving entity needs no pause check of its own:
153
+ The game entity keeps a readable `paused` flag. Because `update` is never called while halted, a moving entity needs no pause check of its own:
153
154
 
154
155
  ```javascript
155
156
  update(entity, dt) {
@@ -172,14 +173,14 @@ The default is to **stop**. Anything that keeps going has to say so, so forgetti
172
173
 
173
174
  ## Testing a game
174
175
 
175
- `@inglorious/engine/test` is the harness for testing a game against its own store: no
176
+ `@inglorious/engine/test.js` is the harness for testing a game against its own store: no
176
177
  canvas, no browser, no loop.
177
178
 
178
179
  ```javascript
179
180
  // test/game.test.js
180
181
  import { beforeEach, describe, expect, test } from "vitest"
181
182
 
182
- import { createGame } from "@inglorious/engine/test"
183
+ import { createGame } from "@inglorious/engine/test.js"
183
184
 
184
185
  import gameConfig from "../src/game.ijs"
185
186
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inglorious/engine",
3
- "version": "24.13.0",
3
+ "version": "24.15.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",
@@ -41,7 +41,7 @@
41
41
  },
42
42
  "sideEffects": false,
43
43
  "dependencies": {
44
- "@inglorious/utils": "^5.10.0"
44
+ "@inglorious/utils": "^5.11.0"
45
45
  },
46
46
  "peerDependencies": {
47
47
  "@inglorious/store": "^12.9.6",
@@ -1,5 +1,55 @@
1
1
  const DEFAULT_VOLUME = 1
2
2
 
3
+ // What each Audio entity plays with, by id. Decoded buffers, sources and the
4
+ // AudioContext cannot live in the state: the store copies entities, and these
5
+ // objects cannot be cloned (https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm).
6
+ const players = new Map()
7
+
8
+ /**
9
+ * What `playSound` and `stopSound` go through, so the test harness can listen
10
+ * to the sounds a game plays without a browser (`createGame`'s `playedSounds`).
11
+ */
12
+ export const speaker = {
13
+ play(entity, name) {
14
+ players.get(entity.id)?.play(entity, name)
15
+ },
16
+
17
+ stop(entity, name) {
18
+ players.get(entity.id)?.stop(name)
19
+ },
20
+ }
21
+
22
+ /**
23
+ * Plays one of the Audio entity's sounds, by name. Call it from the Audio
24
+ * type's own handlers, answering what happened in the game:
25
+ * `Audio: { ballBounce(entity) { playSound(entity, "bounce") } }`.
26
+ *
27
+ * There is no `soundPlay` event on purpose: an event names what happened
28
+ * (`ballBounce`), and each entity decides what that means to it. A
29
+ * `soundPlay` would be a command dressed as an event, the sender deciding the
30
+ * effect, which nobody but the Audio entity could ever answer.
31
+ *
32
+ * @param {Object} entity - The Audio entity, as its handler was given it.
33
+ * @param {string} name - A key of its `sounds`.
34
+ */
35
+ export function playSound(entity, name) {
36
+ speaker.play(entity, name)
37
+ }
38
+
39
+ /**
40
+ * Stops one of the Audio entity's sounds, by name (a looping one: music).
41
+ *
42
+ * @param {Object} entity - The Audio entity, as its handler was given it.
43
+ * @param {string} name - A key of its `sounds`.
44
+ */
45
+ export function stopSound(entity, name) {
46
+ speaker.stop(entity, name)
47
+ }
48
+
49
+ /**
50
+ * The behaviour of an Audio entity: loads its `sounds`, plays them through
51
+ * `playSound` and `stopSound`, and goes quiet while the page is hidden.
52
+ */
3
53
  export function audio() {
4
54
  const audioBufferCache = new Map()
5
55
  const activeSources = new Map()
@@ -35,8 +85,39 @@ export function audio() {
35
85
  activeSources.clear()
36
86
  }
37
87
 
88
+ function play(entity, name) {
89
+ const { volume = DEFAULT_VOLUME, loop } = entity.sounds[name] || {}
90
+ const audioBuffer = audioBufferCache.get(name)
91
+
92
+ if (!audioBuffer) return
93
+
94
+ activeSources.get(name)?.stop()
95
+
96
+ const source = context().createBufferSource()
97
+ const gainNode = context().createGain()
98
+
99
+ source.buffer = audioBuffer
100
+ gainNode.gain.value = volume
101
+
102
+ source.connect(gainNode)
103
+ gainNode.connect(context().destination)
104
+
105
+ source.loop = loop
106
+ source.start()
107
+
108
+ activeSources.set(name, source)
109
+ }
110
+
111
+ function stop(name) {
112
+ const source = activeSources.get(name)
113
+ source?.stop()
114
+ activeSources.delete(name)
115
+ }
116
+
38
117
  return {
39
- create() {
118
+ create(entity) {
119
+ if (entity) players.set(entity.id, { play, stop })
120
+
40
121
  // Browsers keep an AudioContext suspended until the user interacts with
41
122
  // the page, so playback would be silently dropped until then.
42
123
  window.addEventListener("pointerdown", resume)
@@ -53,35 +134,6 @@ export function audio() {
53
134
  )
54
135
  },
55
136
 
56
- soundPlay(entity, name) {
57
- const { volume = DEFAULT_VOLUME, loop } = entity.sounds[name] || {}
58
- const audioBuffer = audioBufferCache.get(name)
59
-
60
- if (!audioBuffer) return
61
-
62
- activeSources.get(name)?.stop()
63
-
64
- const source = context().createBufferSource()
65
- const gainNode = context().createGain()
66
-
67
- source.buffer = audioBuffer
68
- gainNode.gain.value = volume
69
-
70
- source.connect(gainNode)
71
- gainNode.connect(context().destination)
72
-
73
- source.loop = loop
74
- source.start()
75
-
76
- activeSources.set(name, source)
77
- },
78
-
79
- soundStop(entity, name) {
80
- const source = activeSources.get(name)
81
- source?.stop()
82
- activeSources.delete(name)
83
- },
84
-
85
137
  // A hidden page goes quiet, and its sound comes back with it. Browsers keep
86
138
  // playing Web Audio in a background tab, so a game would go on sounding from a
87
139
  // tab the player has left. Suspending the context rather than stopping the
@@ -102,7 +154,10 @@ export function audio() {
102
154
 
103
155
  stop: release,
104
156
 
105
- destroy: release,
157
+ destroy(entity) {
158
+ if (entity) players.delete(entity.id)
159
+ release()
160
+ },
106
161
  }
107
162
  }
108
163
 
@@ -39,6 +39,19 @@ export function images() {
39
39
  return imageCache.get(id)
40
40
  },
41
41
 
42
+ // An image the game made rather than loaded: a canvas it painted, such as pixel art
43
+ // baked by `@inglorious/renderer-2d/image/pixels.js`. It is kept here, by id, because an
44
+ // entity can only name an image: the store copies entities with `structuredClone`,
45
+ // which refuses canvases (MDN, "The structured clone algorithm":
46
+ // https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm),
47
+ // and a store holding one would copy its pixels on every change anyway.
48
+ set(id, image) {
49
+ image.id = id
50
+ imageCache.set(id, image)
51
+ loadingPromises.delete(id)
52
+ return image
53
+ },
54
+
42
55
  stop() {
43
56
  imageCache.clear()
44
57
  loadingPromises.clear()
@@ -50,14 +50,22 @@ const SCHEMA = {
50
50
  *
51
51
  * What every particle shares -- `image`, `size`, `layer` -- is said once, on the
52
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.
53
+ * and their colour. A different look is a different particles entity, with its own
54
+ * type: the type answers the game's events with bursts (see `burst`).
54
55
  *
55
56
  * @example
56
57
  * ```js
57
- * types: { Particles: [{ render: renderParticles }, particles()] },
58
+ * types: {
59
+ * Debris: [
60
+ * { render: renderParticles },
61
+ * particles(),
62
+ * { brickBreak(entity, brick) { burst(entity, { count: 64, position: brick.position }) } },
63
+ * ],
64
+ * },
58
65
  * entities: {
59
66
  * debris: createParticles({
60
67
  * id: "debris",
68
+ * type: "Debris",
61
69
  * size: v(8, 8, 0),
62
70
  * layer: 0.5,
63
71
  * image: { id: "particle", imageSize: [8, 8] },
@@ -66,7 +74,7 @@ const SCHEMA = {
66
74
  * ```
67
75
  *
68
76
  * @param {Object} [options]
69
- * @param {string} [options.id="particles"] - Where bursts are sent.
77
+ * @param {string} [options.id="particles"] - The entity's id.
70
78
  * @param {number} [options.capacity=1024] - The most particles alive at once: a burst
71
79
  * past it emits only those that fit.
72
80
  * @returns {Object} The entity, of type `Particles` unless `type` says otherwise. Any
@@ -89,10 +97,10 @@ export function createParticles({
89
97
 
90
98
  /**
91
99
  * 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`).
100
+ * fades out over its lifetime, then leaves the pool. New ones come from `burst`, called
101
+ * by the type's own handlers.
94
102
  *
95
- * Pair it with `renderParticles` from `@inglorious/renderer-2d/particles.js`.
103
+ * Pair it with `renderParticles` from `@inglorious/renderer-2d/crowds/particles.js`.
96
104
  */
97
105
  export function particles() {
98
106
  return {
@@ -116,15 +124,18 @@ export function particles() {
116
124
  pool.z[index] += pool.vz[index] * dt
117
125
  }
118
126
  },
119
-
120
- particlesBurst(entity, params) {
121
- burst(entity, params)
122
- },
123
127
  }
124
128
  }
125
129
 
126
130
  /**
127
- * Sends a burst of particles to a particles entity.
131
+ * Adds a burst's particles to the pool, as many as fit. Call it from the particles
132
+ * type's own handlers, answering what happened in the game (`brickBreak`), not from
133
+ * the entity where it happened.
134
+ *
135
+ * There is no `particlesBurst` event on purpose: an event names what happened, and
136
+ * each entity decides what that means to it (debris bursts, the camera shakes, the
137
+ * audio plays). A burst event would be a command dressed as an event, the sender
138
+ * deciding the effect for an entity it should not know about.
128
139
  *
129
140
  * Each particle picks its own lifetime, its own acceleration and its own place in the
130
141
  * emission box, so one call reads as a burst rather than a grid.
@@ -134,32 +145,6 @@ export function particles() {
134
145
  * can reach. `spread` is the half-extent of the box particles are emitted in, so
135
146
  * `[5, 5, 0]` emits within five of the position on each axis.
136
147
  *
137
- * @example
138
- * ```js
139
- * // Debris falling away from something that was hit.
140
- * emitBurst(api, {
141
- * into: "debris",
142
- * count: 64,
143
- * position: v(100, 100, 0),
144
- * lifetime: [0.5, 1],
145
- * tint: "rgb(99, 155, 255)",
146
- * acceleration: [v(-15, -80, 0), v(15, 0, 0)],
147
- * spread: v(5, 5, 0),
148
- * })
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`.
154
- */
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
148
  * @param {Object} entity - A particles entity, from `createParticles`.
164
149
  * @param {Object} params
165
150
  * @param {number} [params.count=1]
package/src/test.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { expect, vi } from "vitest"
2
2
 
3
+ import { speaker } from "./behaviors/audio.js"
3
4
  import { Engine } from "./core/engine.js"
4
5
 
5
6
  const DEFAULT_DT = 0.016
@@ -39,11 +40,9 @@ export function createGame(gameConfig, extendWith = {}) {
39
40
  const engine = new Engine(gameConfig)
40
41
  const playedSounds = []
41
42
 
42
- vi.spyOn(engine._store.getType("Audio"), "soundPlay").mockImplementation(
43
- function soundPlay(_, name) {
44
- playedSounds.push(name)
45
- },
46
- )
43
+ vi.spyOn(speaker, "play").mockImplementation(function play(_, name) {
44
+ playedSounds.push(name)
45
+ })
47
46
 
48
47
  return {
49
48
  playedSounds,
@@ -14,12 +14,26 @@ export interface AudioEntity extends BaseEntity {
14
14
  sounds: Record<string, Sound>
15
15
  }
16
16
 
17
- /** Loads the entity's sounds and plays them on `soundPlay`, by name. */
17
+ /**
18
+ * Plays one of the Audio entity's sounds, by name, from the Audio type's own
19
+ * handler answering what happened: `ballBounce(entity) { playSound(entity, "bounce") }`.
20
+ */
21
+ export function playSound(entity: AudioEntity, name: string): void
22
+
23
+ /** Stops one of the Audio entity's sounds, by name (a looping one: music). */
24
+ export function stopSound(entity: AudioEntity, name: string): void
25
+
26
+ /** What `playSound` and `stopSound` go through; the test harness listens to it. */
27
+ export const speaker: {
28
+ play: (entity: AudioEntity, name: string) => void
29
+ stop: (entity: AudioEntity, name: string) => void
30
+ }
31
+
32
+ /** Loads the entity's sounds, plays them through `playSound`, and hushes a hidden page. */
18
33
  export function audio(): {
19
34
  create: Handler<AudioEntity>
20
35
  init: (entity: AudioEntity) => Promise<void>
21
- soundPlay: Handler<AudioEntity, string>
22
- soundStop: Handler<AudioEntity, string>
36
+ visibilityChange: Handler<AudioEntity, "hidden" | "visible">
23
37
  stop: () => void
24
- destroy: () => void
38
+ destroy: Handler<AudioEntity>
25
39
  }
@@ -12,10 +12,23 @@ export interface ImagesEntity extends BaseEntity {
12
12
  /** A loaded image, with the id it was loaded under. */
13
13
  export type LoadedImage = HTMLImageElement & { id: string }
14
14
 
15
- /** Loads images up front with `init`, or on demand with `load`, and hands them out by id. */
15
+ /** Anything `drawImage` takes that a game can make itself, such as a painted canvas. */
16
+ export type MadeImage = (OffscreenCanvas | HTMLCanvasElement | ImageBitmap) & {
17
+ id: string
18
+ }
19
+
20
+ /**
21
+ * Loads images up front with `init`, or on demand with `load`, and hands them out by id.
22
+ * `set` keeps an image the game made (a canvas it painted) under an id, for entities to
23
+ * name as they name a loaded one.
24
+ */
16
25
  export function images(): {
17
26
  init: (entity: ImagesEntity) => Promise<void>
18
27
  load: (id: string, src: string) => Promise<LoadedImage>
19
- get: (id: string) => LoadedImage | undefined
28
+ get: (id: string) => LoadedImage | MadeImage | undefined
29
+ set: (
30
+ id: string,
31
+ image: OffscreenCanvas | HTMLCanvasElement | ImageBitmap,
32
+ ) => MadeImage
20
33
  stop: () => void
21
34
  }
@@ -1,7 +1,7 @@
1
1
  import type { Pool } from "@inglorious/utils/data-structures/pool.js"
2
2
  import type { Vector3 } from "@inglorious/utils/vector.js"
3
3
 
4
- import type { Entity, GameApi } from "../index"
4
+ import type { Entity } from "../index"
5
5
 
6
6
  /** Each particle's properties, one typed array each, in `entity.particles`. */
7
7
  export type ParticlesPool = Pool<{
@@ -70,19 +70,15 @@ export interface BurstParams {
70
70
  position?: Vector3 | readonly number[]
71
71
  }
72
72
 
73
- /** Moves and fades the particles, and adds those of a `particlesBurst`. */
73
+ /** Moves and fades the particles; new ones come from `burst`. */
74
74
  export function particles(): {
75
75
  update: (entity: ParticlesEntity, dt: number) => void
76
- particlesBurst: (entity: ParticlesEntity, params: BurstParams) => void
77
76
  }
78
77
 
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. */
78
+ /**
79
+ * Adds a burst's particles to an entity's pool, as many as fit, from the
80
+ * particles type's own handler answering what happened in the game.
81
+ */
86
82
  export function burst(entity: ParticlesEntity, params: BurstParams): void
87
83
 
88
84
  /** How opaque a particle is now, fading over its life. */