@wasm-gaming/fbneo-wasm 0.1.2 → 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.
Files changed (54) hide show
  1. package/README.md +103 -69
  2. package/dist/fbneo/app/app.css +112 -0
  3. package/dist/fbneo/app/app.js +646 -0
  4. package/dist/fbneo/engine-specs.js +646 -0
  5. package/dist/fbneo/fbneo.js +2 -0
  6. package/dist/fbneo/fbneo.options.d.ts +66 -19
  7. package/dist/fbneo/fbneo.options.d.ts.map +1 -1
  8. package/dist/fbneo/fbneo.options.js +39 -44
  9. package/dist/fbneo/fbneo.options.js.map +1 -1
  10. package/dist/fbneo/fbneo.sdk.d.ts +137 -8
  11. package/dist/fbneo/fbneo.sdk.d.ts.map +1 -1
  12. package/dist/fbneo/fbneo.sdk.js +588 -184
  13. package/dist/fbneo/fbneo.sdk.js.map +1 -1
  14. package/dist/fbneo/fbneo.wasm +4 -0
  15. package/package.json +10 -15
  16. package/src/app/app.css +112 -0
  17. package/src/app/app.js +646 -0
  18. package/src/fbneo.options.ts +107 -63
  19. package/src/fbneo.sdk.ts +644 -212
  20. package/dist/fbneo/fbneo.manifest.d.ts +0 -4
  21. package/dist/fbneo/fbneo.manifest.d.ts.map +0 -1
  22. package/dist/fbneo/fbneo.manifest.js +0 -33
  23. package/dist/fbneo/fbneo.manifest.js.map +0 -1
  24. package/dist/manifest.json +0 -91
  25. package/src/fbneo.manifest.ts +0 -38
  26. /package/{data → dist/fbneo}/romsets/atari.json +0 -0
  27. /package/{data → dist/fbneo}/romsets/capcom.json +0 -0
  28. /package/{data → dist/fbneo}/romsets/cave.json +0 -0
  29. /package/{data → dist/fbneo}/romsets/channelf.json +0 -0
  30. /package/{data → dist/fbneo}/romsets/coleco.json +0 -0
  31. /package/{data → dist/fbneo}/romsets/cps3.json +0 -0
  32. /package/{data → dist/fbneo}/romsets/dataeast.json +0 -0
  33. /package/{data → dist/fbneo}/romsets/galaxian.json +0 -0
  34. /package/{data → dist/fbneo}/romsets/index.json +0 -0
  35. /package/{data → dist/fbneo}/romsets/irem.json +0 -0
  36. /package/{data → dist/fbneo}/romsets/konami.json +0 -0
  37. /package/{data → dist/fbneo}/romsets/megadrive.json +0 -0
  38. /package/{data → dist/fbneo}/romsets/midway.json +0 -0
  39. /package/{data → dist/fbneo}/romsets/msx.json +0 -0
  40. /package/{data → dist/fbneo}/romsets/neogeo.json +0 -0
  41. /package/{data → dist/fbneo}/romsets/nes.json +0 -0
  42. /package/{data → dist/fbneo}/romsets/pce.json +0 -0
  43. /package/{data → dist/fbneo}/romsets/pgm.json +0 -0
  44. /package/{data → dist/fbneo}/romsets/pgm2.json +0 -0
  45. /package/{data → dist/fbneo}/romsets/pre90s.json +0 -0
  46. /package/{data → dist/fbneo}/romsets/psikyo.json +0 -0
  47. /package/{data → dist/fbneo}/romsets/pst90s.json +0 -0
  48. /package/{data → dist/fbneo}/romsets/sega.json +0 -0
  49. /package/{data → dist/fbneo}/romsets/sg1000.json +0 -0
  50. /package/{data → dist/fbneo}/romsets/sms.json +0 -0
  51. /package/{data → dist/fbneo}/romsets/snes.json +0 -0
  52. /package/{data → dist/fbneo}/romsets/spectrum.json +0 -0
  53. /package/{data → dist/fbneo}/romsets/taito.json +0 -0
  54. /package/{data → dist/fbneo}/romsets/toaplan.json +0 -0
