@vgai/engine 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 (147) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +35 -0
  3. package/package.json +55 -0
  4. package/src/adapter/authoring.ts +402 -0
  5. package/src/adapter/colyseus-networking-adapter.ts +72 -0
  6. package/src/adapter/first-party-systems.ts +103 -0
  7. package/src/adapter/game-adapter.ts +151 -0
  8. package/src/adapter/host-context.ts +77 -0
  9. package/src/adapter/index.ts +85 -0
  10. package/src/adapter/ingest/game-contract.ts +59 -0
  11. package/src/adapter/ingest/overlay-applier.ts +207 -0
  12. package/src/adapter/ingest/overlay-apply.ts +124 -0
  13. package/src/adapter/ingest/overlay-file.ts +126 -0
  14. package/src/adapter/ingest/overlay-report.ts +176 -0
  15. package/src/adapter/ingest/scene-capture.ts +307 -0
  16. package/src/adapter/ingest/upstream-pin.ts +52 -0
  17. package/src/adapter/loop-gate-report.ts +54 -0
  18. package/src/adapter/rapier-physics-adapter.ts +56 -0
  19. package/src/adapter/system-adapter.ts +154 -0
  20. package/src/adapter/transform.ts +18 -0
  21. package/src/adapter/vgai-scene-game-adapter.ts +886 -0
  22. package/src/adapter/world-kind.ts +34 -0
  23. package/src/ai/navigation.ts +164 -0
  24. package/src/animation/anim-graph-types.ts +56 -0
  25. package/src/animation/anim-graph.ts +406 -0
  26. package/src/animation/anim-system.ts +28 -0
  27. package/src/animation/blend-node.ts +119 -0
  28. package/src/animation/property-track.ts +178 -0
  29. package/src/animation/schema.ts +204 -0
  30. package/src/assets.ts +80 -0
  31. package/src/audio/ambient.ts +300 -0
  32. package/src/audio/impacts.ts +212 -0
  33. package/src/audio/index.ts +7 -0
  34. package/src/audio/movement.ts +140 -0
  35. package/src/audio/musical.ts +200 -0
  36. package/src/audio/ui-sounds.ts +171 -0
  37. package/src/audio/vehicle.ts +235 -0
  38. package/src/audio/weapons.ts +152 -0
  39. package/src/core/game-loop.ts +127 -0
  40. package/src/core/system-runner.ts +298 -0
  41. package/src/core/types.ts +58 -0
  42. package/src/dev/console-bridge.ts +83 -0
  43. package/src/dev/debug-draw.ts +80 -0
  44. package/src/dev/logger.ts +119 -0
  45. package/src/ecs/component-manager.ts +748 -0
  46. package/src/ecs/game-component.ts +147 -0
  47. package/src/ecs/hmr-swap-report.ts +65 -0
  48. package/src/input/input-manager.ts +439 -0
  49. package/src/input/input-types.ts +19 -0
  50. package/src/input/schema.ts +129 -0
  51. package/src/loader.ts +70 -0
  52. package/src/manifest/index.ts +24 -0
  53. package/src/manifest/load-file.ts +16 -0
  54. package/src/manifest/load.ts +378 -0
  55. package/src/manifest/schema.ts +375 -0
  56. package/src/physics/collision-system.ts +76 -0
  57. package/src/physics/physics-registry.ts +83 -0
  58. package/src/physics/transform-writer.ts +41 -0
  59. package/src/physics/trigger-dispatch.ts +97 -0
  60. package/src/react/game-state.tsx +172 -0
  61. package/src/render/auto-batcher.ts +169 -0
  62. package/src/render/render-batch-system.ts +268 -0
  63. package/src/render/render-features.ts +146 -0
  64. package/src/render/render-settings.ts +72 -0
  65. package/src/runtime/create-runtime.ts +1152 -0
  66. package/src/runtime/frame-selector-cache.ts +81 -0
  67. package/src/runtime/game.ts +1003 -0
  68. package/src/runtime/input-router.ts +213 -0
  69. package/src/runtime/mount-game.ts +269 -0
  70. package/src/runtime/mount-manifest.ts +361 -0
  71. package/src/runtime/scene-ui-bridge.ts +86 -0
  72. package/src/runtime/scene-ui-data.ts +119 -0
  73. package/src/runtime/state-bridge.ts +79 -0
  74. package/src/runtime/types.ts +196 -0
  75. package/src/scene/asset-loaders.ts +195 -0
  76. package/src/scene/asset-paths.ts +123 -0
  77. package/src/scene/asset-registry.ts +67 -0
  78. package/src/scene/collider-dimensions.ts +125 -0
  79. package/src/scene/component-registry.ts +40 -0
  80. package/src/scene/defaults.ts +164 -0
  81. package/src/scene/geometries/index.ts +7 -0
  82. package/src/scene/geometries/terrain.ts +42 -0
  83. package/src/scene/geometry-registry.ts +42 -0
  84. package/src/scene/instance-registry.ts +84 -0
  85. package/src/scene/instancers/grid.ts +38 -0
  86. package/src/scene/instancers/index.ts +7 -0
  87. package/src/scene/light-camera-factory.ts +97 -0
  88. package/src/scene/material-factory.ts +211 -0
  89. package/src/scene/material-registry.ts +73 -0
  90. package/src/scene/materials/index.ts +7 -0
  91. package/src/scene/materials/water.ts +56 -0
  92. package/src/scene/parse.ts +71 -0
  93. package/src/scene/particles-factory.ts +383 -0
  94. package/src/scene/scene-apply.ts +356 -0
  95. package/src/scene/scene-diff-schema.ts +115 -0
  96. package/src/scene/scene-diff-types.ts +29 -0
  97. package/src/scene/scene-loader.ts +1533 -0
  98. package/src/scene/scene-query.ts +63 -0
  99. package/src/scene/scene-types.ts +34 -0
  100. package/src/scene/scene-version.ts +40 -0
  101. package/src/scene/schema/animation.ts +95 -0
  102. package/src/scene/schema/audio.ts +25 -0
  103. package/src/scene/schema/camera.ts +21 -0
  104. package/src/scene/schema/collider.ts +69 -0
  105. package/src/scene/schema/entity-ref.ts +78 -0
  106. package/src/scene/schema/entity.ts +169 -0
  107. package/src/scene/schema/environment.ts +384 -0
  108. package/src/scene/schema/index.ts +95 -0
  109. package/src/scene/schema/instances.ts +35 -0
  110. package/src/scene/schema/joint.ts +26 -0
  111. package/src/scene/schema/light.ts +38 -0
  112. package/src/scene/schema/material.ts +113 -0
  113. package/src/scene/schema/mesh.ts +108 -0
  114. package/src/scene/schema/particles.ts +398 -0
  115. package/src/scene/schema/physics.ts +49 -0
  116. package/src/scene/schema/scene-file.ts +299 -0
  117. package/src/scene/schema/shadow.ts +24 -0
  118. package/src/scene/schema/spline.ts +21 -0
  119. package/src/scene/schema/tuples.ts +21 -0
  120. package/src/scene/schema/ui.ts +602 -0
  121. package/src/scene/user-data.ts +203 -0
  122. package/src/setup/setup-audio.ts +60 -0
  123. package/src/setup/setup-particles.ts +23 -0
  124. package/src/setup/setup-physics.ts +67 -0
  125. package/src/setup/setup-renderer.ts +529 -0
  126. package/src/types-n8ao.d.ts +37 -0
  127. package/src/types-realism-effects.d.ts +61 -0
  128. package/src/world2d/authoring-2d.ts +208 -0
  129. package/src/world2d/capture-to-scene2d.ts +52 -0
  130. package/src/world2d/collision-2d.ts +106 -0
  131. package/src/world2d/components-2d.ts +86 -0
  132. package/src/world2d/index.ts +66 -0
  133. package/src/world2d/ingest-iframe-2d.ts +255 -0
  134. package/src/world2d/ingest2d.ts +131 -0
  135. package/src/world2d/physics2d-registry.ts +49 -0
  136. package/src/world2d/pixi-game-adapter.ts +325 -0
  137. package/src/world2d/pixi-surface.ts +78 -0
  138. package/src/world2d/scene-capture-2d.ts +117 -0
  139. package/src/world2d/scene2d-loader.ts +308 -0
  140. package/src/world2d/schema/entity2d.ts +145 -0
  141. package/src/world2d/schema/physics2d.ts +53 -0
  142. package/src/world2d/schema/sprite.ts +71 -0
  143. package/src/world2d/schema/tilemap.ts +22 -0
  144. package/src/world2d/schema/tuples2d.ts +25 -0
  145. package/src/world2d/system-adapters-2d.ts +49 -0
  146. package/src/world2d/transform-writer-2d.ts +24 -0
  147. package/src/world2d/types.ts +55 -0
