@wasm-gaming/rsdkv4-wasm 0.1.4 → 0.2.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 +242 -35
- package/dist/rsdkv4/rsdkv4.options.d.ts +355 -16
- package/dist/rsdkv4/rsdkv4.options.d.ts.map +1 -1
- package/dist/rsdkv4/rsdkv4.options.js +170 -31
- package/dist/rsdkv4/rsdkv4.options.js.map +1 -1
- package/dist/rsdkv4/rsdkv4.sdk.d.ts +229 -33
- package/dist/rsdkv4/rsdkv4.sdk.d.ts.map +1 -1
- package/dist/rsdkv4/rsdkv4.sdk.js +1015 -172
- package/dist/rsdkv4/rsdkv4.sdk.js.map +1 -1
- package/package.json +7 -12
- package/src/rsdkv4.options.ts +484 -46
- package/src/rsdkv4.sdk.ts +1282 -192
- package/dist/manifest.json +0 -75
- package/dist/rsdkv4/rsdkv4.js +0 -9268
- package/dist/rsdkv4/rsdkv4.manifest.d.ts +0 -4
- package/dist/rsdkv4/rsdkv4.manifest.d.ts.map +0 -1
- package/dist/rsdkv4/rsdkv4.manifest.js +0 -39
- package/dist/rsdkv4/rsdkv4.manifest.js.map +0 -1
- package/dist/rsdkv4/rsdkv4.wasm +0 -0
- package/src/rsdkv4.manifest.ts +0 -44
package/src/rsdkv4.sdk.ts
CHANGED
|
@@ -1,44 +1,139 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
1
|
+
/**
|
|
2
|
+
* The engine package's entry point: an `EngineSDK` for RSDKv4.
|
|
3
|
+
*
|
|
4
|
+
* ```ts
|
|
5
|
+
* import Rsdkv4SDK from '@wasm-gaming/rsdkv4-wasm';
|
|
6
|
+
*
|
|
7
|
+
* const play = await new Rsdkv4SDK()
|
|
8
|
+
* .mount(document.querySelector('#stage'))
|
|
9
|
+
* .assets({ data: () => library.readBytes('Sonic2') })
|
|
10
|
+
* .storage({ namespace: 'rsdkv4/Sonic2' })
|
|
11
|
+
* .config({ startMenu: 'host' })
|
|
12
|
+
* .on('saves', ({ detail }) => paintSlots(detail))
|
|
13
|
+
* .start({ slot: 0 });
|
|
14
|
+
* ```
|
|
15
|
+
*
|
|
16
|
+
* Everything a host drives is the contract's, and documented there: the four payloads
|
|
17
|
+
* with their descriptors, `mount`, `on`/`off`, `start`, `restart`, `destroy`. What is
|
|
18
|
+
* this engine's own lives in two places — {@link Rsdkv4Config} and friends, which say
|
|
19
|
+
* what the payloads accept *here*, and the extra members of {@link Rsdkv4Play} below:
|
|
20
|
+
* {@link Rsdkv4Play.game} and {@link Rsdkv4Play.devMenu}, for a host that draws
|
|
21
|
+
* RSDKv4's start screens itself, owner-aware {@link Rsdkv4Play.pause}, and
|
|
22
|
+
* {@link Rsdkv4Play.input}, for a host that would rather drive the buttons than let
|
|
23
|
+
* the engine read the keyboard.
|
|
24
|
+
*
|
|
25
|
+
* One game-agnostic `rsdkv4.wasm` runs both Sonic 1 and Sonic 2 — the difference is
|
|
26
|
+
* only which `Data.rsdk` the host hands over in `assets.data`, written into the
|
|
27
|
+
* filesystem at runtime (not baked with `--preload-file`).
|
|
28
|
+
*
|
|
29
|
+
* Filesystem: built with `-sWASMFS`. The working dir is mounted on **OPFS** when the
|
|
30
|
+
* page is cross-origin isolated *and* the build can create the OPFS backend from the
|
|
31
|
+
* main thread (an Asyncify/JSPI build — today's is not, see `WebFS.cpp`); otherwise it
|
|
32
|
+
* falls back to the WASMFS in-memory backend, which boots fine but forgets everything.
|
|
33
|
+
* That fallback is why the SDK mirrors `SData.bin` into OPFS itself: see
|
|
34
|
+
* {@link Rsdkv4Storage.persist}.
|
|
35
|
+
*
|
|
36
|
+
* @module
|
|
37
|
+
* @see [The engine contract](https://wasm-gaming.github.io/engine-specs/api-docs/)
|
|
38
|
+
*/
|
|
39
|
+
|
|
40
|
+
import { EnginePlayBase, EngineSDKBase, EventEmitter } from '@wasm-gaming/engine-specs';
|
|
41
|
+
import type {
|
|
42
|
+
EngineInit,
|
|
43
|
+
EngineSDKConstructor,
|
|
44
|
+
EventsOf,
|
|
45
|
+
PayloadKind,
|
|
46
|
+
PromisePlay,
|
|
47
|
+
PropertiesDefinition,
|
|
48
|
+
PropertyDefinition,
|
|
49
|
+
} from '@wasm-gaming/engine-specs';
|
|
50
|
+
import {
|
|
51
|
+
RSDKV4_BUTTONS,
|
|
52
|
+
RSDKV4_SPEC,
|
|
53
|
+
type Rsdkv4Asset,
|
|
54
|
+
type Rsdkv4AssetData,
|
|
55
|
+
type Rsdkv4Assets,
|
|
56
|
+
type Rsdkv4Buttons,
|
|
57
|
+
type Rsdkv4Config,
|
|
58
|
+
type Rsdkv4Options,
|
|
59
|
+
type Rsdkv4Payloads,
|
|
60
|
+
type Rsdkv4Stage,
|
|
61
|
+
type Rsdkv4Storage,
|
|
62
|
+
type RsdkSaveSlot,
|
|
63
|
+
} from './rsdkv4.options.js';
|
|
64
|
+
|
|
65
|
+
export type {
|
|
66
|
+
Rsdkv4Asset,
|
|
67
|
+
Rsdkv4AssetData,
|
|
68
|
+
Rsdkv4Assets,
|
|
69
|
+
Rsdkv4Button,
|
|
70
|
+
Rsdkv4Buttons,
|
|
71
|
+
Rsdkv4Config,
|
|
72
|
+
Rsdkv4Events,
|
|
73
|
+
Rsdkv4InputDefaults,
|
|
74
|
+
Rsdkv4Options,
|
|
75
|
+
Rsdkv4Payloads,
|
|
76
|
+
Rsdkv4Stage,
|
|
77
|
+
Rsdkv4Storage,
|
|
78
|
+
RsdkSaveSlot,
|
|
79
|
+
} from './rsdkv4.options.js';
|
|
80
|
+
export { RSDKV4_BUTTONS, RSDKV4_INPUT, RSDKV4_SPEC } from './rsdkv4.options.js';
|
|
81
|
+
|
|
82
|
+
/** The core events unioned with this engine's own — what `on`/`off` accept. */
|
|
83
|
+
export type Rsdkv4Events_ = EventsOf<Rsdkv4Payloads>;
|
|
22
84
|
|
|
23
85
|
const WORK_ROOT = '/data';
|
|
24
86
|
const DEFAULT_STORAGE_NAMESPACE = 'default';
|
|
25
87
|
|
|
26
|
-
/**
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
}
|
|
88
|
+
/** RSDKv4's save file, written next to the game data in the working dir. */
|
|
89
|
+
const SAVE_FILE = 'SData.bin';
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Emscripten's SDL2 port locates the canvas via `document.querySelector('#canvas')`,
|
|
93
|
+
* so the element the game draws into has to carry this id.
|
|
94
|
+
*/
|
|
95
|
+
const CANVAS_ID = 'canvas';
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* The picture's native size, which is what the SDK scales to fit its mount.
|
|
99
|
+
*
|
|
100
|
+
* A module constant rather than a manifest field: `EngineManifest` left the contract
|
|
101
|
+
* in 0.3.0, and this was one of only two things the SDK ever read back out of it.
|
|
102
|
+
*/
|
|
103
|
+
export const RSDKV4_VIDEO = { baseWidth: 424, baseHeight: 240, aspect: '16:9' } as const;
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* The embind bridges this SDK drives the engine through. All of them ship in the same
|
|
107
|
+
* rsdkv4.wasm, so a module missing any one of them is an artifact older than this SDK
|
|
108
|
+
* rather than a build variant.
|
|
109
|
+
*/
|
|
110
|
+
const ENGINE_BRIDGES = [
|
|
111
|
+
'web_engine_ready',
|
|
112
|
+
'web_game_type',
|
|
113
|
+
'web_get_players',
|
|
114
|
+
'web_get_save_slots',
|
|
115
|
+
'web_get_game_options',
|
|
116
|
+
'web_start_game',
|
|
117
|
+
'web_audio_stop',
|
|
118
|
+
'web_devmenu_get_stage_list',
|
|
119
|
+
'web_input_set_source',
|
|
120
|
+
] as const;
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* The name the engine's `web_input_pull()` looks the reader up under, on the module
|
|
124
|
+
* object itself rather than on a global: two engines on one page have two modules,
|
|
125
|
+
* and a global would have them fighting over one claim.
|
|
126
|
+
*/
|
|
127
|
+
const INPUT_PULL_HOOK = '__rsdkv4_input_pull';
|
|
128
|
+
|
|
129
|
+
/** How often a pull that keeps throwing is allowed to say so. See {@link Rsdkv4Play}. */
|
|
130
|
+
const INPUT_ERROR_INTERVAL_MS = 1000;
|
|
131
|
+
|
|
132
|
+
/** The Emscripten module. Untyped on purpose: it is generated glue, not our surface. */
|
|
133
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
134
|
+
type EmscriptenModule = any;
|
|
135
|
+
|
|
136
|
+
// ---------------------------------------------------------------- small helpers
|
|
42
137
|
|
|
43
138
|
function toUint8(x: unknown): Uint8Array | null {
|
|
44
139
|
if (x == null) return null;
|
|
@@ -46,10 +141,16 @@ function toUint8(x: unknown): Uint8Array | null {
|
|
|
46
141
|
if (x instanceof Uint8Array) return x;
|
|
47
142
|
if (x instanceof ArrayBuffer) return new Uint8Array(x);
|
|
48
143
|
if (ArrayBuffer.isView(x)) return new Uint8Array(x.buffer, x.byteOffset, x.byteLength);
|
|
49
|
-
throw new TypeError('asset must be Uint8Array | ArrayBuffer | string');
|
|
144
|
+
throw new TypeError('rsdkv4: an asset must be Uint8Array | ArrayBuffer | string');
|
|
50
145
|
}
|
|
51
146
|
|
|
52
|
-
/**
|
|
147
|
+
/** Bytes for an asset, calling the thunk form only when we get this far. */
|
|
148
|
+
async function resolveAsset(asset: Rsdkv4Asset | undefined): Promise<Uint8Array | null> {
|
|
149
|
+
if (asset == null) return null;
|
|
150
|
+
return toUint8(typeof asset === 'function' ? await asset() : asset);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** Normalize a host-provided storage namespace into a safe relative path. */
|
|
53
154
|
function normalizeStorageNamespace(namespace: unknown): string {
|
|
54
155
|
if (typeof namespace !== 'string' || !namespace.trim()) return DEFAULT_STORAGE_NAMESPACE;
|
|
55
156
|
|
|
@@ -64,8 +165,55 @@ function normalizeStorageNamespace(namespace: unknown): string {
|
|
|
64
165
|
return cleaned || DEFAULT_STORAGE_NAMESPACE;
|
|
65
166
|
}
|
|
66
167
|
|
|
168
|
+
/** The plain values behind a descriptor table — what the engine actually needs. */
|
|
169
|
+
function valuesOf<T>(described: PropertiesDefinition<T>): T {
|
|
170
|
+
const out: Record<string, unknown> = {};
|
|
171
|
+
for (const [key, property] of Object.entries(
|
|
172
|
+
described as Record<string, PropertyDefinition<unknown>>,
|
|
173
|
+
)) {
|
|
174
|
+
out[key] = property.value;
|
|
175
|
+
}
|
|
176
|
+
return out as T;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Serialize {@link Rsdkv4Config} into RSDKv4's settings.ini format.
|
|
181
|
+
*
|
|
182
|
+
* The `Starting*` trio is written as 255 — the engine's "unset" — and never anything
|
|
183
|
+
* else. That is not a leftover: anything else there, **including 0**, makes
|
|
184
|
+
* `Engine::Init` skip its normal boot flow and force a stage (see Userdata.cpp). The
|
|
185
|
+
* session's own `stage` is applied after boot instead, through the engine's stage
|
|
186
|
+
* loader, which is why it survives a `restart()`.
|
|
187
|
+
*/
|
|
188
|
+
function buildSettingsIni(config: Rsdkv4Config): string {
|
|
189
|
+
return [
|
|
190
|
+
'[Dev]',
|
|
191
|
+
`EngineDebugMode=${config.engineDebugMode ? 'true' : 'false'}`,
|
|
192
|
+
`DevMenu=${config.devMenu ? 'true' : 'false'}`,
|
|
193
|
+
'StartingCategory=255',
|
|
194
|
+
'StartingScene=255',
|
|
195
|
+
'StartingPlayer=255',
|
|
196
|
+
'',
|
|
197
|
+
'[Game]',
|
|
198
|
+
`SkipStartMenu=${config.startMenu === 'host' ? 'true' : 'false'}`,
|
|
199
|
+
'',
|
|
200
|
+
'[Window]',
|
|
201
|
+
`VSync=${config.vsync ? 'true' : 'false'}`,
|
|
202
|
+
'',
|
|
203
|
+
].join('\n');
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function sameBytes(a: Uint8Array | null, b: Uint8Array | null): boolean {
|
|
207
|
+
if (a === null || b === null) return a === b;
|
|
208
|
+
if (a.length !== b.length) return false;
|
|
209
|
+
for (let i = 0; i < a.length; i += 1) if (a[i] !== b[i]) return false;
|
|
210
|
+
return true;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// ---------------------------------------------------------------- the wasm filesystem
|
|
214
|
+
|
|
67
215
|
/** Best-effort mkdir -p for the Emscripten FS layer. */
|
|
68
|
-
function ensureDir(Module:
|
|
216
|
+
function ensureDir(Module: EmscriptenModule, path: string): void {
|
|
69
217
|
const parts = path.split('/').filter(Boolean);
|
|
70
218
|
let current = '';
|
|
71
219
|
for (const part of parts) {
|
|
@@ -78,217 +226,1159 @@ function ensureDir(Module: any, path: string): void {
|
|
|
78
226
|
}
|
|
79
227
|
}
|
|
80
228
|
|
|
229
|
+
/** True if `path` exists in the (mounted) filesystem. */
|
|
230
|
+
function fileExists(Module: EmscriptenModule, path: string): boolean {
|
|
231
|
+
try {
|
|
232
|
+
Module.FS.stat(path);
|
|
233
|
+
return true;
|
|
234
|
+
} catch {
|
|
235
|
+
return false;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
81
239
|
/**
|
|
82
|
-
*
|
|
83
|
-
* 'opfs' → force an OPFS (persistent) mount; warn + fall back if unavailable.
|
|
84
|
-
* null → force the in-memory WASMFS backend (the MEMFS-equivalent fallback).
|
|
85
|
-
* undefined → auto: OPFS when the page is cross-origin isolated, else in-memory.
|
|
86
|
-
* ('idbfs' isn't supported under WASMFS and is treated as in-memory.)
|
|
240
|
+
* Whether this build can mount OPFS at all, asked of the wasm itself.
|
|
87
241
|
*
|
|
88
|
-
*
|
|
89
|
-
*
|
|
90
|
-
*
|
|
242
|
+
* WASMFS's `wasmfs_create_opfs_backend()` spawns a proxy worker synchronously, which it
|
|
243
|
+
* refuses to do on the main browser thread without Asyncify/JSPI — it *asserts*, and a
|
|
244
|
+
* failed assert calls `abort()`, which tears the module down for good. That is past the
|
|
245
|
+
* point where a try/catch around the call can save us, so we have to know before
|
|
246
|
+
* calling. `web_opfs_supported` (WebFS.cpp) mirrors the same condition; builds predating
|
|
247
|
+
* that helper simply answer "no".
|
|
91
248
|
*/
|
|
92
|
-
function
|
|
249
|
+
function opfsMountSupported(Module: EmscriptenModule): boolean {
|
|
250
|
+
const probe = Module._web_opfs_supported;
|
|
251
|
+
if (typeof probe !== 'function') return false;
|
|
252
|
+
try {
|
|
253
|
+
return probe() !== 0;
|
|
254
|
+
} catch {
|
|
255
|
+
return false;
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* Mount the game working dir, honouring {@link Rsdkv4Storage.persist}. Returns whether
|
|
261
|
+
* the resulting mount is persistent.
|
|
262
|
+
*
|
|
263
|
+
* Cross-origin isolation is necessary but not sufficient: the mount also needs a build
|
|
264
|
+
* whose OPFS backend can run from where we call it (see {@link opfsMountSupported}), so
|
|
265
|
+
* both gates apply before we touch `web_mount_opfs`.
|
|
266
|
+
*/
|
|
267
|
+
function mountWorkingDir(
|
|
268
|
+
Module: EmscriptenModule,
|
|
269
|
+
persist: Rsdkv4Storage['persist'],
|
|
270
|
+
): { persistent: boolean } {
|
|
93
271
|
const isolated = typeof crossOriginIsolated !== 'undefined' && crossOriginIsolated;
|
|
94
|
-
const
|
|
272
|
+
const wantsOpfs = persist === 'opfs' || (persist === undefined && isolated);
|
|
95
273
|
|
|
96
|
-
if (
|
|
274
|
+
if (wantsOpfs && typeof Module.ccall === 'function' && opfsMountSupported(Module)) {
|
|
97
275
|
try {
|
|
98
276
|
const rc = Module.ccall('web_mount_opfs', 'number', ['string'], [WORK_ROOT]);
|
|
99
277
|
if (rc === 0) return { persistent: true };
|
|
100
278
|
} catch {
|
|
101
279
|
/* fall through to in-memory */
|
|
102
280
|
}
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
281
|
+
}
|
|
282
|
+
if (persist === 'opfs') {
|
|
283
|
+
console.warn(
|
|
284
|
+
'[rsdkv4] OPFS requested but unavailable (needs a cross-origin isolated page and an Asyncify/JSPI build) — using in-memory WASMFS',
|
|
285
|
+
);
|
|
106
286
|
}
|
|
107
287
|
ensureDir(Module, WORK_ROOT);
|
|
108
288
|
return { persistent: false };
|
|
109
289
|
}
|
|
110
290
|
|
|
111
|
-
/**
|
|
112
|
-
|
|
291
|
+
/**
|
|
292
|
+
* OPFS handle for `<namespace>/`, reached with the plain (async) OPFS API from JS —
|
|
293
|
+
* which, unlike the WASM side's sync access handles, works on the main thread of any
|
|
294
|
+
* page. Returns null when OPFS isn't available at all.
|
|
295
|
+
*/
|
|
296
|
+
async function opfsNamespaceDir(
|
|
297
|
+
namespace: string,
|
|
298
|
+
create: boolean,
|
|
299
|
+
): Promise<FileSystemDirectoryHandle | null> {
|
|
300
|
+
if (typeof navigator === 'undefined' || !navigator.storage?.getDirectory) return null;
|
|
113
301
|
try {
|
|
114
|
-
|
|
115
|
-
|
|
302
|
+
let dir = await navigator.storage.getDirectory();
|
|
303
|
+
for (const segment of namespace.split('/').filter(Boolean)) {
|
|
304
|
+
dir = await dir.getDirectoryHandle(segment, { create });
|
|
305
|
+
}
|
|
306
|
+
return dir;
|
|
116
307
|
} catch {
|
|
117
|
-
return false
|
|
308
|
+
return null; // missing (create: false), or blocked
|
|
118
309
|
}
|
|
119
310
|
}
|
|
120
311
|
|
|
121
|
-
/**
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
312
|
+
/**
|
|
313
|
+
* Wait for `Engine::Init`, which runs on the engine's first frame (main.cpp's
|
|
314
|
+
* main_loop), not inside `callMain`. Gives up after ~4s rather than hanging the host:
|
|
315
|
+
* everything still works, the first read just comes back empty.
|
|
316
|
+
*/
|
|
317
|
+
async function waitForEngine(Module: EmscriptenModule, timeoutMs = 4000): Promise<boolean> {
|
|
318
|
+
if (typeof Module.web_engine_ready !== 'function') return false;
|
|
319
|
+
const deadline = Date.now() + timeoutMs;
|
|
320
|
+
while (Date.now() < deadline) {
|
|
321
|
+
if (Module.web_engine_ready()) return true;
|
|
322
|
+
await new Promise((resolve) => requestAnimationFrame(resolve));
|
|
129
323
|
}
|
|
324
|
+
console.warn('[rsdkv4] engine did not report ready within %dms', timeoutMs);
|
|
325
|
+
return false;
|
|
130
326
|
}
|
|
131
327
|
|
|
132
|
-
|
|
328
|
+
function engineBridgeComplete(Module: EmscriptenModule): boolean {
|
|
329
|
+
return ENGINE_BRIDGES.every((name) => typeof Module?.[name] === 'function');
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
// ---------------------------------------------------------------- this engine's own surface
|
|
333
|
+
|
|
334
|
+
/** RSDKv4-specific bridge for a host's debug/stage-select UI. */
|
|
133
335
|
export interface RsdkDevMenuBridge {
|
|
134
336
|
getStageList(): Array<{ name: string; stages: Array<{ name: string }> }>;
|
|
135
337
|
loadStage(categoryIdx: number, stageIdx: number): void;
|
|
136
338
|
setPaused(paused: boolean): void;
|
|
137
339
|
}
|
|
138
340
|
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
341
|
+
/**
|
|
342
|
+
* A row of the engine's GAME OPTIONS screen (differs between Sonic 1 and 2), as the
|
|
343
|
+
* engine reports it — with `value` as the raw number it stores.
|
|
344
|
+
*
|
|
345
|
+
* The same rows also come back through `play.options()` as descriptors, where a
|
|
346
|
+
* boolean row reads as a boolean and an enum row as one of its choice labels. This is
|
|
347
|
+
* the untranslated view, for a host that wants it.
|
|
348
|
+
*/
|
|
349
|
+
export interface RsdkGameOption {
|
|
350
|
+
key: string;
|
|
351
|
+
label: string;
|
|
352
|
+
value: number;
|
|
353
|
+
type: 'boolean' | 'enum';
|
|
354
|
+
/** Choice labels, for `type: 'enum'` (item box sets). */
|
|
355
|
+
values?: string[];
|
|
356
|
+
}
|
|
148
357
|
|
|
149
358
|
/**
|
|
150
|
-
*
|
|
151
|
-
*
|
|
152
|
-
*
|
|
359
|
+
* The engine's Start Menu as data, so a host can render save-slot / character /
|
|
360
|
+
* game-option screens itself. Everything here mirrors what RSDKv4's own in-canvas menu
|
|
361
|
+
* does — see WebGame.cpp.
|
|
153
362
|
*/
|
|
154
|
-
export
|
|
155
|
-
|
|
156
|
-
|
|
363
|
+
export interface RsdkGameBridge {
|
|
364
|
+
/** 1 = Sonic 1, 2 = Sonic 2, 0 = unrecognised pack. */
|
|
365
|
+
type(): number;
|
|
366
|
+
/** Playable characters from the pack's GameConfig, in engine order. */
|
|
367
|
+
players(): string[];
|
|
368
|
+
saveSlots(): RsdkSaveSlot[];
|
|
157
369
|
/**
|
|
158
|
-
*
|
|
159
|
-
*
|
|
370
|
+
* Start a game the way the native menu would: a slot with data continues it, an
|
|
371
|
+
* empty slot starts a new game as `player`, and `slot: null` plays without saving.
|
|
372
|
+
* Resumes the engine if the SDK had it paused.
|
|
373
|
+
*
|
|
374
|
+
* This is the index-taking form. `play.restart({ slot, player })` is the same thing
|
|
375
|
+
* through the contract, with the character named rather than numbered.
|
|
160
376
|
*/
|
|
161
|
-
|
|
162
|
-
|
|
377
|
+
start(slot: number | null, player?: number): void;
|
|
378
|
+
/** Wipe a slot back to "NEW GAME". */
|
|
379
|
+
deleteSave(slot: number): void;
|
|
380
|
+
options(): RsdkGameOption[];
|
|
381
|
+
/** Set an option; written through to the engine and its save file, as the engine does. */
|
|
382
|
+
setOption(key: string, value: number): void;
|
|
383
|
+
}
|
|
163
384
|
|
|
164
|
-
/**
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
385
|
+
/**
|
|
386
|
+
* Input ownership, named — the same thing as `options({ buttons })` and
|
|
387
|
+
* `options({ buttons: null })`, for a host that would rather say what it means.
|
|
388
|
+
*
|
|
389
|
+
* See {@link Rsdkv4Options.buttons} for what a claim costs the host: keyup on focus
|
|
390
|
+
* loss, the gamepad, and remembering to release.
|
|
391
|
+
*/
|
|
392
|
+
export interface RsdkInputBridge {
|
|
393
|
+
/**
|
|
394
|
+
* Take input over. The object is kept by reference and read once per tick — write
|
|
395
|
+
* to it, do not replace it.
|
|
396
|
+
*
|
|
397
|
+
* All fourteen keys of {@link Rsdkv4Buttons} must be present and nothing else may
|
|
398
|
+
* be: a missing key would read `false` for ever, and a misspelled one would be
|
|
399
|
+
* written to and never read. Both throw here instead.
|
|
400
|
+
*/
|
|
401
|
+
claim(buttons: Rsdkv4Buttons): PromisePlay<Rsdkv4Payloads>;
|
|
402
|
+
/** Hand input back; the engine polls SDL again from the next tick. */
|
|
403
|
+
release(): PromisePlay<Rsdkv4Payloads>;
|
|
404
|
+
/** Whether a claim is held. The `options()` descriptor deliberately will not say. */
|
|
405
|
+
readonly claimed: boolean;
|
|
406
|
+
}
|
|
169
407
|
|
|
170
|
-
|
|
171
|
-
|
|
408
|
+
/**
|
|
409
|
+
* What `start()` and `restart()` hand back: the contract's chainable promise, narrowed
|
|
410
|
+
* so that awaiting it gives this engine's {@link Rsdkv4Play} rather than the contract's
|
|
411
|
+
* `EnginePlay` — which is what puts {@link Rsdkv4Play.game} within reach without a cast.
|
|
412
|
+
*
|
|
413
|
+
* Chaining (`.mount(…)`, `.options(…)`) returns the contract's own `PromisePlay`, so
|
|
414
|
+
* put the `await` at the end of the chain to keep the narrowing.
|
|
415
|
+
*/
|
|
416
|
+
export interface Rsdkv4Session extends PromisePlay<Rsdkv4Payloads> {
|
|
417
|
+
then<TResult1 = Rsdkv4Play, TResult2 = never>(
|
|
418
|
+
onfulfilled?: ((value: Rsdkv4Play) => TResult1 | PromiseLike<TResult1>) | null,
|
|
419
|
+
onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null,
|
|
420
|
+
): Promise<TResult1 | TResult2>;
|
|
421
|
+
}
|
|
172
422
|
|
|
173
|
-
|
|
174
|
-
try { onEvent?.(e); } catch { /* host handler must not break us */ }
|
|
175
|
-
};
|
|
423
|
+
// ---------------------------------------------------------------- the live engine
|
|
176
424
|
|
|
177
|
-
|
|
178
|
-
|
|
425
|
+
/**
|
|
426
|
+
* The running engine.
|
|
427
|
+
*
|
|
428
|
+
* Most of it is the contract's, inherited: the four getter/setter pairs, the cumulative
|
|
429
|
+
* merge, the chainable promise, the event channel, and `destroy()`. What this class
|
|
430
|
+
* adds is the four hooks the base leaves to an engine — {@link open}, {@link close},
|
|
431
|
+
* {@link mounted}, {@link patched} — plus the members below, which have no contract
|
|
432
|
+
* equivalent and exist because RSDKv4 has a start menu worth drawing from HTML.
|
|
433
|
+
*/
|
|
434
|
+
export class Rsdkv4Play extends EnginePlayBase<Rsdkv4Payloads> {
|
|
435
|
+
#module: EmscriptenModule | null = null;
|
|
436
|
+
/** In flight, so two concurrent `restart()`s do not boot two engines. */
|
|
437
|
+
#booting: Promise<EmscriptenModule> | null = null;
|
|
438
|
+
#destroyed = false;
|
|
179
439
|
|
|
180
|
-
|
|
181
|
-
|
|
440
|
+
#canvas: HTMLCanvasElement | null = null;
|
|
441
|
+
/** False when the host handed us its own canvas: then we neither size nor remove it. */
|
|
442
|
+
#ownsCanvas = false;
|
|
443
|
+
/** The element the picture has to fit inside, in CSS pixels. */
|
|
444
|
+
#box: HTMLElement | null = null;
|
|
445
|
+
#boxObserver: ResizeObserver | null = null;
|
|
182
446
|
|
|
183
|
-
|
|
184
|
-
|
|
447
|
+
#persistent = false;
|
|
448
|
+
#namespace = DEFAULT_STORAGE_NAMESPACE;
|
|
449
|
+
#workDir = `${WORK_ROOT}/${DEFAULT_STORAGE_NAMESPACE}`;
|
|
450
|
+
#mirrorSaves = true;
|
|
451
|
+
#saveTimer: ReturnType<typeof setInterval> | null = null;
|
|
452
|
+
/** Last bytes mirrored out, so the `saves` event means "changed" and not "checked". */
|
|
453
|
+
#lastSave: Uint8Array | null = null;
|
|
185
454
|
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
455
|
+
/**
|
|
456
|
+
* Pause state, with an owner.
|
|
457
|
+
*
|
|
458
|
+
* `masterPaused` only freezes the logic loop — the audio callback keeps mixing, so a
|
|
459
|
+
* paused engine went on playing its music behind whatever the host put on top.
|
|
460
|
+
* Pausing therefore has to stop the sound too.
|
|
461
|
+
*
|
|
462
|
+
* The owner matters because pause/resume has several callers: a pause overlay, a
|
|
463
|
+
* start screen, the host itself. Closing an overlay must not resume a game something
|
|
464
|
+
* else had already frozen, so the *first* pause claims ownership and only that
|
|
465
|
+
* owner's `resume()` lifts it.
|
|
466
|
+
*/
|
|
467
|
+
#pauseOwner: string | null = null;
|
|
468
|
+
|
|
469
|
+
/**
|
|
470
|
+
* The host's button object while it holds a claim, by reference — read on the
|
|
471
|
+
* engine's callback, never copied.
|
|
472
|
+
*/
|
|
473
|
+
#buttons: Rsdkv4Buttons | null = null;
|
|
474
|
+
/** The reader handed to the engine, kept so the same function can be uninstalled. */
|
|
475
|
+
#pull: (() => number) | null = null;
|
|
476
|
+
/** Throttle state for a pull that throws. See {@link Rsdkv4Play.#readButtons}. */
|
|
477
|
+
#pullErrorKey: string | null = null;
|
|
478
|
+
#pullErrorAt = 0;
|
|
479
|
+
#pullErrors = 0;
|
|
195
480
|
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
481
|
+
constructor(init?: EngineInit<Rsdkv4Payloads>, events?: EventEmitter<Rsdkv4Events_>) {
|
|
482
|
+
// The spec goes up rather than being declared as a field: a subclass field
|
|
483
|
+
// initialiser runs after `super()`, which would be too late for the base to seed
|
|
484
|
+
// state from it.
|
|
485
|
+
super(RSDKV4_SPEC, init, events);
|
|
486
|
+
}
|
|
202
487
|
|
|
203
|
-
|
|
204
|
-
const settingsPath = `${workDir}/settings.ini`;
|
|
488
|
+
// ---- The hooks the contract's base class leaves to an engine ----
|
|
205
489
|
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
490
|
+
/**
|
|
491
|
+
* Open or reopen a session. The first call brings the wasm up; every call after that
|
|
492
|
+
* reuses it, because RSDKv4 cannot power-cycle in process and does not need to — a
|
|
493
|
+
* session is a save slot, a character and a stage, and all three are reachable on a
|
|
494
|
+
* running engine.
|
|
495
|
+
*/
|
|
496
|
+
protected override async open(options: Rsdkv4Options): Promise<void> {
|
|
497
|
+
await this.#ensureBooted();
|
|
498
|
+
|
|
499
|
+
// Re-applied from the merged state rather than from a patch, which is what makes a
|
|
500
|
+
// claim survive `restart()`: the engine's own input source was just reset by the
|
|
501
|
+
// boot (or never set, on a reopen), and the host's object is still the one it was.
|
|
502
|
+
if (options.buttons !== undefined) this.#applyButtons(options.buttons);
|
|
503
|
+
|
|
504
|
+
// Absence is "boot the way the engine normally would", so an empty options bag
|
|
505
|
+
// leaves the engine wherever it came up — its own start menu, usually.
|
|
506
|
+
if (options.player !== undefined || options.slot !== undefined) {
|
|
507
|
+
this.game.start(options.slot ?? null, this.#playerIndex(options.player));
|
|
508
|
+
}
|
|
509
|
+
if (options.stage) {
|
|
510
|
+
this.devMenu.loadStage(options.stage.category | 0, options.stage.scene | 0);
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
/**
|
|
515
|
+
* Stop and release. The base emits `exit` once this resolves.
|
|
516
|
+
*
|
|
517
|
+
* There is no coming back: RSDKv4 cannot be restarted in process, so a later
|
|
518
|
+
* `start()` on the same factory reports that rather than quietly doing nothing.
|
|
519
|
+
*/
|
|
520
|
+
protected override async close(): Promise<void> {
|
|
521
|
+
this.#destroyed = true;
|
|
522
|
+
|
|
523
|
+
if (this.#saveTimer !== null) {
|
|
524
|
+
clearInterval(this.#saveTimer);
|
|
525
|
+
this.#saveTimer = null;
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
const Module = this.#module;
|
|
529
|
+
if (Module) {
|
|
530
|
+
// Before anything else: the engine is about to be pumped a few more times on its
|
|
531
|
+
// way down, and there is no reason for those ticks to reach into a host object
|
|
532
|
+
// whose owner has already been told the session is over.
|
|
533
|
+
this.#applyButtons(null);
|
|
534
|
+
|
|
535
|
+
// Last chance to keep whatever the player earned this session.
|
|
536
|
+
if (this.#mirrorSaves) await this.#mirrorSaveData();
|
|
537
|
+
|
|
538
|
+
try {
|
|
539
|
+
Module.pauseMainLoop?.();
|
|
540
|
+
} catch {
|
|
541
|
+
/* engine already down */
|
|
542
|
+
}
|
|
543
|
+
this.#applyPaused(true);
|
|
544
|
+
// Freezing the loop does not silence the audio callback — without this the music
|
|
545
|
+
// kept playing after the host went back to its launcher.
|
|
546
|
+
try {
|
|
547
|
+
Module.web_audio_stop?.();
|
|
548
|
+
} catch {
|
|
549
|
+
/* engine already down */
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
this.#teardownCanvas();
|
|
554
|
+
this.#module = null;
|
|
555
|
+
this.#booting = null;
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
/**
|
|
559
|
+
* Where the picture goes. Called by the base before the first `open()`, which is what
|
|
560
|
+
* guarantees the canvas exists before Emscripten's SDL2 port goes looking for it.
|
|
561
|
+
*
|
|
562
|
+
* Hand over a `<canvas>` and it is used as-is, untouched apart from the id SDL needs;
|
|
563
|
+
* hand over any other element and the SDK creates a canvas inside it and keeps it
|
|
564
|
+
* scaled to fit. Reparenting a live engine is legal — the same canvas moves.
|
|
565
|
+
*/
|
|
566
|
+
protected override async mounted(target: HTMLElement): Promise<void> {
|
|
567
|
+
if (this.#canvas) {
|
|
568
|
+
this.#reparent(target);
|
|
569
|
+
return;
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
const provided = target instanceof HTMLCanvasElement ? target : null;
|
|
573
|
+
const canvas = provided ?? document.createElement('canvas');
|
|
574
|
+
this.#ownsCanvas = provided === null;
|
|
575
|
+
this.#canvas = canvas;
|
|
576
|
+
this.#box = this.#ownsCanvas ? target : canvas;
|
|
577
|
+
|
|
578
|
+
// Emscripten's SDL2 port locates the canvas via document.querySelector('#canvas').
|
|
579
|
+
if (canvas.id !== CANVAS_ID) {
|
|
580
|
+
if (canvas.id) {
|
|
581
|
+
console.warn(
|
|
582
|
+
`[rsdkv4] renaming the render target's id from "${canvas.id}" to "${CANVAS_ID}" — SDL looks the canvas up by that id.`,
|
|
583
|
+
);
|
|
584
|
+
}
|
|
585
|
+
canvas.id = CANVAS_ID;
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
if (this.#ownsCanvas) {
|
|
589
|
+
canvas.style.display = 'block';
|
|
590
|
+
canvas.style.maxWidth = '100%';
|
|
591
|
+
canvas.style.maxHeight = '100%';
|
|
592
|
+
canvas.style.height = 'auto';
|
|
593
|
+
canvas.classList.add('emscripten');
|
|
594
|
+
target.appendChild(canvas);
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
// A canvas is not in the tab order and `focus()` on one is a silent no-op until it
|
|
598
|
+
// has a tabindex. -1 makes it focusable without adding a tab stop.
|
|
599
|
+
if (!canvas.hasAttribute('tabindex')) canvas.setAttribute('tabindex', '-1');
|
|
600
|
+
// …and the focus ring would draw a browser-blue box around the picture.
|
|
601
|
+
canvas.style.outline = 'none';
|
|
602
|
+
|
|
603
|
+
canvas.addEventListener('contextmenu', this.#swallowContextMenu);
|
|
604
|
+
canvas.addEventListener('pointerdown', this.#onPointerDown);
|
|
605
|
+
window.addEventListener('resize', this.#onResize);
|
|
606
|
+
// Fullscreen transitions need a refit too.
|
|
607
|
+
document.addEventListener('fullscreenchange', this.#onFullscreenChange);
|
|
608
|
+
if (typeof ResizeObserver !== 'undefined' && this.#box) {
|
|
609
|
+
this.#boxObserver = new ResizeObserver(this.#onResize);
|
|
610
|
+
this.#boxObserver.observe(this.#box);
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
this.#fitPicture();
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
/**
|
|
617
|
+
* A payload changed on a running engine. Only the GAME OPTIONS rows are `live` here —
|
|
618
|
+
* `config` is `settings.ini`, read once at boot, and `player`/`slot`/`stage` are what
|
|
619
|
+
* a `restart()` is for.
|
|
620
|
+
*/
|
|
621
|
+
protected override async patched(kind: PayloadKind, patch: object): Promise<void> {
|
|
622
|
+
if (kind !== 'options') return;
|
|
623
|
+
|
|
624
|
+
// Ahead of the engine check, unlike everything below it: a claim written onto an
|
|
625
|
+
// engine that has not booted yet is still a claim, and a malformed one should be
|
|
626
|
+
// rejected by the call that made it rather than by the boot three lines later.
|
|
627
|
+
//
|
|
628
|
+
// `undefined` and `null` are not the same key here, and must not be collapsed:
|
|
629
|
+
// absence means "leave the claim as it is" — which is what keeps a later
|
|
630
|
+
// `options({ stage })` from dropping a claim on its way past — and only `null`
|
|
631
|
+
// releases.
|
|
632
|
+
const buttons = (patch as Rsdkv4Options).buttons;
|
|
633
|
+
if (buttons !== undefined) this.#applyButtons(buttons);
|
|
634
|
+
|
|
635
|
+
if (!this.#module) return;
|
|
636
|
+
|
|
637
|
+
const rows = this.game.options();
|
|
638
|
+
for (const [key, value] of Object.entries(patch)) {
|
|
639
|
+
if (key === 'player' || key === 'slot' || key === 'stage' || key === 'buttons') continue;
|
|
640
|
+
const row = rows.find((candidate) => candidate.key === key);
|
|
641
|
+
if (!row) {
|
|
642
|
+
console.warn(
|
|
643
|
+
`[rsdkv4] "${key}" is not a game option this pack declares — ignoring. Read options() for the ones it does.`,
|
|
644
|
+
);
|
|
645
|
+
continue;
|
|
646
|
+
}
|
|
647
|
+
this.game.setOption(row.key, toEngineOption(row, value));
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
// ---- The one place this engine does not simply inherit ----
|
|
652
|
+
|
|
653
|
+
/**
|
|
654
|
+
* The session's descriptors, enriched with what only a loaded pack can say: the
|
|
655
|
+
* playable characters, the stage list, and the engine's own GAME OPTIONS rows.
|
|
656
|
+
*
|
|
657
|
+
* The base builds descriptors from a spec fixed at construction, which is right for
|
|
658
|
+
* every other payload and cannot work for this one — Sonic 1 and Sonic 2 do not offer
|
|
659
|
+
* the same characters or the same options, and neither is knowable before
|
|
660
|
+
* `Data.rsdk` is read. Before the engine is up this answers the static spec, which is
|
|
661
|
+
* still enough for a host to know the keys exist.
|
|
662
|
+
*/
|
|
663
|
+
override options(): Promise<PropertiesDefinition<Rsdkv4Options>>;
|
|
664
|
+
override options(patch: Partial<Rsdkv4Options>): PromisePlay<Rsdkv4Payloads>;
|
|
665
|
+
override options(
|
|
666
|
+
patch?: Partial<Rsdkv4Options>,
|
|
667
|
+
): Promise<PropertiesDefinition<Rsdkv4Options>> | PromisePlay<Rsdkv4Payloads> {
|
|
668
|
+
// `arguments.length`, not `patch === undefined`: `options(undefined)` is a write of
|
|
669
|
+
// nothing, not a read.
|
|
670
|
+
if (arguments.length === 0) return this.#describeOptions();
|
|
671
|
+
return super.options(patch as Partial<Rsdkv4Options>);
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
async #describeOptions(): Promise<PropertiesDefinition<Rsdkv4Options>> {
|
|
675
|
+
const described = (await super.options()) as Record<string, PropertyDefinition<unknown>>;
|
|
676
|
+
// The claim never reads back, engine or no engine. The base would have written the
|
|
677
|
+
// host's live object into `value` here, and this getter is what a host serialises
|
|
678
|
+
// to save its settings and what it reads to paint a settings screen — neither of
|
|
679
|
+
// which fourteen booleans that change sixty times a second belong in.
|
|
680
|
+
// `play.input.claimed` is the honest question, and it is a different one.
|
|
681
|
+
described.buttons = { ...described.buttons, value: null };
|
|
682
|
+
if (!this.#module) return described as PropertiesDefinition<Rsdkv4Options>;
|
|
683
|
+
|
|
684
|
+
const out: Record<string, PropertyDefinition<unknown>> = { ...described };
|
|
685
|
+
|
|
686
|
+
const players = this.game.players();
|
|
687
|
+
if (players.length) out.player = { ...out.player, enum: players };
|
|
688
|
+
|
|
689
|
+
const stages = flattenStages(this.devMenu.getStageList());
|
|
690
|
+
if (stages.length) out.stage = { ...out.stage, enum: stages };
|
|
691
|
+
|
|
692
|
+
for (const row of this.game.options()) {
|
|
693
|
+
if (
|
|
694
|
+
row.key === 'player' ||
|
|
695
|
+
row.key === 'slot' ||
|
|
696
|
+
row.key === 'stage' ||
|
|
697
|
+
row.key === 'buttons'
|
|
698
|
+
) {
|
|
699
|
+
console.warn(`[rsdkv4] the pack declares a game option named "${row.key}" — shadowed`);
|
|
700
|
+
continue;
|
|
701
|
+
}
|
|
702
|
+
out[row.key] = {
|
|
703
|
+
value: fromEngineOption(row),
|
|
704
|
+
description: row.label,
|
|
705
|
+
live: true,
|
|
706
|
+
enum: row.type === 'boolean' ? [false, true] : (row.values ?? []),
|
|
707
|
+
};
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
return out as PropertiesDefinition<Rsdkv4Options>;
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
override restart(options?: Partial<Rsdkv4Options>): Rsdkv4Session {
|
|
714
|
+
return super.restart(options) as Rsdkv4Session;
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
// ---- Members with no contract equivalent ----
|
|
718
|
+
|
|
719
|
+
/**
|
|
720
|
+
* Pause, on behalf of `owner`. The first caller to pause owns it and only that
|
|
721
|
+
* owner's `resume()` lifts it, so a pause overlay cannot resume a game a start
|
|
722
|
+
* screen — or the host — had already frozen. Audio stops with the engine.
|
|
723
|
+
*
|
|
724
|
+
* Emits the contract's `pause` event, whose detail carries the owner.
|
|
725
|
+
*/
|
|
726
|
+
pause(owner: string = 'host'): void {
|
|
727
|
+
if (this.#pauseOwner !== null) return; // whoever got there first keeps the claim
|
|
728
|
+
this.#pauseOwner = owner;
|
|
729
|
+
this.#applyPaused(true);
|
|
730
|
+
// A pause is a natural checkpoint for the save mirror.
|
|
731
|
+
if (this.#mirrorSaves) void this.#mirrorSaveData();
|
|
732
|
+
this.emit('pause', { owner });
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
resume(owner: string = 'host'): void {
|
|
736
|
+
if (this.#pauseOwner !== owner) return; // someone else's pause — leave it alone
|
|
737
|
+
this.#pauseOwner = null;
|
|
738
|
+
this.#applyPaused(false);
|
|
739
|
+
this.emit('resume', { owner });
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
/** Who is holding the engine paused, or null. */
|
|
743
|
+
get pausedBy(): string | null {
|
|
744
|
+
return this.#pauseOwner;
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
/** True when the working dir is OPFS-backed rather than in-memory. */
|
|
748
|
+
get persistent(): boolean {
|
|
749
|
+
return this.#persistent;
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
/** The normalised {@link Rsdkv4Storage.namespace} this session actually used. */
|
|
753
|
+
get namespace(): string {
|
|
754
|
+
return this.#namespace;
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
/**
|
|
758
|
+
* Input ownership, named. `play.input.claim(buttons)` and `play.input.release()`
|
|
759
|
+
* are exactly `options({ buttons })` and `options({ buttons: null })` — same state,
|
|
760
|
+
* same survival across `restart()`, same everything.
|
|
761
|
+
*/
|
|
762
|
+
get input(): RsdkInputBridge {
|
|
763
|
+
// Captured, because `this` inside an object literal's getter is the literal. A
|
|
764
|
+
// host that holds on to `play.input` and asks later still gets today's answer.
|
|
765
|
+
const play = this;
|
|
766
|
+
return {
|
|
767
|
+
claim: (buttons: Rsdkv4Buttons) => this.options({ buttons }),
|
|
768
|
+
release: () => this.options({ buttons: null }),
|
|
769
|
+
get claimed(): boolean {
|
|
770
|
+
return play.#buttons !== null;
|
|
771
|
+
},
|
|
772
|
+
};
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
// ---- Host-driven input ----
|
|
776
|
+
|
|
777
|
+
/**
|
|
778
|
+
* Claim or release, on the engine and here. The only writer of {@link #buttons}.
|
|
779
|
+
*
|
|
780
|
+
* Order matters in both directions: the reader is installed before the engine is
|
|
781
|
+
* told to use it, and the engine is told to stop before it is taken away — so there
|
|
782
|
+
* is never a tick where the engine is pulling at something that is not there.
|
|
783
|
+
*/
|
|
784
|
+
#applyButtons(buttons: Rsdkv4Buttons | null): void {
|
|
785
|
+
if (buttons !== null) validateButtons(buttons);
|
|
786
|
+
|
|
787
|
+
const Module = this.#module;
|
|
788
|
+
this.#buttons = buttons;
|
|
789
|
+
|
|
790
|
+
// Before a boot there is nothing to tell; `open()` re-applies from the merged
|
|
791
|
+
// state once the engine is up, which is the same path a `restart()` takes.
|
|
792
|
+
if (!Module) return;
|
|
793
|
+
|
|
794
|
+
if (typeof Module.web_input_set_source !== 'function') {
|
|
795
|
+
console.error(
|
|
796
|
+
'[rsdkv4] web_input_set_source is missing from this build of rsdkv4.wasm — host-driven input needs an engine built from this SDK\'s build.sh. Rebuild it (`make build-wasm`); the engine keeps polling the keyboard until then.',
|
|
212
797
|
);
|
|
213
|
-
|
|
214
|
-
dataBytes = toUint8(await config.dataProvider());
|
|
798
|
+
return;
|
|
215
799
|
}
|
|
800
|
+
|
|
801
|
+
if (buttons === null) {
|
|
802
|
+
Module.web_input_set_source(0);
|
|
803
|
+
delete Module[INPUT_PULL_HOOK];
|
|
804
|
+
this.#pull = null;
|
|
805
|
+
this.#resetPullErrors();
|
|
806
|
+
return;
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
this.#pull ??= () => this.#readButtons();
|
|
810
|
+
Module[INPUT_PULL_HOOK] = this.#pull;
|
|
811
|
+
Module.web_input_set_source(1);
|
|
216
812
|
}
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
813
|
+
|
|
814
|
+
/**
|
|
815
|
+
* The per-tick read. Called from the engine, at the top of its input pass, through
|
|
816
|
+
* `web_input_pull()` — never from a timer and never from anywhere else.
|
|
817
|
+
*
|
|
818
|
+
* **Keep it on the engine's callback.** A read inside a reactive effect would make
|
|
819
|
+
* all fourteen buttons dependencies of that effect (jq79 attributes every read
|
|
820
|
+
* through a store's `get` trap to whichever effect is running), and every keypress
|
|
821
|
+
* would wake it. The call stack here is always rAF → wasm → EM_JS → this, where no
|
|
822
|
+
* effect can be running, and that is an invariant to preserve rather than a
|
|
823
|
+
* coincidence to rely on.
|
|
824
|
+
*/
|
|
825
|
+
#readButtons(): number {
|
|
826
|
+
const buttons = this.#buttons;
|
|
827
|
+
if (!buttons) return 0;
|
|
828
|
+
|
|
829
|
+
try {
|
|
830
|
+
let mask = 0;
|
|
831
|
+
// Indexed, not `Object.entries`: the array's order is the engine's bit order,
|
|
832
|
+
// and a host object's key order is its own business.
|
|
833
|
+
for (let bit = 0; bit < RSDKV4_BUTTONS.length; bit++) {
|
|
834
|
+
if (buttons[RSDKV4_BUTTONS[bit]]) mask |= 1 << bit;
|
|
835
|
+
}
|
|
836
|
+
this.#resetPullErrors();
|
|
837
|
+
return mask;
|
|
838
|
+
} catch (error) {
|
|
839
|
+
this.#reportPullError(error);
|
|
840
|
+
// Everything released, never the last good mask: a repeated mask with a
|
|
841
|
+
// direction held leaves the character running into a pit on its own.
|
|
842
|
+
return 0;
|
|
843
|
+
}
|
|
223
844
|
}
|
|
224
845
|
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
846
|
+
/**
|
|
847
|
+
* Announce a failing pull at most once a second, with a count.
|
|
848
|
+
*
|
|
849
|
+
* This runs sixty times a second, so an unthrottled `emit` would bury the page. It
|
|
850
|
+
* does **not** release the claim: a transient fault recovers on its own, whereas
|
|
851
|
+
* releasing would change input ownership behind the host's back.
|
|
852
|
+
*
|
|
853
|
+
* With a plain object nothing here can fire. It exists because the API accepts any
|
|
854
|
+
* object and a Proxy runs host code on every read — a store nulled by a component
|
|
855
|
+
* that unmounted without releasing, a revoked `Proxy.revocable`, a `get` trap whose
|
|
856
|
+
* effect scope has been torn down. Claim-time validation covers none of those: it
|
|
857
|
+
* validated once, over a reference that was live at the time.
|
|
858
|
+
*/
|
|
859
|
+
#reportPullError(error: unknown): void {
|
|
860
|
+
const key = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
|
|
861
|
+
// performance.now() rather than a timer: nothing to schedule, nothing to clear,
|
|
862
|
+
// and the comparison is already in the hand.
|
|
863
|
+
const now = typeof performance !== 'undefined' ? performance.now() : Date.now();
|
|
864
|
+
this.#pullErrors++;
|
|
865
|
+
|
|
866
|
+
if (key !== this.#pullErrorKey || now - this.#pullErrorAt >= INPUT_ERROR_INTERVAL_MS) {
|
|
867
|
+
const windowMs = this.#pullErrorKey === null ? 0 : now - this.#pullErrorAt;
|
|
868
|
+
this.emit(
|
|
869
|
+
'error',
|
|
870
|
+
Object.assign(
|
|
871
|
+
new Error(
|
|
872
|
+
`rsdkv4: reading the host's buttons failed (${this.#pullErrors}× in ${Math.round(windowMs)}ms) — input is dead until it recovers, and the claim is still held. Release it with options({ buttons: null }) if the host is gone. Cause: ${key}`,
|
|
873
|
+
),
|
|
874
|
+
{ cause: error },
|
|
875
|
+
),
|
|
876
|
+
);
|
|
877
|
+
this.#pullErrorKey = key;
|
|
878
|
+
this.#pullErrorAt = now;
|
|
879
|
+
this.#pullErrors = 0;
|
|
880
|
+
}
|
|
229
881
|
}
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
882
|
+
|
|
883
|
+
/** Forget the streak, so a relapse announces itself immediately rather than in a second. */
|
|
884
|
+
#resetPullErrors(): void {
|
|
885
|
+
if (this.#pullErrorKey === null) return;
|
|
886
|
+
this.#pullErrorKey = null;
|
|
887
|
+
this.#pullErrorAt = 0;
|
|
888
|
+
this.#pullErrors = 0;
|
|
234
889
|
}
|
|
235
|
-
// else: keep the persisted settings.ini
|
|
236
890
|
|
|
237
|
-
|
|
891
|
+
/** RSDKv4's Start Menu as data. Available once the engine is up. */
|
|
892
|
+
get game(): RsdkGameBridge {
|
|
893
|
+
const Module = this.#requireModule();
|
|
894
|
+
const parse = <T>(fn: unknown, fallback: T, what: string): T => parseJson(fn, fallback, what);
|
|
895
|
+
return {
|
|
896
|
+
type: () => (typeof Module.web_game_type === 'function' ? Module.web_game_type() : 0),
|
|
897
|
+
players: () => parse(Module.web_get_players, [] as string[], 'web_get_players'),
|
|
898
|
+
saveSlots: () =>
|
|
899
|
+
parse(Module.web_get_save_slots, [] as RsdkSaveSlot[], 'web_get_save_slots'),
|
|
900
|
+
options: () =>
|
|
901
|
+
parse(Module.web_get_game_options, [] as RsdkGameOption[], 'web_get_game_options'),
|
|
902
|
+
setOption: (key, value) => {
|
|
903
|
+
Module.web_set_game_option?.(String(key), value | 0);
|
|
904
|
+
},
|
|
905
|
+
deleteSave: (slot) => {
|
|
906
|
+
Module.web_delete_save?.(slot | 0);
|
|
907
|
+
if (this.#mirrorSaves) void this.#mirrorSaveData();
|
|
908
|
+
},
|
|
909
|
+
start: (slot, player = 0) => {
|
|
910
|
+
Module.web_start_game?.(slot == null ? -1 : slot | 0, player | 0);
|
|
911
|
+
// Whatever drove this is done with the engine — hand it back.
|
|
912
|
+
this.#pauseOwner = null;
|
|
913
|
+
this.#applyPaused(false);
|
|
914
|
+
},
|
|
915
|
+
};
|
|
916
|
+
}
|
|
238
917
|
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
918
|
+
/** The engine's stage list and loader. Available once the engine is up. */
|
|
919
|
+
get devMenu(): RsdkDevMenuBridge {
|
|
920
|
+
const Module = this.#requireModule();
|
|
921
|
+
return {
|
|
922
|
+
getStageList: () =>
|
|
923
|
+
parseJson(Module.web_devmenu_get_stage_list, [], 'web_devmenu_get_stage_list'),
|
|
924
|
+
loadStage: (categoryIdx, stageIdx) => {
|
|
925
|
+
Module.web_devmenu_load_stage?.(categoryIdx | 0, stageIdx | 0);
|
|
926
|
+
},
|
|
927
|
+
setPaused: (paused) => {
|
|
928
|
+
if (paused) this.pause('host');
|
|
929
|
+
else this.resume(this.#pauseOwner ?? 'host');
|
|
930
|
+
},
|
|
931
|
+
};
|
|
932
|
+
}
|
|
242
933
|
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
934
|
+
// ---- Bringing the engine up ----
|
|
935
|
+
|
|
936
|
+
#requireModule(): EmscriptenModule {
|
|
937
|
+
if (!this.#module) {
|
|
938
|
+
throw new Error('rsdkv4: the engine is not running — await start() before reaching for it');
|
|
939
|
+
}
|
|
940
|
+
return this.#module;
|
|
941
|
+
}
|
|
942
|
+
|
|
943
|
+
#ensureBooted(): Promise<EmscriptenModule> {
|
|
944
|
+
if (this.#destroyed) {
|
|
945
|
+
throw new Error(
|
|
946
|
+
'rsdkv4: this engine has been destroyed and cannot be restarted in process — build a new Rsdkv4SDK',
|
|
947
|
+
);
|
|
948
|
+
}
|
|
949
|
+
// A boot that failed must not poison the next attempt. The common failure is a
|
|
950
|
+
// host that started before handing over `assets.data` — it fixes that and calls
|
|
951
|
+
// `start()` again, and caching the rejection would tell it "no Data.rsdk" forever.
|
|
952
|
+
this.#booting ??= this.#boot().catch((error: unknown) => {
|
|
953
|
+
this.#booting = null;
|
|
954
|
+
this.#module = null;
|
|
955
|
+
throw error;
|
|
956
|
+
});
|
|
957
|
+
return this.#booting;
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
async #boot(): Promise<EmscriptenModule> {
|
|
961
|
+
const canvas = this.#canvas;
|
|
962
|
+
if (!canvas) {
|
|
963
|
+
throw new Error('rsdkv4: mount(target) before start() — the engine draws into a canvas');
|
|
964
|
+
}
|
|
965
|
+
|
|
966
|
+
const config = valuesOf(await this.config());
|
|
967
|
+
const assets = valuesOf(await this.assets());
|
|
968
|
+
const storage = valuesOf(await this.storage());
|
|
969
|
+
|
|
970
|
+
const Module = await this.#instantiate(canvas, config);
|
|
971
|
+
this.#module = Module;
|
|
972
|
+
|
|
973
|
+
// Mount the working dir first, so we can see what is already persisted (OPFS)
|
|
974
|
+
// before deciding whether to pull assets.
|
|
975
|
+
this.#persistent = mountWorkingDir(Module, storage.persist).persistent;
|
|
976
|
+
this.#namespace = normalizeStorageNamespace(storage.namespace);
|
|
977
|
+
this.#workDir = `${WORK_ROOT}/${this.#namespace}`;
|
|
978
|
+
this.#mirrorSaves = storage.persist !== null;
|
|
979
|
+
ensureDir(Module, this.#workDir);
|
|
980
|
+
|
|
981
|
+
await this.#writeAssets(Module, assets, config);
|
|
982
|
+
|
|
983
|
+
// `persist: null` means the host wants nothing kept, so honour it; otherwise pull
|
|
984
|
+
// any previous SData.bin in before the engine reads it.
|
|
985
|
+
if (this.#mirrorSaves) await this.#restoreSaveData(Module);
|
|
986
|
+
|
|
987
|
+
Module.FS.chdir(this.#workDir);
|
|
988
|
+
|
|
989
|
+
// Run main() from the working dir. simulate_infinite_loop schedules the rAF loop
|
|
990
|
+
// and returns via a benign unwind Emscripten swallows.
|
|
991
|
+
Module.callMain(['UsingCWD']);
|
|
992
|
+
|
|
993
|
+
// callMain only *schedules* the loop: Engine::Init runs on the first frame, and
|
|
994
|
+
// until it has, there is no game config, stage list or saveRAM to read. Waiting
|
|
995
|
+
// here means the bridges answer the moment start() resolves.
|
|
996
|
+
await waitForEngine(Module);
|
|
997
|
+
|
|
998
|
+
this.#focusCanvas();
|
|
999
|
+
|
|
1000
|
+
// The engine writes SData.bin at its own pace (new game, checkpoint, options
|
|
1001
|
+
// change), so copy it out on a slow timer as well as on the way down.
|
|
1002
|
+
if (this.#mirrorSaves) {
|
|
1003
|
+
this.#saveTimer = setInterval(() => void this.#mirrorSaveData(), 10_000);
|
|
1004
|
+
}
|
|
1005
|
+
|
|
1006
|
+
return Module;
|
|
1007
|
+
}
|
|
1008
|
+
|
|
1009
|
+
async #instantiate(canvas: HTMLCanvasElement, config: Rsdkv4Config): Promise<EmscriptenModule> {
|
|
1010
|
+
const jsUrl = config.jsUrl ?? new URL('./rsdkv4.js', import.meta.url).href;
|
|
1011
|
+
const wasmUrl = config.wasmUrl ?? new URL('./rsdkv4.wasm', import.meta.url).href;
|
|
1012
|
+
|
|
1013
|
+
const load = async (bust?: string): Promise<EmscriptenModule> => {
|
|
1014
|
+
const withBust = (url: string): string => {
|
|
1015
|
+
if (!bust) return url;
|
|
1016
|
+
const parsed = new URL(url, location.href);
|
|
1017
|
+
parsed.searchParams.set('_', bust);
|
|
1018
|
+
return parsed.href;
|
|
1019
|
+
};
|
|
1020
|
+
|
|
1021
|
+
const mod = await import(/* @vite-ignore */ withBust(jsUrl));
|
|
1022
|
+
return mod.default({
|
|
1023
|
+
canvas,
|
|
1024
|
+
noInitialRun: true, // built with -sINVOKE_RUN=0; we mount data before main()
|
|
1025
|
+
locateFile: (path: string) => (path.endsWith('.wasm') ? withBust(wasmUrl) : path),
|
|
1026
|
+
print: (...a: unknown[]) => console.log('[rsdkv4]', ...a),
|
|
1027
|
+
printErr: (...a: unknown[]) => console.error('[rsdkv4]', ...a),
|
|
1028
|
+
onAbort: (reason: unknown) => {
|
|
1029
|
+
this.emit('error', new Error(`rsdkv4 aborted: ${reason}`));
|
|
1030
|
+
},
|
|
1031
|
+
});
|
|
1032
|
+
};
|
|
1033
|
+
|
|
1034
|
+
let Module = await load();
|
|
1035
|
+
|
|
1036
|
+
// Self-heal a stale engine.
|
|
1037
|
+
//
|
|
1038
|
+
// rsdkv4.js/.wasm are big and served by most static hosts with nothing but
|
|
1039
|
+
// Last-Modified, so a browser will happily keep a build for hours. The symptom is
|
|
1040
|
+
// nasty: fresh SDK code against an old engine, where the bridges this SDK calls
|
|
1041
|
+
// simply don't exist and every getter quietly answers "empty" — no save slots, no
|
|
1042
|
+
// characters, an empty pause menu. Rather than leave that to the reader's cache
|
|
1043
|
+
// hygiene, notice it and fetch once past the cache.
|
|
1044
|
+
if (!engineBridgeComplete(Module)) {
|
|
1045
|
+
console.warn(
|
|
1046
|
+
'[rsdkv4] the engine that loaded is missing bridges this SDK needs — refetching past the HTTP cache',
|
|
1047
|
+
);
|
|
1048
|
+
Module = await load(String(Date.now()));
|
|
1049
|
+
if (!engineBridgeComplete(Module)) {
|
|
1050
|
+
console.error(
|
|
1051
|
+
'[rsdkv4] still missing engine bridges after a cache-busting reload — rsdkv4.wasm is genuinely older than this SDK; rebuild it (`make build-wasm`)',
|
|
1052
|
+
);
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
|
|
1056
|
+
return Module;
|
|
1057
|
+
}
|
|
1058
|
+
|
|
1059
|
+
/** Data.rsdk and settings.ini into the working dir. See {@link Rsdkv4Assets}. */
|
|
1060
|
+
async #writeAssets(
|
|
1061
|
+
Module: EmscriptenModule,
|
|
1062
|
+
assets: Rsdkv4Assets,
|
|
1063
|
+
config: Rsdkv4Config,
|
|
1064
|
+
): Promise<void> {
|
|
1065
|
+
const dataPath = `${this.#workDir}/Data.rsdk`;
|
|
1066
|
+
const settingsPath = `${this.#workDir}/settings.ini`;
|
|
1067
|
+
|
|
1068
|
+
// The pack — the expensive one, so a persisted copy short-circuits the thunk.
|
|
1069
|
+
if (fileExists(Module, dataPath)) {
|
|
1070
|
+
const explicit = typeof assets.data === 'function' ? null : await resolveAsset(assets.data);
|
|
1071
|
+
if (explicit) Module.FS.writeFile(dataPath, explicit);
|
|
1072
|
+
else {
|
|
1073
|
+
console.log(
|
|
1074
|
+
`[rsdkv4] Data.rsdk already in persistent storage (${this.#namespace}) — skipping fetch`,
|
|
1075
|
+
);
|
|
251
1076
|
}
|
|
252
|
-
}
|
|
253
|
-
|
|
254
|
-
if (
|
|
255
|
-
|
|
1077
|
+
} else {
|
|
1078
|
+
const bytes = await resolveAsset(assets.data);
|
|
1079
|
+
if (!bytes) {
|
|
1080
|
+
throw new Error(
|
|
1081
|
+
'rsdkv4: no Data.rsdk — hand one over as assets.data (bytes or a thunk), or point storage.namespace at a persisted copy',
|
|
1082
|
+
);
|
|
256
1083
|
}
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
};
|
|
1084
|
+
Module.FS.writeFile(dataPath, bytes);
|
|
1085
|
+
}
|
|
260
1086
|
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
1087
|
+
// The settings — cheap, and regenerated every boot so `config` is never shadowed
|
|
1088
|
+
// by a file an earlier session left behind. The engine never writes it back (its
|
|
1089
|
+
// writeSettings() is #ifndef __EMSCRIPTEN__), so there is nothing to lose.
|
|
1090
|
+
const settings = await resolveAsset(assets.settings);
|
|
1091
|
+
Module.FS.writeFile(settingsPath, settings ?? new TextEncoder().encode(buildSettingsIni(config)));
|
|
1092
|
+
}
|
|
1093
|
+
|
|
1094
|
+
// ---- The save mirror ----
|
|
1095
|
+
|
|
1096
|
+
/**
|
|
1097
|
+
* Pull a previously mirrored SData.bin into the wasm before the engine reads it.
|
|
1098
|
+
*
|
|
1099
|
+
* The working dir is in-memory whenever the OPFS *mount* is unavailable (which is
|
|
1100
|
+
* every build without Asyncify/JSPI — see {@link mountWorkingDir}), so SData.bin
|
|
1101
|
+
* would die with the page and every slot would read "NEW GAME" forever. The host-side
|
|
1102
|
+
* OPFS API has no such limitation, so the SDK copies the file in here and back out as
|
|
1103
|
+
* it changes.
|
|
1104
|
+
*/
|
|
1105
|
+
async #restoreSaveData(Module: EmscriptenModule): Promise<void> {
|
|
1106
|
+
const dir = await opfsNamespaceDir(this.#namespace, false);
|
|
1107
|
+
if (!dir) return;
|
|
1108
|
+
try {
|
|
1109
|
+
const file = await (await dir.getFileHandle(SAVE_FILE)).getFile();
|
|
1110
|
+
if (file.size > 0) {
|
|
1111
|
+
const bytes = new Uint8Array(await file.arrayBuffer());
|
|
1112
|
+
Module.FS.writeFile(`${this.#workDir}/${SAVE_FILE}`, bytes);
|
|
1113
|
+
this.#lastSave = bytes;
|
|
276
1114
|
}
|
|
277
|
-
}
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
1115
|
+
} catch {
|
|
1116
|
+
/* no save yet */
|
|
1117
|
+
}
|
|
1118
|
+
}
|
|
1119
|
+
|
|
1120
|
+
/**
|
|
1121
|
+
* Copy SData.bin out of the wasm into `<namespace>/`, and announce it if it moved.
|
|
1122
|
+
*
|
|
1123
|
+
* The division of labour the session settled on: the SDK owns getting the bytes out
|
|
1124
|
+
* of the wasm and into the namespace both sides already agree on; a host owns
|
|
1125
|
+
* reading, parsing and painting them. `saves` is what tells it to look again — which
|
|
1126
|
+
* is why it fires on a change and not on every check.
|
|
1127
|
+
*/
|
|
1128
|
+
async #mirrorSaveData(): Promise<void> {
|
|
1129
|
+
const Module = this.#module;
|
|
1130
|
+
if (!Module) return;
|
|
1131
|
+
|
|
1132
|
+
// Explicitly over an ArrayBuffer, not the default ArrayBufferLike: OPFS's
|
|
1133
|
+
// `write()` will not take a view that might be backed by a SharedArrayBuffer,
|
|
1134
|
+
// and on a cross-origin isolated page that is not a hypothetical distinction.
|
|
1135
|
+
let bytes: Uint8Array<ArrayBuffer>;
|
|
1136
|
+
try {
|
|
1137
|
+
bytes = Module.FS.readFile(`${this.#workDir}/${SAVE_FILE}`);
|
|
1138
|
+
} catch {
|
|
1139
|
+
return; // the engine hasn't written one
|
|
1140
|
+
}
|
|
1141
|
+
if (sameBytes(bytes, this.#lastSave)) return;
|
|
1142
|
+
|
|
1143
|
+
const dir = await opfsNamespaceDir(this.#namespace, true);
|
|
1144
|
+
if (dir) {
|
|
1145
|
+
try {
|
|
1146
|
+
const handle = await dir.getFileHandle(SAVE_FILE, { create: true });
|
|
1147
|
+
const writable = await handle.createWritable();
|
|
1148
|
+
await writable.write(bytes);
|
|
1149
|
+
await writable.close();
|
|
1150
|
+
} catch (e) {
|
|
1151
|
+
console.warn('[rsdkv4] could not persist save data', e);
|
|
1152
|
+
return;
|
|
1153
|
+
}
|
|
1154
|
+
}
|
|
1155
|
+
|
|
1156
|
+
this.#lastSave = bytes;
|
|
1157
|
+
this.emit('saves', this.game.saveSlots());
|
|
1158
|
+
}
|
|
1159
|
+
|
|
1160
|
+
// ---- The render target ----
|
|
1161
|
+
|
|
1162
|
+
#swallowContextMenu = (event: Event): void => event.preventDefault();
|
|
1163
|
+
#onPointerDown = (): void => this.#focusCanvas();
|
|
1164
|
+
#onResize = (): void => this.#fitPicture();
|
|
1165
|
+
#onFullscreenChange = (): void => {
|
|
1166
|
+
this.#fitPicture();
|
|
1167
|
+
requestAnimationFrame(() => this.#fitPicture());
|
|
291
1168
|
};
|
|
1169
|
+
|
|
1170
|
+
#focusCanvas(): void {
|
|
1171
|
+
if (!this.#canvas) return;
|
|
1172
|
+
if (!document.hasFocus()) window.focus();
|
|
1173
|
+
this.#canvas.focus({ preventScroll: true });
|
|
1174
|
+
}
|
|
1175
|
+
|
|
1176
|
+
#fitPicture(): void {
|
|
1177
|
+
if (!this.#ownsCanvas || !this.#canvas || !this.#box) return;
|
|
1178
|
+
const box = this.#box.getBoundingClientRect();
|
|
1179
|
+
if (box.width < 1 || box.height < 1) return;
|
|
1180
|
+
|
|
1181
|
+
const { baseWidth, baseHeight } = RSDKV4_VIDEO;
|
|
1182
|
+
const scale = Math.min(box.width / baseWidth, box.height / baseHeight);
|
|
1183
|
+
this.#canvas.style.width = `${Math.round(baseWidth * scale)}px`;
|
|
1184
|
+
this.#canvas.style.height = `${Math.round(baseHeight * scale)}px`;
|
|
1185
|
+
}
|
|
1186
|
+
|
|
1187
|
+
/**
|
|
1188
|
+
* Move the picture we already have. SDL keeps its canvas; only the parent changes.
|
|
1189
|
+
*
|
|
1190
|
+
* Pointing a second `mount()` at a *different* `<canvas>` is the one case this
|
|
1191
|
+
* refuses: SDL2 resolved `#canvas` once, at instantiation, so swapping the element
|
|
1192
|
+
* would leave the engine drawing into an orphan while the host watched a blank one.
|
|
1193
|
+
*/
|
|
1194
|
+
#reparent(target: HTMLElement): void {
|
|
1195
|
+
const canvas = this.#canvas;
|
|
1196
|
+
if (!canvas || target === canvas || canvas.parentElement === target) return;
|
|
1197
|
+
|
|
1198
|
+
if (target instanceof HTMLCanvasElement) {
|
|
1199
|
+
console.warn(
|
|
1200
|
+
'[rsdkv4] the canvas SDL draws into cannot be swapped after mounting — ignoring this mount()',
|
|
1201
|
+
);
|
|
1202
|
+
return;
|
|
1203
|
+
}
|
|
1204
|
+
|
|
1205
|
+
target.appendChild(canvas);
|
|
1206
|
+
if (this.#box) this.#boxObserver?.unobserve(this.#box);
|
|
1207
|
+
this.#box = this.#ownsCanvas ? target : canvas;
|
|
1208
|
+
if (this.#box) this.#boxObserver?.observe(this.#box);
|
|
1209
|
+
this.#fitPicture();
|
|
1210
|
+
}
|
|
1211
|
+
|
|
1212
|
+
#teardownCanvas(): void {
|
|
1213
|
+
const canvas = this.#canvas;
|
|
1214
|
+
if (canvas) {
|
|
1215
|
+
canvas.removeEventListener('contextmenu', this.#swallowContextMenu);
|
|
1216
|
+
canvas.removeEventListener('pointerdown', this.#onPointerDown);
|
|
1217
|
+
if (this.#ownsCanvas) canvas.remove();
|
|
1218
|
+
}
|
|
1219
|
+
document.removeEventListener('fullscreenchange', this.#onFullscreenChange);
|
|
1220
|
+
window.removeEventListener('resize', this.#onResize);
|
|
1221
|
+
this.#boxObserver?.disconnect();
|
|
1222
|
+
this.#boxObserver = null;
|
|
1223
|
+
this.#canvas = null;
|
|
1224
|
+
this.#box = null;
|
|
1225
|
+
}
|
|
1226
|
+
|
|
1227
|
+
// ---- Misc ----
|
|
1228
|
+
|
|
1229
|
+
#applyPaused(paused: boolean): void {
|
|
1230
|
+
const Module = this.#module;
|
|
1231
|
+
if (!Module) return;
|
|
1232
|
+
if (typeof Module.web_devmenu_set_paused === 'function') Module.web_devmenu_set_paused(paused);
|
|
1233
|
+
if (typeof Module.web_audio_set_paused === 'function') Module.web_audio_set_paused(paused);
|
|
1234
|
+
}
|
|
1235
|
+
|
|
1236
|
+
/** A character name, as the pack spells it, to the index the engine wants. */
|
|
1237
|
+
#playerIndex(player: string | undefined): number {
|
|
1238
|
+
if (player === undefined) return 0;
|
|
1239
|
+
const players = this.game.players();
|
|
1240
|
+
const index = players.findIndex((name) => name.toLowerCase() === player.toLowerCase());
|
|
1241
|
+
if (index < 0) {
|
|
1242
|
+
throw new Error(
|
|
1243
|
+
`rsdkv4: "${player}" is not a playable character in this pack — try one of ${players.join(', ') || '(none reported)'}`,
|
|
1244
|
+
);
|
|
1245
|
+
}
|
|
1246
|
+
return index;
|
|
1247
|
+
}
|
|
1248
|
+
}
|
|
1249
|
+
|
|
1250
|
+
// ---------------------------------------------------------------- the factory
|
|
1251
|
+
|
|
1252
|
+
/**
|
|
1253
|
+
* The factory a host imports: identity on the constructor, one live engine per
|
|
1254
|
+
* instance, and a `start()` that brings the wasm up and opens a session.
|
|
1255
|
+
*
|
|
1256
|
+
* Everything on it is the contract's — see the module doc for the shape of a call.
|
|
1257
|
+
*/
|
|
1258
|
+
export class Rsdkv4SDK extends EngineSDKBase<Rsdkv4Payloads> {
|
|
1259
|
+
static readonly id = 'rsdkv4';
|
|
1260
|
+
/** Kept in step with package.json by `node scripts/sync-version.mjs`. */
|
|
1261
|
+
static readonly version = '0.2.0';
|
|
1262
|
+
static readonly name = 'Retro Software Development Kit v4';
|
|
1263
|
+
static readonly description =
|
|
1264
|
+
'RSDKv4 compiled to WebAssembly via Emscripten. One game-agnostic WASM binary runs both Sonic 1 and Sonic 2 — the difference is only which Data.rsdk the host supplies at runtime. Ships none of the game: the player provides their own Data.rsdk, and it never leaves their browser.';
|
|
1265
|
+
|
|
1266
|
+
protected override createPlay(
|
|
1267
|
+
init: EngineInit<Rsdkv4Payloads>,
|
|
1268
|
+
events: EventEmitter<Rsdkv4Events_>,
|
|
1269
|
+
): Rsdkv4Play {
|
|
1270
|
+
return new Rsdkv4Play(init, events);
|
|
1271
|
+
}
|
|
1272
|
+
|
|
1273
|
+
override start(options?: Partial<Rsdkv4Options>): Rsdkv4Session {
|
|
1274
|
+
return super.start(options) as Rsdkv4Session;
|
|
1275
|
+
}
|
|
1276
|
+
}
|
|
1277
|
+
|
|
1278
|
+
/**
|
|
1279
|
+
* The line that puts the contract in CI: if this file stops satisfying
|
|
1280
|
+
* `EngineSDKConstructor`, `make typecheck` says so.
|
|
1281
|
+
*/
|
|
1282
|
+
export const RSDKV4_ENGINE: EngineSDKConstructor<Rsdkv4Payloads> = Rsdkv4SDK;
|
|
1283
|
+
|
|
1284
|
+
export default Rsdkv4SDK;
|
|
1285
|
+
|
|
1286
|
+
// ---------------------------------------------------------------- module-private helpers
|
|
1287
|
+
|
|
1288
|
+
/**
|
|
1289
|
+
* Call a `web_*` embind getter and parse its JSON.
|
|
1290
|
+
*
|
|
1291
|
+
* A missing function means the loaded rsdkv4.wasm predates that bridge — the usual
|
|
1292
|
+
* cause is a browser serving a cached build. Say so out loud: silently returning an
|
|
1293
|
+
* empty list makes a stale artifact look like an empty save file or a game with no
|
|
1294
|
+
* playable characters.
|
|
1295
|
+
*/
|
|
1296
|
+
function parseJson<T>(fn: unknown, fallback: T, what: string): T {
|
|
1297
|
+
if (typeof fn !== 'function') {
|
|
1298
|
+
console.error(
|
|
1299
|
+
`[rsdkv4] ${what} is missing from this build of rsdkv4.wasm — the page is probably running a cached copy. Hard-reload (or clear the site's storage) after rebuilding.`,
|
|
1300
|
+
);
|
|
1301
|
+
return fallback;
|
|
1302
|
+
}
|
|
1303
|
+
try {
|
|
1304
|
+
return JSON.parse((fn as () => string)());
|
|
1305
|
+
} catch (e) {
|
|
1306
|
+
console.error(`[rsdkv4] ${what} failed`, e);
|
|
1307
|
+
return fallback;
|
|
1308
|
+
}
|
|
292
1309
|
}
|
|
293
1310
|
|
|
294
|
-
|
|
1311
|
+
/**
|
|
1312
|
+
* A claim, checked once — exactly the fourteen buttons, with missing and unknown both
|
|
1313
|
+
* fatal.
|
|
1314
|
+
*
|
|
1315
|
+
* Strict because the two failure modes are silent and asymmetric. A **missing** key
|
|
1316
|
+
* reads `false` on every tick: a dead button, no error anywhere, and easy to blame on
|
|
1317
|
+
* the engine. An **unknown** key is a button the host writes to that nothing ever
|
|
1318
|
+
* reads. The first sketch of this API lost `right` to a duplicated `up` — a duplicate
|
|
1319
|
+
* key in an object literal is legal JavaScript and surfaces only as an absent one.
|
|
1320
|
+
*
|
|
1321
|
+
* `Object.keys`, not `in`: a reactive store's `has` trap can answer `true` for a key
|
|
1322
|
+
* that has been deleted (jq79 does exactly that, deliberately, so a template
|
|
1323
|
+
* expression reading a deleted name takes its else branch instead of dying), and
|
|
1324
|
+
* `ownKeys` has no such licence.
|
|
1325
|
+
*/
|
|
1326
|
+
function validateButtons(buttons: Rsdkv4Buttons): void {
|
|
1327
|
+
if (typeof buttons !== 'object' || buttons === null) {
|
|
1328
|
+
throw new Error(
|
|
1329
|
+
`rsdkv4: options({ buttons }) takes an object of the 14 buttons or null to release, not ${typeof buttons}`,
|
|
1330
|
+
);
|
|
1331
|
+
}
|
|
1332
|
+
|
|
1333
|
+
const keys = new Set(Object.keys(buttons));
|
|
1334
|
+
const missing = RSDKV4_BUTTONS.filter((button) => !keys.has(button));
|
|
1335
|
+
const unknown = [...keys].filter(
|
|
1336
|
+
(key) => !(RSDKV4_BUTTONS as readonly string[]).includes(key),
|
|
1337
|
+
);
|
|
1338
|
+
|
|
1339
|
+
if (missing.length || unknown.length) {
|
|
1340
|
+
const faults = [
|
|
1341
|
+
missing.length && `missing ${missing.join(', ')}`,
|
|
1342
|
+
unknown.length && `unknown ${unknown.join(', ')}`,
|
|
1343
|
+
].filter(Boolean);
|
|
1344
|
+
throw new Error(
|
|
1345
|
+
`rsdkv4: the buttons object must carry exactly the 14 buttons (${RSDKV4_BUTTONS.join(', ')}) — ${faults.join('; ')}. A missing button is dead, not neutral, so this is an error rather than a default.`,
|
|
1346
|
+
);
|
|
1347
|
+
}
|
|
1348
|
+
}
|
|
1349
|
+
|
|
1350
|
+
/** The engine's two-level stage list as flat, writable {@link Rsdkv4Stage} values. */
|
|
1351
|
+
function flattenStages(
|
|
1352
|
+
categories: Array<{ name: string; stages: Array<{ name: string }> }>,
|
|
1353
|
+
): Rsdkv4Stage[] {
|
|
1354
|
+
const out: Rsdkv4Stage[] = [];
|
|
1355
|
+
categories.forEach((category, categoryIdx) => {
|
|
1356
|
+
category.stages.forEach((stage, sceneIdx) => {
|
|
1357
|
+
out.push({ category: categoryIdx, scene: sceneIdx, name: `${category.name} · ${stage.name}` });
|
|
1358
|
+
});
|
|
1359
|
+
});
|
|
1360
|
+
return out;
|
|
1361
|
+
}
|
|
1362
|
+
|
|
1363
|
+
/** A GAME OPTIONS row as a host reads it: a boolean, or the label of the chosen entry. */
|
|
1364
|
+
function fromEngineOption(row: RsdkGameOption): boolean | string | number {
|
|
1365
|
+
if (row.type === 'boolean') return row.value !== 0;
|
|
1366
|
+
return row.values?.[row.value] ?? row.value;
|
|
1367
|
+
}
|
|
1368
|
+
|
|
1369
|
+
/** …and back to the number the engine stores. */
|
|
1370
|
+
function toEngineOption(row: RsdkGameOption, value: unknown): number {
|
|
1371
|
+
if (typeof value === 'boolean') return value ? 1 : 0;
|
|
1372
|
+
if (typeof value === 'number') return value | 0;
|
|
1373
|
+
if (typeof value === 'string') {
|
|
1374
|
+
const index = (row.values ?? []).findIndex(
|
|
1375
|
+
(choice) => choice.toLowerCase() === value.toLowerCase(),
|
|
1376
|
+
);
|
|
1377
|
+
if (index >= 0) return index;
|
|
1378
|
+
}
|
|
1379
|
+
throw new Error(
|
|
1380
|
+
`rsdkv4: ${JSON.stringify(value)} is not a value "${row.key}" accepts — try one of ${
|
|
1381
|
+
row.type === 'boolean' ? 'true, false' : (row.values ?? []).join(', ')
|
|
1382
|
+
}`,
|
|
1383
|
+
);
|
|
1384
|
+
}
|