package/src/fbneo.sdk.ts CHANGED
@@ -1,256 +1,688 @@
1
- import type {
2
- AssetData,
3
- EngineConfig,
4
- EngineEvent,
5
- EngineInstance,
6
- InputPreset,
7
- KeyMap,
1
+ /**
2
+ * The engine package's entry point: an `EngineSDK` for FBNeo (FinalBurn Neo), the
3
+ * arcade emulator.
4
+ *
5
+ * ```js
6
+ * import FbneoSDK from '@wasm-gaming/fbneo-wasm';
7
+ *
8
+ * const play = await new FbneoSDK()
9
+ * .options({ driver: 'mslug' }) // or romFileName: 'mslug.zip'
10
+ * .assets({ rom: () => readZip(), bios: () => readBios() })
11
+ * .storage({ namespace: 'mslug' }) // → OPFS fbneo/mslug/
12
+ * .mount(document.querySelector('#stage'))
13
+ * .start();
14
+ *
15
+ * play.pause('menu'); play.resume('menu');
16
+ * await play.restart(); // soft reset
17
+ * await play.destroy(); // saves flushed, loop stopped
18
+ * ```
19
+ *
20
+ * Everything a host drives is the contract's (`@wasm-gaming/engine-specs`); what is
21
+ * this engine's own: {@link FbneoConfig} and friends, owner-aware
22
+ * {@link FbneoPlay.pause} / {@link FbneoPlay.resume}, {@link FbneoPlay.states},
23
+ * {@link FbneoPlay.storagePath} and the `saves` event.
24
+ *
25
+ * Saves: the build points FBNeo's NVRAM/EEPROM and hiscore paths at MEMFS `/save`.
26
+ * The SDK seeds it from OPFS `fbneo/<namespace>/` before boot and mirrors it back
27
+ * after asking FBNeo to write (`web_persist`): every 10 s, on pause, when the page is
28
+ * hidden and on destroy. Upstream only wrote at exit, which a web page never reaches.
29
+ */
30
+ import {
31
+ EnginePlayBase,
32
+ EngineSDKBase,
33
+ EventEmitter,
34
+ type EngineInit,
35
+ type EngineSDKConstructor,
36
+ type EventsOf,
8
37
  } from '@wasm-gaming/engine-specs';
9
- import { manifest } from './fbneo.manifest.js';
10
- import { DEFAULT_FBNEO_OPTIONS, type FbneoOptions } from './fbneo.options.js';
38
+ import {
39
+ FBNEO_SPEC,
40
+ FBNEO_VIDEO,
41
+ type FbneoAsset,
42
+ type FbneoConfig,
43
+ type FbneoOptions,
44
+ type FbneoPayloads,
45
+ } from './fbneo.options.js';
11
46
 
12
- export { manifest };
47
+ export type {
48
+ FbneoAsset,
49
+ FbneoAssets,
50
+ FbneoConfig,
51
+ FbneoEvents,
52
+ FbneoOptions,
53
+ FbneoPayloads,
54
+ FbneoStorage,
55
+ } from './fbneo.options.js';
56
+ export { FBNEO_SPEC, FBNEO_VIDEO } from './fbneo.options.js';
13
57
 
58
+ const ENGINE_ID = 'fbneo';
59
+ const DEFAULT_STORAGE_NAMESPACE = 'default';
60
+ const SAVE_DIR = '/save';
14
61
  /**
15
- * Shape of the Emscripten Module object exposed by fbneo.js.
16
- *
17
- * FBNeo's Emscripten SDL2 build is expected to be produced with
18
- * `-sMODULARIZE -sEXPORT_NAME=createFbneoModule` and the full `FS` object
19
- * exported (`-sEXPORTED_RUNTIME_METHODS=FS,callMain`). We defensively support
20
- * both the modularized factory and the classic global-`Module` shape.
62
+ * FBNeo's ROM search paths (src/burner/sdl/drv.cpp): the absolute one is always
63
+ * searched; `/roms` covers the cwd-relative `roms/` with the cwd at `/`.
21
64
  */
22
- type FbneoModule = {
65
+ const ROM_DIRS = ['/usr/local/share/roms', '/roms'];
66
+ const SAVE_INTERVAL_MS = 10_000;
67
+ /** How long a ROM set may take to load before start() gives up. */
68
+ const LOAD_TIMEOUT_MS = 30_000;
69
+
70
+ /** The Emscripten module this build produces (`createFbneoModule` from fbneo.js). */
71
+ interface FbneoModule {
23
72
  FS: {
24
73
  mkdirTree(path: string): void;
25
74
  writeFile(path: string, data: Uint8Array): void;
26
- analyzePath(path: string): { exists: boolean };
75
+ readFile(path: string): Uint8Array;
27
76
  readdir(path: string): string[];
77
+ stat(path: string): { mode: number; mtime: Date | number };
78
+ unlink(path: string): void;
79
+ isFile(mode: number): boolean;
28
80
  };
29
81
  callMain(args: string[]): void;
30
- pauseMainLoop?: () => void;
31
- resumeMainLoop?: () => void;
32
- onRuntimeInitialized?: () => void;
33
- locateFile?: (path: string, prefix: string) => string;
34
- noInitialRun?: boolean;
35
- canvas: HTMLCanvasElement;
36
- };
37
-
38
- type FbneoModuleFactory = (overrides: Partial<FbneoModule>) => Promise<FbneoModule>;
39
-
40
- const scriptLoadCache = new Map<string, Promise<void>>();
41
-
42
- function loadClassicScriptOnce(src: string): Promise<void> {
43
- const cached = scriptLoadCache.get(src);
44
- if (cached) return cached;
45
-
46
- const p = new Promise<void>((resolve, reject) => {
47
- const script = document.createElement('script');
48
- script.src = src;
49
- script.async = true;
50
- script.onload = () => resolve();
51
- script.onerror = () => reject(new Error(`fbneo: failed to load script: ${src}`));
52
- document.head.appendChild(script);
53
- });
54
-
55
- scriptLoadCache.set(src, p);
56
- return p;
82
+ _web_set_paused(paused: number): void;
83
+ _web_reset(): void;
84
+ _web_persist(): number;
85
+ _web_save_state(slot: number): number;
86
+ _web_load_state(slot: number): number;
87
+ _web_running(): number;
88
+ _web_quit(): void;
89
+ SDL2?: { audioContext?: AudioContext };
57
90
  }
58
91
 
59
- function toUint8(x: AssetData | undefined | unknown): Uint8Array | null {
60
- if (x == null) return null;
61
- if (typeof x === 'string') return new TextEncoder().encode(x);
62
- if (x instanceof Uint8Array) return x;
63
- if (x instanceof ArrayBuffer) return new Uint8Array(x);
64
- if (ArrayBuffer.isView(x)) return new Uint8Array(x.buffer, x.byteOffset, x.byteLength);
65
- throw new TypeError('fbneo: asset must be Uint8Array | ArrayBuffer | string');
66
- }
92
+ type FbneoFactory = (overrides: Record<string, unknown>) => Promise<FbneoModule>;
67
93
 
68
- /** Strip a directory and extension from a zip filename to get the FBNeo driver name. */
69
- function driverFromFileName(fileName: string): string {
70
- const base = fileName.replace(/^.*[\\/]/, '');
71
- return base.replace(/\.(zip|7z)$/i, '');
94
+ /**
95
+ * Where an engine keeps one namespace: `<engineId>/<namespace>`, relative to the OPFS
96
+ * root. Identical to the other engines': segments cleaned, `.` and `..` dropped,
97
+ * anything outside `[A-Za-z0-9._-]` → `_`, nothing usable → `default`; a leading
98
+ * `<engineId>/` is stripped once.
99
+ */
100
+ export function storagePath(
101
+ engineId: string,
102
+ namespace: unknown,
103
+ ): { namespace: string; path: string; prefixed: boolean } {
104
+ const segments =
105
+ typeof namespace === 'string'
106
+ ? namespace
107
+ .split('/')
108
+ .map((segment) => segment.trim())
109
+ .filter((segment) => segment && segment !== '.' && segment !== '..')
110
+ .map((segment) => segment.replace(/[^A-Za-z0-9._-]/g, '_'))
111
+ : [];
112
+ const prefixed = segments.length > 1 && segments[0] === engineId;
113
+ if (prefixed) segments.shift();
114
+ const cleaned = segments.join('/') || DEFAULT_STORAGE_NAMESPACE;
115
+ return { namespace: cleaned, path: `${engineId}/${cleaned}`, prefixed };
72
116
  }
73
117
 
74
118
  /**
75
- * Resolve the render canvas from the contract's `EngineConfig`.
76
- * The contract is a union: hosts pass either `canvasEl` (a render target) or
77
- * `attachTo` (a container the SDK mounts its own canvas into). Legacy `canvas`
78
- * is still accepted as a defensive fallback for hosts built against 0.1.x.
119
+ * The FBNeo driver for a session: `driver` when given, else the ROM file name's stem
120
+ * (`mslug.zip`, `C:\roms\mslug.7z` → `mslug`). Empty when neither says.
79
121
  */
80
- function resolveCanvas(config: EngineConfig): HTMLCanvasElement {
81
- const c =
82
- (config as { canvasEl?: HTMLCanvasElement }).canvasEl ??
83
- (config as { canvas?: HTMLCanvasElement }).canvas;
84
- if (c) return c;
85
-
86
- const attachTo = (config as { attachTo?: HTMLElement }).attachTo;
87
- if (attachTo) {
88
- const existing = attachTo.querySelector('canvas');
89
- if (existing) return existing;
90
- const created = document.createElement('canvas');
91
- attachTo.appendChild(created);
92
- return created;
122
+ export function driverName(options: { driver?: string; romFileName?: string }): string {
123
+ const explicit = options.driver?.trim();
124
+ if (explicit) return explicit;
125
+ const base = (options.romFileName ?? '').replace(/^.*[\\/]/, '');
126
+ return base.replace(/\.(zip|7z)$/i, '').trim();
127
+ }
128
+
129
+ async function opfsDir(path: string, create: boolean): Promise<FileSystemDirectoryHandle | null> {
130
+ if (typeof navigator === 'undefined' || !navigator.storage?.getDirectory) return null;
131
+ try {
132
+ let dir = await navigator.storage.getDirectory();
133
+ for (const segment of path.split('/').filter(Boolean)) {
134
+ dir = await dir.getDirectoryHandle(segment, { create });
135
+ }
136
+ return dir;
137
+ } catch {
138
+ return null;
93
139
  }
94
- throw new Error('fbneo: config.canvasEl or config.attachTo is required');
95
140
  }
96
141
 
142
+ async function resolveAsset(asset: FbneoAsset | undefined): Promise<Uint8Array | null> {
143
+ const value = typeof asset === 'function' ? await asset() : asset;
144
+ if (value == null) return null;
145
+ if (value instanceof Uint8Array) return value;
146
+ if (value instanceof ArrayBuffer) return new Uint8Array(value);
147
+ throw new TypeError('fbneo: an asset must be a Uint8Array, an ArrayBuffer or a thunk returning one');
148
+ }
149
+
150
+ function sameBytes(a: Uint8Array | undefined, b: Uint8Array): boolean {
151
+ if (!a || a.length !== b.length) return false;
152
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
153
+ return true;
154
+ }
155
+
156
+ /** The player's save-state slots: 0-3. */
157
+ export const STATE_SLOTS = 4;
97
158
  /**
98
- * Ensure the canvas used by FBNeo has `id="canvas"`.
99
- * Emscripten SDL2 queries `document.querySelector('#canvas')` to locate its render target.
159
+ * The *unsaved* suspend point: written when the player leaves, offered when they come
160
+ * back, and saved into a numbered slot only when they ask.
100
161
  */
101
- function prepareCanvas(
102
- canvas: HTMLCanvasElement,
103
- renderFilter: Required<FbneoOptions>['renderFilter'],
104
- ): HTMLCanvasElement {
105
- if (canvas.id !== 'canvas') canvas.id = 'canvas';
106
- if (!canvas.width) canvas.width = manifest.video.baseWidth;
107
- if (!canvas.height) canvas.height = manifest.video.baseHeight;
108
- // SDL2's Emscripten backend measures getBoundingClientRect() (borders/padding
109
- // included) to detect external CSS sizing; decoration on the canvas itself
110
- // makes it create a tiny window. Host pages should decorate a wrapper instead.
111
- canvas.style.border = '0';
112
- canvas.style.padding = '0';
113
- canvas.style.imageRendering = renderFilter === 'pixelated' ? 'pixelated' : 'auto';
114
- return canvas;
162
+ export const AUTO_STATE_SLOT = 9;
163
+
164
+ /** One save-state slot. */
165
+ export interface FbneoStateSlot {
166
+ slot: number;
167
+ /** When the state was written, or null for an empty slot. */
168
+ savedAt: Date | null;
169
+ /** The frame saved with it (PNG), when the host handed one over. */
170
+ thumbnail: Blob | null;
171
+ /** Protected: cannot be overwritten or removed until unlocked. */
172
+ locked: boolean;
115
173
  }
116
174
 
117
- export async function load(config: EngineConfig): Promise<EngineInstance> {
118
- const { assets, onEvent } = config;
175
+ /** Save states: whole-machine snapshots kept in the save folder (and OPFS). */
176
+ export interface FbneoStates {
177
+ /** The player's slots, 0-3. */
178
+ list(): FbneoStateSlot[];
179
+ /** Any slot, {@link AUTO_STATE_SLOT} included. */
180
+ get(slot: number): FbneoStateSlot;
181
+ /** Save the running game into `slot` (paused or not). Refuses a locked slot. */
182
+ save(slot: number, options?: { thumbnail?: Blob | null }): Promise<void>;
183
+ /** Load `slot` into the running game; false when it is empty or FBNeo refused it. */
184
+ load(slot: number): boolean;
185
+ /** Copy a state (and its frame) into another slot — the unsaved point into a numbered one. */
186
+ copy(from: number, to: number): Promise<void>;
187
+ lock(slot: number, locked: boolean): Promise<void>;
188
+ remove(slot: number): Promise<void>;
189
+ }
119
190
 
120
- const emit = (e: EngineEvent): void => {
121
- try {
122
- onEvent?.(e);
123
- } catch {
124
- // host callback must not break the engine runtime
125
- }
126
- };
191
+ const nextFrame = (): Promise<void> => new Promise((resolve) => requestAnimationFrame(() => resolve()));
192
+ const mtimeOf = (value: Date | number | undefined): number =>
193
+ value instanceof Date ? value.getTime() : typeof value === 'number' ? value : 0;
194
+
195
+ /** The live engine: one booted FBNeo and its session. */
196
+ export class FbneoPlay extends EnginePlayBase<FbneoPayloads> {
197
+ #module: FbneoModule | null = null;
198
+ #destroyed = false;
199
+ #pauseOwner: string | null = null;
200
+ #driver = '';
127
201
 
128
- // Generic hosts (e.g. the engine-specs demo shell) pass the picked file's name
129
- // as `options.fileName`; treat it as an alias for `romFileName` so the driver
130
- // can be inferred from the ROM's filename without a FBNeo-specific option.
131
- const rawOptions = config.options as
132
- | (FbneoOptions & { fileName?: string })
133
- | undefined;
134
- const opts: Required<FbneoOptions> = {
135
- ...DEFAULT_FBNEO_OPTIONS,
136
- ...rawOptions,
137
- romFileName:
138
- rawOptions?.romFileName ??
139
- rawOptions?.fileName ??
140
- DEFAULT_FBNEO_OPTIONS.romFileName,
202
+ #canvas: HTMLCanvasElement | null = null;
203
+ #ownsCanvas = false;
204
+ #box: HTMLElement | null = null;
205
+ #boxObserver: ResizeObserver | null = null;
206
+ #canvasObserver: MutationObserver | null = null;
207
+
208
+ #namespace = DEFAULT_STORAGE_NAMESPACE;
209
+ #storagePath = `${ENGINE_ID}/${DEFAULT_STORAGE_NAMESPACE}`;
210
+ #persist = true;
211
+ #saveTimer: ReturnType<typeof setInterval> | null = null;
212
+ #lastSaved = new Map<string, Uint8Array>();
213
+ #flushing: Promise<void> | null = null;
214
+ #onHidden = (): void => {
215
+ if (document.visibilityState === 'hidden') void this.flushSaves();
141
216
  };
142
217
 
143
- const romBytes = toUint8(assets?.rom ?? assets?.data);
144
- if (!romBytes) {
145
- throw new Error('fbneo: no ROM bytes provided — pass assets.rom (an arcade ROM zip)');
218
+ constructor(init?: EngineInit<FbneoPayloads>, events?: EventEmitter<EventsOf<FbneoPayloads>>) {
219
+ super(FBNEO_SPEC, init, events);
220
+ }
221
+
222
+ /** The normalised namespace this session uses. */
223
+ get namespace(): string {
224
+ return this.#namespace;
146
225
  }
147
- const biosBytes = toUint8(assets?.bios);
148
-
149
- const canvas = prepareCanvas(resolveCanvas(config), opts.renderFilter);
150
-
151
- // FBNeo boots a game by its ROM-set short name ("driver", e.g. "mslug") and
152
- // searches its ROM paths for a matching `<driver>.zip`. Prefer an explicit
153
- // `options.driver`; otherwise derive it from the ROM filename (stripping the
154
- // extension). Whatever the source, the zip is mounted as `<driver>.zip` so the
155
- // name FBNeo looks up and the name on disk always agree.
156
- const driver = (opts.driver || driverFromFileName(opts.romFileName)).trim();
157
- if (!driver || driver === 'game') {
158
- throw new Error(
159
- 'fbneo: could not determine the ROM-set name. Pass options.driver (the FBNeo ' +
160
- 'short name, e.g. "mslug") or name the ROM file after it (e.g. mslug.zip).',
161
- );
226
+
227
+ /** Where this session's saves live, relative to the OPFS root: `fbneo/<namespace>`. */
228
+ get storagePath(): string {
229
+ return this.#storagePath;
162
230
  }
163
- const romFileName = `${driver}.zip`;
164
-
165
- const jsUrl = config.jsUrl ?? new URL('./fbneo.js', import.meta.url).href;
166
- const wasmUrl = config.wasmUrl ?? new URL('./fbneo.wasm', jsUrl).href;
167
-
168
- let modRef: FbneoModule | null = null;
169
- let readyResolve: () => void = () => {};
170
- const readyPromise = new Promise<void>((resolve) => {
171
- readyResolve = resolve;
172
- });
173
-
174
- // FBNeo's default ROM search paths (src/burner/sdl/drv.cpp) are the absolute
175
- // "/usr/local/share/roms/" and the cwd-relative "roms/". Under Emscripten the
176
- // cwd is not guaranteed to be "/", so write to the absolute path (always
177
- // searched) as well as "/roms/". FBNeo matches ROM files inside each zip by
178
- // name/CRC, so the zip must be named after the driver.
179
- const romDirs = ['/usr/local/share/roms', '/roms'];
180
- const writeRoms = (mod: FbneoModule): void => {
181
- for (const dir of romDirs) {
182
- mod.FS.mkdirTree(dir);
183
- mod.FS.writeFile(`${dir}/${romFileName}`, romBytes);
184
- if (biosBytes) mod.FS.writeFile(`${dir}/neogeo.zip`, biosBytes);
231
+
232
+ /** The driver (ROM-set short name) this session booted. */
233
+ get driver(): string {
234
+ return this.#driver;
235
+ }
236
+
237
+ /** Who holds the pause, or null while running. */
238
+ get pausedBy(): string | null {
239
+ return this.#pauseOwner;
240
+ }
241
+
242
+ /**
243
+ * The current frame as a PNG (also while paused: the picture is kept). Null when
244
+ * there is nothing to read.
245
+ */
246
+ async snapshot(): Promise<Blob | null> {
247
+ const canvas = this.#canvas;
248
+ if (!canvas || !this.#module) return null;
249
+ await nextFrame();
250
+ const copy = document.createElement('canvas');
251
+ copy.width = canvas.width || FBNEO_VIDEO.width;
252
+ copy.height = canvas.height || FBNEO_VIDEO.height;
253
+ copy.getContext('2d')?.drawImage(canvas, 0, 0, copy.width, copy.height);
254
+ return new Promise((resolve) => copy.toBlob((blob) => resolve(blob), 'image/png'));
255
+ }
256
+
257
+ /** Save states — see {@link FbneoStates}. */
258
+ get states(): FbneoStates {
259
+ const Module = this.#requireModule();
260
+ const { FS } = Module;
261
+ const file = (name: string): string => `${SAVE_DIR}/${name}`;
262
+ const exists = (name: string): boolean => {
263
+ try {
264
+ FS.stat(file(name));
265
+ return true;
266
+ } catch {
267
+ return false;
268
+ }
269
+ };
270
+ const stateName = (slot: number): string => `slot_${slot}.fs`;
271
+ const mtime = (name: string): number | null => {
272
+ try {
273
+ return mtimeOf(FS.stat(file(name)).mtime);
274
+ } catch {
275
+ return null;
276
+ }
277
+ };
278
+ const checkSlot = (slot: number): number => {
279
+ if (slot === AUTO_STATE_SLOT || (Number.isInteger(slot) && slot >= 0 && slot < STATE_SLOTS)) return slot;
280
+ throw new RangeError(`fbneo: a state slot is 0-${STATE_SLOTS - 1} or ${AUTO_STATE_SLOT}, not ${slot}`);
281
+ };
282
+ const isLocked = (slot: number): boolean => exists(`slot_${slot}.lock`);
283
+ const refuseLocked = (slot: number): void => {
284
+ if (isLocked(slot)) throw new Error(`fbneo: state slot ${slot} is locked`);
285
+ };
286
+ // Removed files have to leave OPFS too: the mirror only ever writes.
287
+ const forget = async (names: string[]): Promise<void> => {
288
+ for (const name of names) {
289
+ try {
290
+ FS.unlink(file(name));
291
+ } catch {
292
+ /* not there */
293
+ }
294
+ this.#lastSaved.delete(name);
295
+ }
296
+ const dir = this.#persist ? await opfsDir(this.#storagePath, false) : null;
297
+ for (const name of names) await dir?.removeEntry(name).catch(() => {});
298
+ };
299
+ const get = (slot: number): FbneoStateSlot => {
300
+ checkSlot(slot);
301
+ const savedAt = mtime(stateName(slot));
302
+ let thumbnail: Blob | null = null;
303
+ if (savedAt !== null && exists(`slot_${slot}.png`)) {
304
+ thumbnail = new Blob([new Uint8Array(FS.readFile(file(`slot_${slot}.png`)))], { type: 'image/png' });
305
+ }
306
+ return { slot, savedAt: savedAt === null ? null : new Date(savedAt), thumbnail, locked: isLocked(slot) };
307
+ };
308
+ return {
309
+ list: () => Array.from({ length: STATE_SLOTS }, (_, slot) => get(slot)),
310
+ get,
311
+ save: async (slot, options = {}) => {
312
+ checkSlot(slot);
313
+ refuseLocked(slot);
314
+ // FBNeo writes the state at once (between frames: JS only runs while its loop sleeps).
315
+ if (!Module._web_save_state(slot)) throw new Error('fbneo: the state could not be saved (no game running?)');
316
+ if (options.thumbnail) {
317
+ FS.writeFile(file(`slot_${slot}.png`), new Uint8Array(await options.thumbnail.arrayBuffer()));
318
+ } else await forget([`slot_${slot}.png`]);
319
+ await this.flushSaves();
320
+ },
321
+ load: (slot) => {
322
+ checkSlot(slot);
323
+ if (mtime(stateName(slot)) === null) return false;
324
+ return Module._web_load_state(slot) !== 0;
325
+ },
326
+ copy: async (from, to) => {
327
+ checkSlot(from);
328
+ checkSlot(to);
329
+ refuseLocked(to);
330
+ if (mtime(stateName(from)) === null) throw new Error(`fbneo: state slot ${from} is empty`);
331
+ await forget([stateName(to), `slot_${to}.png`]);
332
+ FS.writeFile(file(stateName(to)), new Uint8Array(FS.readFile(file(stateName(from)))));
333
+ if (exists(`slot_${from}.png`)) {
334
+ FS.writeFile(file(`slot_${to}.png`), new Uint8Array(FS.readFile(file(`slot_${from}.png`))));
335
+ }
336
+ await this.flushSaves();
337
+ },
338
+ lock: async (slot, locked) => {
339
+ checkSlot(slot);
340
+ if (locked) {
341
+ if (mtime(stateName(slot)) === null) throw new Error(`fbneo: state slot ${slot} is empty`);
342
+ FS.writeFile(file(`slot_${slot}.lock`), new Uint8Array([1]));
343
+ await this.flushSaves();
344
+ } else {
345
+ await forget([`slot_${slot}.lock`]);
346
+ this.emit('saves', { files: [`slot_${slot}.lock`] });
347
+ }
348
+ },
349
+ remove: async (slot) => {
350
+ checkSlot(slot);
351
+ refuseLocked(slot);
352
+ const names = [stateName(slot), `slot_${slot}.png`];
353
+ await forget(names);
354
+ this.emit('saves', { files: names });
355
+ },
356
+ };
357
+ }
358
+
359
+ #requireModule(): FbneoModule {
360
+ if (!this.#module) throw new Error('fbneo: the engine is not running — start() it first');
361
+ return this.#module;
362
+ }
363
+
364
+ /**
365
+ * Freeze emulation and sound. The first caller owns the pause, and only that
366
+ * owner's {@link resume} lifts it, so an overlay cannot resume a game the host had
367
+ * already frozen. Saves are flushed, since a paused game is often a closed one.
368
+ */
369
+ pause(owner = 'host'): void {
370
+ const Module = this.#module;
371
+ if (!Module || this.#pauseOwner) return;
372
+ this.#pauseOwner = owner;
373
+ Module._web_set_paused(1);
374
+ void Module.SDL2?.audioContext?.suspend();
375
+ void this.flushSaves();
376
+ this.emit('pause', { owner });
377
+ }
378
+
379
+ resume(owner = 'host'): void {
380
+ const Module = this.#module;
381
+ if (!Module || this.#pauseOwner !== owner) return;
382
+ this.#pauseOwner = null;
383
+ void Module.SDL2?.audioContext?.resume();
384
+ Module._web_set_paused(0);
385
+ this.emit('resume', { owner });
386
+ }
387
+
388
+ /**
389
+ * Ask FBNeo to write its NVRAM, then copy whatever changed in `/save` to OPFS
390
+ * `fbneo/<namespace>/`. Emits `saves` with the files that moved. Safe to call any
391
+ * time; overlapping calls share one flush.
392
+ */
393
+ flushSaves(): Promise<void> {
394
+ this.#flushing ??= this.#flush().finally(() => {
395
+ this.#flushing = null;
396
+ });
397
+ return this.#flushing;
398
+ }
399
+
400
+ // ---- Contract hooks ----
401
+
402
+ protected override mounted(target: HTMLElement): void {
403
+ if (target instanceof HTMLCanvasElement) {
404
+ this.#canvas = target;
405
+ this.#ownsCanvas = false;
406
+ this.#box = target.parentElement;
407
+ } else {
408
+ this.#canvas = document.createElement('canvas');
409
+ this.#ownsCanvas = true;
410
+ this.#box = target;
411
+ target.appendChild(this.#canvas);
185
412
  }
186
- };
413
+ const canvas = this.#canvas;
414
+ // Emscripten's SDL2 finds its window by id, and measures the element: no border or
415
+ // padding on the canvas itself, or SDL creates a tiny window.
416
+ canvas.id = 'canvas';
417
+ if (!canvas.width) canvas.width = FBNEO_VIDEO.width;
418
+ if (!canvas.height) canvas.height = FBNEO_VIDEO.height;
419
+ canvas.tabIndex = 0;
420
+ canvas.style.border = '0';
421
+ canvas.style.padding = '0';
422
+ canvas.style.display = 'block';
423
+ canvas.addEventListener('contextmenu', (event) => event.preventDefault());
424
+ void this.#applyFilter();
187
425
 
188
- const moduleOverrides: Partial<FbneoModule> = {
189
- canvas,
190
- noInitialRun: true,
191
- locateFile(path: string): string {
192
- if (path.endsWith('.wasm')) return wasmUrl;
193
- return new URL(path, jsUrl).href;
194
- },
195
- };
426
+ if (this.#box && this.#ownsCanvas) {
427
+ this.#boxObserver?.disconnect();
428
+ this.#boxObserver = new ResizeObserver(() => this.#fit());
429
+ this.#boxObserver.observe(this.#box);
430
+ // FBNeo sizes the canvas to each game's picture (vertical games too): refit then.
431
+ this.#canvasObserver?.disconnect();
432
+ this.#canvasObserver = new MutationObserver(() => this.#fit());
433
+ this.#canvasObserver.observe(canvas, { attributes: true, attributeFilter: ['width', 'height'] });
434
+ this.#fit();
435
+ }
436
+ }
196
437
 
197
- await loadClassicScriptOnce(jsUrl);
438
+ protected override async open(_options: FbneoOptions): Promise<void> {
439
+ if (this.#destroyed) {
440
+ throw new Error('fbneo: this engine has been destroyed and cannot be started again in this page — build a new FbneoSDK in a new page');
441
+ }
442
+ if (this.#module) {
443
+ // Already running: a restart is the machine's soft reset.
444
+ if (this.#pauseOwner) this.resume(this.#pauseOwner);
445
+ this.#module._web_reset();
446
+ return;
447
+ }
448
+ await this.#boot();
449
+ }
198
450
 
199
- const g = globalThis as {
200
- createFbneoModule?: FbneoModuleFactory;
201
- Module?: FbneoModule;
202
- };
451
+ protected override patched(kind: string, patch: object): void {
452
+ if (kind === 'config' && 'renderFilter' in patch) void this.#applyFilter();
453
+ }
454
+
455
+ protected override async close(): Promise<void> {
456
+ if (this.#saveTimer) clearInterval(this.#saveTimer);
457
+ this.#saveTimer = null;
458
+ document.removeEventListener('visibilitychange', this.#onHidden);
459
+ window.removeEventListener('pagehide', this.#onHidden);
203
460
 
204
- // Our build is a MODULARIZE factory (createFbneoModule). The factory promise
205
- // resolves *after* the runtime is initialized and FS is available, so this is
206
- // the correct point to populate MEMFS — write the ROMs before callMain().
207
- if (typeof g.createFbneoModule === 'function') {
208
- modRef = await g.createFbneoModule(moduleOverrides);
209
- } else if (g.Module) {
210
- modRef = g.Module;
211
- } else {
212
- throw new Error('fbneo: unable to initialize runtime module from fbneo.js');
461
+ const Module = this.#module;
462
+ if (Module) {
463
+ await this.flushSaves();
464
+ const context = Module.SDL2?.audioContext;
465
+ try {
466
+ Module._web_set_paused(1);
467
+ // Ends FBNeo's loop: it exits the game its own way (NVRAM written, sound closed).
468
+ Module._web_quit();
469
+ } catch {
470
+ /* already gone */
471
+ }
472
+ // FBNeo's exit closes the AudioContext on the loop's next turn; close it here only
473
+ // if it didn't (closing it first makes FBNeo's own close throw).
474
+ const deadline = performance.now() + 1000;
475
+ while (context && context.state !== 'closed' && performance.now() < deadline) {
476
+ await new Promise((resolve) => setTimeout(resolve, 50));
477
+ }
478
+ if (context && context.state !== 'closed') await context.close().catch(() => {});
479
+ }
480
+ this.#boxObserver?.disconnect();
481
+ this.#boxObserver = null;
482
+ this.#canvasObserver?.disconnect();
483
+ this.#canvasObserver = null;
484
+ if (this.#ownsCanvas) this.#canvas?.remove();
485
+ this.#canvas = null;
486
+ this.#module = null;
487
+ this.#pauseOwner = null;
488
+ this.#destroyed = true;
213
489
  }
214
490
 
215
- writeRoms(modRef);
216
- readyResolve();
491
+ // ---- Boot ----
217
492
 
218
- await readyPromise;
493
+ async #boot(): Promise<void> {
494
+ const config = await this.#values<FbneoConfig>('config');
495
+ const options = await this.#values<FbneoOptions>('options');
496
+ const assets = await this.#values<{ rom?: FbneoAsset; bios?: FbneoAsset }>('assets');
497
+ const storage = await this.#values<{ namespace?: string; persist?: 'opfs' | null }>('storage');
219
498
 
220
- let running = false;
221
- const boot = (): void => {
222
- if (running) return;
223
- running = true;
224
- // FBNeo SDL takes the ROM set short name and searches its rom paths for it.
225
- modRef!.callMain([driver]);
226
- emit({ type: 'ready' });
227
- };
499
+ if (!this.#canvas) {
500
+ throw new Error('fbneo: mount() an element (or a canvas) before start()');
501
+ }
228
502
 
229
- const setInput = (_map: InputPreset | KeyMap): void => {
230
- // Input is handled by the Emscripten SDL2 event loop; no external override yet.
231
- };
503
+ const driver = driverName(options);
504
+ if (!driver) {
505
+ throw new Error(
506
+ 'fbneo: which game is it? Pass options.driver (the FBNeo short name, e.g. "mslug") ' +
507
+ 'or options.romFileName named after it (mslug.zip).',
508
+ );
509
+ }
510
+ const rom = await resolveAsset(assets.rom);
511
+ if (!rom) throw new Error('fbneo: no ROM set — hand one over as assets.rom (bytes or a thunk)');
512
+ const bios = await resolveAsset(assets.bios);
513
+ this.#driver = driver;
232
514
 
233
- return {
234
- start() {
235
- boot();
236
- },
237
- pause() {
238
- modRef?.pauseMainLoop?.();
239
- },
240
- resume() {
241
- modRef?.resumeMainLoop?.();
242
- },
243
- reset() {
244
- // FBNeo does not expose a soft-reset hook through this WASM build.
245
- throw new Error('fbneo: reset is not supported by this build');
246
- },
247
- setInput,
248
- destroy() {
249
- modRef?.pauseMainLoop?.();
250
- running = false;
251
- emit({ type: 'exit' });
252
- },
253
- };
515
+ const resolved = storagePath(ENGINE_ID, storage.namespace);
516
+ this.#namespace = resolved.namespace;
517
+ this.#storagePath = resolved.path;
518
+ this.#persist = storage.persist !== null;
519
+
520
+ const jsUrl = config.jsUrl ?? new URL('./fbneo.js', import.meta.url).href;
521
+ const wasmUrl = config.wasmUrl ?? new URL('./fbneo.wasm', import.meta.url).href;
522
+ const { default: createFbneoModule } = (await import(/* @vite-ignore */ jsUrl)) as {
523
+ default: FbneoFactory;
524
+ };
525
+
526
+ // The context SDL will use, made first so it keeps its picture between frames:
527
+ // FBNeo draws from timers, not animation frames, so without this snapshot() (the
528
+ // app's suspend-point frames) reads a cleared buffer. SDL gets this one back.
529
+ this.#canvas.getContext('webgl', { preserveDrawingBuffer: true, antialias: false });
530
+
531
+ let failed: ((error: Error) => void) | null = null;
532
+ // FBNeo reports a set it could not load only on stdout (then main() returns).
533
+ let refused: string | null = null;
534
+ const Module = await createFbneoModule({
535
+ canvas: this.#canvas,
536
+ noInitialRun: true,
537
+ locateFile: (path: string) => (path.endsWith('.wasm') ? wasmUrl : new URL(path, jsUrl).href),
538
+ print: (text: string) => {
539
+ if (/error loading your selected game/i.test(text)) refused = text;
540
+ console.log('[fbneo]', text);
541
+ },
542
+ printErr: (text: string) => console.warn('[fbneo]', text),
543
+ onAbort: (what: unknown) => failed?.(new Error(`fbneo: aborted — ${String(what)}`)),
544
+ });
545
+ this.#module = Module;
546
+ failed = (error) => this.emit('error', error);
547
+
548
+ const { FS } = Module;
549
+ // FBNeo finds a game by `<driver>.zip` in its ROM paths, and matches the files
550
+ // inside by name/CRC: whatever the player named the file, it lands as that.
551
+ for (const dir of ROM_DIRS) {
552
+ FS.mkdirTree(dir);
553
+ FS.writeFile(`${dir}/${driver}.zip`, rom);
554
+ if (bios) FS.writeFile(`${dir}/neogeo.zip`, bios);
555
+ }
556
+ FS.mkdirTree(SAVE_DIR);
557
+ if (this.#persist) await this.#restoreSaves();
558
+
559
+ // callMain() returns at FBNeo's first yield, before the set is loaded: wait for
560
+ // the game to run, or for FBNeo to say it refused the set, so a bad set is an
561
+ // error here and not a black screen.
562
+ Module.callMain([driver]);
563
+ const deadline = performance.now() + LOAD_TIMEOUT_MS;
564
+ while (!Module._web_running() && !refused && performance.now() < deadline) {
565
+ await new Promise((resolve) => setTimeout(resolve, 50));
566
+ }
567
+ if (!Module._web_running()) {
568
+ throw new Error(
569
+ refused
570
+ ? `fbneo: FBNeo could not load "${driver}" — the ROM set is incomplete, is not that driver, or needs a BIOS (neogeo.zip for Neo Geo)`
571
+ : `fbneo: "${driver}" did not start within ${LOAD_TIMEOUT_MS / 1000} s`,
572
+ );
573
+ }
574
+
575
+ if (this.#persist) {
576
+ this.#saveTimer = setInterval(() => void this.flushSaves(), SAVE_INTERVAL_MS);
577
+ document.addEventListener('visibilitychange', this.#onHidden);
578
+ window.addEventListener('pagehide', this.#onHidden);
579
+ }
580
+ this.#fit();
581
+ }
582
+
583
+ /** The plain values behind one payload's descriptors. */
584
+ async #values<T>(kind: 'config' | 'options' | 'assets' | 'storage'): Promise<T> {
585
+ const described = (await this[kind]()) as Record<string, { value: unknown }>;
586
+ const out: Record<string, unknown> = {};
587
+ for (const [key, property] of Object.entries(described)) out[key] = property.value;
588
+ return out as T;
589
+ }
590
+
591
+ // ---- Saves ----
592
+
593
+ async #restoreSaves(): Promise<void> {
594
+ const dir = await opfsDir(this.#storagePath, false);
595
+ if (!dir || !this.#module) return;
596
+ const iterable = dir as unknown as { entries(): AsyncIterable<[string, FileSystemHandle]> };
597
+ for await (const [name, handle] of iterable.entries()) {
598
+ if (handle.kind !== 'file') continue;
599
+ const bytes = new Uint8Array(await (await (handle as FileSystemFileHandle).getFile()).arrayBuffer());
600
+ this.#module.FS.writeFile(`${SAVE_DIR}/${name}`, bytes);
601
+ this.#lastSaved.set(name, bytes);
602
+ }
603
+ }
604
+
605
+ async #flush(): Promise<void> {
606
+ const Module = this.#module;
607
+ if (!Module || !this.#persist) return;
608
+ try {
609
+ Module._web_persist();
610
+ } catch (e) {
611
+ console.warn('[fbneo] persist failed', e);
612
+ return;
613
+ }
614
+ const changed: Array<[string, Uint8Array<ArrayBuffer>]> = [];
615
+ for (const name of Module.FS.readdir(SAVE_DIR)) {
616
+ if (name === '.' || name === '..') continue;
617
+ const path = `${SAVE_DIR}/${name}`;
618
+ if (!Module.FS.isFile(Module.FS.stat(path).mode)) continue;
619
+ const bytes = new Uint8Array(Module.FS.readFile(path));
620
+ if (!sameBytes(this.#lastSaved.get(name), bytes)) changed.push([name, bytes]);
621
+ }
622
+ if (changed.length === 0) return;
623
+
624
+ const dir = await opfsDir(this.#storagePath, true);
625
+ if (!dir) return;
626
+ const written: string[] = [];
627
+ for (const [name, bytes] of changed) {
628
+ try {
629
+ const writable = await (await dir.getFileHandle(name, { create: true })).createWritable();
630
+ await writable.write(bytes);
631
+ await writable.close();
632
+ this.#lastSaved.set(name, bytes);
633
+ written.push(name);
634
+ } catch (e) {
635
+ console.warn(`[fbneo] could not persist ${name}`, e);
636
+ }
637
+ }
638
+ if (written.length) this.emit('saves', { files: written });
639
+ }
640
+
641
+ // ---- Picture ----
642
+
643
+ /** Scale the canvas to fit its box, keeping the picture's own proportions. */
644
+ #fit(): void {
645
+ const canvas = this.#canvas;
646
+ const box = this.#box;
647
+ if (!canvas || !box || !this.#ownsCanvas) return;
648
+ const { width, height } = box.getBoundingClientRect();
649
+ const w = canvas.width || FBNEO_VIDEO.width;
650
+ const h = canvas.height || FBNEO_VIDEO.height;
651
+ if (!width || !height) return;
652
+ const scale = Math.min(width / w, height / h);
653
+ canvas.style.width = `${Math.floor(w * scale)}px`;
654
+ canvas.style.height = `${Math.floor(h * scale)}px`;
655
+ }
656
+
657
+ async #applyFilter(): Promise<void> {
658
+ const canvas = this.#canvas;
659
+ if (!canvas) return;
660
+ const { renderFilter } = await this.#values<FbneoConfig>('config');
661
+ canvas.style.imageRendering = renderFilter === 'smooth' ? 'auto' : 'pixelated';
662
+ }
663
+ }
664
+
665
+ /**
666
+ * The factory a host constructs: static identity, the configuration chain, and a
667
+ * `start()` that boots FBNeo and opens a session.
668
+ */
669
+ export class FbneoSDK extends EngineSDKBase<FbneoPayloads> {
670
+ static readonly id = ENGINE_ID;
671
+ /** Kept in step with package.json by `node scripts/sync-version.mjs`. */
672
+ static readonly version = '0.2.0';
673
+ static readonly name = 'FinalBurn Neo';
674
+ static readonly description =
675
+ 'FBNeo, the arcade emulator (Capcom CPS-1/2/3, SNK Neo Geo, Sega System 16 and more), compiled to WebAssembly. Ships no games: the player provides the ROM sets, and they never leave their browser.';
676
+
677
+ protected override createPlay(
678
+ init: EngineInit<FbneoPayloads>,
679
+ events: EventEmitter<EventsOf<FbneoPayloads>>,
680
+ ): FbneoPlay {
681
+ return new FbneoPlay(init, events);
682
+ }
254
683
  }
255
684
 
256
- export default { manifest, load };
685
+ /** CI's conformance line: if this class stops satisfying the contract, `make test` fails. */
686
+ export const FBNEO_ENGINE: EngineSDKConstructor<FbneoPayloads> = FbneoSDK;
687
+
688
+ export default FbneoSDK;