@vgai/engine 0.5.2 → 0.5.3

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 (185) hide show
  1. package/README.md +18 -11
  2. package/package.json +10 -6
  3. package/schemas/engine-api.json +1 -68
  4. package/schemas/engine-api.md +1 -32
  5. package/schemas/engine-capabilities.json +30 -42
  6. package/schemas/{vgai-game.schema.json → vgai-project.schema.json} +52 -34
  7. package/src/adapter/adapter-surface.ts +5 -5
  8. package/src/adapter/authoring.ts +168 -226
  9. package/src/adapter/colyseus-networking-adapter.ts +44 -5
  10. package/src/adapter/first-party-systems.ts +156 -42
  11. package/src/adapter/host-context.ts +177 -46
  12. package/src/adapter/index.ts +47 -51
  13. package/src/adapter/ingest/game-contract.ts +2 -2
  14. package/src/adapter/ingest/scene-capture.ts +18 -19
  15. package/src/adapter/ingest/structural-ids.ts +127 -0
  16. package/src/adapter/ingest/upstream-pin.ts +9 -12
  17. package/src/adapter/loop-gate-report.ts +11 -11
  18. package/src/adapter/rapier-physics-adapter.ts +27 -9
  19. package/src/adapter/root-adapter.ts +217 -0
  20. package/src/adapter/{vgai-scene-game-adapter.ts → setup-three-root-adapter.ts} +173 -351
  21. package/src/adapter/system-adapter.ts +80 -63
  22. package/src/ai/navigation.ts +1 -1
  23. package/src/animation/animation-clock.ts +1 -1
  24. package/src/animation/camera-ownership.ts +1 -2
  25. package/src/animation/cubic-spline-interpolant.ts +132 -0
  26. package/src/animation/theatre-clock-binding.ts +2 -2
  27. package/src/animation/theatre-object-binding.ts +4 -4
  28. package/src/animation/xstate-animation-binding.ts +75 -5
  29. package/src/{scene/schema → asset-formats}/camera.ts +2 -5
  30. package/src/{scene/schema → asset-formats}/collider.ts +2 -5
  31. package/src/asset-formats/index.ts +54 -0
  32. package/src/{scene/schema → asset-formats}/instances.ts +10 -6
  33. package/src/{scene/schema → asset-formats}/light.ts +3 -6
  34. package/src/{scene/schema → asset-formats}/material.ts +4 -7
  35. package/src/{scene/schema → asset-formats}/mesh.ts +4 -7
  36. package/src/asset-formats/parse.ts +39 -0
  37. package/src/{scene/schema → asset-formats}/particles.ts +3 -6
  38. package/src/{scene/schema/environment.ts → asset-formats/render-env.ts} +23 -86
  39. package/src/{scene/schema → asset-formats}/tuples.ts +1 -1
  40. package/src/{scene/asset-loaders.ts → asset-loaders.ts} +8 -9
  41. package/src/asset-parse-error.ts +33 -0
  42. package/src/{scene/asset-registry.ts → asset-registry.ts} +1 -1
  43. package/src/assets.ts +1 -1
  44. package/src/audio/wav-encode.ts +9 -9
  45. package/src/canvas-react/engine-bridge.ts +59 -0
  46. package/src/canvas-react/index.ts +50 -0
  47. package/src/canvas-react/pixi-primitive.tsx +202 -0
  48. package/src/canvas-react/pixi-react-adapter.tsx +290 -0
  49. package/src/canvas-react/pixi-react-root-factory.tsx +88 -0
  50. package/src/canvas-react/world-context.ts +328 -0
  51. package/src/core/frame-pacing.ts +100 -0
  52. package/src/core/game-loop.ts +50 -28
  53. package/src/core/seeded-random.ts +7 -7
  54. package/src/core/sim-clock.ts +388 -0
  55. package/src/core/system-runner.ts +17 -63
  56. package/src/core/types.ts +34 -15
  57. package/src/data/data-asset.ts +3 -3
  58. package/src/data/data-check-core.ts +6 -7
  59. package/src/data/data-ref.ts +11 -11
  60. package/src/data/vite-plugin-data.ts +10 -10
  61. package/src/{scene/defaults.ts → defaults.ts} +18 -40
  62. package/src/dev/render-debug-adapter.ts +1 -1
  63. package/src/dev/webgl-frame-capture.ts +1 -1
  64. package/src/ecs/scene-index.ts +439 -0
  65. package/src/ecs/scene-query.ts +43 -0
  66. package/src/{scene → ecs}/user-data.ts +17 -36
  67. package/src/index.ts +7 -9
  68. package/src/input/input-manager.ts +29 -32
  69. package/src/input/input-types.ts +2 -2
  70. package/src/input/schema.ts +5 -5
  71. package/src/loader.ts +57 -0
  72. package/src/manifest/editor-port.ts +69 -0
  73. package/src/manifest/filename.ts +49 -0
  74. package/src/manifest/index.ts +8 -2
  75. package/src/manifest/load-file.ts +11 -0
  76. package/src/manifest/load.ts +65 -77
  77. package/src/manifest/locate.ts +55 -0
  78. package/src/manifest/schema.ts +400 -233
  79. package/src/{scene → physics}/collider-dimensions.ts +3 -3
  80. package/src/physics/physics-registry.ts +1 -1
  81. package/src/{world2d/authoring-2d.ts → pixi/authoring.ts} +24 -11
  82. package/src/pixi/index.ts +43 -0
  83. package/src/{world2d/ingest-iframe-2d.ts → pixi/ingest-iframe.ts} +9 -9
  84. package/src/{world2d/ingest2d.ts → pixi/ingest.ts} +28 -28
  85. package/src/{world2d/physics2d-registry.ts → pixi/physics-registry.ts} +1 -1
  86. package/src/{world2d/scene-capture-2d.ts → pixi/scene-capture.ts} +3 -3
  87. package/src/{world2d/system-adapters-2d.ts → pixi/system-adapters.ts} +2 -2
  88. package/src/react/unmanaged-root-detector.ts +26 -1
  89. package/src/react/use-data.ts +5 -5
  90. package/src/react/use-selection.tsx +15 -42
  91. package/src/react/{game-state.tsx → world-state.tsx} +44 -46
  92. package/src/render/auto-batcher.ts +1 -2
  93. package/src/{scene → render}/instance-mesh.ts +1 -1
  94. package/src/{scene → render}/light-camera-factory.ts +14 -13
  95. package/src/render/lod.ts +17 -0
  96. package/src/{scene → render}/material-factory.ts +8 -7
  97. package/src/{scene → render}/particles-factory.ts +62 -12
  98. package/src/render/render-batch-system.ts +14 -41
  99. package/src/render/render-features.ts +1 -1
  100. package/src/render/render-settings.ts +1 -2
  101. package/src/render/spark-renderer-lifecycle.ts +1 -1
  102. package/src/runtime/create-runtime.ts +352 -463
  103. package/src/runtime/debug-bridge.ts +148 -93
  104. package/src/runtime/debug-registry.ts +79 -54
  105. package/src/runtime/dev-layers.ts +40 -0
  106. package/src/runtime/frame-selector-cache.ts +4 -4
  107. package/src/runtime/game.ts +618 -369
  108. package/src/runtime/gameplay-rng-trap.ts +6 -7
  109. package/src/runtime/input-router.ts +11 -11
  110. package/src/runtime/mount-game.ts +54 -55
  111. package/src/runtime/mount-manifest.ts +154 -150
  112. package/src/runtime/presentation.ts +141 -0
  113. package/src/runtime/render-audio-control.ts +64 -53
  114. package/src/runtime/render-control.ts +45 -51
  115. package/src/runtime/render-seed.ts +3 -4
  116. package/src/runtime/state-bridge.ts +17 -18
  117. package/src/runtime/types.ts +94 -61
  118. package/src/setup/setup-renderer.ts +11 -6
  119. package/src/world3d-react/engine-bridge.ts +46 -33
  120. package/src/world3d-react/index.ts +31 -26
  121. package/src/world3d-react/r3f-adapter.tsx +211 -96
  122. package/src/world3d-react/r3f-root-factory.tsx +91 -0
  123. package/src/world3d-react/renderer-config.ts +137 -0
  124. package/src/world3d-react/world-context.ts +141 -111
  125. package/schemas/entity2d.schema.json +0 -468
  126. package/schemas/prefab.schema.json +0 -9992
  127. package/schemas/scn2d.schema.json +0 -494
  128. package/schemas/vscn.schema.json +0 -10851
  129. package/src/adapter/game-adapter.ts +0 -164
  130. package/src/adapter/ingest/overlay-applier.ts +0 -207
  131. package/src/adapter/ingest/overlay-apply.ts +0 -168
  132. package/src/adapter/ingest/overlay-file.ts +0 -126
  133. package/src/adapter/ingest/overlay-report.ts +0 -176
  134. package/src/animation/gsap-registration.ts +0 -184
  135. package/src/audio/audio-introspection.ts +0 -290
  136. package/src/audio/index.ts +0 -39
  137. package/src/audio/tone-clock-binding.ts +0 -98
  138. package/src/audio/tone-context.ts +0 -175
  139. package/src/audio/tone-offline-render.ts +0 -167
  140. package/src/ecs/component-manager.ts +0 -814
  141. package/src/ecs/game-component.ts +0 -260
  142. package/src/ecs/hmr-swap-report.ts +0 -65
  143. package/src/physics/trigger-dispatch.ts +0 -97
  144. package/src/react/root-adapter.tsx +0 -49
  145. package/src/scene/asset-paths.ts +0 -121
  146. package/src/scene/asset-ref-check.ts +0 -248
  147. package/src/scene/component-registry.ts +0 -51
  148. package/src/scene/parse.ts +0 -204
  149. package/src/scene/scene-apply.ts +0 -407
  150. package/src/scene/scene-diff-schema.ts +0 -115
  151. package/src/scene/scene-diff-types.ts +0 -29
  152. package/src/scene/scene-loader.ts +0 -1526
  153. package/src/scene/scene-query.ts +0 -63
  154. package/src/scene/scene-types.ts +0 -33
  155. package/src/scene/scene-version.ts +0 -40
  156. package/src/scene/schema/animation.ts +0 -46
  157. package/src/scene/schema/audio.ts +0 -25
  158. package/src/scene/schema/entity-ref.ts +0 -78
  159. package/src/scene/schema/entity.ts +0 -189
  160. package/src/scene/schema/index.ts +0 -51
  161. package/src/scene/schema/joint.ts +0 -26
  162. package/src/scene/schema/physics.ts +0 -49
  163. package/src/scene/schema/scene-file.ts +0 -292
  164. package/src/scene/schema/shadow.ts +0 -24
  165. package/src/scene/schema/spline.ts +0 -21
  166. package/src/world2d/asset-paths2d.ts +0 -44
  167. package/src/world2d/capture-to-scene2d.ts +0 -52
  168. package/src/world2d/collision-2d.ts +0 -99
  169. package/src/world2d/entity2d-asset.ts +0 -22
  170. package/src/world2d/index.ts +0 -91
  171. package/src/world2d/physics2d-transform.ts +0 -173
  172. package/src/world2d/physics2d-units.ts +0 -10
  173. package/src/world2d/pixi-game-adapter.ts +0 -439
  174. package/src/world2d/pixi-surface.ts +0 -78
  175. package/src/world2d/scene2d-identity.ts +0 -49
  176. package/src/world2d/scene2d-loader.ts +0 -433
  177. package/src/world2d/schema/entity2d.ts +0 -163
  178. package/src/world2d/schema/physics2d.ts +0 -64
  179. package/src/world2d/schema/sprite.ts +0 -99
  180. package/src/world2d/schema/tilemap.ts +0 -39
  181. package/src/world2d/schema/tuples2d.ts +0 -25
  182. package/src/world2d/transform-writer-2d.ts +0 -42
  183. package/src/world2d/types.ts +0 -74
  184. package/src/world3d-react/behavior.tsx +0 -146
  185. /package/src/{scene → render}/mesh-shadow.ts +0 -0
