@inglorious/engine 24.12.0 → 24.13.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/package.json +1 -1
- package/src/behaviors/audio.js +20 -0
- package/src/core/core-events.js +1 -0
- package/src/core/engine.js +57 -1
- package/src/core/loops/animation-frame.js +10 -6
- package/src/core/loops/fixed.js +11 -5
- package/src/core/loops/max-dt.js +26 -0
- package/types/core/loops/animation-frame.d.ts +7 -2
- package/types/core/loops/fixed.d.ts +7 -1
- package/types/index.d.ts +8 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@inglorious/engine",
|
|
3
|
-
"version": "24.
|
|
3
|
+
"version": "24.13.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",
|
package/src/behaviors/audio.js
CHANGED
|
@@ -9,6 +9,8 @@ export function audio() {
|
|
|
9
9
|
// imported -- and a module that reaches for `window` on the way in cannot be imported
|
|
10
10
|
// where there is no window, which is anywhere a test runs.
|
|
11
11
|
let audioContext
|
|
12
|
+
// Whether the sound was quieted because the page was hidden, to bring it back.
|
|
13
|
+
let hushed = false
|
|
12
14
|
|
|
13
15
|
function context() {
|
|
14
16
|
audioContext ??= new (window.AudioContext || window.webkitAudioContext)()
|
|
@@ -80,6 +82,24 @@ export function audio() {
|
|
|
80
82
|
activeSources.delete(name)
|
|
81
83
|
},
|
|
82
84
|
|
|
85
|
+
// A hidden page goes quiet, and its sound comes back with it. Browsers keep
|
|
86
|
+
// playing Web Audio in a background tab, so a game would go on sounding from a
|
|
87
|
+
// tab the player has left. Suspending the context rather than stopping the
|
|
88
|
+
// sources keeps every sound where it was, music included. A context still
|
|
89
|
+
// waiting for the user's first gesture is left waiting: resuming it without one
|
|
90
|
+
// is refused by autoplay policy (https://developer.chrome.com/blog/autoplay).
|
|
91
|
+
visibilityChange(entity, state) {
|
|
92
|
+
if (state === "hidden") {
|
|
93
|
+
if (audioContext?.state !== "running") return
|
|
94
|
+
audioContext.suspend()
|
|
95
|
+
hushed = true
|
|
96
|
+
return
|
|
97
|
+
}
|
|
98
|
+
if (!hushed) return
|
|
99
|
+
hushed = false
|
|
100
|
+
audioContext.resume()
|
|
101
|
+
},
|
|
102
|
+
|
|
83
103
|
stop: release,
|
|
84
104
|
|
|
85
105
|
destroy: release,
|
package/src/core/core-events.js
CHANGED
package/src/core/engine.js
CHANGED
|
@@ -20,14 +20,28 @@ import { Loop } from "./loops/index.js"
|
|
|
20
20
|
import { assertTypesAreDeclared } from "./types.js"
|
|
21
21
|
|
|
22
22
|
/**
|
|
23
|
-
* @type {{loop: {type: LoopType, fps: number}, systems: Array, types: Object, entities: Object}}
|
|
23
|
+
* @type {{loop: {type: LoopType, fps: number}, updateStrategy: UpdateStrategy, systems: Array, types: Object, entities: Object}}
|
|
24
24
|
* `loop.type` is a {@link LoopType} and defaults to "animationFrame"; `loop.fps` is
|
|
25
25
|
* what the loops that have a rate measure themselves against, and is ignored by the
|
|
26
26
|
* ones that do not.
|
|
27
|
+
*
|
|
28
|
+
* `updateStrategy` defaults to "copy-on-dispatch". A game hands `update` to most of
|
|
29
|
+
* its entities every frame, and writes to them, so structural sharing's one saving,
|
|
30
|
+
* leaving untouched entities uncopied, rarely applies; what it costs is a proxy on
|
|
31
|
+
* every object a handler reaches. One entity holding a plain world of 300 organisms
|
|
32
|
+
* (the SWARM hackathon game) took 14 ms a frame through the draft proxy, 0.6 ms
|
|
33
|
+
* copied, against 0.35 ms for the bare tick. Immer, whose drafts Mutative follows,
|
|
34
|
+
* says the same of large drafts: https://immerjs.github.io/immer/performance/.
|
|
35
|
+
* Rejected: an opaque-value escape hatch (a class instance or typed array, which the
|
|
36
|
+
* proxy passes through and the game changes in place) is as fast but leaves past
|
|
37
|
+
* states sharing the live world, so time travel and replays lie. A game can still
|
|
38
|
+
* choose "structural-sharing".
|
|
27
39
|
*/
|
|
28
40
|
const DEFAULT_GAME_CONFIG = {
|
|
29
41
|
loop: { type: "animationFrame", fps: 60 },
|
|
30
42
|
|
|
43
|
+
updateStrategy: "copy-on-dispatch",
|
|
44
|
+
|
|
31
45
|
systems: [],
|
|
32
46
|
|
|
33
47
|
types: {
|
|
@@ -103,6 +117,10 @@ export class Engine {
|
|
|
103
117
|
*/
|
|
104
118
|
start() {
|
|
105
119
|
this._store.notify("start")
|
|
120
|
+
globalThis.document?.addEventListener?.(
|
|
121
|
+
"visibilitychange",
|
|
122
|
+
this._onVisibilityChange,
|
|
123
|
+
)
|
|
106
124
|
this._loop.start(this, ONE_SECOND / this._config.loop.fps)
|
|
107
125
|
}
|
|
108
126
|
|
|
@@ -111,11 +129,48 @@ export class Engine {
|
|
|
111
129
|
* this by notifying `quit`, which sets the flag the engine reads after each frame.
|
|
112
130
|
*/
|
|
113
131
|
stop() {
|
|
132
|
+
globalThis.document?.removeEventListener?.(
|
|
133
|
+
"visibilitychange",
|
|
134
|
+
this._onVisibilityChange,
|
|
135
|
+
)
|
|
114
136
|
this._store.notify("stop")
|
|
115
137
|
this._store.update()
|
|
116
138
|
this._loop.stop()
|
|
117
139
|
}
|
|
118
140
|
|
|
141
|
+
/**
|
|
142
|
+
* The page was hidden (another tab, a minimised window) or shown again: the game
|
|
143
|
+
* hears `visibilityChange` with the document's `visibilityState`, "hidden" or
|
|
144
|
+
* "visible", named after the DOM event it comes from.
|
|
145
|
+
*
|
|
146
|
+
* Hidden, it is heard at once rather than queued for the next frame, because
|
|
147
|
+
* browsers stop animation frames in a hidden page and throttle its timers, so the
|
|
148
|
+
* next frame may come only when the page is shown again: too late to quiet the
|
|
149
|
+
* sound. See MDN, Page Visibility API
|
|
150
|
+
* (https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API), and
|
|
151
|
+
* `requestAnimationFrame` ("paused in most browsers when running in background
|
|
152
|
+
* tabs").
|
|
153
|
+
*
|
|
154
|
+
* Shown, the loop leaves out the time it was away (`skipGap`), so the game carries
|
|
155
|
+
* on where it was rather than playing minutes in one frame; the cap on a frame's
|
|
156
|
+
* time (`loops/max-dt.js`) stays for the gaps no event reports. It is heard in the
|
|
157
|
+
* next frame, as any event.
|
|
158
|
+
*
|
|
159
|
+
* Nothing pauses by itself: whether to pause, open a menu or carry on is the
|
|
160
|
+
* game's to decide, and pausing here would unpause, on return, a game the player
|
|
161
|
+
* had paused.
|
|
162
|
+
*/
|
|
163
|
+
_onVisibilityChange = () => {
|
|
164
|
+
const state = document.visibilityState
|
|
165
|
+
if (state === "hidden") {
|
|
166
|
+
this._store.notify("visibilityChange", state)
|
|
167
|
+
this._store.update()
|
|
168
|
+
return
|
|
169
|
+
}
|
|
170
|
+
this._loop.skipGap()
|
|
171
|
+
this._store.notify("visibilityChange", state)
|
|
172
|
+
}
|
|
173
|
+
|
|
119
174
|
/**
|
|
120
175
|
* Returns the current game state.
|
|
121
176
|
* @returns {Entities} The entities of the current state.
|
|
@@ -201,4 +256,5 @@ function isBehavior(value) {
|
|
|
201
256
|
* @typedef {Object.<string, Object>} Entity - An object representing an entity.
|
|
202
257
|
* @typedef {Object.<string, Entity>} Entities - A collection of entities indexed by id.
|
|
203
258
|
* @typedef {import("./loops/index.js").LoopType} LoopType - Which loop drives the game.
|
|
259
|
+
* @typedef {import("@inglorious/store/store.js").UpdateStrategy} UpdateStrategy - How the store copies what an event changes.
|
|
204
260
|
*/
|
|
@@ -1,13 +1,17 @@
|
|
|
1
|
-
|
|
1
|
+
import { cappedDt } from "./max-dt.js"
|
|
2
2
|
|
|
3
3
|
export class AnimationFrameLoop {
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
start(engine) {
|
|
4
|
+
start(engine, msPerUpdate) {
|
|
5
|
+
this._msPerUpdate = msPerUpdate
|
|
6
|
+
this._previousTime = new Date()
|
|
8
7
|
this._tick(engine)
|
|
9
8
|
}
|
|
10
9
|
|
|
10
|
+
/** Measures the next frame from now: the time since the last one is not played. */
|
|
11
|
+
skipGap() {
|
|
12
|
+
this._previousTime = new Date()
|
|
13
|
+
}
|
|
14
|
+
|
|
11
15
|
stop() {
|
|
12
16
|
window.cancelAnimationFrame(this._id)
|
|
13
17
|
this._id = null
|
|
@@ -18,7 +22,7 @@ export class AnimationFrameLoop {
|
|
|
18
22
|
this._id = window.requestAnimationFrame(() => this._tick(engine))
|
|
19
23
|
const dt = currentTime - this._previousTime
|
|
20
24
|
|
|
21
|
-
engine.update(dt
|
|
25
|
+
engine.update(cappedDt(dt, this._msPerUpdate))
|
|
22
26
|
|
|
23
27
|
this._previousTime = currentTime
|
|
24
28
|
}
|
package/src/core/loops/fixed.js
CHANGED
|
@@ -1,24 +1,30 @@
|
|
|
1
|
-
|
|
1
|
+
import { cappedDt } from "./max-dt.js"
|
|
2
|
+
|
|
2
3
|
const NO_WAIT = 0
|
|
3
4
|
|
|
4
5
|
export class FixedLoop {
|
|
5
6
|
_shouldStop = false
|
|
6
7
|
|
|
7
8
|
async start(engine, msPerUpdate) {
|
|
8
|
-
|
|
9
|
+
this._previousTime = Date.now()
|
|
9
10
|
|
|
10
11
|
while (!this._shouldStop) {
|
|
11
12
|
const currentTime = Date.now()
|
|
12
|
-
const dt = currentTime -
|
|
13
|
+
const dt = currentTime - this._previousTime
|
|
13
14
|
|
|
14
|
-
engine.update(dt
|
|
15
|
+
engine.update(cappedDt(dt, msPerUpdate))
|
|
15
16
|
|
|
16
|
-
|
|
17
|
+
this._previousTime = currentTime
|
|
17
18
|
|
|
18
19
|
await sleep(Math.max(NO_WAIT, msPerUpdate - (Date.now() - currentTime)))
|
|
19
20
|
}
|
|
20
21
|
}
|
|
21
22
|
|
|
23
|
+
/** Measures the next frame from now: the time since the last one is not played. */
|
|
24
|
+
skipGap() {
|
|
25
|
+
this._previousTime = Date.now()
|
|
26
|
+
}
|
|
27
|
+
|
|
22
28
|
stop() {
|
|
23
29
|
this._shouldStop = true
|
|
24
30
|
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
const ONE_SECOND = 1000
|
|
2
|
+
// The longest frame a loop reports, in milliseconds. A quarter of a second, as in
|
|
3
|
+
// Glenn Fiedler's "Fix Your Timestep!"
|
|
4
|
+
// (https://gafferongames.com/post/fix_your_timestep/), where it keeps a fixed-step
|
|
5
|
+
// world from the "spiral of death": a long frame owes many steps, those steps make
|
|
6
|
+
// the next frame long, and so on. It is well above any frame a working game makes
|
|
7
|
+
// (it allows down to 4 frames a second), so it never slows a slow device; a much
|
|
8
|
+
// lower cap, such as 1/60 s, would: at 30 frames a second the game would run at half
|
|
9
|
+
// speed, and a world turned faster than real time could never keep up.
|
|
10
|
+
const MAX_FRAME = 250
|
|
11
|
+
const NO_RATE = 0
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* The milliseconds a frame may cover: `elapsed` as measured, but at most a quarter
|
|
15
|
+
* of a second, or one interval when the loop's own rate is slower than that. A tab
|
|
16
|
+
* left in the background stops its animation frames and slows its timers (Chrome
|
|
17
|
+
* wakes chained timers at most once a minute after five minutes hidden:
|
|
18
|
+
* https://developer.chrome.com/blog/timer-throttling-in-chrome-88), so the first
|
|
19
|
+
* frame back can measure minutes: passed on whole, it would jump the world that far
|
|
20
|
+
* ahead in one step. The engine leaves out the time a page was hidden anyway
|
|
21
|
+
* (`skipGap`); the cap is for the gaps no event reports: a debugger's breakpoint, a
|
|
22
|
+
* computer waking from sleep, a long freeze, and Node, where there is no page.
|
|
23
|
+
*/
|
|
24
|
+
export function cappedDt(elapsed, msPerUpdate = NO_RATE) {
|
|
25
|
+
return Math.min(elapsed, Math.max(MAX_FRAME, msPerUpdate)) / ONE_SECOND
|
|
26
|
+
}
|
|
@@ -1,7 +1,12 @@
|
|
|
1
1
|
import type { Updatable } from "./index"
|
|
2
2
|
|
|
3
|
-
/**
|
|
3
|
+
/**
|
|
4
|
+
* Updates once per animation frame, as fast as the screen takes it. A frame covers
|
|
5
|
+
* at most a quarter of a second, so a tab back from the background does not jump.
|
|
6
|
+
*/
|
|
4
7
|
export class AnimationFrameLoop {
|
|
5
|
-
start(engine: Updatable): void
|
|
8
|
+
start(engine: Updatable, msPerUpdate?: number): void
|
|
9
|
+
/** Measures the next frame from now: the time since the last one is not played. */
|
|
10
|
+
skipGap(): void
|
|
6
11
|
stop(): void
|
|
7
12
|
}
|
|
@@ -1,7 +1,13 @@
|
|
|
1
1
|
import type { Updatable } from "./index"
|
|
2
2
|
|
|
3
|
-
/**
|
|
3
|
+
/**
|
|
4
|
+
* Updates every `msPerUpdate` milliseconds. A frame covers at most a quarter of a
|
|
5
|
+
* second, or one interval if that is longer, so a tab back from the background
|
|
6
|
+
* does not jump.
|
|
7
|
+
*/
|
|
4
8
|
export class FixedLoop {
|
|
5
9
|
start(engine: Updatable, msPerUpdate: number): Promise<void>
|
|
10
|
+
/** Measures the next frame from now: the time since the last one is not played. */
|
|
11
|
+
skipGap(): void
|
|
6
12
|
stop(): void
|
|
7
13
|
}
|
package/types/index.d.ts
CHANGED
|
@@ -4,6 +4,7 @@ import type {
|
|
|
4
4
|
EntitiesState,
|
|
5
5
|
Stored,
|
|
6
6
|
System,
|
|
7
|
+
UpdateStrategy,
|
|
7
8
|
} from "@inglorious/store"
|
|
8
9
|
import type { MultiplayerMiddlewareConfig } from "@inglorious/store/client/multiplayer-middleware.js"
|
|
9
10
|
import type { Vector3 } from "@inglorious/utils/vector.js"
|
|
@@ -123,6 +124,13 @@ export type EntityConfig = BaseEntity & { [key: string]: unknown }
|
|
|
123
124
|
export interface GameConfig {
|
|
124
125
|
/** Which loop drives the game, and the rate the fixed one keeps. */
|
|
125
126
|
loop?: { type?: LoopType; fps?: number }
|
|
127
|
+
/**
|
|
128
|
+
* How the store copies what an event changes. Defaults to `"copy-on-dispatch"`:
|
|
129
|
+
* each entity is deep-copied before an event changes it, with no proxy, so a big
|
|
130
|
+
* plain world in one entity stays cheap and past states stay real snapshots.
|
|
131
|
+
* `"structural-sharing"` drafts through a proxy and copies only what changed.
|
|
132
|
+
*/
|
|
133
|
+
updateStrategy?: UpdateStrategy
|
|
126
134
|
types?: Record<string, GameTypeDefinition>
|
|
127
135
|
entities?: Record<string, BaseEntity | EntityConfig>
|
|
128
136
|
systems?: (System | GameSystem)[]
|