@inglorious/engine 24.8.0 → 24.10.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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inglorious/engine",
3
- "version": "24.8.0",
3
+ "version": "24.10.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.8.0"
44
+ "@inglorious/utils": "^5.9.0"
45
45
  },
46
46
  "peerDependencies": {
47
47
  "@inglorious/store": "^12.9.6",
@@ -51,7 +51,7 @@
51
51
  "@inglorious/eslint-config": "1.2.2",
52
52
  "prettier": "^3.10.1",
53
53
  "typescript": "~7.0.2",
54
- "vite": "^8.3.8",
54
+ "vite": "^8.4.0",
55
55
  "vitest": "^5.1.2"
56
56
  },
57
57
  "engines": {
@@ -0,0 +1,81 @@
1
+ const FIRST_FINGER = 0
2
+
3
+ /**
4
+ * Dragging across the scene, the same with a mouse and with a finger: a press on
5
+ * the scene (not on an entity: see `scenePress` and `sceneTouchStart`) starts a
6
+ * drag, moving draws it, letting go ends it. Only the first finger drags, so a
7
+ * second one resting on the screen does nothing.
8
+ *
9
+ * The entity keeps `pointer`, where the pointer is (null once a finger lifts, since
10
+ * there is then no pointer at all, while a mouse stays where it was), and `dragging`.
11
+ * Each move while dragging calls the type's `sceneDrag(entity, { from, to }, api)`,
12
+ * in the same event, so whatever it adds up is there for the next turn: a brush
13
+ * stroke, a pan, a line drawn. A game that should not drag at the moment (paused,
14
+ * say) returns early there. Moving the mouse without pressing only moves `pointer`,
15
+ * for a cursor of the game's own. Put it after the type's own behaviors, so it wraps
16
+ * them.
17
+ *
18
+ * @returns {Function} The behavior.
19
+ */
20
+ export function sceneDrag() {
21
+ return (type) => {
22
+ function start(entity, position, api) {
23
+ entity.pointer = position
24
+ entity.dragging = true
25
+ type.sceneDragStart?.(entity, position, api)
26
+ }
27
+
28
+ function move(entity, position, api) {
29
+ const from = entity.pointer
30
+ entity.pointer = position
31
+ if (!entity.dragging || !from) return
32
+ type.sceneDrag?.(entity, { from, to: position }, api)
33
+ }
34
+
35
+ function end(entity, api) {
36
+ if (!entity.dragging) return
37
+ entity.dragging = false
38
+ type.sceneDragEnd?.(entity, entity.pointer, api)
39
+ }
40
+
41
+ return {
42
+ create(entity, payload, api) {
43
+ type.create?.(entity, payload, api)
44
+ entity.pointer ??= null
45
+ entity.dragging ??= false
46
+ },
47
+
48
+ scenePress(entity, position, api) {
49
+ type.scenePress?.(entity, position, api)
50
+ start(entity, position, api)
51
+ },
52
+
53
+ mouseMove(entity, position, api) {
54
+ type.mouseMove?.(entity, position, api)
55
+ move(entity, position, api)
56
+ },
57
+
58
+ mouseUp(entity, position, api) {
59
+ type.mouseUp?.(entity, position, api)
60
+ end(entity, api)
61
+ },
62
+
63
+ sceneTouchStart(entity, position, api) {
64
+ type.sceneTouchStart?.(entity, position, api)
65
+ start(entity, position, api)
66
+ },
67
+
68
+ touchMove(entity, touch, api) {
69
+ type.touchMove?.(entity, touch, api)
70
+ if (touch.index === FIRST_FINGER) move(entity, touch.position, api)
71
+ },
72
+
73
+ touchEnd(entity, touch, api) {
74
+ type.touchEnd?.(entity, touch, api)
75
+ if (touch.index !== FIRST_FINGER) return
76
+ end(entity, api)
77
+ entity.pointer = null
78
+ },
79
+ }
80
+ }
81
+ }
@@ -1,16 +1,22 @@
1
- import {
2
- createRecorder,
3
- isSession,
4
- } from "@inglorious/utils/data-structures/recorder.js"
5
1
  import { saveJSON } from "@inglorious/utils/files.js"
6
2
 
3
+ import { createRecorder, isSession } from "../core/recorder.js"
4
+
7
5
  const NO_TURNS = 0
8
6
  const STAMP_START = 0
9
7
  const STAMP_LENGTH = 19 // "2026-12-01T13:42:32", to the second
8
+ const STORE_EVERY_MS = 5000
9
+ // characters, well under the browsers' quota for local storage (5 MB and up)
10
+ const STORE_LIMIT = 1_000_000
11
+ const LAST_RUN = 1
12
+ const NEVER = 0
13
+ const NO_CHARACTERS = 0
10
14
 
11
15
  // One recorder per entity: kept outside the state, which the store copies on every
12
16
  // event, while a recording grows all game long.
13
17
  const recorders = new Map()
18
+ // when each entity's session was last stored
19
+ const storedAt = new Map()
14
20
 
15
21
  /**
16
22
  * Records an entity that holds a deterministic simulation, turned on `tick` (see the
@@ -41,6 +47,13 @@ const recorders = new Map()
41
47
  * `{ run, runs, diverged, over }`, else null; once `over`, `tick` holds the simulation
42
48
  * still, and the player's input is still replaced by none.
43
49
  *
50
+ * With `storageKey`, the session is also kept in the browser's local storage under
51
+ * that key, every few seconds while playing and whenever a run starts, so a page
52
+ * closed by mistake loses little: opened again, the recorder carries on the stored
53
+ * session (see `resume`), and a saved file holds both visits. Past a million
54
+ * characters the oldest runs are left out of the stored copy. A replay is not
55
+ * stored.
56
+ *
44
57
  * @param {Object} options
45
58
  * @param {(entity: Object) => number | null} options.turn
46
59
  * @param {(entity: Object) => *} options.state
@@ -53,6 +66,7 @@ const recorders = new Map()
53
66
  * @param {string} [options.format] - What the recordings are; a session of another format is refused.
54
67
  * @param {string} [options.build] - Which build of the game made them.
55
68
  * @param {string} [options.name] - The start of a saved file's name, followed by the time.
69
+ * @param {string} [options.storageKey] - Where to keep the session in local storage; not kept without one.
56
70
  * @returns {Function} The behavior.
57
71
  */
58
72
  export function recorded({
@@ -67,6 +81,7 @@ export function recorded({
67
81
  format = "recording",
68
82
  build,
69
83
  name = format,
84
+ storageKey,
70
85
  }) {
71
86
  const recorderOf = (entity) => recorders.get(entity.id)
72
87
 
@@ -80,6 +95,35 @@ export function recorded({
80
95
  if (turn(entity) != null) recorderOf(entity).open(about(entity))
81
96
  }
82
97
 
98
+ /** Keeps the session so far in local storage, if asked to, and not while replaying. */
99
+ function store(entity) {
100
+ if (!storageKey || entity.replay) return
101
+ storedAt.set(entity.id, Date.now())
102
+ const session = recorderOf(entity).session(
103
+ turn(entity) ?? NO_TURNS,
104
+ state(entity),
105
+ )
106
+ try {
107
+ globalThis.localStorage?.setItem(storageKey, stringify(session))
108
+ } catch (error) {
109
+ console.warn(`The recording could not be stored: ${error.message}`)
110
+ }
111
+ }
112
+
113
+ /** Carries on the session left in local storage, if it is one the game can play. */
114
+ function restore(entity) {
115
+ if (!storageKey) return
116
+ try {
117
+ const stored = globalThis.localStorage?.getItem(storageKey)
118
+ const session = stored && JSON.parse(stored)
119
+ if (isSession(session, format) && isPlayable(session)) {
120
+ recorderOf(entity).resume(session)
121
+ }
122
+ } catch (error) {
123
+ console.warn(`The stored recording could not be read: ${error.message}`)
124
+ }
125
+ }
126
+
83
127
  function play(entity, run) {
84
128
  replayRun(entity, run.about)
85
129
  entity.replay = recorderOf(entity).progress()
@@ -94,6 +138,7 @@ export function recorded({
94
138
  close(entity)
95
139
  type[event]?.(entity, payload, api)
96
140
  open(entity)
141
+ store(entity)
97
142
  },
98
143
  ]),
99
144
  )
@@ -103,7 +148,9 @@ export function recorded({
103
148
 
104
149
  create(entity, payload, api) {
105
150
  recorders.set(entity.id, createRecorder({ format, build }))
151
+ storedAt.delete(entity.id)
106
152
  entity.replay = null
153
+ restore(entity)
107
154
  type.create?.(entity, payload, api)
108
155
  open(entity)
109
156
  },
@@ -130,6 +177,8 @@ export function recorded({
130
177
  if (after === before) return
131
178
  if (!entity.replay) {
132
179
  recorder.record(before, done)
180
+ const since = Date.now() - (storedAt.get(entity.id) ?? NEVER)
181
+ if (since >= STORE_EVERY_MS) store(entity)
133
182
  return
134
183
  }
135
184
 
@@ -170,3 +219,15 @@ export function recorded({
170
219
  }
171
220
  }
172
221
  }
222
+
223
+ /** A session as JSON, leaving out its oldest runs (but the last) while it is too long. */
224
+ function stringify(session) {
225
+ const runs = [...session.runs]
226
+ const sizes = runs.map((run) => JSON.stringify(run).length)
227
+ let total = sizes.reduce((sum, size) => sum + size, NO_CHARACTERS)
228
+ while (total > STORE_LIMIT && runs.length > LAST_RUN) {
229
+ runs.shift()
230
+ total -= sizes.shift()
231
+ }
232
+ return JSON.stringify({ ...session, runs })
233
+ }
@@ -0,0 +1,60 @@
1
+ // What a game is playing kept in the page's address, `/level-2?tank=base&seed=3`, so
2
+ // it can be shared as a link and a reload goes back to it: a page as the last segment
3
+ // of the path, settings in the query. Only noted, with `replaceState`, so Back does
4
+ // not step through every change. Outside a browser, reads give their fallbacks and
5
+ // notes do nothing.
6
+
7
+ const LAST = -1
8
+ const NONE = 0
9
+ const FROM_START = 0
10
+
11
+ /** The last segment of the address's path, `/level-2` → "level-2", "" at the root. */
12
+ export function pageInAddress() {
13
+ return globalThis.location?.pathname.split("/").at(LAST) ?? ""
14
+ }
15
+
16
+ /** The value under `key` in the address's query, if it is one of `choices`, else `fallback`. */
17
+ export function choiceInAddress(key, choices, fallback) {
18
+ const value = query().get(key)
19
+ return choices.includes(value) ? value : fallback
20
+ }
21
+
22
+ /** The whole number above zero under `key` in the address's query, else `fallback`. */
23
+ export function countInAddress(key, fallback) {
24
+ const number = Number(query().get(key))
25
+ return Number.isInteger(number) && number > NONE ? number : fallback
26
+ }
27
+
28
+ /** Notes `values` in the address's query, without reloading or adding to the history. */
29
+ export function noteInAddress(values) {
30
+ const address = query()
31
+ for (const [key, value] of Object.entries(values)) address.set(key, value)
32
+ replaceAddress(globalThis.location?.pathname, address)
33
+ }
34
+
35
+ /**
36
+ * Notes `page` as the last segment of the address's path, in place of the one there,
37
+ * but only if that is the root or one of `pages`: where the game is served from a
38
+ * file (`/html/123/index.html`, as on itch.io), the path is left alone, since a
39
+ * reload would not find it.
40
+ */
41
+ export function notePageInAddress(page, pages) {
42
+ const pathname = globalThis.location?.pathname ?? ""
43
+ const segments = pathname.split("/")
44
+ if (!["", ...pages].includes(segments.at(LAST))) return
45
+ replaceAddress([...segments.slice(FROM_START, LAST), page].join("/"), query())
46
+ }
47
+
48
+ function query() {
49
+ return new URLSearchParams(globalThis.location?.search ?? "")
50
+ }
51
+
52
+ function replaceAddress(pathname, query) {
53
+ if (!globalThis.history?.replaceState) return
54
+ const search = query.size ? `?${query}` : ""
55
+ globalThis.history.replaceState(
56
+ null,
57
+ "",
58
+ `${pathname}${search}${globalThis.location.hash}`,
59
+ )
60
+ }
@@ -0,0 +1,154 @@
1
+ import { fingerprint } from "@inglorious/utils/data-structures/object.js"
2
+
3
+ const FORMAT_VERSION = 1
4
+ const NO_TICKS = 0
5
+ const FIRST_RUN = 0
6
+ const COUNT_FROM = 1 // runs are counted from 1 for people
7
+ const NONE = 0
8
+
9
+ /**
10
+ * Records a deterministic simulation as what was done to it, turn by turn, and plays
11
+ * a recording back.
12
+ *
13
+ * A simulation that turns in fixed steps, with all its randomness in its own state
14
+ * (see `createRng`), gives the same state again from the same start and the same
15
+ * inputs at the same turns. So a game need not be recorded as states, only as how
16
+ * each run started and what the player did: small enough to save as a file, and to
17
+ * watch again at any speed.
18
+ *
19
+ * A session is every run played since the recorder was made or reset, a run being
20
+ * one simulation from its start: `about` is whatever the game needs to create it
21
+ * again (a level, a seed), `inputs` maps a turn to what was done before it, and
22
+ * `ticks` and `fingerprint` (see `fingerprint`) are where it ended, so a replay can
23
+ * tell whether it reached the same state. A recording made before a rule changed no
24
+ * longer does, and is better reported than trusted.
25
+ *
26
+ * Keep the recorder outside the game's state: it grows all game long, and a store
27
+ * that copies state on every event would copy it too.
28
+ *
29
+ * @param {Object} [options]
30
+ * @param {string} [options.format] - What the recordings are, written in each session and checked by `isSession`.
31
+ * @param {string} [options.build] - Which build of the game made them, for whoever reads the file.
32
+ */
33
+ export function createRecorder({ format = "recording", build } = {}) {
34
+ let runs = []
35
+ let current = null
36
+ let replay = null
37
+
38
+ return {
39
+ /** Forgets every run and stops any replay. */
40
+ reset() {
41
+ runs = []
42
+ current = null
43
+ replay = null
44
+ },
45
+
46
+ /**
47
+ * Carries on `session`, saved earlier (by a page closed and opened again): its
48
+ * runs come before the ones recorded from now on.
49
+ */
50
+ resume(session) {
51
+ runs = [...session.runs, ...runs]
52
+ },
53
+
54
+ /** Starts recording a run, `about` being what it takes to start it again; not while replaying. */
55
+ open(about) {
56
+ if (replay) return
57
+ current = { about, inputs: {}, ticks: NO_TICKS, fingerprint: null }
58
+ },
59
+
60
+ /** Notes what was done before turn `tick` of the run being recorded; nothing is noted for nothing. */
61
+ record(tick, input) {
62
+ if (current && input != null) current.inputs[tick] = input
63
+ },
64
+
65
+ /** Ends the run being recorded at turn `tick`, in `state`; a run where no turn passed is dropped. */
66
+ close(tick, state) {
67
+ if (!current) return
68
+ if (tick > NO_TICKS) runs.push(ended(current, tick, state))
69
+ current = null
70
+ },
71
+
72
+ /** Every run so far, as plain data to save; the one being recorded ends at turn `tick`, in `state`. */
73
+ session(tick, state) {
74
+ const open =
75
+ current && tick > NO_TICKS ? [ended(current, tick, state)] : []
76
+ return {
77
+ format,
78
+ version: FORMAT_VERSION,
79
+ build,
80
+ recordedAt: new Date().toISOString(),
81
+ runs: [...runs, ...open],
82
+ }
83
+ },
84
+
85
+ /** Plays `session` back, returning its first run; nothing is recorded meanwhile. */
86
+ load(session) {
87
+ replay = { runs: session.runs, index: FIRST_RUN, diverged: NONE }
88
+ return replay.runs[FIRST_RUN]
89
+ },
90
+
91
+ /** The run being played back, or null. */
92
+ replayed() {
93
+ return replay?.runs[replay.index] ?? null
94
+ },
95
+
96
+ /** What was done before turn `tick` of the run being played back, if anything. */
97
+ input(tick) {
98
+ return replay?.runs[replay.index]?.inputs[tick]
99
+ },
100
+
101
+ /**
102
+ * The run being played back has reached its last turn, in `state`: counts it as
103
+ * diverged if that is not where it ended when recorded, and moves on to the next
104
+ * run, which it returns (null after the last).
105
+ */
106
+ finish(state) {
107
+ const run = replay.runs[replay.index]
108
+ if (run.fingerprint !== fingerprint(state)) replay.diverged += 1
109
+ replay.index += 1
110
+ return replay.runs[replay.index] ?? null
111
+ },
112
+
113
+ /** Where the replay is: its run, from 1, how many there are, and how many diverged; null when none. */
114
+ progress() {
115
+ if (!replay) return null
116
+ const { runs, index, diverged } = replay
117
+ return { run: index + COUNT_FROM, runs: runs.length, diverged }
118
+ },
119
+
120
+ /** Stops playing back; what comes next is recorded again. */
121
+ stop() {
122
+ replay = null
123
+ },
124
+ }
125
+ }
126
+
127
+ /**
128
+ * Whether `session` looks like one a recorder of `format` saved, with at least one
129
+ * run. Whether its runs make sense for the game (a level that exists) is the game's
130
+ * to check.
131
+ *
132
+ * @param {*} session - Anything, typically a parsed file.
133
+ * @param {string} [format] - The recorder's format.
134
+ * @returns {boolean}
135
+ */
136
+ export function isSession(session, format = "recording") {
137
+ return (
138
+ session?.format === format &&
139
+ session.version === FORMAT_VERSION &&
140
+ Array.isArray(session.runs) &&
141
+ session.runs.length > NONE &&
142
+ session.runs.every(
143
+ (run) =>
144
+ run?.ticks > NO_TICKS &&
145
+ Number.isInteger(run.ticks) &&
146
+ typeof run.inputs === "object" &&
147
+ run.inputs !== null,
148
+ )
149
+ )
150
+ }
151
+
152
+ function ended(run, ticks, state) {
153
+ return { ...run, ticks, fingerprint: fingerprint(state) }
154
+ }
@@ -0,0 +1,24 @@
1
+ import type { Vector3 } from "@inglorious/utils/vector.js"
2
+
3
+ import type { Decorator, Entity, Handler } from "../../index"
4
+
5
+ export interface SceneDragEntity extends Entity {
6
+ /** Where the pointer is; null once a finger lifts. */
7
+ pointer?: Vector3 | null
8
+ /** Whether a drag is under way. */
9
+ dragging?: boolean
10
+ }
11
+
12
+ /**
13
+ * Dragging across the scene with a mouse or the first finger; each move while
14
+ * dragging calls the type's `sceneDrag(entity, { from, to }, api)`.
15
+ */
16
+ export function sceneDrag(): Decorator<{
17
+ create: Handler<SceneDragEntity, unknown>
18
+ scenePress: Handler<SceneDragEntity, Vector3>
19
+ mouseMove: Handler<SceneDragEntity, Vector3>
20
+ mouseUp: Handler<SceneDragEntity, Vector3>
21
+ sceneTouchStart: Handler<SceneDragEntity, Vector3>
22
+ touchMove: Handler<SceneDragEntity, { index: number; position: Vector3 }>
23
+ touchEnd: Handler<SceneDragEntity, { index: number }>
24
+ }>
@@ -1,8 +1,4 @@
1
- import type {
2
- RecordedSession,
3
- ReplayProgress,
4
- } from "@inglorious/utils/data-structures/recorder"
5
-
1
+ import type { RecordedSession, ReplayProgress } from "../core/recorder"
6
2
  import type { Decorator, Entity, Handler } from "../index"
7
3
 
8
4
  export interface RecordedEntity extends Entity {
@@ -35,6 +31,8 @@ export interface RecordedOptions<
35
31
  build?: string
36
32
  /** The start of a saved file's name. */
37
33
  name?: string
34
+ /** Where to keep the session in local storage, carried on when the page opens again. */
35
+ storageKey?: string
38
36
  }
39
37
 
40
38
  /**
@@ -0,0 +1,20 @@
1
+ /** The last segment of the address's path, "" at the root. */
2
+ export function pageInAddress(): string
3
+
4
+ /** The value under `key` in the query, if it is one of `choices`, else `fallback`. */
5
+ export function choiceInAddress<T extends string>(
6
+ key: string,
7
+ choices: readonly T[],
8
+ fallback: T,
9
+ ): T
10
+
11
+ /** The whole number above zero under `key` in the query, else `fallback`. */
12
+ export function countInAddress(key: string, fallback: number): number
13
+
14
+ /** Notes `values` in the query, without reloading or adding to the history. */
15
+ export function noteInAddress(
16
+ values: Record<string, string | number | boolean>,
17
+ ): void
18
+
19
+ /** Notes `page` as the path's last segment, only in place of the root or one of `pages`. */
20
+ export function notePageInAddress(page: string, pages: readonly string[]): void
@@ -0,0 +1,50 @@
1
+ /** One run: how it started, what was done at each turn, and where it ended. */
2
+ export interface RecordedRun<About = unknown, Input = unknown> {
3
+ about: About
4
+ inputs: Record<number, Input>
5
+ ticks: number
6
+ fingerprint: number
7
+ }
8
+
9
+ /** Every run of a session, as saved. */
10
+ export interface RecordedSession<About = unknown, Input = unknown> {
11
+ format: string
12
+ version: number
13
+ build?: string
14
+ recordedAt: string
15
+ runs: RecordedRun<About, Input>[]
16
+ }
17
+
18
+ /** Where a replay is: its run, from 1, how many there are, how many diverged. */
19
+ export interface ReplayProgress {
20
+ run: number
21
+ runs: number
22
+ diverged: number
23
+ }
24
+
25
+ export interface Recorder<About = unknown, Input = unknown> {
26
+ reset(): void
27
+ resume(session: RecordedSession<About, Input>): void
28
+ open(about: About): void
29
+ record(tick: number, input: Input | null | undefined): void
30
+ close(tick: number, state: unknown): void
31
+ session(tick: number, state: unknown): RecordedSession<About, Input>
32
+ load(session: RecordedSession<About, Input>): RecordedRun<About, Input>
33
+ replayed(): RecordedRun<About, Input> | null
34
+ input(tick: number): Input | undefined
35
+ finish(state: unknown): RecordedRun<About, Input> | null
36
+ progress(): ReplayProgress | null
37
+ stop(): void
38
+ }
39
+
40
+ /** Records a deterministic simulation as its inputs by turn, and plays a recording back. */
41
+ export function createRecorder<About = unknown, Input = unknown>(options?: {
42
+ format?: string
43
+ build?: string
44
+ }): Recorder<About, Input>
45
+
46
+ /** Whether a value looks like a session a recorder of `format` saved. */
47
+ export function isSession(
48
+ session: unknown,
49
+ format?: string,
50
+ ): session is RecordedSession