@@ -1,407 +0,0 @@
1
- /**
2
- * `applyDiff` — the exact inverse of `diffScene` (T4.5, `vgai apply-diff`).
3
- *
4
- * `diffScene` (packages/editor/src/scene-diff.ts) computes a `SceneDiff` from
5
- * two `SceneFile`s. This module does the other direction: given ONE
6
- * `SceneFile` and a `SceneDiff`, produce the `SceneFile` the diff describes —
7
- * a pure function, no editor/live-scene state involved.
8
- *
9
- * DEPENDENCY-DIRECTION NOTE (why this lives in the engine, not next to
10
- * `diffScene`): the natural home for `applyDiff` is beside `diffScene` in
11
- * `packages/editor/src/`. But the CLI (`packages/vgai-cli`) is the caller —
12
- * `vgai apply-diff <scene> <patch>` — and `packages/vgai-cli/package.json`
13
- * does not depend on `@vgai/editor` today (it depends on `@vgai/editor-sdk`,
14
- * a thin RPC client for a *running* editor server, and `create-vgai-project`
15
- * — neither pulls in editor source). Adding a cli→editor edge purely to reach
16
- * one pure function would be a real, new dependency inversion (the T3.7 row
17
- * for `deploy.ts` recorded the opposite call deliberately staying out for the
18
- * same reason). `@vgai/engine`, by contrast, is already a dependency of
19
- * `@vgai/editor` (one-directional: editor → engine) and is trivially addable
20
- * to vgai-cli (mirroring `packages/editor/template/validate-scenes.ts`, which
21
- * already imports `@vgai/engine/scene/parse` by its real published subpath).
22
- * So: `DiffOp`/`SceneDiff` (the shared TYPES) and `applyDiff`/`SceneDiffSchema`
23
- * (the new CODE) live in the engine; `scene-diff.ts` keeps its `diffScene`
24
- * implementation where it is and re-exports the two type names, so no editor
25
- * call site changes. Net edge added: vgai-cli → @vgai/engine (already the
26
- * direction every other package depends on engine). Zero new editor edges.
27
- *
28
- * ROUND-TRIP LAW: for any two scenes A, B — `applyDiff(A, diffScene(A, B))`
29
- * is deep-equal to B, WITH ONE NORMALIZATION: an entity whose `children`
30
- * becomes empty is left with `children` omitted (not `children: []`) —
31
- * matching the convention `cleanDocument`/`serializeScene`
32
- * (packages/editor/src/scene-serializer.ts) already use for saved scene
33
- * files. If B's own file happened to spell "no children" as a literal
34
- * `children: []` rather than omitting the key, a byte-level diff would show
35
- * that one field; every other field, and the full entity tree/order, matches
36
- * exactly. This holds because `diffScene` emits an explicit `move` op for
37
- * ANY entity whose absolute sibling index changes for ANY reason — not just
38
- * reparenting, but also a sibling being added/removed/reordered earlier in
39
- * the same array — so `applyDiff` never has to guess whether an untouched
40
- * entity's position shifted; every position-relevant entity carries an
41
- * explicit target index in the FINAL array.
42
- *
43
- * OP-ORDERING RULE (why applying `diff.ops` in array order would be wrong,
44
- * and what this function does instead):
45
- *
46
- * 1. Detach every `move` target from wherever it currently sits — BEFORE
47
- * processing any `remove`. Proof this matters: consider "remove parent
48
- * with moved-out child" — parent P is deleted in the new doc, but one
49
- * of P's old children, C, survives (reparented elsewhere). `diffScene`
50
- * necessarily emits BOTH `{ remove: P }` and `{ move: C, parentId: ... }`
51
- * (C's parentId can't still be P, since P doesn't exist in the new doc,
52
- * so a parentId change — hence a move op — is guaranteed). If `remove P`
53
- * ran first, it would delete P's whole subtree, including C, before C's
54
- * `move` op ever got to detach it. Detaching every mover first means C
55
- * is already pulled out of P's subtree by the time `remove P` runs, so
56
- * only what's genuinely being deleted is deleted.
57
- * 2. Process `remove` ops. A remove target that's already gone (not found)
58
- * is NOT an error IF it was swept away as a descendant of an earlier
59
- * remove in the SAME diff — `diffScene` lists every removed id
60
- * independently (both a removed parent AND its removed descendants each
61
- * get their own `remove` op, since `flattenEntities` flattens every
62
- * level regardless of ancestor state). A remove target not found and
63
- * not swept is a genuine error (bad id).
64
- * 3. Build a complete id → node resolution map covering EVERY entity that
65
- * will exist in the output: the stationary survivors (walked fresh from
66
- * what's left of the tree), then a freshly-created node object for each
67
- * `add` (children stripped — see below), then the already-detached node
68
- * for each `move`. Because this map is built in full before any
69
- * placement happens, a node object exists (and is resolvable as a
70
- * parent) from the moment it's created, independent of whether it has
71
- * itself been spliced into ITS OWN parent's array yet. This is what
72
- * makes "add-under-added-parent" (a newly-added parent with newly-added
73
- * children in the same diff) work with no dependency/topological-sort
74
- * logic: a child's `add`/`move` op resolves its `parentId` against this
75
- * map regardless of which op appears first in `diff.ops`.
76
- * 4. Placement: group `add` + `move` ops by target parentId, sort each
77
- * group ascending by `index`, then splice one at a time into the target
78
- * array in that order. Inserting in ascending order of FINAL target
79
- * index into an array that already holds every untouched sibling in
80
- * their final relative order (untouched siblings never move — any
81
- * absolute-index change gets its own `move` op, per the round-trip-law
82
- * note above) reconstructs the exact final array: by induction, every
83
- * element with a smaller final index than the one being inserted is
84
- * already in the array, so splicing at `index` places it correctly
85
- * relative to all of them, whether the array started empty (a brand
86
- * new parent) or partially populated (survivors of an existing parent).
87
- * 5. `update` ops last (order relative to placement doesn't matter — they
88
- * mutate an object by reference, found via the same id map, regardless
89
- * of where in the tree that reference currently lives).
90
- *
91
- * Every thrown error is an `ApplyDiffError` naming the 0-based index into
92
- * `diff.ops`, the op's `type`, and the entity id involved — enough for an
93
- * agent to locate and fix the offending op from the message alone.
94
- */
95
-
96
- import type { DiffOp, SceneDiff } from './scene-diff-types';
97
- import type { SceneEntity, SceneFile } from './scene-types';
98
-
99
- export class ApplyDiffError extends Error {
100
- readonly opIndex: number;
101
- readonly opType: DiffOp['type'];
102
- readonly entityId: string;
103
-
104
- constructor(message: string, opIndex: number, opType: DiffOp['type'], entityId: string) {
105
- super(`op #${opIndex} (${opType}, id=${entityId}): ${message}`);
106
- this.name = 'ApplyDiffError';
107
- this.opIndex = opIndex;
108
- this.opType = opType;
109
- this.entityId = entityId;
110
- }
111
- }
112
-
113
- function cloneEntity(e: SceneEntity): SceneEntity {
114
- return JSON.parse(JSON.stringify(e)) as SceneEntity;
115
- }
116
-
117
- /** True iff at least one entity in the tree (at any depth) carries a persisted `id`. */
118
- function hasAnyPersistedId(entities: SceneEntity[]): boolean {
119
- for (const e of entities) {
120
- if (e.id) return true;
121
- if (e.children && hasAnyPersistedId(e.children)) return true;
122
- }
123
- return false;
124
- }
125
-
126
- /**
127
- * The id-persistence trap, made honest.
128
- *
129
- * `id` is `z.string().optional()` in the entity schema ("auto-generated if
130
- * omitted"), and the ids an agent can actually DISCOVER — `vgai status`' —
131
- * are the RUNTIME uuids a live editor session assigns to id-less entities on
132
- * load (`editor-store.ts`'s `assignMissingIds`). `applyDiff` resolves ops
133
- * against the FILE. So for any scene authored the normal way (hand-written,
134
- * or scaffolded — none of which shipped with ids), the only ids on offer
135
- * could never resolve here, and the failure read `entity not found` — as if
136
- * the CALLER had typo'd the id. It is not a typo: NOTHING in that file could
137
- * ever have matched.
138
- *
139
- * The durable half of the fix makes ids real (the editor now persists
140
- * auto-assigned ids back to the scene file on load — see `loadDocument`), so
141
- * this message is the safety net for a file that has not been through that
142
- * path yet. It fires ONLY when the scene has zero persisted ids at all — a
143
- * genuine bad-id typo against an id-carrying scene still gets the plain,
144
- * unpadded message.
145
- */
146
- const NO_IDS_HINT =
147
- ' — and this scene file has NO persisted entity ids AT ALL, so nothing in it could have ' +
148
- 'matched, whatever id the op named. This is almost certainly not a typo: `vgai status` ' +
149
- 'reports RUNTIME ids a live editor session assigns to id-less entities on load, and those ' +
150
- 'only exist in the FILE once the editor has written them back (it now does that ' +
151
- 'automatically, via autosave, shortly after the scene loads). Open this scene in the editor ' +
152
- '(`vgai edit`), let it autosave, then re-read the ids with `vgai status` and retry. Do not ' +
153
- 'hand-write ids into the file.';
154
-
155
- /** Append the no-ids explanation to a not-found message when (and only when) the file has no ids. */
156
- function notFound(message: string, sceneHasIds: boolean): string {
157
- return sceneHasIds ? message : message + NO_IDS_HINT;
158
- }
159
-
160
- /** Recursively search `list` (and descendants) for `id`; if found, splice it out (subtree intact) and return it. */
161
- function detachById(list: SceneEntity[], id: string): SceneEntity | undefined {
162
- for (let i = 0; i < list.length; i++) {
163
- const node = list[i]!;
164
- if (node.id === id) {
165
- list.splice(i, 1);
166
- return node;
167
- }
168
- if (node.children) {
169
- const found = detachById(node.children, id);
170
- if (found) return found;
171
- }
172
- }
173
- return undefined;
174
- }
175
-
176
- /** Collect the id of `node` and every descendant's id into `into`. */
177
- function collectIds(node: SceneEntity, into: Set<string>): void {
178
- if (node.id) into.add(node.id);
179
- if (node.children) {
180
- for (const child of node.children) collectIds(child, into);
181
- }
182
- }
183
-
184
- /** Delete `children` if it is now an empty array, to match the `cleanDocument`/`serializeScene` convention (see the round-trip-law note above). */
185
- function stripEmptyChildrenArrays(list: SceneEntity[]): void {
186
- for (const node of list) {
187
- if (node.children) {
188
- if (node.children.length === 0) {
189
- delete node.children;
190
- } else {
191
- stripEmptyChildrenArrays(node.children);
192
- }
193
- }
194
- }
195
- }
196
-
197
- interface Placement {
198
- index: number;
199
- node: SceneEntity;
200
- opIndex: number;
201
- opType: 'add' | 'move';
202
- entityId: string;
203
- }
204
-
205
- /**
206
- * Apply a `SceneDiff` to a `SceneFile`, returning a NEW `SceneFile` (input is
207
- * not mutated). See the module jsdoc above for the round-trip law and the
208
- * op-ordering rule/proof.
209
- */
210
- // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: one cohesive apply-in-5-phases pipeline (detach movers, remove, index survivors, place adds+moves, update) — the phases share too much local state (working tree, id maps) to split without just passing that state through a longer parameter list.
211
- export function applyDiff(scene: SceneFile, diff: SceneDiff): SceneFile {
212
- const working: SceneFile = JSON.parse(JSON.stringify(scene)) as SceneFile;
213
- const ops = diff.ops;
214
- // Captured from the INPUT scene, before any op mutates `working` — see
215
- // `NO_IDS_HINT` above for what this distinguishes and why.
216
- const sceneHasIds = hasAnyPersistedId(scene.entities);
217
-
218
- // --- Metadata / environment (independent of entity ops) ---
219
- if (diff.metaChanged && diff.newName !== undefined) {
220
- working.name = diff.newName;
221
- }
222
- if (diff.environmentChanged) {
223
- if (diff.newEnvironment) {
224
- working.environment = diff.newEnvironment;
225
- } else {
226
- delete working.environment;
227
- }
228
- }
229
-
230
- // --- Phase 1: detach every `move` target before any `remove` runs ---
231
- //
232
- // A move target isn't always reachable directly off `working.entities`: if
233
- // its immediate (or more distant) ancestor ALSO has a `move` op that gets
234
- // detached first, the target now hangs off that already-detached ancestor
235
- // node, not off the main tree. `diffScene` always emits an ancestor's own
236
- // move/update entry before its descendants' (`flattenEntities` sets a
237
- // parent's map entry before recursing into children), so a single forward
238
- // pass already covers every diffScene-computed diff — but this loop doesn't
239
- // assume that ordering: it retries whatever hasn't been found yet against
240
- // the growing set of already-detached movers' subtrees, to a fixed point,
241
- // so `diff.ops` order genuinely does not matter (per SceneDiffSchema's
242
- // `ops` doc).
243
- const movedNodes = new Map<string, SceneEntity>();
244
- function detachFromAnywhere(id: string): SceneEntity | undefined {
245
- const direct = detachById(working.entities, id);
246
- if (direct) return direct;
247
- for (const mover of movedNodes.values()) {
248
- if (mover.children) {
249
- const found = detachById(mover.children, id);
250
- if (found) return found;
251
- }
252
- }
253
- return undefined;
254
- }
255
-
256
- const moveOpIndices = ops
257
- .map((op, i) => ({ op, i }))
258
- .filter((x): x is { op: Extract<DiffOp, { type: 'move' }>; i: number } => x.op.type === 'move');
259
- const pendingMoves = new Set(moveOpIndices.map((x) => x.i));
260
- let madeProgress = true;
261
- while (pendingMoves.size > 0 && madeProgress) {
262
- madeProgress = false;
263
- for (const { op, i } of moveOpIndices) {
264
- if (!pendingMoves.has(i)) continue;
265
- const node = detachFromAnywhere(op.id);
266
- if (node) {
267
- movedNodes.set(op.id, node);
268
- pendingMoves.delete(i);
269
- madeProgress = true;
270
- }
271
- }
272
- }
273
- if (pendingMoves.size > 0) {
274
- const i = [...pendingMoves][0]!;
275
- const op = ops[i] as Extract<DiffOp, { type: 'move' }>;
276
- throw new ApplyDiffError(
277
- notFound('entity not found (nothing to move)', sceneHasIds),
278
- i,
279
- 'move',
280
- op.id,
281
- );
282
- }
283
-
284
- // --- Phase 2: removes (a not-found target is fine if it was already swept
285
- // up as a descendant of an earlier remove, OR if it hangs off a node
286
- // that was itself moved in phase 1 — see `detachFromAnywhere` above) ---
287
- const sweptIds = new Set<string>();
288
- ops.forEach((op, i) => {
289
- if (op.type !== 'remove') return;
290
- const node = detachFromAnywhere(op.id);
291
- if (node) {
292
- collectIds(node, sweptIds);
293
- return;
294
- }
295
- if (sweptIds.has(op.id)) return;
296
- throw new ApplyDiffError(
297
- notFound('entity not found (already removed via an ancestor, or an invalid id)', sceneHasIds),
298
- i,
299
- 'remove',
300
- op.id,
301
- );
302
- });
303
-
304
- // --- Phase 3: build the complete id -> node resolution map ---
305
- const byId = new Map<string, SceneEntity>();
306
- const indexStationary = (list: SceneEntity[]): void => {
307
- for (const node of list) {
308
- if (node.id) byId.set(node.id, node);
309
- if (node.children) indexStationary(node.children);
310
- }
311
- };
312
- indexStationary(working.entities);
313
-
314
- const addNodes = new Map<number, SceneEntity>(); // opIndex -> freshly created node
315
- ops.forEach((op, i) => {
316
- if (op.type !== 'add') return;
317
- const entity = cloneEntity(op.entity);
318
- delete entity.children; // children are position-managed by their own add/move ops
319
- if (!entity.id) entity.id = crypto.randomUUID();
320
- if (byId.has(entity.id)) {
321
- throw new ApplyDiffError(
322
- 'duplicate id — an entity with this id already exists',
323
- i,
324
- 'add',
325
- entity.id,
326
- );
327
- }
328
- byId.set(entity.id, entity);
329
- addNodes.set(i, entity);
330
- });
331
-
332
- ops.forEach((op, i) => {
333
- if (op.type !== 'move') return;
334
- if (byId.has(op.id)) {
335
- throw new ApplyDiffError('duplicate id — conflicts with an added entity', i, 'move', op.id);
336
- }
337
- byId.set(op.id, movedNodes.get(op.id)!);
338
- });
339
-
340
- // --- Phase 4: placement — group add+move ops by target parent, insert ascending by index ---
341
- const groups = new Map<string | null, Placement[]>();
342
- ops.forEach((op, i) => {
343
- if (op.type === 'add') {
344
- const node = addNodes.get(i)!;
345
- const list = groups.get(op.parentId) ?? [];
346
- list.push({ index: op.index, node, opIndex: i, opType: 'add', entityId: node.id! });
347
- groups.set(op.parentId, list);
348
- } else if (op.type === 'move') {
349
- const node = movedNodes.get(op.id)!;
350
- const list = groups.get(op.parentId) ?? [];
351
- list.push({ index: op.index, node, opIndex: i, opType: 'move', entityId: op.id });
352
- groups.set(op.parentId, list);
353
- }
354
- });
355
-
356
- for (const [parentId, placements] of groups) {
357
- let targetArray: SceneEntity[];
358
- if (parentId === null) {
359
- targetArray = working.entities;
360
- } else {
361
- const parentNode = byId.get(parentId);
362
- if (!parentNode) {
363
- const bad = placements[0]!;
364
- throw new ApplyDiffError(
365
- notFound(`parent entity "${parentId}" not found`, sceneHasIds),
366
- bad.opIndex,
367
- bad.opType,
368
- bad.entityId,
369
- );
370
- }
371
- parentNode.children ??= [];
372
- targetArray = parentNode.children;
373
- }
374
-
375
- const sorted = [...placements].sort((a, b) => a.index - b.index);
376
- for (const p of sorted) {
377
- if (p.index < 0) {
378
- throw new ApplyDiffError(
379
- `negative target index (${p.index})`,
380
- p.opIndex,
381
- p.opType,
382
- p.entityId,
383
- );
384
- }
385
- const clamped = Math.min(p.index, targetArray.length);
386
- targetArray.splice(clamped, 0, p.node);
387
- }
388
- }
389
-
390
- // --- Phase 5: updates — full field replace (except id/children), deleting omitted fields ---
391
- ops.forEach((op, i) => {
392
- if (op.type !== 'update') return;
393
- const node = byId.get(op.id);
394
- if (!node) {
395
- throw new ApplyDiffError(notFound('entity not found', sceneHasIds), i, 'update', op.id);
396
- }
397
- const { id: _id, children: _children, ...fields } = op.entity;
398
- for (const key of Object.keys(node) as (keyof SceneEntity)[]) {
399
- if (key === 'id' || key === 'children') continue;
400
- if (!(key in fields)) delete node[key];
401
- }
402
- Object.assign(node, fields);
403
- });
404
-
405
- stripEmptyChildrenArrays(working.entities);
406
- return working;
407
- }
@@ -1,115 +0,0 @@
1
- /**
2
- * Zod schema for a `SceneDiff` JSON patch (T4.5 — `vgai apply-diff`).
3
- *
4
- * Validates the SHAPE of a hand-authored or `diffScene`-computed patch before
5
- * `applyDiff` (./scene-apply.ts) touches it. Not wired into
6
- * `scripts/generate-schema.ts` — that script's output feeds the *scene file*
7
- * JSON Schema (autocomplete/reference for `.vscn.json`/`.prefab.json`/
8
- * `vgai.game.json`), a different artifact from a diff/patch file. Adding a
9
- * 5th line there would be mechanically trivial, but a generated
10
- * `scene-diff.schema.json` has no current consumer (no editor autocomplete
11
- * targets *.json patch files) — left undone; revisit if one appears.
12
- *
13
- * `SceneEntitySchema` is reused as-is for `add`/`update` payloads even though
14
- * both operations ignore any `children` the payload carries (children are
15
- * position-managed exclusively by their own `add`/`move` ops — see
16
- * `applyDiff`'s jsdoc). Rejecting `children` at the schema level would need
17
- * an `.omit()` off a plain object schema, but `SceneEntitySchema` is a
18
- * `z.lazy()`-wrapped discriminated union (recursive type), so this schema
19
- * takes the more permissive-but-documented path: allow it through and let
20
- * `applyDiff` silently drop it, rather than add a second near-duplicate
21
- * entity schema just to forbid one field.
22
- */
23
-
24
- import { z } from 'zod';
25
- import { SceneEntitySchema } from './schema/entity';
26
- import { SceneEnvironmentSchema } from './schema/environment';
27
-
28
- const ParentIdSchema = z
29
- .string()
30
- .nullable()
31
- .describe('Parent entity id, or null for a top-level (root) entity');
32
-
33
- const TargetIndexSchema = z
34
- .number()
35
- .int()
36
- .describe(
37
- 'Target position among the (new) parent’s children, counted in the FINAL tree ' +
38
- '(after every op in this diff has been applied) — not the position at the moment this ' +
39
- 'one op runs. Negative values are rejected; out-of-range values are clamped to the end.',
40
- );
41
-
42
- export const DiffOpSchema = z.discriminatedUnion('type', [
43
- z
44
- .object({
45
- type: z.literal('add').describe('Insert a new entity into the scene tree'),
46
- entity: SceneEntitySchema.describe(
47
- 'The entity to insert. Any `children` on this payload are ignored — insert descendants ' +
48
- 'via their own `add` ops with `parentId` set to this entity’s `id`.',
49
- ),
50
- parentId: ParentIdSchema,
51
- index: TargetIndexSchema,
52
- })
53
- .describe('Add operation'),
54
- z
55
- .object({
56
- type: z.literal('remove').describe('Delete an entity, and its whole subtree, from the scene'),
57
- id: z.string().describe('Id of the entity to remove'),
58
- })
59
- .describe('Remove operation'),
60
- z
61
- .object({
62
- type: z
63
- .literal('update')
64
- .describe(
65
- 'Replace an entity’s fields (every field except `id` and `children`) with new values — ' +
66
- 'a full replace, not a merge: fields present on the live entity but absent from this ' +
67
- 'payload are deleted',
68
- ),
69
- id: z.string().describe('Id of the entity to update'),
70
- entity: SceneEntitySchema.describe(
71
- 'The new field values. `id` and any `children` on this payload are ignored — repositioning ' +
72
- 'is exclusively a `move` op’s job.',
73
- ),
74
- })
75
- .describe('Update operation'),
76
- z
77
- .object({
78
- type: z.literal('move').describe('Reparent and/or reorder an existing entity'),
79
- id: z.string().describe('Id of the entity to move'),
80
- parentId: ParentIdSchema,
81
- index: TargetIndexSchema,
82
- })
83
- .describe('Move operation'),
84
- ]);
85
-
86
- export const SceneDiffSchema = z
87
- .object({
88
- ops: z
89
- .array(DiffOpSchema)
90
- .describe(
91
- 'add/remove/update/move operations. Order in this array does not matter for correctness — ' +
92
- 'applyDiff derives its own safe application order (moves are detached before removes run, ' +
93
- 'so a child moved out of a removed parent survives; adds/moves are placed by a fully ' +
94
- 'pre-resolved id map, so a newly-added parent is always resolvable for its newly-added ' +
95
- 'children regardless of array position).',
96
- ),
97
- environmentChanged: z.boolean().describe('Whether the scene-level `environment` block changed'),
98
- newEnvironment: SceneEnvironmentSchema.optional().describe(
99
- 'New `environment` block. Applied only when `environmentChanged` is true; ignored otherwise. ' +
100
- 'Absent (with `environmentChanged: true`) clears the scene’s environment block.',
101
- ),
102
- metaChanged: z.boolean().describe('Whether scene metadata (currently just `name`) changed'),
103
- newName: z
104
- .string()
105
- .optional()
106
- .describe(
107
- 'New scene `name`. Applied only when `metaChanged` is true and this is present; ignored otherwise.',
108
- ),
109
- })
110
- .describe(
111
- 'A scene-diff patch — the JSON format produced by `diffScene` (packages/editor/src/scene-diff.ts) ' +
112
- 'and consumed by `applyDiff` (./scene-apply.ts) / `vgai apply-diff`.',
113
- );
114
-
115
- export type SceneDiffPatch = z.infer<typeof SceneDiffSchema>;
@@ -1,29 +0,0 @@
1
- /**
2
- * Scene diff types — shared shape for `DiffOp`/`SceneDiff`.
3
- *
4
- * Lives in the engine (not next to the compute function in
5
- * `packages/editor/src/scene-diff.ts`) so that `packages/vgai-cli` — which
6
- * does not depend on `@vgai/editor` — can validate/apply a diff without
7
- * introducing a new cli→editor dependency edge. See the dependency-direction
8
- * note in `./scene-apply.ts` for the full rationale (T4.5).
9
- *
10
- * `packages/editor/src/scene-diff.ts` (the ONLY place that computes a
11
- * `SceneDiff`, via `diffScene`) re-exports these two names so existing
12
- * editor imports are unaffected.
13
- */
14
-
15
- import type { SceneEntity, SceneEnvironment } from './scene-types';
16
-
17
- export type DiffOp =
18
- | { type: 'add'; entity: SceneEntity; parentId: string | null; index: number }
19
- | { type: 'remove'; id: string }
20
- | { type: 'update'; id: string; entity: SceneEntity }
21
- | { type: 'move'; id: string; parentId: string | null; index: number };
22
-
23
- export interface SceneDiff {
24
- ops: DiffOp[];
25
- environmentChanged: boolean;
26
- newEnvironment?: SceneEnvironment | undefined;
27
- metaChanged: boolean;
28
- newName?: string | undefined;
29
- }