@@ -0,0 +1,255 @@
1
+ /**
2
+ * world2d iframe ingest tiers — the PixiJS analogs of the 3D ingest-iframe adapters.
3
+ *
4
+ * - OPAQUE EMBED (tier 0-1): a prebuilt/self-contained bundle runs in a sandboxed
5
+ * iframe; hosted + sized + disposed, NOT introspectable.
6
+ * - IFRAME-REACHABLE (tier 2-3): a bundle runs in its own iframe realm, but its
7
+ * `import 'pixi.js'` is wired (via an importmap) to a blob module re-exporting the
8
+ * HOST's pixi instance, so every Application/Sprite it creates is a HOST-realm
9
+ * object → the host `Application.prototype.render` trap fires and capture works.
10
+ */
11
+ import {
12
+ type CapturedRuntime2D,
13
+ installSceneCapture2D,
14
+ type SceneCapture2DHandle,
15
+ } from './scene-capture-2d';
16
+
17
+ export interface EmbedMount2D {
18
+ iframe: HTMLIFrameElement;
19
+ dispose: () => void;
20
+ }
21
+
22
+ /** OPAQUE EMBED: sandboxed iframe, no scene introspection (tier 0-1). */
23
+ export function mountIngestGame2DEmbed(html: string, container: HTMLElement): EmbedMount2D {
24
+ const iframe = document.createElement('iframe');
25
+ iframe.setAttribute('sandbox', 'allow-scripts');
26
+ iframe.style.border = '0';
27
+ iframe.style.width = '100%';
28
+ iframe.style.height = '100%';
29
+ iframe.srcdoc = html;
30
+ container.appendChild(iframe);
31
+ return { iframe, dispose: () => iframe.remove() };
32
+ }
33
+
34
+ const HOST_PIXI_KEY = '__vgaiHostPixi';
35
+
36
+ /** Build a blob module that re-exports the host's pixi namespace (for the importmap). */
37
+ function makeHostPixiReexportUrl(pixiNamespace: Record<string, unknown>): string {
38
+ (window as unknown as Record<string, unknown>)[HOST_PIXI_KEY] = pixiNamespace;
39
+ const ident = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
40
+ const keys = Object.keys(pixiNamespace).filter((k) => k !== 'default' && ident.test(k));
41
+ const body =
42
+ `const T = window.parent[${JSON.stringify(HOST_PIXI_KEY)}];\n` +
43
+ `export default T;\n` +
44
+ keys.map((k) => `export const ${k} = T[${JSON.stringify(k)}];`).join('\n');
45
+ return URL.createObjectURL(new Blob([body], { type: 'text/javascript' }));
46
+ }
47
+
48
+ let _reexportKeySeq = 0;
49
+
50
+ /**
51
+ * Generalized host-namespace re-export (the multi-dep analog of {@link makeHostPixiReexportUrl}).
52
+ * Stashes `ns` (an ES module namespace object, e.g. `import * as ns from 'gsap'`) on a unique
53
+ * window key and builds a blob module re-exporting it, so the iframe's importmap can map a bare
54
+ * specifier (pixi.js, @pixi/sound, @pixi/ui, gsap, …) to the HOST's single instance. Default-export
55
+ * handling: `export default T.default ?? T` so `import gsap from 'gsap'` gets gsap, while a
56
+ * default-less namespace (pixi.js) re-exports the namespace itself for `import * as`.
57
+ */
58
+ function makeHostNamespaceReexportUrl(ns: Record<string, unknown>): string {
59
+ const key = `__vgaiHostNs_${_reexportKeySeq++}`;
60
+ (window as unknown as Record<string, unknown>)[key] = ns;
61
+ const ident = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
62
+ const keys = Object.keys(ns).filter((k) => k !== 'default' && ident.test(k));
63
+ const body =
64
+ `const T = window.parent[${JSON.stringify(key)}];\n` +
65
+ `export default (T && T.default !== undefined ? T.default : T);\n` +
66
+ keys.map((k) => `export const ${k} = T[${JSON.stringify(k)}];`).join('\n');
67
+ return URL.createObjectURL(new Blob([body], { type: 'text/javascript' }));
68
+ }
69
+
70
+ export interface IframeReachableMultiOpts {
71
+ captureTimeoutMs?: number;
72
+ /**
73
+ * Bare-specifier → host module-namespace map. MUST include the pixi.js instance the trap is
74
+ * installed on (passed separately as `pixiNamespace`); list the game's OTHER shared bare deps
75
+ * here (@pixi/sound, @pixi/ui, gsap, pixi-filters) so they resolve to host instances and their
76
+ * extension side-effects register on the host pixi (the trapped instance).
77
+ */
78
+ extraDeps?: Record<string, Record<string, unknown>>;
79
+ /**
80
+ * D-Z3 (docs/WAVE3-ADAPTER-PLUMBING-DESIGN.md) — bare-specifier -> VERBATIM
81
+ * URL importmap entries (the project-node_modules fallback for a specifier
82
+ * that isn't in the host-namespace registry but IS installed in the open
83
+ * project's own `node_modules`). Written into the importmap DIRECTLY
84
+ * alongside the `extraDeps` blob-namespace entries — no host-side import,
85
+ * no blob wrapping, no decision logic here: this function just merges
86
+ * whatever `Record<specifier, url>` the caller (editor-side
87
+ * `host-namespace-registry.ts`) already decided. The URL's own transitive
88
+ * `import 'pixi.js'` resolves through this SAME importmap back to the host
89
+ * pixi trap (§0.3), keeping module identity converged without a second pixi
90
+ * instance.
91
+ */
92
+ extraDepUrls?: Record<string, string>;
93
+ /** <base href> for the iframe so the game's relative asset URLs (Assets basePath) resolve. */
94
+ baseHref?: string;
95
+ /**
96
+ * HOST-SIDE asset URL remap (the Pixi analog of the three.js DefaultLoadingManager.setURLModifier
97
+ * asset adapter). A document.write iframe keeps the PARENT's window.location, so PixiJS's Assets
98
+ * resolver (which builds absolute URLs from window.location, not document.baseURI) would resolve
99
+ * the game's relative `basePath:'assets'` against the parent page. Wrapping the host pixi's
100
+ * Assets.init to force this ABSOLUTE basePath fixes resolution without touching the game source —
101
+ * pure host library configuration, restored on dispose.
102
+ */
103
+ assetBaseUrl?: string;
104
+ /** Load the game bundle from this absolute URL (a built multi-file game). */
105
+ bundleUrl?: string;
106
+ /** …or run this inline module source (a single-file game). One of bundleUrl/inlineSrc required. */
107
+ inlineSrc?: string;
108
+ /** DOM the game expects to find before it boots (e.g. a `<div id="game-root">` it appends to). */
109
+ bodyHtml?: string;
110
+ }
111
+
112
+ /**
113
+ * IFRAME-REACHABLE for REAL MULTI-FILE GAMES (cov2d-bundled-dedupe): run a built game bundle
114
+ * (its OWN unaltered source, externalized against pixi at build time) in its own iframe realm
115
+ * whose importmap maps EVERY shared bare dep — pixi.js + @pixi/sound/@pixi/ui/gsap/… — to the
116
+ * HOST instances, and (optionally) a <base href> so its AssetPack/manifest URLs resolve. The
117
+ * host `Application.prototype.render` trap then captures the live stage IN-REALM. The game's
118
+ * source is never touched; all of this is host-side wiring.
119
+ */
120
+ export async function mountIngestGame2DIframeReachableMulti(
121
+ pixiNamespace: unknown,
122
+ container: HTMLElement,
123
+ opts: IframeReachableMultiOpts,
124
+ ): Promise<IframeReachableMount2D> {
125
+ const capture = installSceneCapture2D(pixiNamespace);
126
+ const created: string[] = [];
127
+ const mkUrl = (ns: Record<string, unknown>): string => {
128
+ const u = makeHostNamespaceReexportUrl(ns);
129
+ created.push(u);
130
+ return u;
131
+ };
132
+
133
+ const imports: Record<string, string> = {
134
+ 'pixi.js': mkUrl(pixiNamespace as Record<string, unknown>),
135
+ };
136
+ for (const [spec, ns] of Object.entries(opts.extraDeps ?? {})) imports[spec] = mkUrl(ns);
137
+ // D-Z3 fallback: verbatim URL entries, no blob wrapping, merged in beside
138
+ // the host-namespace ones — decision-free (see `extraDepUrls`'s doc comment).
139
+ for (const [spec, url] of Object.entries(opts.extraDepUrls ?? {})) imports[spec] = url;
140
+
141
+ // Host-side asset URL remap (asset adapter): force the game's Assets.init basePath to an
142
+ // absolute URL so its assets resolve to the served bundle dir, not the parent page path.
143
+ let restoreInit: (() => void) | undefined;
144
+ if (opts.assetBaseUrl) {
145
+ const assetsApi = (
146
+ pixiNamespace as { Assets?: { init?: (o?: Record<string, unknown>) => unknown } }
147
+ ).Assets;
148
+ if (assetsApi?.init) {
149
+ const orig = assetsApi.init.bind(assetsApi);
150
+ assetsApi.init = (o: Record<string, unknown> = {}) =>
151
+ orig({ ...o, basePath: opts.assetBaseUrl });
152
+ restoreInit = () => {
153
+ assetsApi.init = orig;
154
+ };
155
+ }
156
+ }
157
+
158
+ const iframe = document.createElement('iframe');
159
+ iframe.style.border = '0';
160
+ iframe.style.width = '100%';
161
+ iframe.style.height = '100%';
162
+ container.appendChild(iframe);
163
+
164
+ // Split the closing script token so this module's own bundling never sees a literal
165
+ // </script> (defensive; matches the single-dep mount's convention).
166
+ const close = `</${'scr'}ipt>`;
167
+ const baseTag = opts.baseHref ? `<base href="${opts.baseHref}">` : '';
168
+ const scriptTag = opts.bundleUrl
169
+ ? `<script type="module" src="${opts.bundleUrl}">${close}`
170
+ : `<script type="module">${opts.inlineSrc ?? ''}${close}`;
171
+ const importmapTag = `<script type="importmap">${JSON.stringify({ imports })}${close}`;
172
+ const bodyHtml = opts.bodyHtml ?? '';
173
+
174
+ const doc = iframe.contentDocument!;
175
+ doc.open();
176
+ doc.write(
177
+ `<!doctype html><html><head><meta charset="utf-8">${baseTag}${importmapTag}</head><body>${bodyHtml}${scriptTag}</body></html>`,
178
+ );
179
+ doc.close();
180
+
181
+ let captured: CapturedRuntime2D | null = null;
182
+ try {
183
+ captured = await capture.waitForCapture(opts.captureTimeoutMs ?? 12_000);
184
+ } catch {
185
+ captured = null;
186
+ }
187
+
188
+ return {
189
+ iframe,
190
+ capture,
191
+ captured,
192
+ dispose: () => {
193
+ capture.uninstall();
194
+ restoreInit?.();
195
+ for (const u of created) URL.revokeObjectURL(u);
196
+ iframe.remove();
197
+ },
198
+ };
199
+ }
200
+
201
+ export interface IframeReachableMount2D {
202
+ iframe: HTMLIFrameElement;
203
+ capture: SceneCapture2DHandle;
204
+ captured: CapturedRuntime2D | null;
205
+ dispose: () => void;
206
+ }
207
+
208
+ /**
209
+ * IFRAME-REACHABLE (tier 2-3): run `gameModuleSrc` in an iframe whose importmap maps
210
+ * `pixi.js` to a host-pixi re-export blob, and trap the host `Application.prototype`
211
+ * so the bundle's render is captured in-realm.
212
+ */
213
+ export async function mountIngestGame2DIframeReachable(
214
+ pixiNamespace: unknown,
215
+ gameModuleSrc: string,
216
+ container: HTMLElement,
217
+ opts: { captureTimeoutMs?: number } = {},
218
+ ): Promise<IframeReachableMount2D> {
219
+ const capture = installSceneCapture2D(pixiNamespace);
220
+ const reexportUrl = makeHostPixiReexportUrl(pixiNamespace as Record<string, unknown>);
221
+
222
+ const iframe = document.createElement('iframe');
223
+ iframe.style.border = '0';
224
+ iframe.style.width = '100%';
225
+ iframe.style.height = '100%';
226
+ container.appendChild(iframe);
227
+
228
+ const doc = iframe.contentDocument!;
229
+ doc.open();
230
+ doc.write(
231
+ `<!doctype html><html><head><meta charset="utf-8">` +
232
+ `<script type="importmap">${JSON.stringify({ imports: { 'pixi.js': reexportUrl } })}</scr` +
233
+ `ipt></head><body><script type="module">${gameModuleSrc}</scr` +
234
+ `ipt></body></html>`,
235
+ );
236
+ doc.close();
237
+
238
+ let captured: CapturedRuntime2D | null = null;
239
+ try {
240
+ captured = await capture.waitForCapture(opts.captureTimeoutMs ?? 8000);
241
+ } catch {
242
+ captured = null;
243
+ }
244
+
245
+ return {
246
+ iframe,
247
+ capture,
248
+ captured,
249
+ dispose: () => {
250
+ capture.uninstall();
251
+ URL.revokeObjectURL(reexportUrl);
252
+ iframe.remove();
253
+ },
254
+ };
255
+ }
@@ -0,0 +1,131 @@
1
+ import { installSceneCapture2D, type SceneCapture2DHandle } from './scene-capture-2d';
2
+
3
+ /**
4
+ * D-Z3 (docs/WAVE3-ADAPTER-PLUMBING-DESIGN.md) — a manifest's `extraDeps`
5
+ * resolve to TWO kinds of importmap entry: `namespaces` are today's
6
+ * registry-known bare specifiers (host-namespace-registry.ts), re-exported
7
+ * via a blob module (`ingest-iframe-2d.ts`'s `makeHostNamespaceReexportUrl`);
8
+ * `urls` are the D-Z3 fallback — a specifier that isn't registered but IS
9
+ * present in the open project's own `node_modules`, mapped DIRECTLY to its
10
+ * `/project-game-static/node_modules/<spec>/<esm entry>` URL (no host-side
11
+ * import, no blob — the dep executes in the iframe realm and its own
12
+ * transitive `import 'pixi.js'` resolves through the same importmap back to
13
+ * the host pixi trap). All probing/decision logic (which kind a specifier
14
+ * resolves to, exports-map parsing, anti-shim throws) lives editor-side
15
+ * (`host-namespace-registry.ts`) — this engine module only carries the
16
+ * ALREADY-DECIDED shape; `ingest-iframe-2d.ts` stays decision-free and just
17
+ * merges both maps into the iframe importmap.
18
+ */
19
+ export interface ExtraDepsResolution2D {
20
+ namespaces: Record<string, Record<string, unknown>>;
21
+ urls: Record<string, string>;
22
+ }
23
+
24
+ /** A registered unmodified PixiJS game (the world2d analog of `IngestGame`). */
25
+ export interface IngestGame2D {
26
+ id: string;
27
+ name: string;
28
+ description: string;
29
+ /** Shared-pixi path: import + run the unmodified game module. */
30
+ load?: () => Promise<unknown>;
31
+ /** Tier ceiling: how reachable the game's pixi instance is. */
32
+ tier?: 'shared' | 'iframe-reachable' | 'opaque-embed';
33
+ captureTimeoutMs?: number;
34
+ /**
35
+ * IFRAME-REACHABLE-MULTI fields (Track P, docs/PIXI-INGEST-LANDING-DESIGN.md
36
+ * §2): an externalized built bundle mounted via
37
+ * `mountIngestGame2DIframeReachableMulti` (`./ingest-iframe-2d.ts`) instead
38
+ * of `load()` — populated only when `tier` is `'iframe-reachable'` AND
39
+ * `load` is absent. Mirror `IframeReachableMultiOpts`'s fields, EXCEPT
40
+ * `extraDeps`/`pixiNamespace` are THUNKS here, not resolved values — the
41
+ * same "lazy, only invoked at mount time" shape `load` already uses, so
42
+ * building this descriptor (`resolveIngest2DDescriptor` / `discovery2d.ts`,
43
+ * editor-side) never has to be async just to wire up which specifiers/
44
+ * version-skew URL a game needs; only actually MOUNTING it (the ingest-mode
45
+ * mount bridge) pays for the dynamic import of `@pixi/sound`/`gsap`/spine/
46
+ * a standalone pixi build.
47
+ */
48
+ bundleUrl?: string;
49
+ /** <base href> for the iframe (see `IframeReachableMultiOpts.baseHref`). */
50
+ baseHref?: string;
51
+ /** Host-side Assets.init basePath remap (see `IframeReachableMultiOpts.assetBaseUrl`). */
52
+ assetBaseUrl?: string;
53
+ /**
54
+ * Lazily resolve this game's bare-specifier -> extraDeps resolution via the
55
+ * editor's host-namespace registry. Absent (or omitted) means no extra deps
56
+ * beyond pixi.js.
57
+ */
58
+ extraDeps?: () => Promise<ExtraDepsResolution2D>;
59
+ /**
60
+ * Lazily resolve the trapped-pixi namespace for version-skewed games (a
61
+ * dynamic `import()` of the manifest's `pixiModuleUrl`) — absent means
62
+ * "mount against the host's own `pixi.js`" (no skew).
63
+ */
64
+ pixiNamespace?: () => Promise<unknown>;
65
+ /** DOM the game expects before boot (see `IframeReachableMultiOpts.bodyHtml`). */
66
+ bodyHtml?: string;
67
+ /**
68
+ * Lazily read an OPAQUE prebuilt bundle's self-contained HTML (D-W2,
69
+ * docs/WAVE4-FTUE-HARDENING-DESIGN.md) — the pixi twin of `IngestGame.embedHtml`.
70
+ * Always a lazy thunk here (no in-tree world2d opaque-embed fixture exists
71
+ * yet to need a plain-string form, unlike the three side):
72
+ * `resolveIngest2DDescriptor` (adapter-resolver.ts) builds one that reads
73
+ * the declared `entryHtml` file's bytes through the `/project-game-static/`
74
+ * route, only when the game is actually mounted. The host runs the
75
+ * resolved HTML in a sandboxed iframe at the embed-only floor (Tier 0-1),
76
+ * `mountIngestGame2DEmbed` (`./ingest-iframe-2d.ts`).
77
+ */
78
+ embedHtml?: () => Promise<string>;
79
+ }
80
+
81
+ export interface IngestMount2D {
82
+ /** The captured live stage Container (null if capture failed/degraded). */
83
+ stage: unknown | null;
84
+ capture: SceneCapture2DHandle;
85
+ embedOnly: boolean;
86
+ setPaused(paused: boolean): void;
87
+ dispose(): void;
88
+ }
89
+
90
+ /**
91
+ * Mount an UNMODIFIED PixiJS game via the shared-instance capture path — the 2D
92
+ * analog of `mountIngestGame`. Installs the render trap on the host's pixi
93
+ * instance, runs the game's `load()`, waits for the game to render its first
94
+ * frame (capturing its live stage), and exposes loop gating + cleanup. If capture
95
+ * times out (pixi unreachable / bundled / mismatched), degrades to embed-only —
96
+ * never a silent failure.
97
+ */
98
+ export async function mountIngestGame2D(
99
+ pixiNamespace: unknown,
100
+ game: IngestGame2D,
101
+ opts: { captureTimeoutMs?: number } = {},
102
+ ): Promise<IngestMount2D> {
103
+ const capture = installSceneCapture2D(pixiNamespace);
104
+ try {
105
+ await game.load?.();
106
+ } catch (err) {
107
+ capture.uninstall();
108
+ throw new Error(`world2d ingest: game "${game.id}" failed to load: ${err}`);
109
+ }
110
+
111
+ const timeout = opts.captureTimeoutMs ?? game.captureTimeoutMs ?? 8000;
112
+ try {
113
+ const rt = await capture.waitForCapture(timeout);
114
+ return {
115
+ stage: rt.stage,
116
+ capture,
117
+ embedOnly: false,
118
+ setPaused: (p) => capture.setPaused(p),
119
+ dispose: () => capture.uninstall(),
120
+ };
121
+ } catch {
122
+ // Capture failed → pixi unreachable/mismatched → degrade to embed-only.
123
+ return {
124
+ stage: null,
125
+ capture,
126
+ embedOnly: true,
127
+ setPaused: () => {},
128
+ dispose: () => capture.uninstall(),
129
+ };
130
+ }
131
+ }
@@ -0,0 +1,49 @@
1
+ import type RAPIER from '@dimforge/rapier2d-compat';
2
+ import type { Container } from 'pixi.js';
3
+
4
+ /** The Rapier 2D handles owned by a single display-object entity. */
5
+ export interface Physics2DRefs {
6
+ body: RAPIER.RigidBody;
7
+ collider: RAPIER.Collider;
8
+ }
9
+
10
+ /**
11
+ * Maps PixiJS display objects to their Rapier 2D bodies/colliders and back —
12
+ * the world2d analog of `PhysicsRegistry`. Two indexes:
13
+ * - `Container → {body, collider}` for the postPhysics transform writer.
14
+ * - `colliderHandle → Container` reverse index for collision/trigger dispatch.
15
+ */
16
+ export function createPhysics2DRegistry() {
17
+ const byObject = new Map<Container, Physics2DRefs>();
18
+ const byColliderHandle = new Map<number, Container>();
19
+
20
+ return {
21
+ add(display: Container, body: RAPIER.RigidBody, collider: RAPIER.Collider): void {
22
+ byObject.set(display, { body, collider });
23
+ byColliderHandle.set(collider.handle, display);
24
+ },
25
+ get(display: Container): Physics2DRefs | undefined {
26
+ return byObject.get(display);
27
+ },
28
+ getByColliderHandle(handle: number): Container | undefined {
29
+ return byColliderHandle.get(handle);
30
+ },
31
+ remove(display: Container): void {
32
+ const refs = byObject.get(display);
33
+ if (refs) byColliderHandle.delete(refs.collider.handle);
34
+ byObject.delete(display);
35
+ },
36
+ entries(): IterableIterator<[Container, Physics2DRefs]> {
37
+ return byObject.entries();
38
+ },
39
+ get size(): number {
40
+ return byObject.size;
41
+ },
42
+ clear(): void {
43
+ byObject.clear();
44
+ byColliderHandle.clear();
45
+ },
46
+ };
47
+ }
48
+
49
+ export type Physics2DRegistry = ReturnType<typeof createPhysics2DRegistry>;