@forgeax/engine-scene 0.1.33 → 0.1.35

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/assets/scene-decoder.ts","../src/instances/legacy.ts","../src/components/children.ts","../src/components/transform.ts","../src/collect-subtree.ts","../src/components/morph-weights.ts","../src/components/name.ts","../src/errors.ts","../src/instances/binding.ts","../src/instances/collect-profile.ts","../src/instances/externalization.ts","../src/instances/keyed.ts","../src/instances/scene-instances.ts","../src/instances/state.ts","../src/systems/propagate-transforms.ts","../src/plugin.ts","../src/systems/hierarchy-projection.ts"],"sourcesContent":["import {\n type AssetDecoder,\n type AssetDecoderContribution,\n type AssetKind,\n type AssetLoadError,\n err,\n ok,\n type Result,\n type SceneAsset,\n type SceneEntity,\n type SceneInstanceOverride,\n} from '@forgeax/engine-types';\nimport { normalizeLegacySceneAsset } from '../instances/legacy.js';\n\nexport const sceneAssetKind: AssetKind<SceneAsset, 'scene'> = {\n kind: 'scene',\n} as AssetKind<SceneAsset, 'scene'>;\n\nfunction invalidScene(guid: string, reason: string): Result<SceneAsset, AssetLoadError> {\n return err({\n code: 'asset-package-invalid',\n expected: 'a scene payload with keyed entities',\n hint: 'recook the SceneAsset and publish its complete envelope',\n detail: { guid, reason },\n });\n}\n\ntype SceneWireRefResult =\n | { readonly ok: true; readonly value: SceneAsset }\n | { readonly ok: false; readonly reason: string };\n\n// The Pack envelope owns refs[] while the decoded SceneAsset remains the\n// portable payload. Keep that wire-only fact beside the decoded object so the\n// World-local projection can interpret shared-field indices without putting a\n// component registry or World into the decoder contract.\nconst sceneWireRefs = new WeakMap<object, readonly string[]>();\n\n/** @internal Read the Pack refs[] retained for a decoded SceneAsset payload. */\nexport function sceneAssetWireRefs(asset: SceneAsset): readonly string[] | undefined {\n return sceneWireRefs.get(asset);\n}\n\nfunction resolveWireRef(\n refs: readonly string[],\n value: number,\n location: string,\n): { readonly ok: true; readonly value: string } | { readonly ok: false; readonly reason: string } {\n const guid = refs[value];\n if (!Number.isInteger(value) || value < 0 || guid === undefined) {\n return {\n ok: false,\n reason: `${location} references refs[${value}], but refs contains ${refs.length} entries`,\n };\n }\n return { ok: true, value: guid };\n}\n\nfunction resolveInstanceSource(\n source: unknown,\n refs: readonly string[],\n location: string,\n): { readonly ok: true; readonly value: string } | { readonly ok: false; readonly reason: string } {\n if (typeof source === 'string' && source.length > 0) return { ok: true, value: source };\n if (typeof source !== 'number' || !Number.isInteger(source)) {\n return { ok: false, reason: `${location} must be a GUID or refs index` };\n }\n return resolveWireRef(refs, source, location);\n}\n\nfunction resolveSkinGuids(\n skinGuids: readonly (number | string)[] | undefined,\n refs: readonly string[],\n):\n | { readonly ok: true; readonly value: readonly string[] | undefined }\n | { readonly ok: false; readonly reason: string } {\n if (skinGuids === undefined) return { ok: true, value: undefined };\n const resolved: string[] = [];\n for (let index = 0; index < skinGuids.length; index += 1) {\n const value = skinGuids[index];\n if (typeof value === 'string') {\n resolved.push(value);\n continue;\n }\n if (typeof value !== 'number' || !Number.isInteger(value)) {\n return { ok: false, reason: `skinGuids[${index}] is not a GUID or refs index` };\n }\n const ref = resolveWireRef(refs, value, `skinGuids[${index}]`);\n if (!ref.ok) return ref;\n resolved.push(ref.value);\n }\n return { ok: true, value: resolved };\n}\n\nfunction resolveSceneWireRefs(\n payload: { readonly entities: unknown; readonly skinGuids?: unknown },\n refs: readonly string[],\n): SceneWireRefResult {\n const normalized = normalizeLegacySceneAsset({ kind: 'scene', entities: payload.entities });\n const rawEntities = normalized.entities;\n if (rawEntities === null || typeof rawEntities !== 'object' || Array.isArray(rawEntities)) {\n return { ok: false, reason: 'entities must be a keyed object' };\n }\n const entities: Record<string, SceneEntity> = {};\n for (const [key, rawEntity] of Object.entries(rawEntities as Record<string, unknown>)) {\n const entity = rawEntity as\n | {\n readonly components?: unknown;\n readonly instance?: {\n readonly source?: unknown;\n readonly overrides?: unknown;\n };\n }\n | undefined;\n if (key.length === 0 || entity === undefined || typeof entity !== 'object') {\n return { ok: false, reason: `entities[${JSON.stringify(key)}] is malformed` };\n }\n if (\n entity.components === null ||\n typeof entity.components !== 'object' ||\n Array.isArray(entity.components)\n ) {\n return { ok: false, reason: `entities.${key}.components must be an object` };\n }\n const components: Record<string, Record<string, unknown>> = {};\n for (const [componentName, rawFields] of Object.entries(\n entity.components as Record<string, unknown>,\n )) {\n if (rawFields === null || typeof rawFields !== 'object' || Array.isArray(rawFields)) {\n return {\n ok: false,\n reason: `entities.${key}.components.${componentName} must be an object`,\n };\n }\n // Component schema lookup is World-local after the ECS core reduction.\n // The runtime projection owns the World-local schema and converts\n // authored GUID fields into World.sharedRefs handles. Keep this loader\n // boundary POD-only instead of consulting a removed process-global ECS\n // component registry.\n components[componentName] = { ...(rawFields as Record<string, unknown>) };\n }\n const instance = entity.instance;\n let resolvedInstance: SceneEntity['instance'];\n if (instance !== undefined) {\n if (instance === null || typeof instance !== 'object') {\n return { ok: false, reason: `entities.${key}.instance must be an object` };\n }\n const source = resolveInstanceSource(\n instance.source,\n refs,\n `entities.${key}.instance.source`,\n );\n if (!source.ok) return source;\n if (instance.overrides !== undefined && !Array.isArray(instance.overrides)) {\n return { ok: false, reason: `entities.${key}.instance.overrides must be an array` };\n }\n let overrides: NonNullable<SceneEntity['instance']>['overrides'] | undefined;\n if (instance.overrides === undefined) {\n overrides = undefined;\n } else {\n const resolvedOverrides: SceneInstanceOverride[] = [];\n for (const [index, rawOverride] of (instance.overrides as readonly unknown[]).entries()) {\n if (\n rawOverride === null ||\n typeof rawOverride !== 'object' ||\n Array.isArray(rawOverride) ||\n !Array.isArray((rawOverride as { readonly target?: unknown }).target) ||\n (rawOverride as { readonly target?: unknown[] }).target?.some(\n (part) => typeof part !== 'string' || part.length === 0,\n )\n ) {\n return {\n ok: false,\n reason: `entities.${key}.instance.overrides[${index}] is malformed`,\n };\n }\n const target = (rawOverride as { readonly target: readonly string[] }).target;\n const rawComponents = (rawOverride as { readonly components?: unknown }).components;\n if (\n rawComponents === null ||\n typeof rawComponents !== 'object' ||\n Array.isArray(rawComponents)\n ) {\n return {\n ok: false,\n reason: `entities.${key}.instance.overrides[${index}].components is malformed`,\n };\n }\n resolvedOverrides.push({\n target: [...target] as [string, ...string[]],\n components: rawComponents as SceneEntity['components'],\n });\n }\n overrides = resolvedOverrides;\n }\n resolvedInstance = {\n source: source.value,\n ...(overrides === undefined ? {} : { overrides }),\n };\n }\n entities[key] = {\n components,\n ...(resolvedInstance === undefined ? {} : { instance: resolvedInstance }),\n };\n }\n\n const skinGuids = resolveSkinGuids(\n Array.isArray(payload.skinGuids)\n ? (payload.skinGuids as readonly (number | string)[])\n : payload.skinGuids === undefined\n ? undefined\n : ([] as readonly (number | string)[]),\n refs,\n );\n if (!skinGuids.ok) return skinGuids;\n\n return {\n ok: true,\n value: {\n kind: 'scene',\n entities,\n ...(skinGuids.value === undefined ? {} : { skinGuids: skinGuids.value }),\n },\n };\n}\n\n/** Scene owns structural validation; World-local projection resolves shared refs. */\nexport const sceneAssetDecoder: AssetDecoder<SceneAsset> = {\n async decode({ envelope }): Promise<Result<SceneAsset, AssetLoadError>> {\n const payload = envelope.payload;\n if (\n payload.kind !== 'scene' ||\n payload.entities === null ||\n typeof payload.entities !== 'object'\n ) {\n return invalidScene(envelope.guid, 'scene payload is missing keyed entities');\n }\n const resolved = resolveSceneWireRefs(payload, envelope.refs);\n if (!resolved.ok) return invalidScene(envelope.guid, resolved.reason);\n sceneWireRefs.set(resolved.value, Object.freeze([...envelope.refs]));\n return ok(resolved.value);\n },\n};\n\nexport const sceneAssetContribution: AssetDecoderContribution<SceneAsset, 'scene'> = {\n kind: sceneAssetKind,\n decoder: sceneAssetDecoder,\n consumer: 'Scene',\n};\n","/**\n * Normalize the small set of SceneAsset fields emitted by the 0.1.27\n * ScriptablePack template before the current keyed runtime validates them.\n *\n * This is deliberately a boundary migration. Current authoring and runtime\n * types stay keyed and use `shadowFilter`; only old payloads carry numeric\n * ChildOf addresses or `pcfKernelSize`.\n */\nexport function migrateLegacySceneComponentFields(\n componentName: string,\n source: Record<string, unknown>,\n addressByLocalId?: ReadonlyMap<number, string>,\n): Record<string, unknown> {\n const fields = { ...source };\n const address = (value: unknown): unknown =>\n Number.isSafeInteger(value) ? (addressByLocalId?.get(value as number) ?? String(value)) : value;\n if (componentName === 'DirectionalLight' && Object.hasOwn(fields, 'pcfKernelSize')) {\n const kernel = fields.pcfKernelSize;\n const shadowFilter = kernel === 1 ? 1 : kernel === 3 ? 2 : kernel === 5 ? 3 : undefined;\n if (shadowFilter !== undefined && !Object.hasOwn(fields, 'shadowFilter')) {\n delete fields.pcfKernelSize;\n fields.shadowFilter = shadowFilter;\n }\n }\n if (componentName === 'ChildOf' && Number.isSafeInteger(fields.parent)) {\n fields.parent = address(fields.parent);\n }\n if (componentName === 'Children' && Array.isArray(fields.entities)) {\n fields.entities = fields.entities.map(address);\n }\n return fields;\n}\n\ninterface LegacySceneEntity {\n readonly localId?: unknown;\n readonly bindingKey?: unknown;\n readonly components?: unknown;\n readonly instance?: unknown;\n}\n\n/**\n * Lift the pre-keyed SceneAsset array into the current keyed shape.\n *\n * The 0.1.27 template used `localId` for storage and `bindingKey` for the\n * gameplay-facing names. Keeping the binding key is essential: the runtime\n * resolves `player`, `camera`, and joints by that name, not by the old number.\n * This function is intentionally structural and accepts `unknown` only at the\n * compatibility boundary; current authoring types remain keyed.\n */\nexport function normalizeLegacySceneAsset(\n scene: unknown,\n): import('@forgeax/engine-types').SceneAsset {\n if (scene === null || typeof scene !== 'object') return scene as never;\n const candidate = scene as { readonly entities?: unknown };\n if (!Array.isArray(candidate.entities))\n return scene as import('@forgeax/engine-types').SceneAsset;\n\n const rows = candidate.entities as readonly LegacySceneEntity[];\n const addressByLocalId = new Map<number, string>();\n const rowKeys: string[] = [];\n const used = new Set<string>();\n for (const [index, row] of rows.entries()) {\n const localId = Number.isSafeInteger(row?.localId) ? (row.localId as number) : index;\n const bindingKey =\n typeof row?.bindingKey === 'string' && row.bindingKey.length > 0\n ? row.bindingKey\n : String(localId);\n const key = used.has(bindingKey) ? String(localId) : bindingKey;\n used.add(key);\n addressByLocalId.set(localId, key);\n rowKeys.push(key);\n }\n\n const entities: Record<\n string,\n { readonly components: Record<string, Record<string, unknown>>; readonly instance?: unknown }\n > = {};\n for (const [index, row] of rows.entries()) {\n const key = rowKeys[index] as string;\n const rawComponents = row?.components;\n const components: Record<string, Record<string, unknown>> = {};\n if (\n rawComponents !== null &&\n typeof rawComponents === 'object' &&\n !Array.isArray(rawComponents)\n ) {\n for (const [componentName, rawFields] of Object.entries(\n rawComponents as Record<string, unknown>,\n )) {\n if (rawFields === null || typeof rawFields !== 'object' || Array.isArray(rawFields))\n continue;\n components[componentName] = migrateLegacySceneComponentFields(\n componentName,\n rawFields as Record<string, unknown>,\n addressByLocalId,\n );\n }\n }\n entities[key] = {\n components,\n ...(row?.instance === undefined ? {} : { instance: row.instance }),\n };\n }\n return {\n ...(scene as Record<string, unknown>),\n entities,\n } as import('@forgeax/engine-types').SceneAsset;\n}\n","// @forgeax/engine-runtime - Children (forward-list of child entities).\n//\n// Schema: 1 array<entity> field `entities` (variable-length, ECS-managed via\n// the BufferPool slot column + sidecar count column allocated by the ECS\n// relationship owner).\n//\n// feat-20260515-buffer-array-vocab-collapse M3 / w17:\n// the legacy `VarArrayView<Entity>` value-shape wrapper was retired in\n// favour of a direct `TypedArray` snapshot returned by `world.get`. AI users\n// read the engine-maintained list through the read-only `Uint32Array` snapshot:\n//\n// const snap = world.get(parent, Children).unwrap().entities;\n// const liveCount = snap.length;\n// for (let i = 0; i < liveCount; i++) { const child = snap[i]; ... }\n//\n// Snapshot length equals the live element count (sidecar count column owned\n// by the ECS layer); the public snapshot is detached and rematerialised on\n// every `world.get` (D-4 no-cache), so `fill` or index writes cannot mutate the\n// target. Internal relationship maintenance and Scene traversal borrow the\n// live array through the package-internal zero-copy seams instead.\n//\n// feat-20260531-ecs-relationship-abstraction-bidirectional-sync M4 / t20:\n// Children is the MIRROR side of the ChildOf relationship. Its schema is\n// unchanged (the `entities: 'array<entity>'` shape is exactly what the\n// relationship mirror contract requires), but the engine now maintains this\n// list automatically whenever ChildOf is added / removed / reparented on a\n// child entity (M2 bidirectional-sync hook on ChildOf). The prior OOS-10\n// \"AI users keep the two sides consistent themselves\" contract is retired:\n// `world.addComponent(child, ChildOf{parent})` appends `child` to\n// `parent.Children.entities`, `world.removeComponent` / reparent prunes it.\n// For the ChildOf hierarchy the engine owns consistency; no public target\n// write can diverge from the source relationship.\n//\n// feat-20260514-ecs-children-instances-managed-buffer-array M3 / w13 (kept\n// for context): migrated from the legacy `{ count: 'u32' }` advisory marker\n// to the real variable-length entity-array storage path.\n// - OOS-09 (prior loop): no `addChild` / `removeChild` / `removeChildren`\n// Commands API. Retired this feat: `world.addChild` / `world.removeChild`\n// / `world.reparent` ship in M3, plus the relationship hook above.\n// - Normal ChildOf child despawn invokes the source onRemove hook and\n// removes the child before the row is retired; parent despawn follows the\n// linkedSpawn cascade. A dangling u32 is therefore an explicitly malformed\n// internal fixture or a non-linked generic relationship, not a normal\n// ChildOf lifecycle result. Consumers still probe liveness before using a\n// handle and receive the structured ECS error for malformed state.\n//\n// charter mapping: proposition 2 (Bevy ChildOf+Children pair, holder\n// perspective) + proposition 3 (machine-readable schema:\n// `componentSchema(Children).entities === 'array<entity>'`) + proposition 4 (explicit\n// failure: dangling entries surface to the AI user via `world.get(parent, Entity)` liveness probe,\n// not silent drop) + proposition 5 (consistent abstraction: Children is the\n// generic relationship-mirror shape, not a ChildOf special case).\n\nimport { defineRelationship } from '@forgeax/engine-ecs';\nimport { Transform } from './transform';\n\n/**\n * Hierarchy forward-list of child entities.\n *\n * `entities` is a variable-length `array<entity>` field; each element is\n * an `Entity` u32 the ECS relationship owner materialized. The value returned\n * by `world.get(parent, Children).unwrap().entities` is a detached read-only\n * `Uint32Array` snapshot rematerialised fresh on every read (D-4 no-cache);\n * mutating the returned array cannot change ECS-owned storage, and the\n * snapshot's `length` equals the live element count. Internal Scene/ECS paths\n * use the package-internal zero-copy array seams instead of this snapshot.\n *\n * Invariants:\n * - `propagateTransforms` consumes Children from the ECS-owned materialized\n * buffer and expands each root parent-first. The forward list is also\n * available for AI-user traversal / debug / inspection.\n * - Children <-> ChildOf consistency is maintained by the engine via the\n * ChildOf `relationship` mirror hook (see ./child-of.ts): adding /\n * removing / reparenting ChildOf on a child auto-updates the parent's\n * `entities` list. AI users do not hand-sync the two sides for the\n * hierarchy.\n * - ChildOf's linked lifecycle keeps ordinary Children entries aligned: a\n * child despawn prunes its source slot and a parent despawn cascades. A\n * deliberately malformed/non-linked edge remains observable as a dead\n * handle and must be diagnosed through the structured error channel.\n *\n * @example Spawn a parent and two children via ChildOf (engine maintains Children):\n * const parent = world.spawn({ component: Transform, data: identityXf() }).unwrap();\n * const a = world.spawn(\n * { component: Transform, data: identityXf() },\n * { component: ChildOf, data: { parent } },\n * ).unwrap();\n * const b = world.spawn(\n * { component: Transform, data: identityXf() },\n * { component: ChildOf, data: { parent } },\n * ).unwrap();\n * // Read back via the read-only snapshot - engine appended a, b:\n * const snap = world.get(parent, Children).unwrap().entities;\n * for (let i = 0; i < snap.length; i++) {\n * const child = snap[i];\n * // ... consume; probe the handle before using it when reading a\n * // deliberately malformed/non-linked relationship.\n * }\n */\nexport const { source: ChildOf, target: Children } = defineRelationship({\n sourceName: 'ChildOf',\n sourceField: 'parent',\n targetName: 'Children',\n targetField: 'entities',\n // Every scene hierarchy node is spatial. Adding ChildOf therefore\n // materializes the local/derived transform pair at the same structural\n // boundary, so render- and scene-authored children cannot enter a frame\n // with an incomplete hierarchy node.\n sourceRequires: [Transform],\n exclusive: true,\n linkedSpawn: true,\n});\n","// @forgeax/engine-runtime - authored local transform and derived world output.\n\nimport { defineComponent } from '@forgeax/engine-ecs';\n\nconst IDENTITY_MAT4 = new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);\n\n/** Scene-owned derived world transform. Only TransformPropagation writes it. */\nexport const GlobalTransform = defineComponent(\n 'GlobalTransform',\n {\n world: { type: 'array<f32, 16>', default: IDENTITY_MAT4 },\n },\n { transient: true },\n);\n\n/**\n * Authored local position, rotation and scale columns.\n *\n * The ECS `requires` declaration is the generic structural invariant: callers\n * add `Transform`, while `GlobalTransform` is materialized once at spawn/add.\n */\nexport const Transform = defineComponent(\n 'Transform',\n {\n pos: { type: 'array<f32, 3>', default: new Float32Array([0, 0, 0]) },\n // Component order [x, y, z, w] is shared with glTF.\n quat: { type: 'array<f32, 4>', default: new Float32Array([0, 0, 0, 1]) },\n scale: { type: 'array<f32, 3>', default: new Float32Array([1, 1, 1]) },\n },\n { requires: [GlobalTransform] },\n);\n","// Scene-owned hierarchy traversal shared by scene collection and render hooks.\n\nimport type { EntityHandle, World } from '@forgeax/engine-ecs';\n\nimport { Children } from './components/children';\n\n/** Walk a Children hierarchy breadth-first, reusing an optional visited set. */\nexport function collectSubtree(\n world: World,\n spawnRoot: EntityHandle,\n visited?: Set<number>,\n): Set<number> {\n if (visited === undefined) visited = new Set<number>();\n if (visited.has(spawnRoot as number)) return visited;\n const queue: number[] = [spawnRoot as number];\n visited.add(spawnRoot as number);\n for (let cursor = 0; cursor < queue.length; cursor += 1) {\n const current = queue[cursor] as number;\n const children = world.get(current as EntityHandle, Children);\n if (!children.ok) continue;\n const entities = children.value.entities as ArrayLike<number>;\n for (let index = 0; index < entities.length; index += 1) {\n const child = entities[index] as number;\n if (visited.has(child)) continue;\n visited.add(child);\n queue.push(child);\n }\n }\n return visited;\n}\n","import { defineComponent } from '@forgeax/engine-ecs';\n\n/** Per-entity morph weights; length is validated against the mesh target count. */\nexport const MorphWeights = defineComponent('MorphWeights', {\n weights: { type: 'array<f32>' },\n});\n","// @forgeax/engine-runtime --- Name component (built-in identifier).\n//\n// Single-field minimal skeleton: { value: 'string' }. Bare 'string' schema\n// vocab keyword routes through ECS UniqueRefStore (D-R3 single-arm managed\n// dispatch); the read shape is a native JS string.\n//\n// Lives in `runtime` rather than `ecs` because Name is a built-in *component*,\n// not part of the ECS framework itself (it does not participate in archetype /\n// query / world mechanics like the essential `Entity` component does). Mirrors\n// Bevy's split: `Entity` lives in `bevy_ecs`; `Name` lives in `bevy_core`.\n//\n// Migrated from packages/ecs/src/name.ts by tweak-20260612-ecs-concept-compression\n// (architecture-principles.md §1 SSOT: Name's authoritative location is the\n// runtime built-in components surface, not the ECS framework barrel).\n//\n// Naming follows the Bevy-aligned convention locked by feat-20260513:\n// single-semantic component drops the 'Component' suffix (Transform / Camera\n// / DirectionalLight / Name).\n\nimport { defineComponent } from '@forgeax/engine-ecs';\n\nexport const Name = defineComponent('Name', { value: { type: 'string' } });\n","import type { EcsError, EntityHandle } from '@forgeax/engine-ecs';\n\nexport type SceneErrorCode = 'hierarchy-broken' | 'hierarchy-cycle';\n\n/** Scene-instantiation failures owned by the scene package. */\nexport type SceneInstanceErrorCode = 'component-not-defined' | 'scene-override-type-mismatch';\n\nexport { ComponentNotDefinedError } from '@forgeax/engine-ecs/projection';\n\n/** The structured ECS failure retained by a Scene derived-write diagnostic. */\nexport interface SceneErrorCause {\n readonly code: EcsError['code'];\n readonly expected?: string;\n readonly hint?: string;\n readonly detail?: unknown;\n}\n\n/** Location detail shared by hierarchy diagnostics and derived-write errors. */\nexport interface SceneHierarchyErrorDetail {\n readonly kind?: 'hierarchy';\n readonly entity: EntityHandle;\n readonly parent: EntityHandle;\n}\n\n/** A flat derived publication failure with its original ECS error intact. */\nexport interface SceneDerivedWriteErrorDetail {\n readonly kind: 'derived-write';\n readonly entity: EntityHandle;\n readonly parent: EntityHandle;\n readonly bindingIndex: number;\n readonly base: number;\n readonly start: number;\n readonly count: number;\n readonly cause: SceneErrorCause;\n}\n\nexport type SceneErrorDetail = SceneHierarchyErrorDetail | SceneDerivedWriteErrorDetail;\n\nexport class SceneError extends Error {\n readonly code: SceneErrorCode;\n readonly expected: string;\n readonly hint: string;\n readonly detail: SceneErrorDetail | undefined;\n\n constructor(args: {\n code: SceneErrorCode;\n expected: string;\n hint: string;\n detail?: SceneErrorDetail;\n }) {\n super(`[SceneError ${args.code}] expected: ${args.expected}; hint: ${args.hint}`);\n this.name = 'SceneError';\n this.code = args.code;\n this.expected = args.expected;\n this.hint = args.hint;\n this.detail = args.detail;\n }\n}\n","import type { EntityHandle } from '@forgeax/engine-ecs';\nimport type { SceneEntityAddress, SceneEntityRef } from '@forgeax/engine-types';\nimport { err, ok, type Result } from '@forgeax/engine-types';\n\nexport type { SceneEntityRef } from '@forgeax/engine-types';\n\nexport type SceneBindingError = {\n readonly code: 'scene-binding-missing' | 'scene-binding-wrong-instance';\n readonly expected: string;\n readonly hint: string;\n readonly detail: { readonly sceneSourceKey: string; readonly address: SceneEntityAddress };\n};\n\nexport type SceneBindingDeclarationError = {\n readonly code: 'scene-binding-duplicate' | 'scene-binding-source-missing';\n readonly expected: string;\n readonly hint: string;\n readonly detail: { readonly sceneSourceKey?: string; readonly address?: SceneEntityAddress };\n};\n\nexport function validateSceneEntityKeys(\n sceneSourceKey: string,\n entityKeys: readonly string[],\n): Result<readonly string[], SceneBindingDeclarationError> {\n if (sceneSourceKey.length === 0) {\n return err({\n code: 'scene-binding-source-missing',\n expected: 'a non-empty scene sourceKey',\n hint: 'declare the scene sourceKey in the author inventory',\n detail: {},\n });\n }\n const seen = new Set<string>();\n for (const entityKey of entityKeys) {\n if (entityKey.length === 0 || seen.has(entityKey)) {\n return err({\n code: 'scene-binding-duplicate',\n expected: 'unique non-empty entity keys within one scene',\n hint: 'rename the duplicate entity key in the scene producer',\n detail: { sceneSourceKey, address: entityKey },\n });\n }\n seen.add(entityKey);\n }\n return ok([...entityKeys]);\n}\n\nexport function sceneEntity(sceneSourceKey: string, address: SceneEntityAddress): SceneEntityRef {\n return { sceneSourceKey, address };\n}\n\n/** Stable map key shared by direct and nested SceneEntityRef addresses. */\nexport function sceneEntityAddressKey(address: SceneEntityAddress): string {\n if (typeof address === 'string') return `s:${JSON.stringify(address)}`;\n if (address.length === 1) return `s:${JSON.stringify(address[0] ?? '')}`;\n return `a:${JSON.stringify(address)}`;\n}\n\nexport function resolveSceneEntity(\n ref: SceneEntityRef,\n instance: {\n readonly sceneSourceKey: string;\n readonly bindings: ReadonlyMap<string, EntityHandle | number>;\n },\n): Result<EntityHandle | number, SceneBindingError> {\n if (ref.sceneSourceKey !== instance.sceneSourceKey) {\n return err({\n code: 'scene-binding-wrong-instance',\n expected: `scene instance ${ref.sceneSourceKey}`,\n hint: 'resolve the SceneEntityRef against its owning SceneInstance',\n detail: { sceneSourceKey: ref.sceneSourceKey, address: ref.address },\n });\n }\n const value = instance.bindings.get(sceneEntityAddressKey(ref.address));\n if (value === undefined) {\n return err({\n code: 'scene-binding-missing',\n expected: 'entity key declared by the scene producer',\n hint: 'declare the entity key in the scene producer before consuming it',\n detail: { sceneSourceKey: ref.sceneSourceKey, address: ref.address },\n });\n }\n return ok(value);\n}\n","/** Immutable Scene collection policy shared by runtime collectors. */\nexport interface SceneCollectProfile {\n readonly includeComponent: (componentName: string, transient: boolean) => boolean;\n readonly includeField: (componentName: string, fieldName: string, transient: boolean) => boolean;\n}\n\nexport const SCENE_COLLECT_PROFILE: SceneCollectProfile = Object.freeze({\n includeComponent: (_componentName: string, transient: boolean) => !transient,\n includeField: (_componentName: string, _fieldName: string, transient: boolean) => !transient,\n});\n","import type { AssetRef, SceneAsset, SceneInstanceOverride } from '@forgeax/engine-types';\nimport { err, ok, type Result } from '@forgeax/engine-types';\nimport { migrateLegacySceneComponentFields, normalizeLegacySceneAsset } from './legacy.js';\n\nexport type SceneComponentSchemaResolver = (\n componentName: string,\n) => Readonly<Record<string, string>> | undefined;\n\nexport interface SceneExternalizationError {\n readonly field: string;\n readonly value: unknown;\n}\n\nexport interface ExternalizedSceneAsset {\n readonly payload: Record<string, unknown>;\n readonly refs: readonly AssetRef[];\n}\n\nfunction sharedKind(type: string | undefined): 'one' | 'many' | undefined {\n if (type?.startsWith('shared<')) return 'one';\n if (type?.startsWith('array<shared<')) return 'many';\n return undefined;\n}\n\ninterface RefContext {\n readonly refs: AssetRef[];\n readonly indexByGuid: Map<string, number>;\n}\n\nfunction addRef(\n context: RefContext,\n guid: string,\n sourceField: NonNullable<AssetRef['sourceField']>,\n sceneEntityKey?: string,\n): number {\n const prior = context.indexByGuid.get(guid);\n if (prior !== undefined) return prior;\n const index = context.refs.length;\n context.refs.push({\n guid,\n sourceField,\n ...(sceneEntityKey === undefined ? {} : { sceneEntityKey }),\n } as AssetRef);\n context.indexByGuid.set(guid, index);\n return index;\n}\n\nfunction externalizeFields(\n componentName: string,\n source: Record<string, unknown>,\n resolveSchema: SceneComponentSchemaResolver,\n context: RefContext,\n sceneEntityKey: string | undefined,\n): Record<string, unknown> {\n const schema = resolveSchema(componentName);\n const fields: Record<string, unknown> = {};\n for (const [fieldName, value] of Object.entries(\n migrateLegacySceneComponentFields(componentName, source),\n )) {\n if (value === undefined) continue;\n const kind = sharedKind(schema?.[fieldName]);\n if (kind === 'one' && typeof value === 'string') {\n fields[fieldName] = addRef(context, value, { componentName, fieldName }, sceneEntityKey);\n } else if (kind === 'many' && Array.isArray(value)) {\n fields[fieldName] = value.map((item, arrayIndex) =>\n typeof item === 'string'\n ? addRef(context, item, { componentName, fieldName, arrayIndex }, sceneEntityKey)\n : item,\n );\n } else {\n fields[fieldName] = value;\n }\n }\n return fields;\n}\n\nfunction externalizeOverride(\n override: SceneInstanceOverride,\n resolveSchema: SceneComponentSchemaResolver,\n context: RefContext,\n sceneEntityKey: string,\n): SceneInstanceOverride {\n const components: Record<string, Record<string, unknown>> = {};\n for (const [componentName, rawFields] of Object.entries(override.components)) {\n components[componentName] = externalizeFields(\n componentName,\n { ...(rawFields as Record<string, unknown>) },\n resolveSchema,\n context,\n sceneEntityKey,\n );\n }\n return {\n target: [...override.target],\n components,\n };\n}\n\n/** Project a keyed SceneAsset's shared asset fields into a payload plus refs. */\nexport function externalizeSceneAsset(\n scene: SceneAsset,\n resolveSchema: SceneComponentSchemaResolver,\n): Result<ExternalizedSceneAsset, SceneExternalizationError> {\n const normalized = normalizeLegacySceneAsset(scene);\n const context: RefContext = { refs: [], indexByGuid: new Map() };\n const entities: Record<string, Record<string, unknown>> = {};\n for (const [key, entity] of Object.entries(normalized.entities)) {\n const components: Record<string, Record<string, unknown>> = {};\n for (const [componentName, raw] of Object.entries(entity.components)) {\n const source = raw as Record<string, unknown> | undefined;\n if (source === undefined) continue;\n components[componentName] = externalizeFields(\n componentName,\n source,\n resolveSchema,\n context,\n key,\n );\n }\n const instance = entity.instance;\n entities[key] = {\n components,\n ...(instance === undefined\n ? {}\n : {\n instance: {\n source: addRef(\n context,\n instance.source,\n { componentName: 'SceneInstance', fieldName: 'source' },\n key,\n ),\n ...(instance.overrides === undefined\n ? {}\n : {\n overrides: instance.overrides.map((override) =>\n externalizeOverride(override, resolveSchema, context, key),\n ),\n }),\n },\n }),\n };\n }\n\n for (const [arrayIndex, guid] of (normalized.skinGuids ?? []).entries()) {\n if (typeof guid !== 'string') return err({ field: 'skinGuids', value: guid });\n addRef(context, guid, { componentName: '<scene>', fieldName: 'skinGuids', arrayIndex });\n }\n return ok({\n payload: {\n kind: 'scene',\n entities,\n ...(normalized.skinGuids === undefined\n ? {}\n : {\n skinGuids: normalized.skinGuids.map((guid) => context.indexByGuid.get(guid) as number),\n }),\n },\n refs: context.refs,\n });\n}\n","import type { Component, World } from '@forgeax/engine-ecs';\nimport { classifyEntityField, remapEntityFieldValue } from '@forgeax/engine-ecs/externalization';\nimport { componentSchema } from '@forgeax/engine-ecs/internal';\nimport type {\n ComponentValuesMap,\n LocalEntityId,\n SceneAsset,\n SceneEntityAddress,\n} from '@forgeax/engine-types';\nimport {\n err,\n type Handle,\n ok,\n PACK_ERROR_HINTS,\n type Result,\n type SceneEntity,\n} from '@forgeax/engine-types';\nimport { migrateLegacySceneComponentFields, normalizeLegacySceneAsset } from './legacy.js';\nimport type { MountOverride, SceneInstanceMount } from './runtime-types.js';\n\n/** Numeric representation used only inside the Scene runtime. */\nexport interface CompiledSceneEntity {\n readonly localId: LocalEntityId;\n readonly components: Partial<ComponentValuesMap>;\n}\n\nexport interface CompiledSceneAsset {\n readonly kind: 'scene';\n readonly entities: readonly CompiledSceneEntity[];\n readonly mounts?: readonly SceneInstanceMount[];\n readonly skinGuids?: readonly string[];\n}\n\nexport interface CompiledSceneResult {\n readonly asset: CompiledSceneAsset;\n readonly keyByLocalId: ReadonlyMap<number, string>;\n readonly mountKeyByLocalId: ReadonlyMap<number, string>;\n /** Private slots that attach directly to this scene's synthetic root. */\n readonly rootLocalIds: readonly number[];\n /** Effective private ChildOf edges, including nested scene attachment. */\n readonly hierarchyParentByLocalId: ReadonlyMap<number, number>;\n readonly resolveAddress: (address: unknown, field?: string) => number | undefined;\n}\n\nexport interface KeyedSceneCompileContext {\n readonly resolveSource: (\n source: string,\n parent: Handle<'SceneAsset', 'shared'>,\n ) => Result<Handle<'SceneAsset', 'shared'>, unknown>;\n readonly resolveAsset: (handle: Handle<'SceneAsset', 'shared'>) => Result<SceneAsset, unknown>;\n readonly stack: ReadonlySet<number>;\n}\n\nfunction fail(reason: string, detail: Record<string, unknown> = {}): Result<never, unknown> {\n return err({\n code: 'asset-package-invalid',\n expected: 'a keyed SceneAsset with valid entity and instance addresses',\n hint: 'repair the SceneAsset source and recook the asset',\n detail: { reason, ...detail },\n });\n}\n\nfunction keyList(entities: Readonly<Record<string, SceneEntity>>): string[] {\n return Object.keys(entities).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));\n}\n\nfunction addressParts(value: unknown): readonly string[] | undefined {\n if (typeof value === 'string' && value.length > 0) return [value];\n // ScriptablePack 0.1.27 serialized ChildOf/Children addresses as numeric\n // local IDs. Accept that legacy wire form only at this compiler boundary;\n // the authoring contract remains string keyed.\n if (Number.isSafeInteger(value)) return [String(value)];\n if (!Array.isArray(value) || value.length === 0) return undefined;\n if (!value.every((part) => typeof part === 'string' && part.length > 0)) return undefined;\n return value as readonly string[];\n}\n\nfunction fieldRemap(\n world: World,\n componentName: string,\n fields: Record<string, unknown>,\n resolveAddress: (address: unknown, field: string) => number | undefined,\n entityKey?: string,\n): Result<Record<string, unknown>, unknown> {\n const token = world.components.resolve(componentName);\n if (token === undefined) return fail('unknown component', { component: componentName });\n const schema = componentSchema(token) as Record<string, string>;\n const out: Record<string, unknown> = {};\n for (const [fieldName, value] of Object.entries(\n migrateLegacySceneComponentFields(componentName, fields),\n )) {\n const fieldType = schema[fieldName];\n if (fieldType === undefined) {\n return fail('unknown component field', {\n component: componentName,\n field: fieldName,\n ...(entityKey === undefined ? {} : { entity: entityKey }),\n });\n }\n const kind = classifyEntityField(token as Component, fieldName);\n if (kind === null) {\n out[fieldName] = value;\n continue;\n }\n const remap = (address: number): number =>\n resolveAddress(address, `${componentName}.${fieldName}`) ?? address;\n // The keyed authoring model uses string addresses for scalar entity fields\n // and an address per element for array<entity>. The ECS kernel still gets\n // numeric local slots, so conversion is complete before spawn.\n if (kind.isArray) {\n if (!Array.isArray(value))\n return fail('array entity field is not an array', {\n component: componentName,\n field: fieldName,\n });\n const numeric: number[] = [];\n for (const item of value) {\n const parts = addressParts(item);\n if (parts === undefined)\n return fail('invalid entity address', {\n component: componentName,\n field: fieldName,\n address: item,\n });\n const slot = resolveAddress(parts, `${componentName}.${fieldName}`);\n if (slot === undefined)\n return fail('missing entity address target', {\n component: componentName,\n field: fieldName,\n address: parts,\n });\n numeric.push(slot);\n }\n out[fieldName] = remapEntityFieldValue(numeric, kind, remap);\n continue;\n }\n if (value === null) {\n out[fieldName] = null;\n continue;\n }\n const parts = addressParts(value);\n if (parts === undefined)\n return fail('invalid entity address', {\n component: componentName,\n field: fieldName,\n address: value,\n });\n const slot = resolveAddress(parts, `${componentName}.${fieldName}`);\n if (slot === undefined)\n return fail('missing entity address target', {\n component: componentName,\n field: fieldName,\n address: parts,\n });\n out[fieldName] = remapEntityFieldValue(slot, kind, remap);\n }\n return ok(out);\n}\n\n/**\n * Compile keyed author data to the private numeric Scene representation. The\n * compiler establishes every local and nested address before the caller starts\n * spawning entities, so malformed references and recursive instances cannot\n * leave a partially usable World projection.\n */\nexport function compileKeyedSceneAsset(\n world: World,\n handle: Handle<'SceneAsset', 'shared'>,\n asset: SceneAsset,\n context: KeyedSceneCompileContext,\n): Result<CompiledSceneResult, unknown> {\n asset = normalizeLegacySceneAsset(asset);\n if (\n asset.kind !== 'scene' ||\n asset.entities === null ||\n typeof asset.entities !== 'object' ||\n Array.isArray(asset.entities)\n ) {\n return fail('entities must be a keyed object');\n }\n const currentRaw = Number(handle);\n const activeStack = context.stack.has(currentRaw)\n ? context.stack\n : new Set([...context.stack, currentRaw]);\n const keys = keyList(asset.entities);\n if (keys.some((key) => key.length === 0)) return fail('entity keys must be non-empty');\n\n const ownKeys = keys.filter((key) => asset.entities[key]?.instance === undefined);\n const instanceKeys = keys.filter((key) => asset.entities[key]?.instance !== undefined);\n const ownSlotByKey = new Map<string, number>();\n const instanceSlotByKey = new Map<string, number>();\n const keyByLocalId = new Map<number, string>();\n for (let index = 0; index < ownKeys.length; index += 1) {\n const key = ownKeys[index] as string;\n ownSlotByKey.set(key, index);\n keyByLocalId.set(index, key);\n }\n for (let index = 0; index < instanceKeys.length; index += 1) {\n const key = instanceKeys[index] as string;\n const slot = ownKeys.length + index;\n instanceSlotByKey.set(key, slot);\n keyByLocalId.set(slot, key);\n }\n\n const childCompiled = new Map<\n string,\n { handle: Handle<'SceneAsset', 'shared'>; compiled: CompiledSceneResult }\n >();\n for (const key of instanceKeys) {\n const declaration = asset.entities[key]?.instance;\n if (\n declaration === undefined ||\n typeof declaration.source !== 'string' ||\n declaration.source.length === 0\n ) {\n return fail('instance source must be a non-empty GUID', { entity: key });\n }\n const childHandle = context.resolveSource(declaration.source, handle);\n if (!childHandle.ok) return childHandle;\n const childRaw = Number(childHandle.value);\n if (activeStack.has(childRaw)) {\n return err({\n code: 'pack-cyclic-reference',\n expected: 'acyclic SceneAsset instance graph',\n hint: PACK_ERROR_HINTS['pack-cyclic-reference'],\n detail: {\n code: 'pack-cyclic-reference',\n kind: 'mount-asset',\n cycle: [...activeStack, childRaw].map(String),\n },\n });\n }\n const childAsset = context.resolveAsset(childHandle.value);\n if (!childAsset.ok) return childAsset;\n const childContext: KeyedSceneCompileContext = {\n ...context,\n stack: activeStack,\n };\n const compiled = compileKeyedSceneAsset(\n world,\n childHandle.value,\n childAsset.value,\n childContext,\n );\n if (!compiled.ok) return compiled;\n childCompiled.set(key, { handle: childHandle.value, compiled: compiled.value });\n }\n\n const mountKeyByLocalId = new Map<number, string>();\n const mounts: SceneInstanceMount[] = [];\n let nextMemberFirst = ownKeys.length + instanceKeys.length;\n for (let index = 0; index < instanceKeys.length; index += 1) {\n const key = instanceKeys[index] as string;\n const slot = instanceSlotByKey.get(key) as number;\n const child = childCompiled.get(key) as {\n handle: Handle<'SceneAsset', 'shared'>;\n compiled: CompiledSceneResult;\n };\n const node = asset.entities[key] as SceneEntity;\n mountKeyByLocalId.set(slot, key);\n mounts.push({\n localId: slot as LocalEntityId,\n source: Number(child.handle),\n memberFirst: nextMemberFirst as LocalEntityId,\n memberCount:\n child.compiled.asset.entities.length +\n (child.compiled.asset.mounts?.length ?? 0) +\n (child.compiled.asset.mounts ?? []).reduce((sum, mount) => sum + mount.memberCount, 0),\n ...(Object.keys(node.components).length > 0 ? { components: node.components } : {}),\n });\n nextMemberFirst += mounts[index]?.memberCount ?? 0;\n }\n\n const mountByKey = new Map<string, SceneInstanceMount>();\n for (const mount of mounts)\n mountByKey.set(mountKeyByLocalId.get(Number(mount.localId)) as string, mount);\n\n const resolveInChild = (\n childResult: CompiledSceneResult,\n value: unknown,\n _field?: string,\n ): number | undefined => {\n const parts = addressParts(value);\n if (parts === undefined) return undefined;\n return childResult.resolveAddress(parts);\n };\n\n const resolveAddress = (value: unknown, field?: string): number | undefined => {\n const parts = addressParts(value);\n if (parts === undefined) return undefined;\n const first = parts[0];\n if (first === undefined) return undefined;\n const own = ownSlotByKey.get(first) ?? instanceSlotByKey.get(first);\n if (own !== undefined && parts.length === 1) return own;\n const mount = mountByKey.get(first);\n if (mount === undefined) return undefined;\n const child = childCompiled.get(first);\n if (child === undefined) return undefined;\n const childSlot = resolveInChild(child.compiled, parts.slice(1), field);\n return childSlot === undefined ? undefined : (mount.memberFirst as number) + childSlot;\n };\n\n // Instance entities carry their own authored components. They occupy the\n // mount slot in the private representation, so run the same schema driven\n // conversion as ordinary entities before any spawn occurs.\n for (const key of instanceKeys) {\n const node = asset.entities[key] as SceneEntity;\n const mount = mountByKey.get(key) as SceneInstanceMount;\n const convertedFields = Object.fromEntries(\n Object.entries(node.components).map(([componentName, raw]) => [\n componentName,\n fieldRemap(\n world,\n componentName,\n { ...(raw as Record<string, unknown>) },\n resolveAddress,\n key,\n ),\n ]),\n ) as Record<string, Result<Record<string, unknown>, unknown>>;\n const bad = Object.values(convertedFields).find((result) => !result.ok);\n if (bad !== undefined && !bad.ok) return bad;\n const components: Record<string, Record<string, unknown>> = {};\n for (const [componentName, result] of Object.entries(convertedFields)) {\n if (!result.ok) return result;\n components[componentName] = result.value;\n }\n const index = mounts.findIndex((item) => item.localId === mount.localId);\n if (index >= 0) {\n const childOf = components.ChildOf?.parent;\n // An instance declaration's ChildOf belongs to the private mount slot,\n // whose deferred parent wiring runs after own entities exist. Keeping it\n // inside mount.components would remap the parent before that slot is\n // live and silently lose the authored hierarchy edge.\n if (typeof childOf === 'number') {\n const { ChildOf: _ignored, ...mountComponents } = components;\n void _ignored;\n mounts[index] = { ...mount, components: mountComponents, parent: childOf as LocalEntityId };\n } else {\n mounts[index] = { ...mount, components };\n }\n }\n }\n\n const converted: CompiledSceneEntity[] = [];\n for (const key of ownKeys) {\n const node = asset.entities[key] as SceneEntity;\n const components: Record<string, Record<string, unknown>> = {};\n for (const [componentName, raw] of Object.entries(node.components)) {\n const convertedFields = fieldRemap(\n world,\n componentName,\n { ...(raw as Record<string, unknown>) },\n resolveAddress,\n key,\n );\n if (!convertedFields.ok) return convertedFields;\n components[componentName] = convertedFields.value;\n }\n converted.push({ localId: ownSlotByKey.get(key) as LocalEntityId, components });\n }\n\n // Convert ordered child-relative overrides into the private field patch\n // representation. Values resolve in the declaring parent namespace.\n // A component declaration that is absent on the target is represented as one\n // component-add override; an existing component stays field-granular so an\n // override cannot erase fields that were not mentioned by the author.\n const childHasComponent = (\n result: CompiledSceneResult,\n target: number,\n componentName: string,\n ): boolean => {\n const own = result.asset.entities.find((entity) => Number(entity.localId) === target);\n if (own !== undefined && own.components[componentName] !== undefined) return true;\n const mount = result.asset.mounts?.find((entry) => Number(entry.localId) === target);\n return mount?.components?.[componentName] !== undefined;\n };\n for (const key of instanceKeys) {\n const node = asset.entities[key] as SceneEntity;\n const declaration = node.instance as NonNullable<SceneEntity['instance']>;\n const mount = mountByKey.get(key) as SceneInstanceMount;\n const child = childCompiled.get(key) as { compiled: CompiledSceneResult };\n const childSlot = (target: SceneEntityAddress): number | undefined =>\n resolveInChild(child.compiled, target, `${key}.instance`);\n const overrides: MountOverride[] = [];\n for (const override of declaration.overrides ?? []) {\n const target = childSlot(override.target);\n if (target === undefined)\n return fail('instance override target does not exist', {\n entity: key,\n target: override.target,\n });\n for (const [componentName, fields] of Object.entries(override.components)) {\n const convertedFields = fieldRemap(\n world,\n componentName,\n { ...(fields as Record<string, unknown>) },\n resolveAddress,\n `${key}.instance.${override.target.join('.')}`,\n );\n if (!convertedFields.ok) return convertedFields;\n if (!childHasComponent(child.compiled, target, componentName)) {\n overrides.push({\n localId: ((mount.memberFirst as number) + target) as LocalEntityId,\n comp: componentName,\n value: convertedFields.value,\n });\n } else {\n overrides.push(\n ...Object.entries(convertedFields.value).map(([field, value]) => ({\n localId: ((mount.memberFirst as number) + target) as LocalEntityId,\n comp: componentName,\n field,\n value,\n })),\n );\n }\n }\n }\n if (overrides.length > 0) {\n const index = mounts.findIndex((item) => item.localId === mount.localId);\n const existing = mounts[index];\n if (index >= 0 && existing !== undefined) mounts[index] = { ...existing, overrides };\n }\n }\n\n const rootLocalIds: number[] = [\n ...convertedRootLocalIds(converted),\n ...mounts.filter((mount) => mount.parent === undefined).map((mount) => Number(mount.localId)),\n ];\n\n // Validate the authored hierarchy using the same keyed address resolver that\n // will be used for component fields. General component reference cycles are\n // legal; only ChildOf cycles are rejected before any spawn.\n const hierarchyParentByLocalId = new Map<number, number>();\n for (const node of converted) {\n const parent = node.components.ChildOf?.parent;\n if (typeof parent === 'number' && parent >= 0) {\n hierarchyParentByLocalId.set(Number(node.localId), parent);\n }\n }\n for (const mount of mounts) {\n if (mount.parent !== undefined) {\n hierarchyParentByLocalId.set(Number(mount.localId), mount.parent);\n }\n const key = mountKeyByLocalId.get(Number(mount.localId));\n const child = key === undefined ? undefined : childCompiled.get(key);\n if (child !== undefined) {\n for (const [childLocalId, childParent] of child.compiled.hierarchyParentByLocalId) {\n hierarchyParentByLocalId.set(\n Number(mount.memberFirst) + childLocalId,\n Number(mount.memberFirst) + childParent,\n );\n }\n for (const childRoot of child.compiled.rootLocalIds) {\n hierarchyParentByLocalId.set(Number(mount.memberFirst) + childRoot, Number(mount.localId));\n }\n }\n for (const override of mount.overrides ?? []) {\n if (override.comp !== 'ChildOf') continue;\n if (override.field === 'parent' && typeof override.value === 'number') {\n hierarchyParentByLocalId.set(Number(override.localId), override.value);\n } else if (\n override.field === undefined &&\n typeof override.value === 'object' &&\n override.value !== null\n ) {\n const parentValue = (override.value as Record<string, unknown>).parent;\n if (typeof parentValue === 'number') {\n hierarchyParentByLocalId.set(Number(override.localId), parentValue);\n }\n }\n }\n }\n for (const start of hierarchyParentByLocalId.keys()) {\n const seen = new Set<number>();\n let current: number | undefined = start;\n while (current !== undefined && hierarchyParentByLocalId.has(current)) {\n if (seen.has(current))\n return fail('hierarchy cycle', { entity: keyByLocalId.get(start), address: [...seen] });\n seen.add(current);\n current = hierarchyParentByLocalId.get(current);\n }\n }\n\n return ok({\n asset: {\n kind: 'scene',\n entities: converted,\n ...(mounts.length > 0 ? { mounts } : {}),\n ...(asset.skinGuids === undefined ? {} : { skinGuids: asset.skinGuids }),\n },\n keyByLocalId,\n mountKeyByLocalId,\n rootLocalIds,\n hierarchyParentByLocalId,\n resolveAddress,\n });\n}\n\nfunction convertedRootLocalIds(nodes: readonly CompiledSceneEntity[]): number[] {\n return nodes\n .filter((node) => node.components.ChildOf === undefined)\n .map((node) => Number(node.localId));\n}\n","// @forgeax/engine-scene — scene instantiation and instance-state subsystem.\n\nimport {\n type Component,\n type ComponentData,\n type ComponentSchema,\n type EcsError,\n ENTITY_NULL_RAW,\n type EntityHandle,\n type InputShapeOf,\n type ShapeOf,\n type World,\n} from '@forgeax/engine-ecs';\nimport { classifyEntityField, remapEntityFieldValue } from '@forgeax/engine-ecs/externalization';\nimport { componentSchema } from '@forgeax/engine-ecs/internal';\nimport { fillComponentDefaults, StaleEntityError } from '@forgeax/engine-ecs/projection';\nimport type {\n Handle,\n LocalEntityId,\n PackErrorCode,\n PackErrorDetail,\n SceneAsset,\n SceneEntityAddress,\n SceneEntityRef,\n} from '@forgeax/engine-types';\nimport {\n err,\n ok,\n PACK_ERROR_HINTS,\n type Result,\n toUnique,\n unwrapHandle,\n} from '@forgeax/engine-types';\nimport { ComponentNotDefinedError } from '../errors';\nimport { resolveSceneEntity, sceneEntityAddressKey } from './binding.js';\nimport {\n type CompiledSceneAsset,\n type CompiledSceneEntity,\n compileKeyedSceneAsset,\n} from './keyed.js';\nimport type { MountOverride, SceneInstanceMount } from './runtime-types.js';\nimport {\n isPrimitiveScalarFieldType,\n mountOverrideStateKey,\n primitiveJsType,\n type SceneInstanceStatePayload,\n sceneWorldState,\n} from './state.js';\n\nexport type { SceneInstanceStatePayload } from './state.js';\n\nconst entityIndex = (entity: EntityHandle): number => (entity as number) & 0x00ffffff;\nconst entityGeneration = (entity: EntityHandle): number => ((entity as number) >>> 24) & 0xff;\n\n/**\n * Legacy diagnostic shape retained on the scene-instantiation result for\n * non-blocking runtime observations. SceneAsset schema violations are\n * rejected by the keyed compiler before this result is produced; no authored\n * unknown-field record is emitted by the current path.\n *\n * const r = worldInstantiateScene(world, handle);\n * if (r.ok) for (const d of r.value.diagnostics)\n * console.warn('scene diagnostic', d);\n *\n * Direct `world.spawn` / `world.addComponent` / `Commands.spawn` remain\n * fail-fast with `SpawnDataUnknownFieldError`.\n */\nexport type SceneInstantiateDiagnostic = {\n /** Component name associated with the observation. */\n readonly component: string;\n /** Field associated with the observation. */\n readonly field: string;\n /** LocalEntityId within the owning SceneAsset, when applicable. */\n readonly localId: number;\n};\n\n/**\n * Success value of `worldInstantiateScene`. `root` is the synthetic scene-root\n * EntityHandle (carries `SceneInstance`); `diagnostics` contains only\n * non-blocking runtime observations. Schema-invalid authored fields fail before\n * an entity is created.\n */\nexport type SceneInstantiateOk = {\n readonly root: EntityHandle;\n readonly diagnostics: readonly SceneInstantiateDiagnostic[];\n};\n\n/**\n * Success value of `worldInstantiateSceneFlat` — the \"edit the scene itself\"\n * primitive. Unlike `instantiateScene`, NO synthetic SceneInstance root is\n * minted and NO `ChildOf` is forced onto top-level members: the scene's own\n * entities become plain top-level world entities whose hierarchy is exactly\n * their authored `ChildOf` (an entity with no `ChildOf` stays a root). `roots`\n * is the set of those top-level handles (own rootless entities + top-level\n * mount carriers). Nested prefabs inside the scene STILL materialise as their\n * own SceneInstance anchors (charter P4: instance == entity-with-SceneInstance)\n * — only THIS scene is flat.\n */\nexport type SceneInstantiateFlatOk = {\n readonly roots: EntityHandle[];\n /**\n * All mount carrier entities spawned while flattening this scene. These are\n * separate from `roots`: carriers with an authored parent are not roots,\n * but still delimit a nested prefab subtree for post-spawn hooks.\n */\n readonly mountEntities: EntityHandle[];\n readonly diagnostics: readonly SceneInstantiateDiagnostic[];\n};\n\n/**\n * @internal Intermediate produced by `_spawnSceneMembers` and consumed by both\n * the anchor finisher (`_instantiateSceneAsset`) and the flat finisher\n * (`_instantiateSceneAssetFlat`). Holds everything the shared member-spawn\n * (mounts recursion + own-entity spawn + deferred owned-parent wiring) computes,\n * before either finisher decides whether to wrap the members in a synthetic\n * SceneInstance root.\n */\nexport interface SceneMembersSpawn {\n /** LocalEntityId → live Entity u32 (ENTITY_NULL_RAW for unspawned slots). */\n readonly mapping: Uint32Array;\n /** Reverse map live Entity → LocalEntityId for override / detach bookkeeping. */\n readonly entityToLocalId: Map<EntityHandle, LocalEntityId>;\n /** Own entities that carried no `ChildOf` — the scene's authored top-level roots. */\n readonly rootEntities: EntityHandle[];\n /** Mount carriers whose `mount.parent === undefined` (default-parented). */\n readonly mountEntitiesNeedingRootParent: EntityHandle[];\n /** Every mount carrier spawned by this scene, including explicitly parented carriers. */\n readonly mountEntities: EntityHandle[];\n /**\n * The child anchor and mapping for each mount. Flat scene opening has no\n * outer SceneInstance state to own parent-namespace mount overrides, so it\n * records those overrides on this child anchor after the shared spawn pass.\n */\n readonly mountInstances: readonly {\n readonly mount: SceneInstanceMount;\n readonly root: EntityHandle;\n readonly mapping: Uint32Array;\n readonly key?: string;\n }[];\n /** `entities.length + mounts + Σ memberCount`, captured at instantiate-time. */\n readonly totalSlots: number;\n}\n\n/**\n * Populate the instance binding projection from the private numeric mapping.\n * The authored key remains the only lookup identity: nested instance paths are\n * represented as the same string/tuple key accepted by `SceneEntityRef`, while\n * the numeric mapping stays local to the Scene owner.\n */\nfunction collectSceneEntityBindings(\n world: World,\n root: EntityHandle,\n prefix: readonly string[],\n bindings: Map<string, EntityHandle>,\n visited = new Set<number>(),\n): void {\n const rootRaw = root as unknown as number;\n if (visited.has(rootRaw)) return;\n visited.add(rootRaw);\n const state = worldResolveSceneInstanceStatePayload(world, root);\n if (!state.ok) return;\n const sceneInstance = world.components.resolve('SceneInstance');\n if (sceneInstance === undefined) return;\n const component = world.get(root, sceneInstance);\n if (!component.ok) return;\n const mapping = (component.value as unknown as { mapping: ArrayLike<number> }).mapping;\n for (const [slot, key] of state.value.keyByLocalId) {\n const raw = mapping[slot];\n if (raw === undefined || raw === ENTITY_NULL_RAW) continue;\n const address: SceneEntityAddress =\n prefix.length === 0 ? key : ([...prefix, key] as unknown as [string, ...string[]]);\n bindings.set(sceneEntityAddressKey(address), raw as unknown as EntityHandle);\n }\n for (const childRoot of state.value.mountRoots) {\n const childState = worldResolveSceneInstanceStatePayload(world, childRoot);\n const childKey = childState.ok ? childState.value.instanceKey : undefined;\n if (childKey === undefined) continue;\n collectSceneEntityBindings(world, childRoot, [...prefix, childKey], bindings, visited);\n }\n}\n\nexport type SceneAssetResolver = (\n source: number | string,\n parentHandle: Handle<'SceneAsset', 'shared'>,\n) => Result<Handle<'SceneAsset', 'shared'>, unknown>;\n\n/** @internal */\nexport function worldSetSceneAssetResolver(world: World, resolver: SceneAssetResolver): void {\n sceneWorldState(world).resolver = resolver;\n}\n\n/** @internal */\nexport function worldGetSceneAssetResolver(world: World): SceneAssetResolver | null {\n return sceneWorldState(world).resolver as SceneAssetResolver | null;\n}\n\n/**\n * Materialise a SceneAsset (and any nested SceneAsset references via\n * `mounts[]`) into live entities. Returns the synthetic root Entity that\n * carries the `SceneInstance` ECS component (charter P4: instance ==\n * entity-with-SceneInstance).\n *\n * Recursion path is closed inside `_instantiateSceneRec(handle, parent,\n * stack)` (D-3); cycle detection is fail-fast `pack-cyclic-reference +\n * detail.kind:'mount-asset'` (D-1 mirror, plan-strategy §D-3). The\n * caller-supplied `parent` flows to the synthetic root's `ChildOf` so the\n * full sub-tree attaches under the AI user's host entity.\n *\n * @example\n * const r = worldInstantiateScene(world, handle);\n * if (!r.ok) return r;\n * const { root, diagnostics } = r.value;\n * for (const d of diagnostics) // non-blocking runtime observations\n * console.warn('scene diagnostic', d);\n * const inst = world.get(root, SceneInstance).value;\n * const member = inst.mapping[0]; // first member entity\n */\nexport function worldInstantiateScene(\n world: World,\n handle: Handle<'SceneAsset', 'shared'>,\n parent?: EntityHandle,\n sceneSourceKey?: string,\n): Result<SceneInstantiateOk, EcsError> {\n const stack = new Set<number>();\n // Keep the existing result shape for non-blocking runtime observations. The\n // keyed compiler rejects schema-invalid authoring data before spawning.\n const diagnostics: SceneInstantiateDiagnostic[] = [];\n const r = worldInstantiateSceneRec(\n world,\n handle,\n parent,\n stack,\n diagnostics,\n undefined,\n sceneSourceKey,\n );\n if (!r.ok) return r;\n return ok({ root: r.value, diagnostics });\n}\n\n/**\n * Materialise a projected `SceneAsset` payload without exposing the temporary\n * shared-ref handle to the caller. The World remains the owner of both the\n * handle and the instantiated SceneInstance: the producer grant is released\n * after the SceneInstance retains its source, including when instantiation\n * fails. This is the payload-shaped counterpart to `worldInstantiateScene` for\n * hosts that load a SceneAsset directly from the Engine AssetRegistry.\n */\nexport function worldInstantiateScenePayload(\n world: World,\n asset: SceneAsset,\n parent?: EntityHandle,\n): Result<SceneInstantiateOk, EcsError> {\n const handle = world.allocSharedRef('SceneAsset', asset);\n try {\n return worldInstantiateScene(world, handle, parent);\n } finally {\n // The SceneInstance source column retains the handle on success. On a\n // failed materialisation there should be no remaining holder; either way\n // release the producer grant owned by this convenience entrypoint.\n world.sharedRefs.release(handle);\n }\n}\n\n/**\n * Materialise a SceneAsset FLAT — the \"edit the scene itself\" primitive.\n * Unlike `instantiateScene`, this mints NO synthetic SceneInstance root and\n * forces NO `ChildOf` onto top-level members: the scene's own entities become\n * plain top-level world entities whose hierarchy is exactly their authored\n * `ChildOf` (an entity with no `ChildOf` is a root). Use this to OPEN a scene\n * for editing; use `instantiateScene` (anchor) at runtime / for nested\n * prefabs where an instance boundary + override isolation is wanted.\n *\n * Nested prefabs referenced via `mounts[]` STILL materialise as their own\n * SceneInstance anchors (charter P4 preserved) — only THIS top scene is flat.\n *\n * @example\n * const r = worldInstantiateSceneFlat(world, handle);\n * if (!r.ok) return r;\n * const { roots, diagnostics } = r.value; // roots = top-level handles\n */\nexport function worldInstantiateSceneFlat(\n world: World,\n handle: Handle<'SceneAsset', 'shared'>,\n): Result<SceneInstantiateFlatOk, EcsError> {\n const stack = new Set<number>();\n const diagnostics: SceneInstantiateDiagnostic[] = [];\n const handleKey = unwrapHandle(handle);\n const resolved = worldResolveSceneAsset(world, handle);\n if (!resolved.ok) return resolved;\n stack.add(handleKey);\n let r: Result<{ roots: EntityHandle[]; mountEntities: EntityHandle[] }, EcsError>;\n try {\n r = worldInstantiateSceneAssetFlat(world, handle, resolved.value, stack, diagnostics);\n } finally {\n stack.delete(handleKey);\n }\n if (!r.ok) return r;\n return ok({ ...r.value, diagnostics });\n}\n/**\n * @internal Recursive helper carrying the cycle-detection stack. Sugar /\n * other public callers must not see this mechanic — use `instantiateScene`\n * (D-3 / charter P1).\n */\nexport function worldInstantiateSceneRec(\n world: World,\n handle: Handle<'SceneAsset', 'shared'>,\n parent: EntityHandle | undefined,\n stack: Set<number>,\n diagnostics: SceneInstantiateDiagnostic[],\n instanceKey?: string,\n sceneSourceKey?: string,\n): Result<EntityHandle, EcsError> {\n const handleKey = unwrapHandle(handle);\n if (stack.has(handleKey)) {\n const cycleArr: string[] = [];\n for (const k of stack) cycleArr.push(String(k));\n cycleArr.push(String(handleKey));\n const detail: PackErrorDetail = {\n code: 'pack-cyclic-reference',\n kind: 'mount-asset',\n cycle: cycleArr,\n };\n return err({\n code: 'pack-cyclic-reference' as PackErrorCode,\n expected: 'acyclic SceneAsset mount graph',\n hint: PACK_ERROR_HINTS['pack-cyclic-reference'],\n detail,\n } as unknown as EcsError);\n }\n const resolved = worldResolveSceneAsset(world, handle);\n if (!resolved.ok) return resolved;\n const asset = resolved.value;\n stack.add(handleKey);\n try {\n return worldInstantiateSceneAsset(\n world,\n handle,\n asset,\n parent,\n stack,\n diagnostics,\n instanceKey,\n sceneSourceKey,\n );\n } finally {\n stack.delete(handleKey);\n }\n}\n/**\n * @internal Resolve a SceneAsset handle through the SharedRefStore.\n * The handle u32 is the SharedRefStore slot id (`world.allocSharedRef\n * ('SceneAsset', asset)` is the producer; rc starts at 1, the SceneInstance\n * spawn retains to rc=2 in M4 / w13). Errors propagate as EcsError so the\n * instantiateScene chain returns a single closed union.\n */\nexport function worldResolveSceneAsset(\n world: World,\n handle: Handle<'SceneAsset', 'shared'>,\n): Result<SceneAsset, EcsError> {\n const r = world.sharedRefs.resolve(handle);\n if (!r.ok) {\n return err(r.error as unknown as EcsError);\n }\n return ok(r.value as SceneAsset);\n}\n/**\n * @internal Spawn one SceneAsset's members — the shared body of both scene\n * finishers. Recurses into `mounts[]` (each nested prefab becomes its own\n * SceneInstance anchor), spawns `entities[]` honouring their authored\n * `ChildOf`, and wires deferred owned-parent mount edges. Does NOT create a\n * synthetic root or force any `ChildOf` — that is the caller's (finisher's)\n * job. `_instantiateSceneRec` owns cycle bookkeeping.\n */\nexport function worldSpawnSceneMembers(\n world: World,\n handle: Handle<'SceneAsset', 'shared'>,\n asset: CompiledSceneAsset,\n stack: Set<number>,\n diagnostics: SceneInstantiateDiagnostic[],\n mountKeys?: ReadonlyMap<number, string>,\n): Result<SceneMembersSpawn, EcsError> {\n const sceneInstanceToken = world.components.resolve('SceneInstance');\n if (sceneInstanceToken === undefined) {\n return err(new ComponentNotDefinedError('SceneInstance'));\n }\n const childOfToken = world.components.resolve('ChildOf');\n // ChildOf is optional — only needed if the asset declares ChildOf or a\n // caller-supplied parent must be wired. If absent and we need it, we\n // fail-fast at the wiring site below.\n\n const ownEntities = asset.entities;\n const ownMounts = asset.mounts ?? [];\n const memberSum = ownMounts.reduce((s, m) => s + m.memberCount, 0);\n const countBaseline = ownEntities.length + ownMounts.length + memberSum;\n // C-R1 (studio-issues #6): mapping table must be sized to maxLocalId+1,\n // not to the entity count. An editor scene may have non-contiguous\n // localIds (deleted entities leave gaps); sizing to count means any\n // localId >= count is a silent Uint32Array OOB no-op -> entity spawns\n // but is unreachable by localId -> users report \"character can't move\".\n // Take the max of count-baseline and id-range so both packed and\n // sparse scenes work without over-allocation in the common case.\n let maxLocalId = ownEntities.reduce((m, e) => Math.max(m, e.localId as unknown as number), -1);\n for (const mount of ownMounts) {\n maxLocalId = Math.max(maxLocalId, mount.localId as unknown as number);\n const last = (mount.memberFirst as unknown as number) + mount.memberCount - 1;\n maxLocalId = Math.max(maxLocalId, last);\n }\n const totalSlots = Math.max(countBaseline, maxLocalId + 1);\n\n // R2/Bonus: namespace-overlap fail-fast (AC-05 /\n // pack-mount-localid-overlap). Each LocalEntityId in\n // [0, totalSlots) must be claimed by exactly one of:\n // - entities[i].localId\n // - mounts[i].localId\n // - mounts[i] window slot (memberFirst .. memberFirst+memberCount-1)\n // Overlap or duplicate claim => fail-fast with the offending localIds\n // and human-readable origin labels.\n {\n const claims = new Map<number, string>();\n const overlapLids = new Set<number>();\n const overlapSources: string[] = [];\n const claim = (lid: number, src: string): void => {\n const prior = claims.get(lid);\n if (prior !== undefined) {\n if (!overlapLids.has(lid)) {\n overlapLids.add(lid);\n overlapSources.push(prior);\n overlapSources.push(src);\n } else {\n overlapSources.push(src);\n }\n return;\n }\n claims.set(lid, src);\n };\n for (const ent of ownEntities) {\n claim(ent.localId as unknown as number, `entities[${ent.localId as unknown as number}]`);\n }\n for (const mount of ownMounts) {\n const mLid = mount.localId as unknown as number;\n claim(mLid, `mount[${mLid}]`);\n const first = mount.memberFirst as unknown as number;\n for (let k = 0; k < mount.memberCount; k += 1) {\n claim(first + k, `mount[${mLid}].member[${k}]`);\n }\n }\n if (overlapLids.size > 0) {\n const overlapping = Array.from(overlapLids).sort((a, b) => a - b);\n return err({\n code: 'pack-mount-localid-overlap' as PackErrorCode,\n expected: 'each LocalEntityId claimed by exactly one entity or mount slot',\n hint: PACK_ERROR_HINTS['pack-mount-localid-overlap'],\n detail: {\n code: 'pack-mount-localid-overlap',\n overlapping,\n sources: overlapSources,\n } as PackErrorDetail,\n } as unknown as EcsError);\n }\n }\n\n // Slot table: indexed by LocalEntityId; populated as entities / mounts /\n // members are spawned. mapping[localId] = encoded Entity u32. Unspawned\n // slots hold ENTITY_NULL_RAW (0xffffffff) — NOT 0, because a fresh World's\n // first spawn encodes to gen=0+idx=0=raw 0, which is a valid Entity. The\n // remap path in `_buildSceneEntityComponentDatas` distinguishes the two\n // (live=ENTITY_NULL_RAW => parent unspawned at remap time => surface as\n // null sentinel; live=any other u32 => valid live Entity, including 0).\n const mapping = new Uint32Array(totalSlots).fill(ENTITY_NULL_RAW);\n const entityToLocalId = new Map<EntityHandle, LocalEntityId>();\n const rootEntities: EntityHandle[] = [];\n const mountEntities: EntityHandle[] = [];\n // R2/B-1: mount entities whose `mount.parent === undefined` need their\n // ChildOf wired to the outer synthetic root (this scene's root). Step 5\n // does the wiring once the synthetic root entity is materialised; we\n // collect them here in step 1.\n const mountEntitiesNeedingRootParent: EntityHandle[] = [];\n // D-8 (feat-20260707): mount entities whose `mount.parent` points at an\n // OWNED entity slot are wired AFTER step 2 spawns the owned entities —\n // mounts are processed first (step 1), so the owned parent slot is still\n // ENTITY_NULL_RAW at mount-processing time. Same deferred-wiring shape as\n // mountEntitiesNeedingRootParent: register [mountEntity, parentSlot] here,\n // wire ChildOf once the slot is live. Without this the edge was silently\n // dropped, and the mount carrier stayed unreachable from its owned parent.\n const mountEntitiesNeedingDeferredParent: Array<[EntityHandle, number]> = [];\n const mountInstances: Array<{\n readonly mount: SceneInstanceMount;\n readonly root: EntityHandle;\n readonly mapping: Uint32Array;\n }> = [];\n\n // 1. Recurse into mounts[] FIRST so the mount-window slots\n // (`mount.localId` + `[memberFirst, memberFirst+memberCount)`) are\n // populated before any owned entity tries to remap a LocalEntityId\n // pointing into the mount window (AC-24 cross-boundary reference).\n for (const mount of ownMounts) {\n // R2/B-3 + R2/B-4: validate overrides BEFORE child resolution so a\n // malformed override fails fast without observable side-effects.\n const overrideValidationRes = worldValidateMountOverrides(world, mount);\n if (!overrideValidationRes.ok) {\n return overrideValidationRes;\n }\n\n // Spawn the mount entity (carries mount.components).\n const mountLid = mount.localId as unknown as number;\n const mountSpawnRes = worldSpawnMountEntity(world, mount, mapping, diagnostics);\n if (!mountSpawnRes.ok) return mountSpawnRes;\n const mountEntity = mountSpawnRes.value;\n mountEntities.push(mountEntity);\n mapping[mountLid] = mountEntity as unknown as number;\n\n // Resolve mount.source -> child SceneAsset handle.\n const childHandleRes = worldResolveMountSource(world, mount.source, handle);\n if (!childHandleRes.ok) return childHandleRes;\n const childHandle = childHandleRes.value;\n\n // Recursively instantiate the child. Its synthetic root attaches as a\n // child of the mount entity; runtime observations share the same result\n // accumulator and bubble to the top-level instance.\n const childRes = worldInstantiateSceneRec(\n world,\n childHandle,\n mountEntity,\n stack,\n diagnostics,\n mountKeys?.get(mountLid),\n );\n if (!childRes.ok) return childRes;\n\n // R2/B-2: cross-check mount.memberCount === child.totalSlots BEFORE\n // copying the mount window. The child SceneInstance.mapping length is\n // the authoritative `totalSlots` of the child. AC-04 / requirements\n // S-5 mandate fail-fast at runtime for this disagreement.\n const childInstRes = world.get(childRes.value, sceneInstanceToken);\n if (!childInstRes.ok) return childInstRes;\n const childMapping = (childInstRes.value as unknown as { mapping: Uint32Array }).mapping;\n mountInstances.push({\n mount,\n root: childRes.value,\n mapping: childMapping,\n ...(mountKeys?.get(mountLid) === undefined ? {} : { key: mountKeys.get(mountLid) }),\n });\n if (childMapping.length !== mount.memberCount) {\n return err({\n code: 'pack-mount-count-mismatch' as PackErrorCode,\n expected: 'mount.memberCount === child SceneAsset totalSlots',\n hint: PACK_ERROR_HINTS['pack-mount-count-mismatch'],\n detail: {\n code: 'pack-mount-count-mismatch',\n mountLocalId: mountLid,\n declared: mount.memberCount,\n actual: childMapping.length,\n } as PackErrorDetail,\n } as unknown as EcsError);\n }\n\n // Pull the child's mapping into our parent window. Default unset slots\n // to ENTITY_NULL_RAW so downstream \"live\" checks distinguish them from\n // the first Entity (gen=0+idx=0 encodes to raw u32 0).\n const window = mount.memberCount;\n for (let k = 0; k < window; k += 1) {\n mapping[(mount.memberFirst as unknown as number) + k] = childMapping[k] ?? ENTITY_NULL_RAW;\n }\n\n // Apply mount.overrides at instantiate-time (AC-19).\n // Each override.localId addresses a slot in *this* (parent) namespace\n // (R2/F-8 cement: parent-namespace + memberFirst+offset addressing).\n // The state map will be populated below with these overrides — but we\n // must also write the value through to the live entity column so the\n // readback invariant holds.\n // Mount-entity itself never has children attached by the caller other\n // than via the recursive child; nothing else to wire here.\n if (childOfToken !== undefined) {\n if (mount.parent !== undefined) {\n // Reparent the mount-entity ChildOf to the caller-specified parent.\n const parentSlot = mount.parent as unknown as number;\n const parentEntity = mapping[parentSlot];\n if (parentEntity !== undefined && parentEntity !== ENTITY_NULL_RAW) {\n const r = world.addComponent(mountEntity, {\n component: childOfToken,\n data: { parent: parentEntity } as never,\n });\n if (!r.ok) {\n // ChildOf may already be present from layer-1; reparent via set.\n const set = world.set(mountEntity, childOfToken, {\n parent: parentEntity,\n } as never);\n if (!set.ok) return set as Result<SceneMembersSpawn, EcsError>;\n }\n } else {\n // D-8: the owned parent slot is not spawned yet (owned entities\n // spawn in step 2, after this mount loop). Defer the ChildOf wire\n // to step 2's tail once mapping[parentSlot] is live.\n mountEntitiesNeedingDeferredParent.push([mountEntity, parentSlot]);\n }\n } else {\n // R2/B-1: default semantic — mount.parent === undefined wires the\n // mount entity ChildOf to *this* scene's synthetic root (created\n // in step 3 below). Defer the actual wire to step 5 after the\n // synthetic root spawn; record the mount entity here.\n mountEntitiesNeedingRootParent.push(mountEntity);\n }\n }\n }\n\n // 2. Spawn entities[] entities. Topo-sort by ChildOf so parents are\n // spawned before children (so localId remap can read mapping live).\n // This runs AFTER mount processing (step 1) so cross-boundary\n // `ChildOf {parent: <mount-window-localId>}` references resolve\n // correctly (AC-24).\n const order = sceneTopoSort(ownEntities);\n for (const idx of order) {\n const node = ownEntities[idx];\n if (node === undefined) continue;\n const lid = node.localId as unknown as number;\n const compDataRes = worldBuildSceneEntityComponentDatas(world, node, mapping, diagnostics);\n if (!compDataRes.ok) return compDataRes;\n const sp = (world.spawn as (...c: ComponentData[]) => Result<EntityHandle, EcsError>)(\n ...compDataRes.value,\n );\n if (!sp.ok) return sp as Result<SceneMembersSpawn, EcsError>;\n const e = sp.value;\n mapping[lid] = e as unknown as number;\n entityToLocalId.set(e, lid as unknown as LocalEntityId);\n if (node.components.ChildOf === undefined) {\n rootEntities.push(e);\n }\n }\n\n // 2b. D-8 (feat-20260707): wire deferred owned-parent mount ChildOf edges.\n // Owned entities are now live (step 2 above), so mapping[parentSlot]\n // resolves. Same shape as the mountEntitiesNeedingRootParent wiring in\n // step 5. The relationship mirror hook (relationshipOnInsert) pushes the\n // carrier into the owned parent's Children mirror automatically.\n if (childOfToken !== undefined) {\n for (const [mountEntity, parentSlot] of mountEntitiesNeedingDeferredParent) {\n const parentEntity = mapping[parentSlot];\n if (parentEntity === undefined || parentEntity === ENTITY_NULL_RAW) continue;\n const set = world.set(mountEntity, childOfToken, { parent: parentEntity } as never);\n if (!set.ok) {\n const r = world.addComponent(mountEntity, {\n component: childOfToken,\n data: { parent: parentEntity } as never,\n });\n if (!r.ok) return r as Result<SceneMembersSpawn, EcsError>;\n }\n }\n }\n\n return ok({\n mapping,\n entityToLocalId,\n rootEntities,\n mountEntitiesNeedingRootParent,\n mountEntities,\n mountInstances,\n totalSlots,\n });\n}\n/**\n * @internal Spawn one SceneAsset's entities + apply mounts recursively, then\n * wrap them in a synthetic SceneInstance root (the anchor). This is the\n * runtime / Play / nested-mount finisher (charter P4: instance ==\n * entity-with-SceneInstance). Caller (`_instantiateSceneRec`) owns cycle\n * bookkeeping.\n */\nexport function worldInstantiateSceneAsset(\n world: World,\n handle: Handle<'SceneAsset', 'shared'>,\n asset: SceneAsset,\n parent: EntityHandle | undefined,\n stack: Set<number>,\n diagnostics: SceneInstantiateDiagnostic[],\n instanceKey?: string,\n sceneSourceKey?: string,\n): Result<EntityHandle, EcsError> {\n const sceneInstanceToken = world.components.resolve('SceneInstance');\n if (sceneInstanceToken === undefined) {\n return err(new ComponentNotDefinedError('SceneInstance'));\n }\n const childOfToken = world.components.resolve('ChildOf');\n\n const compiled = compileKeyedSceneAsset(world, handle, asset, {\n resolveSource: (source, parentHandle) => worldResolveMountSource(world, source, parentHandle),\n resolveAsset: (childHandle) => worldResolveSceneAsset(world, childHandle),\n stack,\n });\n if (!compiled.ok) return err(compiled.error as EcsError);\n const compiledAsset = compiled.value.asset;\n const membersRes = worldSpawnSceneMembers(\n world,\n handle,\n compiledAsset,\n stack,\n diagnostics,\n compiled.value.mountKeyByLocalId,\n );\n if (!membersRes.ok) return membersRes;\n const { mapping, entityToLocalId, rootEntities, mountEntitiesNeedingRootParent, totalSlots } =\n membersRes.value;\n const { mountInstances } = membersRes.value;\n const ownMounts = compiledAsset.mounts ?? [];\n\n // 3. Spawn the synthetic root entity carrying SceneInstance.\n // First alloc the state ref so the SceneInstance.state column has a\n // live u32; then attach SceneInstance to a fresh entity.\n let stateRef: Handle<'SceneInstanceState', 'unique'>;\n stateRef = world.allocUniqueRef('SceneInstanceState', null, () => {\n sceneWorldState(world).statePayloads.delete(Number(stateRef));\n });\n // Spawn the root with SceneInstance component, mapping snapshot, and\n // state ref. The mapping is a Uint32Array (array<entity> field shape).\n // Convert mapping Uint32Array to plain number[] for spawn write — the\n // ECS array<entity> arm copies element-by-element and accepts both, but\n // the plain-array form sidesteps a Uint32Array.length=0 corner case\n // observed during M2 testing where a non-empty Uint32Array was written\n // as if empty (suspect: archetype write-array dispatch on instanceof\n // Array vs TypedArray).\n const mappingPlain: number[] = Array.from(mapping);\n // The synthetic root is the ChildOf parent of every owned root entity\n // (step 5 below) and may itself become a ChildOf parent of a caller-\n // supplied `parent` chain. propagateTransforms expands the ECS-maintained\n // Children lists parent-first and treats a parent missing Transform\n // as `hierarchy-broken`, so the synthetic root must carry Transform\n // (identity TRS via layer-2 defaults) when Transform is defined.\n const rootComponents: ComponentData[] = [\n {\n component: sceneInstanceToken,\n data: {\n source: handle,\n mapping: mappingPlain,\n state: stateRef,\n } as never,\n },\n ];\n const transformToken = world.components.resolve('Transform');\n if (transformToken !== undefined) {\n rootComponents.push({\n component: transformToken,\n data: {} as never,\n });\n }\n const rootSpawn = (world.spawn as (...c: ComponentData[]) => Result<EntityHandle, EcsError>)(\n ...rootComponents,\n );\n if (!rootSpawn.ok) {\n return rootSpawn;\n }\n const rootEntity = rootSpawn.value;\n\n // 4. Build SceneInstanceState payload + register it in the UniqueRefStore\n // under the same handle. We use the public `_setUniqueRefPayload`\n // helper (added below) so the alloc -> populate sequence stays atomic.\n const overrides = new Map<LocalEntityId, Map<string, MountOverride>>();\n for (const mount of ownMounts) {\n for (const ov of mount.overrides ?? []) {\n // feat-20260713 M2 / w8: `MountOverride.field` is optional (add-or-patch\n // discriminant carried by the shape itself). Record the override into\n // the SceneInstanceState map keyed by comp (no field) or comp:field\n // (field-patch), then apply it to the live member column via the shared\n // add-or-patch helper.\n const lid = ov.localId as unknown as LocalEntityId;\n let fieldMap = overrides.get(lid);\n if (fieldMap === undefined) {\n fieldMap = new Map();\n overrides.set(lid, fieldMap);\n }\n fieldMap.set(mountOverrideStateKey(ov), ov);\n // Apply override to the live member entity column.\n const memberEntityRaw = mapping[lid as unknown as number];\n if (memberEntityRaw !== undefined && memberEntityRaw !== ENTITY_NULL_RAW) {\n const memberEntity = memberEntityRaw as unknown as EntityHandle;\n const applyRes = worldApplyMountOverride(\n world,\n memberEntity,\n worldRemapMountOverride(world, ov, mapping),\n );\n if (!applyRes.ok) {\n return applyRes as Result<EntityHandle, EcsError>;\n }\n }\n }\n }\n\n const detached = new Set<LocalEntityId>();\n const bindings = new Map<string, EntityHandle>();\n const state: Record<string, unknown> = {\n source: handle,\n ...(sceneSourceKey === undefined ? {} : { sceneSourceKey }),\n keyByLocalId: new Map(compiled.value.keyByLocalId),\n ...(instanceKey === undefined ? {} : { instanceKey }),\n bindings,\n entityToLocalId,\n detachedLocalIds: detached,\n // Convert overrides Map<LocalEntityId, Map<string, MountOverride>>\n // into Map<LocalEntityId, Map<string, SceneInstanceOverrideRecord>>\n overrides: worldMountOverridesToStateMap(overrides),\n rootEntities,\n mountRoots: mountInstances.map(({ root }) => root),\n totalSlots,\n mountTimeOverrides: ownMounts.flatMap((m) => m.overrides ?? []),\n };\n // Stuff the state into the UniqueRefStore under the existing slot. We\n // re-use the slot we allocated above by writing directly into the\n // payloads map via a `_setUniqueRefPayload` shim.\n worldSetUniqueRefPayload(world, stateRef, state);\n // Populate direct and nested keyed addresses only after this root state is\n // visible. Child SceneInstance states were published by the recursive spawn\n // above, so the same walk can project the complete address closure.\n collectSceneEntityBindings(world, rootEntity, [], bindings);\n\n // 5. Wire ChildOf for every owned root entity (no ChildOf at layer-1)\n // to the synthetic root.\n if (childOfToken !== undefined) {\n for (const rootE of rootEntities) {\n const has = world.get(rootE, childOfToken);\n if (!has.ok) {\n // No ChildOf yet — attach to synthetic root.\n const r = world.addComponent(rootE, {\n component: childOfToken,\n data: { parent: rootEntity } as never,\n });\n if (!r.ok) return r as Result<EntityHandle, EcsError>;\n }\n }\n // R2/B-1: wire mount entities with default `mount.parent === undefined`\n // to this scene's synthetic root. _spawnMountEntity may have attached a\n // placeholder ChildOf {parent: ENTITY_NULL_RAW} when mount.components\n // was empty; overwrite via set so the ChildOf chain meshRenderer ->\n // childSyntheticRoot -> mountEntity -> outerSyntheticRoot resolves\n // through Transform-bearing parents (AC-16 / requirements S-7).\n for (const mountE of mountEntitiesNeedingRootParent) {\n const set = world.set(mountE, childOfToken, { parent: rootEntity } as never);\n if (!set.ok) {\n const r = world.addComponent(mountE, {\n component: childOfToken,\n data: { parent: rootEntity } as never,\n });\n if (!r.ok) return r as Result<EntityHandle, EcsError>;\n }\n }\n // Caller-supplied parent: synthetic root's ChildOf -> parent.\n if (parent !== undefined) {\n const r = world.addComponent(rootEntity, {\n component: childOfToken,\n data: { parent } as never,\n });\n if (!r.ok) return r as Result<EntityHandle, EcsError>;\n }\n }\n\n return ok(rootEntity);\n}\n/**\n * @internal Flat finisher — spawn one SceneAsset's members WITHOUT wrapping\n * them in a synthetic SceneInstance root and WITHOUT forcing `ChildOf` onto\n * top-level members. Used for \"opening a scene to edit\": the scene's own\n * entities become plain top-level world entities whose hierarchy is exactly\n * their authored `ChildOf`. Nested prefabs inside still materialise as their\n * own SceneInstance anchors (the mount recursion in `_spawnSceneMembers` is\n * always anchored). Returns the top-level handles (own rootless entities +\n * top-level mount carriers).\n */\nexport function worldInstantiateSceneAssetFlat(\n world: World,\n handle: Handle<'SceneAsset', 'shared'>,\n asset: SceneAsset,\n stack: Set<number>,\n diagnostics: SceneInstantiateDiagnostic[],\n): Result<{ roots: EntityHandle[]; mountEntities: EntityHandle[] }, EcsError> {\n const compiled = compileKeyedSceneAsset(world, handle, asset, {\n resolveSource: (source, parentHandle) => worldResolveMountSource(world, source, parentHandle),\n resolveAsset: (childHandle) => worldResolveSceneAsset(world, childHandle),\n stack,\n });\n if (!compiled.ok) return err(compiled.error as EcsError);\n const membersRes = worldSpawnSceneMembers(\n world,\n handle,\n compiled.value.asset,\n stack,\n diagnostics,\n compiled.value.mountKeyByLocalId,\n );\n if (!membersRes.ok) return membersRes;\n const { rootEntities, mountEntitiesNeedingRootParent, mountEntities, mountInstances } =\n membersRes.value;\n const childOfToken = world.components.resolve('ChildOf');\n\n // Apply parent mount overrides to the live columns and record them on the\n // nested child anchor. Flat mode has no outer SceneInstance state; without\n // this hand-authored mounts[].overrides affect the live value but disappear\n // from the child state, so Gateway re-open cannot discover or revert them.\n for (const { mount, root, mapping: childMapping } of mountInstances) {\n const childStateRes = worldGetSceneInstanceState(world, root);\n if (!childStateRes.ok) return childStateRes;\n for (const ov of mount.overrides ?? []) {\n const childLocalId =\n (ov.localId as unknown as number) - (mount.memberFirst as unknown as number);\n const memberEntityRaw = childMapping[childLocalId];\n if (memberEntityRaw === undefined || memberEntityRaw === ENTITY_NULL_RAW) continue;\n const memberEntity = memberEntityRaw as unknown as EntityHandle;\n const applyRes = worldApplyMountOverride(\n world,\n memberEntity,\n worldRemapMountOverride(world, ov, childMapping),\n );\n if (!applyRes.ok) {\n return applyRes as Result<\n { roots: EntityHandle[]; mountEntities: EntityHandle[] },\n EcsError\n >;\n }\n let fieldMap = childStateRes.value.overrides.get(childLocalId as LocalEntityId);\n if (fieldMap === undefined) {\n fieldMap = new Map();\n childStateRes.value.overrides.set(childLocalId as LocalEntityId, fieldMap);\n }\n fieldMap.set(mountOverrideStateKey(ov), {\n comp: ov.comp,\n ...(ov.field === undefined ? {} : { field: ov.field }),\n value: ov.value,\n });\n }\n }\n\n // Default-parented mount carriers (`mount.parent === undefined`) would, in\n // anchor mode, attach to the synthetic root. Flat mode has none, so they\n // stay top-level. `_spawnMountEntity` may have left a placeholder\n // `ChildOf {parent: ENTITY_NULL_RAW}` (rare: mount with no components AND\n // Transform unregistered) — strip it so the carrier is a genuine root.\n if (childOfToken !== undefined) {\n for (const mountE of mountEntitiesNeedingRootParent) {\n const co = world.get(mountE, childOfToken);\n if (co.ok && (co.value as { parent: number }).parent === ENTITY_NULL_RAW) {\n world.removeComponent(mountE, childOfToken);\n }\n }\n }\n\n return ok({ roots: [...rootEntities, ...mountEntitiesNeedingRootParent], mountEntities });\n}\n/** @internal Build ComponentData[] for one SceneEntity, remapping localIds.\n *\n * SceneAsset payloads use the same schema contract as explicit ECS writes.\n * Unknown fields fail before the first entity is spawned, with the component\n * schema's structured error. The source object is never mutated.\n */\nexport function worldBuildSceneEntityComponentDatas(\n world: World,\n node: CompiledSceneEntity,\n mapping: Uint32Array,\n _diagnostics: SceneInstantiateDiagnostic[],\n): Result<ComponentData[], EcsError> {\n const out: ComponentData[] = [];\n const nodeLocalId = node.localId as unknown as number;\n for (const compName of Object.keys(node.components)) {\n const token = world.components.resolve(compName);\n if (token === undefined) {\n return err(new ComponentNotDefinedError(compName));\n }\n const raw = node.components[compName] ?? {};\n const schema = componentSchema(token) as Record<string, string>;\n const remappedRaw: Record<string, unknown> = {};\n for (const fieldName of Object.keys(raw)) {\n const fieldType = schema[fieldName];\n // Do not mutate the source `raw`. SceneAsset compilation normally catches\n // this earlier; this guard keeps the private numeric projection fail-fast\n // for callers that provide a precompiled asset.\n if (fieldType === undefined) {\n return err({\n code: 'spawn-data-unknown-field',\n expected: `field name in {${Object.keys(schema).sort().join(', ')}}`,\n hint: `unknown field '${fieldName}' on component '${compName}' at scene localId ${nodeLocalId}`,\n detail: {\n component: compName,\n field: fieldName,\n entity: nodeLocalId,\n knownFields: Object.keys(schema).sort(),\n },\n } as unknown as EcsError);\n }\n const value = (raw as Record<string, unknown>)[fieldName];\n const kind = classifyEntityField(token, fieldName);\n if (kind !== null) {\n // Entity / array<entity> field — remap through the shared kernel.\n // localId -> live Entity. Slots not yet spawned hold ENTITY_NULL_RAW.\n const sceneRemap = (localId: number): number => {\n if (localId < 0 || localId >= mapping.length) return ENTITY_NULL_RAW;\n const live = mapping[localId];\n return live === undefined || live === ENTITY_NULL_RAW ? ENTITY_NULL_RAW : live;\n };\n remappedRaw[fieldName] = remapEntityFieldValue(value, kind, sceneRemap);\n } else {\n remappedRaw[fieldName] = value;\n }\n }\n const filled = fillComponentDefaults(token, remappedRaw);\n out.push({ component: token, data: filled as never });\n }\n return ok(out);\n}\n\n/**\n * Resolve the private local-slot values produced by keyed SceneAsset\n * compilation before an instance override is written to a live ECS row.\n * Override references are authored in the declaring parent namespace, while\n * `worldApplyMountOverride` deliberately accepts ordinary live component data.\n */\nfunction worldRemapMountOverride(\n world: World,\n override: MountOverride,\n mapping: Uint32Array,\n): MountOverride {\n const token = world.components.resolve(override.comp);\n if (token === undefined) return override;\n const remapField = (field: string, value: unknown): unknown => {\n const kind = classifyEntityField(token as Component, field);\n if (kind === null) return value;\n const toLive = (slot: number): number => {\n if (slot < 0 || slot >= mapping.length) return ENTITY_NULL_RAW;\n return mapping[slot] ?? ENTITY_NULL_RAW;\n };\n return remapEntityFieldValue(value, kind, toLive);\n };\n if (override.field !== undefined) {\n return { ...override, value: remapField(override.field, override.value) };\n }\n if (\n typeof override.value !== 'object' ||\n override.value === null ||\n Array.isArray(override.value)\n ) {\n return override;\n }\n const value: Record<string, unknown> = {};\n for (const [field, fieldValue] of Object.entries(override.value as Record<string, unknown>)) {\n value[field] = remapField(field, fieldValue);\n }\n return { ...override, value };\n}\n\n/**\n * @internal feat-20260713 M2 / w8: apply one MountOverride to a live member\n * entity column. The `field?` shape is the add-or-patch discriminant:\n *\n * - `field` present -> PATCH one field: `world.set(member, comp, {[field]:\n * value})`. Omitted fields keep their authored / existing values.\n * - `field` absent -> ADD/UPSERT the whole component: `value` is the\n * per-field value map for `comp`. When the member already carries `comp`\n * it is upserted (set-over each supplied field + schema defaults for the\n * omitted ones — the whole component is rewritten from the value map +\n * defaults, never a `component-already-present` error). When absent it is\n * added fresh via `addComponent` (fillComponentDefaults fills omitted\n * fields). The value-map is fed through `fillComponentDefaults` so the\n * add and upsert paths write byte-identical rows.\n *\n * Component registration + value-key validation happened at\n * `_validateMountOverrides` (fail-fast before any spawn); by this point the\n * comp resolves through the World-local catalog and the value keys are schema-valid.\n * still guards defensively (an unregistered comp is a no-op skip, matching\n * the prior field-patch behaviour). Returns the underlying set / addComponent\n * Result so a shared-field value gate (D-4) or any other write error\n * propagates unchanged.\n */\nexport function worldApplyMountOverride(\n world: World,\n member: EntityHandle,\n ov: MountOverride,\n): Result<void, EcsError> {\n const ovToken = world.components.resolve(ov.comp);\n if (ovToken === undefined) return ok(undefined);\n if (ov.field !== undefined) {\n // PATCH one field.\n return world.set(member, ovToken, { [ov.field]: ov.value } as never);\n }\n // ADD/UPSERT the whole component. Fill omitted fields from the schema so\n // add and upsert produce identical rows (upsert = full rewrite from the\n // value map + defaults).\n const rawValue = (ov.value ?? {}) as Record<string, unknown>;\n const filled = fillComponentDefaults(ovToken as Component, rawValue);\n const has = world.get(member, ovToken);\n if (has.ok) {\n // Already present -> upsert (set every filled field, no duplicate error).\n return world.set(member, ovToken, filled as never);\n }\n return world.addComponent(member, { component: ovToken, data: filled as never });\n}\n/**\n * @internal R2/B-3 + R2/B-4: validate `mount.overrides[]` BEFORE any\n * spawn so a malformed override fails fast with no observable side\n * effects (charter P3 explicit-failure). Two checks:\n *\n * 1. `override.localId` must address a slot inside the parent-namespace\n * member window `[memberFirst, memberFirst + memberCount)` (AC-06).\n * 2. `override.field` must exist in the resolved component schema\n * (AC-07). When the component is unregistered we cannot validate the\n * field shape; let the existing fall-through path proceed (the\n * catalog guard inside the override-application loop\n * will skip the write).\n */\nexport function worldValidateMountOverrides(\n world: World,\n mount: SceneInstanceMount,\n): Result<void, EcsError> {\n const overrides = mount.overrides;\n if (overrides === undefined) return ok(undefined);\n const memberFirst = mount.memberFirst as unknown as number;\n const memberCount = mount.memberCount;\n const memberLast = memberFirst + memberCount;\n const mountLid = mount.localId as unknown as number;\n for (const ov of overrides) {\n const ovLid = ov.localId as unknown as number;\n // R2/B-3: parent-namespace check — override.localId must lie in the\n // member window [memberFirst, memberFirst + memberCount).\n if (ovLid < memberFirst || ovLid >= memberLast) {\n return err({\n code: 'pack-mount-override-localid-out-of-range' as PackErrorCode,\n expected: `override.localId in [${memberFirst}, ${memberLast})`,\n hint: PACK_ERROR_HINTS['pack-mount-override-localid-out-of-range'],\n detail: {\n code: 'pack-mount-override-localid-out-of-range',\n overrideLocalId: ovLid,\n mountLocalId: mountLid,\n memberCount,\n } as PackErrorDetail,\n } as unknown as EcsError);\n }\n // feat-20260713 M2 / w8: double-branch schema check.\n // - field-patch form (field present): the component (when registered)\n // must declare `override.field` in its schema (R2/B-4, unchanged).\n // - component-add form (field absent): the component MUST be registered\n // (component-not-defined otherwise) AND every key in the value map\n // must be a schema field (pack-mount-override-unknown-field).\n const ovToken = world.components.resolve(ov.comp);\n if (ov.field !== undefined) {\n if (ovToken !== undefined) {\n const schema = componentSchema(ovToken) as Record<string, unknown>;\n if (!(ov.field in schema)) {\n return err({\n code: 'pack-mount-override-unknown-field' as PackErrorCode,\n expected: `override.field defined on component '${ov.comp}'`,\n hint: PACK_ERROR_HINTS['pack-mount-override-unknown-field'],\n detail: {\n code: 'pack-mount-override-unknown-field',\n comp: ov.comp,\n field: ov.field,\n mountLocalId: mountLid,\n } as PackErrorDetail,\n } as unknown as EcsError);\n }\n }\n } else {\n // component-add form: comp must be registered so we can validate + apply\n // the whole component (add/upsert needs the schema).\n if (ovToken === undefined) {\n return err(new ComponentNotDefinedError(ov.comp));\n }\n const schema = componentSchema(ovToken) as Record<string, unknown>;\n const valueMap = (ov.value ?? {}) as Record<string, unknown>;\n for (const key of Object.keys(valueMap)) {\n if (!(key in schema)) {\n return err({\n code: 'pack-mount-override-unknown-field' as PackErrorCode,\n expected: `override.value keys defined on component '${ov.comp}'`,\n hint: PACK_ERROR_HINTS['pack-mount-override-unknown-field'],\n detail: {\n code: 'pack-mount-override-unknown-field',\n comp: ov.comp,\n field: key,\n mountLocalId: mountLid,\n } as PackErrorDetail,\n } as unknown as EcsError);\n }\n }\n }\n }\n return ok(undefined);\n}\n/** @internal Spawn the mount-entity slot carrying mount.components (if any).\n *\n * R2/B-1: the mount entity is a structural intermediate in the ChildOf\n * chain `cube -> innerSyntheticRoot -> mountEntity -> outerSyntheticRoot`,\n * so it MUST carry Transform whenever Transform is registered (mirrors\n * the D-V-0 synthetic-root invariant). Otherwise propagateTransforms\n * expanding the chain hits a Transform-less parent and emits per-frame\n * `RhiError(hierarchy-broken)` (verify R1 root cause of the\n * hello-scene-nesting demo black frames).\n */\nexport function worldSpawnMountEntity(\n world: World,\n mount: SceneInstanceMount,\n mapping: Uint32Array,\n diagnostics: SceneInstantiateDiagnostic[],\n): Result<EntityHandle, EcsError> {\n const fakeNode: CompiledSceneEntity = {\n localId: mount.localId,\n components: mount.components ?? {},\n };\n const cdRes = worldBuildSceneEntityComponentDatas(world, fakeNode, mapping, diagnostics);\n if (!cdRes.ok) return cdRes;\n // R2/B-1: ensure Transform is attached so propagateTransforms can expand\n // through this entity. Layer-2 defaults supply identity TRS; the\n // mount.components overlay (when present and including Transform) takes\n // precedence and is already in cdRes.value.\n const transformToken = world.components.resolve('Transform');\n if (transformToken !== undefined) {\n const hasTransform = cdRes.value.some((c) => c.component === transformToken);\n if (!hasTransform) {\n cdRes.value.push({ component: transformToken, data: {} as never });\n }\n }\n if (cdRes.value.length === 0) {\n // Mount has no components AND Transform is unregistered (rare unit-\n // test path). Fall back to the placeholder ChildOf so the spawn has\n // a real archetype. Step 5 overwrites this placeholder.\n const childOfToken = world.components.resolve('ChildOf');\n if (childOfToken === undefined) {\n return err(new ComponentNotDefinedError('ChildOf'));\n }\n cdRes.value.push({\n component: childOfToken,\n data: { parent: ENTITY_NULL_RAW } as never,\n });\n }\n return (world.spawn as (...c: ComponentData[]) => Result<EntityHandle, EcsError>)(...cdRes.value);\n}\n/** @internal Resolve mount.source through the wired SceneAssetResolver. */\nexport function worldResolveMountSource(\n world: World,\n source: number | string,\n parentHandle: Handle<'SceneAsset', 'shared'>,\n): Result<Handle<'SceneAsset', 'shared'>, EcsError> {\n const resolver = worldGetSceneAssetResolver(world);\n if (resolver === null) {\n return err({\n code: 'stale-entity' as const,\n expected: 'wired SceneAssetResolver (auto-wired by engine.assets.instantiate)',\n hint:\n 'engine.assets.instantiate sugar wires this for you; ' +\n 'call worldSetSceneAssetResolver before nested scene expansion.',\n detail: { entity: 0, slot: 0, generation: 0 },\n } as unknown as EcsError);\n }\n const r = resolver(source, parentHandle);\n if (!r.ok) {\n // Resolver carries `unknown` err (loose contract — engine-runtime may\n // wire any shape); narrow back to EcsError here at the boundary.\n return err(r.error as EcsError);\n }\n return ok(r.value);\n}\n/** @internal Convert mount.overrides Map shape to the SceneInstanceState shape.\n *\n * feat-20260713 M1 / w4: `field` is optional (add-or-patch discriminant). In\n * M1 only the field-patch form reaches this builder (the component-add form\n * fails fast in the apply loops); the record type stays `field?: string` so\n * the M2 add path can flow through untouched. `exactOptionalPropertyTypes`\n * forbids writing an explicit `field: undefined`, so omit the key when absent.\n */\nexport function worldMountOverridesToStateMap(\n src: Map<LocalEntityId, Map<string, MountOverride>>,\n): Map<LocalEntityId, Map<string, { comp: string; field?: string; value: unknown }>> {\n const out = new Map<\n LocalEntityId,\n Map<string, { comp: string; field?: string; value: unknown }>\n >();\n for (const [lid, fields] of src) {\n const m = new Map<string, { comp: string; field?: string; value: unknown }>();\n for (const [k, v] of fields) {\n m.set(k, {\n comp: v.comp,\n value: v.value,\n ...(v.field !== undefined ? { field: v.field } : {}),\n });\n }\n out.set(lid, m);\n }\n return out;\n}\n/** @internal Set the payload of an already-allocated SceneInstance state ref. */\nexport function worldSetUniqueRefPayload<T>(\n world: World,\n handle: Handle<string, 'unique'>,\n payload: T,\n): void {\n sceneWorldState(world).statePayloads.set(Number(handle), payload);\n}\n\n/**\n * @internal Resolve the SceneInstanceState payload behind the\n * `SceneInstance.state` ref column on `root`. Returns Err when `root`\n * does not carry SceneInstance or the ref slot is dead.\n */\nexport function worldResolveSceneInstanceStatePayload(\n world: World,\n root: EntityHandle,\n): Result<SceneInstanceStatePayload, EcsError> {\n const sceneInstanceToken = world.components.resolve('SceneInstance');\n if (sceneInstanceToken === undefined) {\n return err(new ComponentNotDefinedError('SceneInstance'));\n }\n const r = world.get(root, sceneInstanceToken);\n if (!r.ok) return r;\n const stateRefRaw = (r.value as unknown as { state: number }).state;\n const stateRefHandle = toUnique<'SceneInstanceState'>(stateRefRaw);\n const payload = sceneWorldState(world).statePayloads.get(Number(stateRefHandle));\n if (payload === undefined) {\n return err(\n new StaleEntityError(root as unknown as number, entityIndex(root), entityGeneration(root), {\n operation: 'resolveSceneInstanceState',\n component: 'SceneInstance',\n expectedGeneration: entityGeneration(root),\n actualGeneration: entityGeneration(root),\n }),\n );\n }\n return ok(payload as SceneInstanceStatePayload);\n}\n/**\n * Public sugar — get the SceneInstanceState payload (Map / Set view) for\n * `root`. Equivalent to `world.get(root, SceneInstance)` followed by a\n * managed-ref resolution; provided so AI users do not have to learn the\n * `ref<T>` slot resolution mechanic for the common read path.\n */\nexport function worldGetSceneInstanceState(\n world: World,\n root: EntityHandle,\n): Result<SceneInstanceStatePayload, EcsError> {\n return worldResolveSceneInstanceStatePayload(world, root);\n}\n\n/** Resolve a generated SceneEntityRef against one concrete SceneInstance. */\nexport function worldResolveSceneEntity(\n world: World,\n root: EntityHandle,\n ref: SceneEntityRef,\n): Result<EntityHandle, EcsError> {\n const state = worldResolveSceneInstanceStatePayload(world, root);\n if (!state.ok) return state;\n // Anonymous POD scenes remain addressable with an explicit empty source key.\n // Never let the caller supply the identity used for the comparison: that\n // would make an anonymous instance accept a fabricated persistent ref.\n const resolved = resolveSceneEntity(ref, {\n sceneSourceKey: state.value.sceneSourceKey ?? '',\n bindings: state.value.bindings,\n });\n if (!resolved.ok) return err(resolved.error as unknown as EcsError);\n return ok(resolved.value as EntityHandle);\n}\n/**\n * Despawn a SceneInstance root + all its members. `opts.keepDetached`\n * preserves members marked via `worldDetachSceneMember` (plan-strategy\n * §D-5). Returns the count of entities actually despawned (root + each\n * non-detached member).\n *\n * For a plain entity (no SceneInstance), behaviour matches\n * `world.despawn(entity)` followed by `despawnDescendants(entity)` — i.e.\n * `keepDetached` is a no-op.\n */\nexport function worldDespawnScene(\n world: World,\n root: EntityHandle,\n opts?: { keepDetached?: boolean },\n): Result<number, EcsError> {\n const dRes = worldDespawnDescendants(world, root, opts);\n if (!dRes.ok) return dRes;\n const drop = world.despawn(root);\n if (!drop.ok) return drop;\n return ok(dRes.value + 1);\n}\n/**\n * Despawn every descendant of `root` reachable through Children mirror /\n * SceneInstance.mapping. `opts.keepDetached` is honoured only when `root`\n * carries a SceneInstance (otherwise the option is ignored — there is no\n * detached set on a plain entity).\n *\n * Returns the count of entities despawned. The `root` itself is NOT\n * despawned (that is `despawnScene`'s extra step).\n */\nexport function worldDespawnDescendants(\n world: World,\n root: EntityHandle,\n opts?: { keepDetached?: boolean },\n): Result<number, EcsError> {\n let detached: Set<LocalEntityId> | null = null;\n let entityToLocalId: Map<EntityHandle, LocalEntityId> | null = null;\n if (opts?.keepDetached === true) {\n const stateRes = worldResolveSceneInstanceStatePayload(world, root);\n if (stateRes.ok) {\n detached = stateRes.value.detachedLocalIds;\n entityToLocalId = stateRes.value.entityToLocalId;\n }\n }\n let count = 0;\n // Collect descendants first (DFS via iterDescendants) to avoid mutating\n // while iterating. SceneInstance.mapping also owns members that may not be\n // reachable through a Children mirror in a partially registered host. The\n // nested anchor list closes that same ownership boundary for mounted scenes.\n const list: EntityHandle[] = [];\n const seen = new Set<number>();\n const collect = (anchor: EntityHandle): void => {\n for (const e of world.iterDescendants(anchor)) {\n const raw = e as unknown as number;\n if (!seen.has(raw)) {\n seen.add(raw);\n list.push(e);\n }\n }\n const stateRes = worldResolveSceneInstanceStatePayload(world, anchor);\n if (!stateRes.ok) return;\n for (const e of stateRes.value.entityToLocalId.keys()) {\n const raw = e as unknown as number;\n if (!seen.has(raw)) {\n seen.add(raw);\n list.push(e);\n }\n }\n for (const nestedRoot of stateRes.value.mountRoots) {\n const raw = nestedRoot as unknown as number;\n if (seen.has(raw)) continue;\n seen.add(raw);\n list.push(nestedRoot);\n collect(nestedRoot);\n }\n };\n collect(root);\n const childOfToken = world.components.resolve('ChildOf');\n // ChildOf uses linkedSpawn, so a parent-first pass would recursively retire\n // its children before this function can count them. Sort the ownership set\n // by its live ChildOf depth instead of relying on mirror traversal order;\n // nested SceneInstance roots are siblings of their mount carrier in the\n // flattened traversal but parents of the mounted members.\n const owned = new Set(list.map((entity) => Number(entity)));\n const ownedDepth = (entity: EntityHandle): number => {\n if (childOfToken === undefined) return 0;\n let current = entity;\n let depth = 0;\n const visited = new Set<number>();\n while (!visited.has(Number(current))) {\n visited.add(Number(current));\n const parentRes = world.get(current, childOfToken);\n if (!parentRes.ok) break;\n const parent = (parentRes.value as { parent: EntityHandle }).parent;\n if (!owned.has(Number(parent))) break;\n depth += 1;\n current = parent;\n }\n return depth;\n };\n list.sort((a, b) => ownedDepth(b) - ownedDepth(a));\n for (const e of list) {\n if (detached !== null) {\n const lid = entityToLocalId?.get(e);\n if (lid !== undefined && detached.has(lid)) {\n if (childOfToken !== undefined) {\n world.removeComponent(e, childOfToken);\n }\n continue;\n }\n }\n const r = world.despawn(e);\n if (!r.ok) {\n if (r.error.code === 'stale-entity') continue;\n return r;\n }\n count += 1;\n }\n return ok(count);\n}\n/**\n * Write a runtime override to a member entity belonging to `root`. Routes\n * through `world.set(member, comp, { [field]: value })` after an entity-\n * scope guard so cross-instance writes fail-fast. Type-mismatch surfaces\n * `EcsErrorCode = 'scene-override-type-mismatch'` (D-9).\n */\nexport function worldSetSceneOverride<S extends ComponentSchema>(\n world: World,\n root: EntityHandle,\n member: EntityHandle,\n component: Component<string, S>,\n field: keyof ShapeOf<S> & string,\n value: unknown,\n): Result<void, EcsError> {\n const stateRes = worldResolveSceneInstanceStatePayload(world, root);\n if (!stateRes.ok) return stateRes;\n const state = stateRes.value;\n const lid = state.entityToLocalId.get(member);\n if (lid === undefined) {\n return err(\n new StaleEntityError(\n member as unknown as number,\n entityIndex(member),\n entityGeneration(member),\n {\n operation: 'setSceneOverride',\n component: component.name,\n expectedGeneration: entityGeneration(member),\n actualGeneration: entityGeneration(member),\n },\n ),\n );\n }\n // Type guard: only check primitive scalar field types where we can\n // narrow `typeof`; ref / handle / entity / array / buffer fields skip\n // (write would surface a deeper error from set).\n const schemaType = (componentSchema(component) as Record<string, string>)[field];\n if (schemaType !== undefined && isPrimitiveScalarFieldType(schemaType)) {\n const expectJsType = primitiveJsType(schemaType);\n const actualJsType = typeof value;\n if (expectJsType !== actualJsType) {\n return err({\n code: 'scene-override-type-mismatch' as const,\n expected: `value typeof === ${expectJsType}`,\n hint:\n `setSceneOverride(${component.name}.${field}) expected ${expectJsType}, ` +\n `got ${actualJsType}; coerce or pick a different override path.`,\n detail: {\n code: 'scene-override-type-mismatch' as const,\n comp: component.name,\n field: field as string,\n expectedType: schemaType,\n actualType: actualJsType,\n },\n } as unknown as EcsError);\n }\n }\n const setRes = world.set(member, component, { [field]: value } as Partial<InputShapeOf<S>>);\n if (!setRes.ok) return setRes;\n // Record into state.overrides\n let fieldMap = state.overrides.get(lid);\n if (fieldMap === undefined) {\n fieldMap = new Map();\n state.overrides.set(lid, fieldMap);\n }\n fieldMap.set(`${component.name}:${field}`, {\n comp: component.name,\n field: field as string,\n value,\n });\n return ok(undefined);\n}\n/**\n * Drop a runtime override (and any mount-time override for the same\n * (member, comp, field) triple); roll the live column value back to the\n * source SceneAsset's layer-1 explicit value (M2 v1 — M3+ widens to layer\n * 2/3 defaults via fillComponentDefaults).\n */\nexport function worldRemoveSceneOverride<S extends ComponentSchema>(\n world: World,\n root: EntityHandle,\n member: EntityHandle,\n component: Component<string, S>,\n field: keyof ShapeOf<S> & string,\n): Result<void, EcsError> {\n const stateRes = worldResolveSceneInstanceStatePayload(world, root);\n if (!stateRes.ok) return stateRes;\n const state = stateRes.value;\n const lid = state.entityToLocalId.get(member);\n if (lid === undefined) return ok(undefined);\n const fieldMap = state.overrides.get(lid);\n if (fieldMap !== undefined) {\n fieldMap.delete(`${component.name}:${field}`);\n if (fieldMap.size === 0) state.overrides.delete(lid);\n }\n // Look up the source SceneAsset layer-1 value.\n const assetRes = worldResolveSceneAsset(world, state.source);\n if (!assetRes.ok) return assetRes;\n const key = state.keyByLocalId.get(lid as unknown as number);\n const node = key === undefined ? undefined : assetRes.value.entities[key];\n const layer1 = node?.components[component.name] as Record<string, unknown> | undefined;\n if (layer1 !== undefined && field in layer1) {\n const r = world.set(member, component, { [field]: layer1[field] } as Partial<InputShapeOf<S>>);\n if (!r.ok) return r;\n }\n return ok(undefined);\n}\n/** Mark a member entity detached. Idempotent (set semantics). */\nexport function worldDetachSceneMember(\n world: World,\n root: EntityHandle,\n member: EntityHandle,\n): Result<void, EcsError> {\n const sceneInstanceToken = world.components.resolve('SceneInstance');\n if (sceneInstanceToken === undefined) {\n return err(new ComponentNotDefinedError('SceneInstance'));\n }\n const stateRes = worldResolveSceneInstanceStatePayload(world, root);\n if (!stateRes.ok) return stateRes;\n const state = stateRes.value;\n const lid = state.entityToLocalId.get(member);\n if (lid === undefined) return ok(undefined);\n state.detachedLocalIds.add(lid);\n return ok(undefined);\n}\n/** Clear a detached mark. Idempotent (set semantics). */\nexport function worldReattachSceneMember(\n world: World,\n root: EntityHandle,\n member: EntityHandle,\n): Result<void, EcsError> {\n const stateRes = worldResolveSceneInstanceStatePayload(world, root);\n if (!stateRes.ok) return stateRes;\n const state = stateRes.value;\n const lid = state.entityToLocalId.get(member);\n if (lid === undefined) return ok(undefined);\n state.detachedLocalIds.delete(lid);\n return ok(undefined);\n}\n/**\n * Get the SceneAsset handle a SceneInstance root was instantiated from.\n * Returns Err on a plain entity (no SceneInstance component).\n */\nexport function worldGetSceneAssetForInstance(\n world: World,\n root: EntityHandle,\n): Result<Handle<'SceneAsset', 'shared'>, EcsError> {\n const stateRes = worldResolveSceneInstanceStatePayload(world, root);\n if (!stateRes.ok) return stateRes;\n return ok(stateRes.value.source);\n}\n\n/**\n * Topological sort over the implicit ChildOf graph (parents before children).\n * Cycle-free input always covers all n nodes; cyclic input emits whatever was\n * reachable from indegree-0 (the fallback caller handles cycle reporting via\n * `pack-cyclic-reference` at the upstream scanner / runtime path).\n */\nfunction sceneTopoSort(nodes: readonly CompiledSceneEntity[]): readonly number[] {\n const n = nodes.length;\n const childrenOf: number[][] = Array.from({ length: n }, () => []);\n const indeg = new Uint32Array(n);\n const localIdToIdx = new Map<number, number>();\n for (let i = 0; i < n; i += 1) {\n const node = nodes[i];\n if (node === undefined) continue;\n localIdToIdx.set(node.localId as unknown as number, i);\n }\n for (let i = 0; i < n; i += 1) {\n const node = nodes[i];\n if (node === undefined) continue;\n const child = node.components.ChildOf;\n if (child === undefined) continue;\n const p = (child as Record<string, unknown>).parent;\n if (typeof p === 'number') {\n const parentIdx = localIdToIdx.get(p);\n if (parentIdx !== undefined && parentIdx !== i) {\n childrenOf[parentIdx]?.push(i);\n indeg[i] = (indeg[i] ?? 0) + 1;\n }\n }\n }\n const order: number[] = [];\n const queue: number[] = [];\n for (let i = 0; i < n; i += 1) if ((indeg[i] ?? 0) === 0) queue.push(i);\n while (queue.length > 0) {\n const head = queue.shift();\n if (head === undefined) break;\n order.push(head);\n for (const c of childrenOf[head] ?? []) {\n indeg[c] = (indeg[c] ?? 0) - 1;\n if ((indeg[c] ?? 0) === 0) queue.push(c);\n }\n }\n // Append any nodes left unvisited (defensive — cycle would surface here).\n for (let i = 0; i < n; i += 1) {\n if (!order.includes(i) && nodes[i] !== undefined) order.push(i);\n }\n return order;\n}\n","import type { EntityHandle, World } from '@forgeax/engine-ecs';\nimport type { Handle, LocalEntityId } from '@forgeax/engine-types';\nimport type { MountOverride } from './runtime-types.js';\n\n/** Internal state retained by a SceneInstance root. */\nexport interface SceneInstanceStatePayload {\n readonly source: Handle<'SceneAsset', 'shared'>;\n readonly sceneSourceKey?: string;\n /** Authored key for each private numeric slot, retained for collection. */\n readonly keyByLocalId: Map<number, string>;\n /** Authored key of this instance when it is nested in a parent scene. */\n readonly instanceKey?: string;\n readonly bindings: Map<string, EntityHandle>;\n readonly entityToLocalId: Map<EntityHandle, LocalEntityId>;\n readonly detachedLocalIds: Set<LocalEntityId>;\n readonly overrides: Map<\n LocalEntityId,\n Map<string, { readonly comp: string; readonly field?: string; readonly value: unknown }>\n >;\n readonly rootEntities: EntityHandle[];\n readonly mountRoots: EntityHandle[];\n readonly totalSlots: number;\n readonly mountTimeOverrides: readonly MountOverride[];\n}\n\nexport interface SceneWorldState {\n resolver: unknown;\n readonly statePayloads: Map<number, unknown>;\n}\n\nconst sceneWorldStates = new WeakMap<World, SceneWorldState>();\n\nexport function sceneWorldState(world: World): SceneWorldState {\n const current = sceneWorldStates.get(world);\n if (current !== undefined) return current;\n const created: SceneWorldState = { resolver: null, statePayloads: new Map<number, unknown>() };\n sceneWorldStates.set(world, created);\n return created;\n}\n\nexport function mountOverrideStateKey(ov: MountOverride): string {\n return ov.field !== undefined ? `${ov.comp}:${ov.field}` : ov.comp;\n}\n\nexport function isPrimitiveScalarFieldType(fieldType: string): boolean {\n if (\n fieldType === 'f32' ||\n fieldType === 'f64' ||\n fieldType === 'u32' ||\n fieldType === 'i32' ||\n fieldType === 'u8' ||\n fieldType === 'i8' ||\n fieldType === 'u16' ||\n fieldType === 'i16' ||\n fieldType === 'bool' ||\n fieldType === 'string'\n ) {\n return true;\n }\n return fieldType.startsWith('enum<');\n}\n\nexport function primitiveJsType(fieldType: string): string {\n if (fieldType === 'bool') return 'boolean';\n if (fieldType === 'string') return 'string';\n return 'number';\n}\n","import {\n defineSystem,\n defineSystemSet,\n type EcsError,\n ENTITY_NULL_RAW,\n type EntityHandle,\n FixedUpdate,\n type Query,\n type SystemHandle,\n Update,\n type World,\n} from '@forgeax/engine-ecs';\nimport {\n type DerivedColumnBinding,\n type DerivedRangeCursor,\n type DerivedRangeWriter,\n getDerivedWriter,\n} from '@forgeax/engine-ecs/internal';\nimport { worldRead } from '@forgeax/engine-ecs/world-read';\nimport { type Mat4, mat4 } from '@forgeax/engine-math';\nimport { err, ok, type Result } from '@forgeax/engine-types';\nimport { ChildOf } from '../components/child-of';\nimport { Children } from '../components/children';\nimport { GlobalTransform, Transform } from '../components/transform';\nimport { SceneError } from '../errors';\n\nexport const PROPAGATE_TRANSFORMS_SYSTEM = 'propagateTransforms' as const;\nexport const PROPAGATE_TRANSFORMS_FIXED_SYSTEM = 'propagateTransformsFixed' as const;\nexport const TransformSet = defineSystemSet({ name: 'transform' });\nexport const TransformFixedSet = defineSystemSet({ name: 'transform-fixed' });\n\n/**\n * Optional, test-owned counters for the parent-first executor. The counters\n * are disabled unless a caller brackets a run with begin/end; production\n * propagation therefore pays only one predictable branch per instrumented\n * event. They are deliberately not a second execution state or a public\n * dirty/cache contract.\n */\nexport interface TransformPropagationTrace {\n hierarchyRootInvocations: number;\n hierarchyRootCursorReuses: number;\n hierarchyRootCursorAllocations: number;\n hierarchyEntityLookups: number;\n hierarchyRowsEvaluated: number;\n hierarchyEdgesVisited: number;\n hierarchyPublishedRows: number;\n hierarchyPublishedRuns: number;\n hierarchyResidualParentProbes: number;\n flatStructuralRootRows: number;\n}\n\nlet propagationTrace: TransformPropagationTrace | undefined;\nlet hierarchyRootCursorAllocationCount = 0;\nlet propagationTraceRootCursorAllocationStart = 0;\n\nfunction createHierarchyRootCursor(): DerivedRangeCursor {\n hierarchyRootCursorAllocationCount += 1;\n return { bindingIndex: -1, row: -1 };\n}\n\nexport function beginTransformPropagationTrace(): void {\n propagationTraceRootCursorAllocationStart = hierarchyRootCursorAllocationCount;\n propagationTrace = {\n hierarchyRootInvocations: 0,\n hierarchyRootCursorReuses: 0,\n hierarchyRootCursorAllocations: 0,\n hierarchyEntityLookups: 0,\n hierarchyRowsEvaluated: 0,\n hierarchyEdgesVisited: 0,\n hierarchyPublishedRows: 0,\n hierarchyPublishedRuns: 0,\n hierarchyResidualParentProbes: 0,\n flatStructuralRootRows: 0,\n };\n}\n\nexport function endTransformPropagationTrace(): TransformPropagationTrace {\n const trace = propagationTrace;\n propagationTrace = undefined;\n const rootCursorAllocations =\n hierarchyRootCursorAllocationCount - propagationTraceRootCursorAllocationStart;\n propagationTraceRootCursorAllocationStart = hierarchyRootCursorAllocationCount;\n if (trace !== undefined) {\n trace.hierarchyRootCursorAllocations = rootCursorAllocations;\n return trace;\n }\n return {\n hierarchyRootInvocations: 0,\n hierarchyRootCursorReuses: 0,\n hierarchyRootCursorAllocations: 0,\n hierarchyEntityLookups: 0,\n hierarchyRowsEvaluated: 0,\n hierarchyEdgesVisited: 0,\n hierarchyPublishedRows: 0,\n hierarchyPublishedRuns: 0,\n hierarchyResidualParentProbes: 0,\n flatStructuralRootRows: 0,\n };\n}\n\nfunction countPropagation(name: keyof TransformPropagationTrace): void {\n const trace = propagationTrace;\n if (trace !== undefined) trace[name] += 1;\n}\n\ninterface Scratch {\n position: Float32Array;\n rotation: Float32Array;\n scale: Float32Array;\n local: Mat4;\n parent: Mat4;\n candidate: Mat4;\n hierarchyStackEntities: EntityHandle[];\n hierarchyStackChildren: number[];\n hierarchyProbeEntities: EntityHandle[];\n hierarchyCurrentCursor: DerivedRangeCursor;\n hierarchyParentCursor: DerivedRangeCursor;\n hierarchyChildCursor: DerivedRangeCursor;\n hierarchyResidualCursor: DerivedRangeCursor;\n hierarchyResidualParentCursor: DerivedRangeCursor;\n hierarchyRootCursor: DerivedRangeCursor;\n hierarchyStates: Uint8Array[];\n hierarchyChanged: Uint8Array[];\n hierarchyBindingTables: number[];\n hierarchyBindingRows: number[];\n flatChanged: Uint8Array[];\n flatBindingTables: number[];\n flatBindingRows: number[];\n flatStructureEpoch: number;\n flatQuery?: FlatQuery;\n hierarchyQuery?: HierarchyQuery;\n transformQuery?: TransformQuery;\n hierarchyWriter?: HierarchyWriter;\n transformWriter?: TransformWriter;\n missingGlobalQuery?: MissingGlobalQuery;\n missingTransformQuery?: MissingTransformQuery;\n}\n\ntype FlatQuery = Query<readonly [typeof Transform], readonly [typeof GlobalTransform]>;\ntype HierarchyQuery = Query<\n readonly [typeof Transform, typeof ChildOf],\n readonly [typeof GlobalTransform]\n>;\ntype TransformQuery = Query<readonly [typeof Transform], readonly [typeof GlobalTransform]>;\ntype HierarchyWriter = DerivedRangeWriter<\n typeof Transform | typeof ChildOf,\n typeof GlobalTransform\n>;\ntype TransformWriter = DerivedRangeWriter<typeof Transform, typeof GlobalTransform>;\ntype HierarchyBinding = DerivedColumnBinding<\n typeof Transform | typeof ChildOf,\n typeof GlobalTransform\n>;\ntype TransformBinding = DerivedColumnBinding<typeof Transform, typeof GlobalTransform>;\ntype MissingGlobalQuery = Query<readonly [], readonly [], readonly []>;\ntype MissingTransformQuery = Query<readonly [], readonly [], readonly []>;\n\ninterface RegistrationLease {\n refs: number;\n}\n\nconst SCRATCH = new WeakMap<World, Scratch>();\nconst REGISTRATION_LEASES = new WeakMap<World, RegistrationLease>();\n\nfunction pairError(entity: EntityHandle, expected: string): Result<void, SceneError> {\n return err(\n new SceneError({\n code: 'hierarchy-broken',\n expected,\n hint: 'attach both Transform and GlobalTransform at scene authoring or import time, then retry propagation',\n detail: { entity, parent: entity },\n }),\n );\n}\n\nfunction ensureQueries(world: World, scratch: Scratch): Result<void, SceneError> {\n if (\n scratch.flatQuery !== undefined &&\n scratch.hierarchyQuery !== undefined &&\n scratch.transformQuery !== undefined &&\n scratch.hierarchyWriter !== undefined &&\n scratch.transformWriter !== undefined &&\n scratch.missingGlobalQuery !== undefined &&\n scratch.missingTransformQuery !== undefined\n ) {\n return ok(undefined);\n }\n const flatOutput = world.query({\n read: [Transform],\n write: [GlobalTransform],\n without: [ChildOf],\n changed: [Transform],\n });\n const hierarchy = world.query({ read: [Transform, ChildOf], write: [GlobalTransform] });\n const transform = world.query({ read: [Transform], write: [GlobalTransform] });\n const missingGlobal = world.query({ with: [Transform], without: [GlobalTransform] });\n const missingTransform = world.query({ with: [GlobalTransform], without: [Transform] });\n if (\n !flatOutput.ok ||\n !hierarchy.ok ||\n !transform.ok ||\n !missingGlobal.ok ||\n !missingTransform.ok\n ) {\n return pairError(0 as EntityHandle, 'valid Transform and GlobalTransform pair queries');\n }\n const hierarchyWriter = getDerivedWriter(hierarchy.value, GlobalTransform);\n const transformWriter = getDerivedWriter(transform.value, GlobalTransform);\n if (!hierarchyWriter.ok || !transformWriter.ok) {\n return pairError(0 as EntityHandle, 'dense Transform and ChildOf derived bindings');\n }\n scratch.flatQuery = flatOutput.value as FlatQuery;\n scratch.hierarchyQuery = hierarchy.value as HierarchyQuery;\n scratch.transformQuery = transform.value as TransformQuery;\n scratch.hierarchyWriter = hierarchyWriter.value as HierarchyWriter;\n scratch.transformWriter = transformWriter.value as TransformWriter;\n scratch.missingGlobalQuery = missingGlobal.value as MissingGlobalQuery;\n scratch.missingTransformQuery = missingTransform.value as MissingTransformQuery;\n return ok(undefined);\n}\n\nfunction validateTransformPairs(world: World, scratch: Scratch): Result<void, SceneError> {\n const queryResult = ensureQueries(world, scratch);\n if (!queryResult.ok) return queryResult;\n const missingGlobal = scratch.missingGlobalQuery;\n const missingTransform = scratch.missingTransformQuery;\n if (missingGlobal === undefined || missingTransform === undefined) {\n return pairError(0 as EntityHandle, 'valid Transform and GlobalTransform pair queries');\n }\n for (const row of missingGlobal) {\n return pairError(row.entity, 'each Transform entity to carry a GlobalTransform pair');\n }\n for (const row of missingTransform) {\n return pairError(row.entity, 'each GlobalTransform entity to carry a Transform pair');\n }\n return ok(undefined);\n}\n\nfunction scratchFor(world: World): Scratch {\n const existing = SCRATCH.get(world);\n if (existing !== undefined) return existing;\n const created = {\n position: new Float32Array(3),\n rotation: new Float32Array(4),\n scale: new Float32Array(3),\n local: mat4.create(),\n parent: mat4.create(),\n candidate: mat4.create(),\n hierarchyStackEntities: [] as EntityHandle[],\n hierarchyStackChildren: [] as number[],\n hierarchyProbeEntities: [] as EntityHandle[],\n hierarchyCurrentCursor: { bindingIndex: -1, row: -1 },\n hierarchyParentCursor: { bindingIndex: -1, row: -1 },\n hierarchyChildCursor: { bindingIndex: -1, row: -1 },\n hierarchyResidualCursor: { bindingIndex: -1, row: -1 },\n hierarchyResidualParentCursor: { bindingIndex: -1, row: -1 },\n hierarchyRootCursor: createHierarchyRootCursor(),\n hierarchyStates: [],\n hierarchyChanged: [],\n hierarchyBindingTables: [],\n hierarchyBindingRows: [],\n flatChanged: [],\n flatBindingTables: [],\n flatBindingRows: [],\n flatStructureEpoch: -1,\n };\n SCRATCH.set(world, created);\n return created;\n}\n\nfunction composeColumns(\n position: ArrayLike<number>,\n rotation: ArrayLike<number>,\n scale: ArrayLike<number>,\n out: Mat4,\n scratch: Scratch,\n positionStart = 0,\n rotationStart = 0,\n): void {\n scratch.position[0] = position[positionStart] ?? 0;\n scratch.position[1] = position[positionStart + 1] ?? 0;\n scratch.position[2] = position[positionStart + 2] ?? 0;\n scratch.rotation[0] = rotation[rotationStart] ?? 0;\n scratch.rotation[1] = rotation[rotationStart + 1] ?? 0;\n scratch.rotation[2] = rotation[rotationStart + 2] ?? 0;\n scratch.rotation[3] = rotation[rotationStart + 3] ?? 1;\n scratch.scale[0] = scale[positionStart] ?? 1;\n scratch.scale[1] = scale[positionStart + 1] ?? 1;\n scratch.scale[2] = scale[positionStart + 2] ?? 1;\n mat4.compose(out, scratch.position, scratch.rotation, scratch.scale);\n}\n\nfunction composeFlatColumns(\n positions: ArrayLike<number>,\n rotations: ArrayLike<number>,\n scales: ArrayLike<number>,\n worlds: Float32Array,\n count: number,\n): void {\n for (let row = 0; row < count; row += 1) {\n const position = row * 3;\n const rotation = row * 4;\n const world = row * 16;\n const x = rotations[rotation] ?? 0;\n const y = rotations[rotation + 1] ?? 0;\n const z = rotations[rotation + 2] ?? 0;\n const w = rotations[rotation + 3] ?? 1;\n const x2 = x + x;\n const y2 = y + y;\n const z2 = z + z;\n const xx = x * x2;\n const xy = x * y2;\n const xz = x * z2;\n const yy = y * y2;\n const yz = y * z2;\n const zz = z * z2;\n const wx = w * x2;\n const wy = w * y2;\n const wz = w * z2;\n const sx = scales[position] ?? 1;\n const sy = scales[position + 1] ?? 1;\n const sz = scales[position + 2] ?? 1;\n\n worlds[world] = (1 - (yy + zz)) * sx;\n worlds[world + 1] = (xy + wz) * sx;\n worlds[world + 2] = (xz - wy) * sx;\n worlds[world + 3] = 0;\n worlds[world + 4] = (xy - wz) * sy;\n worlds[world + 5] = (1 - (xx + zz)) * sy;\n worlds[world + 6] = (yz + wx) * sy;\n worlds[world + 7] = 0;\n worlds[world + 8] = (xz + wy) * sz;\n worlds[world + 9] = (yz - wx) * sz;\n worlds[world + 10] = (1 - (xx + yy)) * sz;\n worlds[world + 11] = 0;\n worlds[world + 12] = positions[position] ?? 0;\n worlds[world + 13] = positions[position + 1] ?? 0;\n worlds[world + 14] = positions[position + 2] ?? 0;\n worlds[world + 15] = 1;\n }\n}\n\nfunction propagateFlat(world: World, scratch: Scratch): Result<void, SceneError> {\n const query = scratch.flatQuery;\n if (query === undefined)\n return err(\n new SceneError({\n code: 'hierarchy-broken',\n expected: 'a valid changed Transform write query',\n hint: 'register the scene components before running TransformPropagation',\n }),\n );\n const spans = query.spans();\n if (!spans.ok) return pairError(0 as EntityHandle, 'dense numeric Transform spans');\n let bindingIndex = 0;\n try {\n for (const span of spans.value) {\n const local = span.get(Transform);\n const world = span.mut(GlobalTransform).world;\n composeFlatColumns(local.pos, local.quat, local.scale, world, span.length);\n bindingIndex += 1;\n }\n } catch (cause) {\n const error = cause as EcsError;\n return err(derivedWriteError(error, bindingIndex));\n }\n\n // A structural relation change can turn an unchanged Transform row into a\n // flat root (most importantly ChildOf removal). The changed Transform query\n // above cannot observe that transition, so once per structure epoch scan the\n // already-bound numeric Transform rows and publish only differing roots.\n const transformWriter = scratch.transformWriter;\n if (transformWriter === undefined) {\n return pairError(0 as EntityHandle, 'dense Transform and GlobalTransform derived bindings');\n }\n const transformBindings = transformWriter.bindings as readonly TransformBinding[];\n const structureEpoch = world.getStructureEpoch();\n if (scratch.flatStructureEpoch === structureEpoch) return ok(undefined);\n\n ensureFlatBuffers(scratch, transformBindings);\n resetFlatBuffers(scratch);\n for (let bindingIndex = 0; bindingIndex < transformBindings.length; bindingIndex += 1) {\n const binding = transformBindings[bindingIndex];\n const changed = scratch.flatChanged[bindingIndex];\n if (binding === undefined || changed === undefined) continue;\n for (let row = 0; row < binding.rowCapacity; row += 1) {\n const entity = (binding.entities[row] ?? 0) as EntityHandle;\n const parentRaw = world[worldRead].getFieldValue(entity, ChildOf, 'parent');\n if (parentRaw !== undefined && parentRaw !== ENTITY_NULL_RAW) continue;\n countPropagation('flatStructuralRootRows');\n composeBindingRow(binding, row, undefined, 0, scratch, changed);\n }\n }\n for (let bindingIndex = 0; bindingIndex < transformBindings.length; bindingIndex += 1) {\n const changed = scratch.flatChanged[bindingIndex];\n if (changed === undefined) continue;\n const published = transformWriter.publishChangedRows(bindingIndex, changed);\n if (!published.ok) return err(derivedWriteError(published.error, bindingIndex));\n }\n scratch.flatStructureEpoch = structureEpoch;\n return ok(undefined);\n}\n\ninterface TransformColumnShape {\n readonly pos: ArrayLike<number>;\n readonly quat: ArrayLike<number>;\n readonly scale: ArrayLike<number>;\n}\n\ninterface OutputColumnShape {\n readonly world: Float32Array;\n}\n\ninterface HierarchyColumnShape extends TransformColumnShape {\n readonly parent: ArrayLike<number>;\n}\n\nfunction transformColumns(binding: TransformBinding | HierarchyBinding): TransformColumnShape {\n return binding.read as unknown as TransformColumnShape;\n}\n\nfunction hierarchyColumns(binding: HierarchyBinding): HierarchyColumnShape {\n return binding.read as unknown as HierarchyColumnShape;\n}\n\nfunction worldColumn(binding: TransformBinding | HierarchyBinding): Float32Array {\n return (binding.write as unknown as OutputColumnShape).world;\n}\n\nfunction hierarchyError(\n code: 'hierarchy-broken' | 'hierarchy-cycle',\n entity: EntityHandle,\n parent: EntityHandle,\n expected: string,\n hint: string,\n): SceneError {\n return new SceneError({ code, expected, hint, detail: { entity, parent } });\n}\n\nfunction writeCandidate(\n binding: TransformBinding | HierarchyBinding,\n row: number,\n candidate: Mat4,\n changed: Uint8Array,\n): void {\n const worlds = worldColumn(binding);\n const base = row * 16;\n for (let index = 0; index < 16; index += 1) {\n if (worlds[base + index] !== candidate[index]) {\n worlds.set(candidate, base);\n changed[row] = 1;\n return;\n }\n }\n}\n\nfunction composeBindingRow(\n binding: TransformBinding | HierarchyBinding,\n row: number,\n parentBinding: TransformBinding | undefined,\n parentRow: number,\n scratch: Scratch,\n changed: Uint8Array,\n): void {\n // Hierarchy bindings carry the parent column; flat structural-root repair\n // uses the same numeric kernel but is intentionally counted separately.\n if ('parent' in (binding.read as object)) countPropagation('hierarchyRowsEvaluated');\n const local = transformColumns(binding);\n const offset = row * 3;\n composeColumns(local.pos, local.quat, local.scale, scratch.local, scratch, offset, row * 4);\n if (parentBinding === undefined) {\n scratch.candidate.set(scratch.local);\n } else {\n const parentWorld = worldColumn(parentBinding);\n const parentOffset = parentRow * 16;\n for (let index = 0; index < 16; index += 1) {\n scratch.parent[index] = parentWorld[parentOffset + index] ?? 0;\n }\n // Column-major composition is intentionally identical to the previous\n // matrix path: Global = Parent * Local, with no TRS decomposition.\n mat4.multiply(scratch.candidate, scratch.parent, scratch.local);\n }\n writeCandidate(binding, row, scratch.candidate, changed);\n}\n\nfunction ensureHierarchyBuffers(scratch: Scratch, bindings: readonly HierarchyBinding[]): void {\n let same = scratch.hierarchyBindingTables.length === bindings.length;\n if (same) {\n for (let index = 0; index < bindings.length; index += 1) {\n const binding = bindings[index];\n if (\n binding === undefined ||\n scratch.hierarchyBindingTables[index] !== binding.tableId ||\n scratch.hierarchyBindingRows[index] !== binding.rowCapacity\n ) {\n same = false;\n break;\n }\n }\n }\n if (same) return;\n scratch.hierarchyBindingTables = bindings.map((binding) => binding.tableId);\n scratch.hierarchyBindingRows = bindings.map((binding) => binding.rowCapacity);\n scratch.hierarchyStates = bindings.map((binding) => new Uint8Array(binding.rowCapacity));\n scratch.hierarchyChanged = bindings.map((binding) => new Uint8Array(binding.rowCapacity));\n}\n\nfunction resetHierarchyBuffers(scratch: Scratch): void {\n for (let index = 0; index < scratch.hierarchyStates.length; index += 1) {\n scratch.hierarchyStates[index]?.fill(0);\n scratch.hierarchyChanged[index]?.fill(0);\n }\n}\n\nfunction ensureFlatBuffers(scratch: Scratch, bindings: readonly TransformBinding[]): void {\n let same = scratch.flatBindingTables.length === bindings.length;\n if (same) {\n for (let index = 0; index < bindings.length; index += 1) {\n const binding = bindings[index];\n if (\n binding === undefined ||\n scratch.flatBindingTables[index] !== binding.tableId ||\n scratch.flatBindingRows[index] !== binding.rowCapacity\n ) {\n same = false;\n break;\n }\n }\n }\n if (same) return;\n scratch.flatBindingTables = bindings.map((binding) => binding.tableId);\n scratch.flatBindingRows = bindings.map((binding) => binding.rowCapacity);\n scratch.flatChanged = bindings.map((binding) => new Uint8Array(binding.rowCapacity));\n}\n\nfunction resetFlatBuffers(scratch: Scratch): void {\n for (const changed of scratch.flatChanged) changed.fill(0);\n}\n\nfunction derivedWriteError(cause: EcsError, bindingIndex: number): SceneError {\n return new SceneError({\n code: 'hierarchy-broken',\n expected: 'derived GlobalTransform range publication to succeed',\n hint: cause.hint ?? 'retry propagation on a healthy World',\n detail: {\n kind: 'derived-write',\n entity: 0 as EntityHandle,\n parent: 0 as EntityHandle,\n bindingIndex,\n base: 0,\n start: 0,\n count: 0,\n cause,\n },\n });\n}\n\nfunction findHierarchyLocation(\n writer: HierarchyWriter,\n bindings: readonly HierarchyBinding[],\n entity: EntityHandle,\n cursor: DerivedRangeCursor,\n): HierarchyBinding | undefined {\n countPropagation('hierarchyEntityLookups');\n if (!writer.locateEntity(entity, cursor)) return undefined;\n return bindings[cursor.bindingIndex];\n}\n\nfunction findTransformLocation(\n writer: TransformWriter,\n bindings: readonly TransformBinding[],\n entity: EntityHandle,\n cursor: DerivedRangeCursor,\n): TransformBinding | undefined {\n countPropagation('hierarchyEntityLookups');\n if (!writer.locateEntity(entity, cursor)) return undefined;\n return bindings[cursor.bindingIndex];\n}\n\nfunction countPublishedRows(changed: Uint8Array): void {\n const trace = propagationTrace;\n if (trace === undefined) return;\n let runOpen = false;\n for (let row = 0; row < changed.length; row += 1) {\n if ((changed[row] ?? 0) !== 0) {\n trace.hierarchyPublishedRows += 1;\n if (!runOpen) {\n trace.hierarchyPublishedRuns += 1;\n runOpen = true;\n }\n } else {\n runOpen = false;\n }\n }\n}\n\nfunction noteHierarchyError(current: SceneError | undefined, next: SceneError): SceneError {\n if (current === undefined) return next;\n const currentEntity = Number(current.detail?.entity ?? Number.MAX_SAFE_INTEGER);\n const nextEntity = Number(next.detail?.entity ?? Number.MAX_SAFE_INTEGER);\n return nextEntity < currentEntity ||\n (nextEntity === currentEntity && next.code.localeCompare(current.code) < 0)\n ? next\n : current;\n}\n\nfunction composeLocalHierarchyEntity(\n writer: HierarchyWriter,\n bindings: readonly HierarchyBinding[],\n entity: EntityHandle,\n scratch: Scratch,\n changed: Uint8Array[],\n): boolean {\n const cursor = scratch.hierarchyCurrentCursor;\n const binding = findHierarchyLocation(writer, bindings, entity, cursor);\n if (binding === undefined) return false;\n composeBindingRow(\n binding,\n cursor.row,\n undefined,\n 0,\n scratch,\n changed[cursor.bindingIndex] as Uint8Array,\n );\n const states = scratch.hierarchyStates[cursor.bindingIndex];\n if (states !== undefined) states[cursor.row] = 3;\n return true;\n}\n\nfunction handleActiveCycle(\n repeated: EntityHandle,\n stackEntities: EntityHandle[],\n stackChildren: number[],\n writer: HierarchyWriter,\n bindings: readonly HierarchyBinding[],\n scratch: Scratch,\n changed: Uint8Array[],\n report: (error: SceneError) => void,\n): void {\n let cycleStart = -1;\n for (let index = 0; index < stackEntities.length; index += 1) {\n if (stackEntities[index] === repeated) {\n cycleStart = index;\n break;\n }\n }\n if (cycleStart < 0) return;\n const repeatedCursor: DerivedRangeCursor = { bindingIndex: -1, row: -1 };\n const repeatedBinding = findHierarchyLocation(writer, bindings, repeated, repeatedCursor);\n const repeatedParent =\n repeatedBinding === undefined\n ? repeated\n : ((hierarchyColumns(repeatedBinding).parent[repeatedCursor.row] ??\n ENTITY_NULL_RAW) as number as EntityHandle);\n report(\n hierarchyError(\n 'hierarchy-cycle',\n repeated,\n repeatedParent,\n 'a parent-before-child Transform hierarchy',\n 'repair the ChildOf cycle and retry TransformPropagation',\n ),\n );\n for (let index = cycleStart; index < stackEntities.length; index += 1) {\n const cycleEntity = stackEntities[index];\n if (cycleEntity === undefined) continue;\n composeLocalHierarchyEntity(writer, bindings, cycleEntity, scratch, changed);\n stackChildren[index] = 0;\n }\n}\n\nfunction walkChildren(\n world: World,\n root: EntityHandle,\n writer: HierarchyWriter,\n bindings: readonly HierarchyBinding[],\n transformWriter: TransformWriter,\n transformBindings: readonly TransformBinding[],\n scratch: Scratch,\n report: (error: SceneError) => void,\n allowCompletedRoot: boolean,\n): void {\n countPropagation('hierarchyRootInvocations');\n const stackEntities = scratch.hierarchyStackEntities;\n const stackChildren = scratch.hierarchyStackChildren;\n stackEntities.length = 0;\n stackChildren.length = 0;\n\n if (allowCompletedRoot) {\n // Residual recovery may be entered once for each member of a malformed\n // parent path. State 4 means a previous fallback walk already expanded\n // this root and all reachable Children edges, so do not repeat that\n // subtree for every cycle member.\n const rootCursor = scratch.hierarchyRootCursor;\n const rootBinding = findHierarchyLocation(writer, bindings, root, rootCursor);\n if (rootBinding !== undefined) {\n const state = scratch.hierarchyStates[rootCursor.bindingIndex]?.[rootCursor.row] ?? 0;\n if (state === 4) return;\n }\n } else {\n // This cursor is scratch-owned and reused for every root. A root walk is\n // a hot invocation; allocating a cursor here would scale object churn with\n // the number of roots even after all bindings have warmed.\n const rootCursor = scratch.hierarchyRootCursor;\n countPropagation('hierarchyRootCursorReuses');\n const rootBinding = findHierarchyLocation(writer, bindings, root, rootCursor);\n if (rootBinding !== undefined) {\n const state = scratch.hierarchyStates[rootCursor.bindingIndex]?.[rootCursor.row] ?? 0;\n if (state !== 0) return;\n }\n }\n stackEntities.push(root);\n stackChildren.push(-1);\n\n const currentCursor = scratch.hierarchyCurrentCursor;\n const parentCursor = scratch.hierarchyParentCursor;\n const childCursor = scratch.hierarchyChildCursor;\n while (stackEntities.length > 0) {\n const top = stackEntities.length - 1;\n const current = stackEntities[top];\n if (current === undefined) {\n stackEntities.pop();\n stackChildren.pop();\n continue;\n }\n const hierarchyBinding = findHierarchyLocation(writer, bindings, current, currentCursor);\n const nextChild = stackChildren[top] ?? -1;\n if (nextChild < 0) {\n if (hierarchyBinding !== undefined) {\n const state = scratch.hierarchyStates[currentCursor.bindingIndex]?.[currentCursor.row] ?? 0;\n if (state === 0) {\n const states = scratch.hierarchyStates[currentCursor.bindingIndex];\n if (states !== undefined) states[currentCursor.row] = 1;\n const parentRaw = (hierarchyColumns(hierarchyBinding).parent[currentCursor.row] ??\n ENTITY_NULL_RAW) as number;\n let completed = false;\n if (parentRaw === ENTITY_NULL_RAW) {\n composeBindingRow(\n hierarchyBinding,\n currentCursor.row,\n undefined,\n 0,\n scratch,\n scratch.hierarchyChanged[currentCursor.bindingIndex] as Uint8Array,\n );\n completed = true;\n } else {\n const parent = parentRaw as EntityHandle;\n const parentBinding = findTransformLocation(\n transformWriter,\n transformBindings,\n parent,\n parentCursor,\n );\n const parentHierarchy = findHierarchyLocation(writer, bindings, parent, childCursor);\n if (parentBinding === undefined) {\n report(\n hierarchyError(\n 'hierarchy-broken',\n current,\n parent,\n 'each ChildOf parent to carry Transform and GlobalTransform',\n 'repair the missing parent pair before retrying propagation',\n ),\n );\n composeBindingRow(\n hierarchyBinding,\n currentCursor.row,\n undefined,\n 0,\n scratch,\n scratch.hierarchyChanged[currentCursor.bindingIndex] as Uint8Array,\n );\n completed = true;\n } else if (parentHierarchy !== undefined) {\n const parentState =\n scratch.hierarchyStates[childCursor.bindingIndex]?.[childCursor.row] ?? 0;\n if (parentState === 1) {\n handleActiveCycle(\n parent,\n stackEntities,\n stackChildren,\n writer,\n bindings,\n scratch,\n scratch.hierarchyChanged,\n report,\n );\n completed = true;\n } else if (parentState === 0) {\n report(\n hierarchyError(\n 'hierarchy-broken',\n current,\n parent,\n 'Children to enumerate every parent-before-child edge',\n 'repair the Children mirror and retry TransformPropagation',\n ),\n );\n composeBindingRow(\n hierarchyBinding,\n currentCursor.row,\n undefined,\n 0,\n scratch,\n scratch.hierarchyChanged[currentCursor.bindingIndex] as Uint8Array,\n );\n completed = true;\n } else {\n composeBindingRow(\n hierarchyBinding,\n currentCursor.row,\n parentBinding,\n parentCursor.row,\n scratch,\n scratch.hierarchyChanged[currentCursor.bindingIndex] as Uint8Array,\n );\n completed = true;\n }\n } else {\n composeBindingRow(\n hierarchyBinding,\n currentCursor.row,\n parentBinding,\n parentCursor.row,\n scratch,\n scratch.hierarchyChanged[currentCursor.bindingIndex] as Uint8Array,\n );\n completed = true;\n }\n }\n if (completed && states !== undefined && states[currentCursor.row] === 1) {\n states[currentCursor.row] = 2;\n }\n }\n }\n stackChildren[top] = 0;\n continue;\n }\n\n const childrenLength = world[worldRead].getArrayLength(current, Children, 'entities') ?? 0;\n if (nextChild >= childrenLength) {\n stackEntities.pop();\n stackChildren.pop();\n if (allowCompletedRoot) {\n const completedCursor = scratch.hierarchyResidualCursor;\n const completedBinding = findHierarchyLocation(writer, bindings, current, completedCursor);\n const completedStates =\n completedBinding === undefined\n ? undefined\n : scratch.hierarchyStates[completedCursor.bindingIndex];\n if (completedStates !== undefined && completedStates[completedCursor.row] === 3) {\n completedStates[completedCursor.row] = 4;\n }\n }\n continue;\n }\n stackChildren[top] = nextChild + 1;\n countPropagation('hierarchyEdgesVisited');\n const childRaw = world[worldRead].getArrayElement(current, Children, 'entities', nextChild);\n if (childRaw === undefined || childRaw === ENTITY_NULL_RAW) {\n report(\n hierarchyError(\n 'hierarchy-broken',\n current,\n current,\n 'Children.entities to contain live child handles',\n 'repair the Children mirror and retry TransformPropagation',\n ),\n );\n continue;\n }\n const child = childRaw as EntityHandle;\n const childBinding = findHierarchyLocation(writer, bindings, child, childCursor);\n if (childBinding === undefined) {\n report(\n hierarchyError(\n 'hierarchy-broken',\n child,\n current,\n 'each Children entry to carry Transform, GlobalTransform, and ChildOf',\n 'repair the child component pair before retrying propagation',\n ),\n );\n continue;\n }\n const childParent = (hierarchyColumns(childBinding).parent[childCursor.row] ??\n ENTITY_NULL_RAW) as number;\n const childState = scratch.hierarchyStates[childCursor.bindingIndex]?.[childCursor.row] ?? 0;\n if (childParent !== (current as number)) {\n // Leave an unvisited child for the residual row-state pass. That pass\n // can classify the complete path (including a rootless cycle) without\n // emitting a premature mirror error that would hide the cycle cause.\n if (childState === 0) continue;\n report(\n hierarchyError(\n 'hierarchy-broken',\n child,\n current,\n 'Children and ChildOf to describe the same parent',\n 'repair the relationship mirror and retry TransformPropagation',\n ),\n );\n continue;\n }\n if (childState === 1) {\n handleActiveCycle(\n child,\n stackEntities,\n stackChildren,\n writer,\n bindings,\n scratch,\n scratch.hierarchyChanged,\n report,\n );\n } else if (childState === 0) {\n stackEntities.push(child);\n stackChildren.push(-1);\n }\n }\n}\n\nfunction fallbackResidualPath(\n world: World,\n path: readonly EntityHandle[],\n writer: HierarchyWriter,\n bindings: readonly HierarchyBinding[],\n transformWriter: TransformWriter,\n transformBindings: readonly TransformBinding[],\n scratch: Scratch,\n report: (error: SceneError) => void,\n): void {\n // Root traversal owns the normal path. A residual path is necessarily a\n // malformed Children projection (or a rootless cycle); cut the complete\n // path to local roots in one pass so no stale GlobalTransform survives the\n // diagnostic. Keeping the path as an explicit work list also makes this\n // recovery O(path length), rather than repeatedly searching parent chains.\n for (const entity of path) {\n composeLocalHierarchyEntity(writer, bindings, entity, scratch, scratch.hierarchyChanged);\n }\n for (const entity of path) {\n walkChildren(\n world,\n entity,\n writer,\n bindings,\n transformWriter,\n transformBindings,\n scratch,\n report,\n true,\n );\n }\n}\n\nfunction resolveResidualPath(\n world: World,\n entity: EntityHandle,\n writer: HierarchyWriter,\n bindings: readonly HierarchyBinding[],\n transformWriter: TransformWriter,\n transformBindings: readonly TransformBinding[],\n scratch: Scratch,\n report: (error: SceneError) => void,\n): void {\n const path = scratch.hierarchyProbeEntities;\n path.length = 0;\n const cursor = scratch.hierarchyResidualCursor;\n const parentTransformCursor = scratch.hierarchyParentCursor;\n const parentHierarchyCursor = scratch.hierarchyResidualParentCursor;\n let current = entity;\n while (true) {\n countPropagation('hierarchyResidualParentProbes');\n const binding = findHierarchyLocation(writer, bindings, current, cursor);\n if (binding === undefined) break;\n const states = scratch.hierarchyStates[cursor.bindingIndex];\n const state = states?.[cursor.row] ?? 0;\n if (state !== 0) {\n const columns = hierarchyColumns(binding);\n const parentRaw = (columns.parent[cursor.row] ?? ENTITY_NULL_RAW) as number;\n report(\n hierarchyError(\n 'hierarchy-cycle',\n current,\n parentRaw === ENTITY_NULL_RAW ? current : (parentRaw as EntityHandle),\n 'a parent-before-child Transform hierarchy',\n 'repair the ChildOf cycle and retry TransformPropagation',\n ),\n );\n fallbackResidualPath(\n world,\n path,\n writer,\n bindings,\n transformWriter,\n transformBindings,\n scratch,\n report,\n );\n return;\n }\n\n if (states !== undefined) states[cursor.row] = 1;\n path.push(current);\n const parentRaw = (hierarchyColumns(binding).parent[cursor.row] ?? ENTITY_NULL_RAW) as number;\n if (parentRaw === ENTITY_NULL_RAW) {\n // Every null-parent row is enumerated as a root above. Reaching one\n // here means the materialized Children graph failed to expose the\n // parent-first edge; preserve the explicit malformed-graph error.\n report(\n hierarchyError(\n 'hierarchy-broken',\n current,\n current,\n 'Children to enumerate every parent-before-child edge',\n 'repair the Children mirror and retry TransformPropagation',\n ),\n );\n fallbackResidualPath(\n world,\n path,\n writer,\n bindings,\n transformWriter,\n transformBindings,\n scratch,\n report,\n );\n return;\n }\n\n const parent = parentRaw as EntityHandle;\n const parentTransform = findTransformLocation(\n transformWriter,\n transformBindings,\n parent,\n parentTransformCursor,\n );\n const parentHierarchy = findHierarchyLocation(writer, bindings, parent, parentHierarchyCursor);\n if (parentHierarchy === undefined) {\n report(\n hierarchyError(\n 'hierarchy-broken',\n current,\n parent,\n parentTransform === undefined\n ? 'each ChildOf parent to carry Transform and GlobalTransform'\n : 'Children to enumerate every parent-before-child edge',\n parentTransform === undefined\n ? 'repair the missing parent pair before retrying propagation'\n : 'repair the Children mirror and retry TransformPropagation',\n ),\n );\n fallbackResidualPath(\n world,\n path,\n writer,\n bindings,\n transformWriter,\n transformBindings,\n scratch,\n report,\n );\n return;\n }\n\n const parentState =\n scratch.hierarchyStates[parentHierarchyCursor.bindingIndex]?.[parentHierarchyCursor.row] ?? 0;\n if (parentState === 0) {\n current = parent;\n continue;\n }\n if (parentState === 1) {\n report(\n hierarchyError(\n 'hierarchy-cycle',\n parent,\n current,\n 'a parent-before-child Transform hierarchy',\n 'repair the ChildOf cycle and retry TransformPropagation',\n ),\n );\n } else {\n report(\n hierarchyError(\n 'hierarchy-broken',\n current,\n parent,\n 'Children to enumerate every parent-before-child edge',\n 'repair the Children mirror and retry TransformPropagation',\n ),\n );\n }\n fallbackResidualPath(\n world,\n path,\n writer,\n bindings,\n transformWriter,\n transformBindings,\n scratch,\n report,\n );\n return;\n }\n}\n\nfunction propagateHierarchy(world: World, scratch: Scratch): Result<void, SceneError> {\n const hierarchyWriter = scratch.hierarchyWriter;\n const transformWriter = scratch.transformWriter;\n if (hierarchyWriter === undefined || transformWriter === undefined) {\n return err(\n new SceneError({\n code: 'hierarchy-broken',\n expected: 'paired Transform and GlobalTransform derived bindings',\n hint: 'register the scene components before running TransformPropagation',\n }),\n );\n }\n const hierarchyBindings = hierarchyWriter.bindings as readonly HierarchyBinding[];\n const transformBindings = transformWriter.bindings as readonly TransformBinding[];\n if (hierarchyBindings.length === 0) {\n // Keep the flat-only lane independent: it must not allocate hierarchy\n // markers or scan every Transform row merely to prove that no ChildOf\n // archetype exists.\n scratch.hierarchyBindingTables.length = 0;\n scratch.hierarchyBindingRows.length = 0;\n scratch.hierarchyStates.length = 0;\n scratch.hierarchyChanged.length = 0;\n return ok(undefined);\n }\n ensureHierarchyBuffers(scratch, hierarchyBindings);\n resetHierarchyBuffers(scratch);\n let firstError: SceneError | undefined;\n const report = (error: SceneError): void => {\n firstError = noteHierarchyError(firstError, error);\n };\n\n // Start only at actual roots (flat Transform rows and null-parent\n // ChildOf rows). Descendants are discovered exclusively through the ECS\n // materialized Children lists, so every normal frame is parent-first and\n // linear in rows plus relationship edges.\n for (const binding of transformBindings) {\n const entities = binding.entities;\n for (let row = 0; row < binding.rowCapacity; row += 1) {\n const entity = (entities[row] ?? 0) as EntityHandle;\n const parentRaw = world[worldRead].getFieldValue(entity, ChildOf, 'parent');\n if (parentRaw === undefined || parentRaw === ENTITY_NULL_RAW) {\n walkChildren(\n world,\n entity,\n hierarchyWriter,\n hierarchyBindings,\n transformWriter,\n transformBindings,\n scratch,\n report,\n false,\n );\n }\n }\n }\n\n // Any remaining hierarchy row is either behind a malformed/missing mirror\n // edge or belongs to a rootless cycle. Follow each residual parent chain\n // once with the same row-state machine (not a per-node parent search), then\n // cut that complete residual path to local space. This keeps malformed\n // coverage linear in residual rows and edges while normal frames remain\n // exclusively Children-driven.\n for (let bindingIndex = 0; bindingIndex < hierarchyBindings.length; bindingIndex += 1) {\n const binding = hierarchyBindings[bindingIndex];\n if (binding === undefined) continue;\n const entities = binding.entities;\n const states = scratch.hierarchyStates[bindingIndex];\n for (let row = 0; row < binding.rowCapacity; row += 1) {\n if ((states?.[row] ?? 0) !== 0) continue;\n const entity = (entities[row] ?? 0) as EntityHandle;\n resolveResidualPath(\n world,\n entity,\n hierarchyWriter,\n hierarchyBindings,\n transformWriter,\n transformBindings,\n scratch,\n report,\n );\n }\n }\n\n for (let bindingIndex = 0; bindingIndex < hierarchyBindings.length; bindingIndex += 1) {\n const changed = scratch.hierarchyChanged[bindingIndex];\n if (changed === undefined) continue;\n countPublishedRows(changed);\n const published = hierarchyWriter.publishChangedRows(bindingIndex, changed);\n if (!published.ok) {\n const cause = published.error as EcsError;\n report(derivedWriteError(cause, bindingIndex));\n }\n }\n return firstError === undefined ? ok(undefined) : err(firstError);\n}\n\nexport function propagateTransforms(world: World): Result<void, SceneError> {\n const scratch = scratchFor(world);\n const pairs = validateTransformPairs(world, scratch);\n if (!pairs.ok) return pairs;\n const flat = propagateFlat(world, scratch);\n if (!flat.ok) return flat;\n return propagateHierarchy(world, scratch);\n}\n\nexport const PropagateTransforms: SystemHandle<readonly []> = defineSystem({\n name: PROPAGATE_TRANSFORMS_SYSTEM,\n queries: [],\n fn: (world) => {\n const result = propagateTransforms(world);\n if (!result.ok) throw result.error;\n },\n});\n\nexport const PropagateTransformsFixed: SystemHandle<readonly []> = defineSystem({\n name: PROPAGATE_TRANSFORMS_FIXED_SYSTEM,\n queries: [],\n fn: PropagateTransforms.fn,\n});\n\nexport function registerPropagateTransforms(\n world: World,\n options: { beforeSystemName?: string } = {},\n): () => void {\n const existing = REGISTRATION_LEASES.get(world);\n if (existing !== undefined) {\n existing.refs += 1;\n let active = true;\n return () => {\n if (!active) return;\n active = false;\n existing.refs -= 1;\n if (existing.refs === 0) {\n world.removeSystem(FixedUpdate, PROPAGATE_TRANSFORMS_FIXED_SYSTEM);\n world.removeSystem(Update, PROPAGATE_TRANSFORMS_SYSTEM);\n REGISTRATION_LEASES.delete(world);\n SCRATCH.delete(world);\n }\n };\n }\n if (options.beforeSystemName === undefined) {\n world.addSystems(Update, TransformSet, [PropagateTransforms]).unwrap();\n } else {\n world\n .addSystems(Update, TransformSet, [\n {\n name: PROPAGATE_TRANSFORMS_SYSTEM,\n queries: [],\n fn: PropagateTransforms.fn,\n before: [options.beforeSystemName],\n },\n ])\n .unwrap();\n }\n world.addSystems(FixedUpdate, TransformFixedSet, [PropagateTransformsFixed]).unwrap();\n REGISTRATION_LEASES.set(world, { refs: 1 });\n let active = true;\n return () => {\n if (!active) return;\n active = false;\n const lease = REGISTRATION_LEASES.get(world);\n if (lease === undefined) return;\n lease.refs -= 1;\n if (lease.refs !== 0) return;\n world.removeSystem(FixedUpdate, PROPAGATE_TRANSFORMS_FIXED_SYSTEM);\n world.removeSystem(Update, PROPAGATE_TRANSFORMS_SYSTEM);\n REGISTRATION_LEASES.delete(world);\n SCRATCH.delete(world);\n };\n}\n","import type { Component, World } from '@forgeax/engine-ecs';\nimport type { Plugin } from '@forgeax/engine-plugin';\nimport { ChildOf } from './components/child-of';\nimport { Children } from './components/children';\nimport { MorphWeights } from './components/morph-weights';\nimport { Name } from './components/name';\nimport { GlobalTransform, Transform } from './components/transform';\nimport { registerPropagateTransforms } from './systems/propagate-transforms';\n\nconst SCENE_COMPONENTS: readonly Component[] = [\n ChildOf,\n Children,\n MorphWeights,\n Name,\n Transform,\n GlobalTransform,\n];\n\nfunction registerSceneComponents(world: World): () => void {\n const leases = SCENE_COMPONENTS.map((component) => world.components.register(component).unwrap());\n return () => {\n for (let index = leases.length - 1; index >= 0; index -= 1) leases[index]?.dispose();\n };\n}\n\nexport function scenePlugin(): Plugin {\n return {\n name: 'scene',\n inject: ['world'],\n apply(ctx) {\n ctx.effect(() => registerSceneComponents(ctx.world), 'scene/components');\n ctx.effect(() => registerPropagateTransforms(ctx.world), 'scene/propagate-transforms');\n },\n };\n}\n","import { Entity, type EntityHandle, type Query, type World } from '@forgeax/engine-ecs';\nimport { ChildOf } from '../components/child-of';\nimport type { SceneErrorCode, SceneErrorDetail } from '../errors';\n\nexport interface SceneHierarchyDiagnostic {\n readonly code: SceneErrorCode;\n readonly expected: string;\n readonly hint: string;\n readonly detail: SceneErrorDetail;\n}\n\nexport interface SceneHierarchySnapshot {\n readonly parentOf: ReadonlyMap<EntityHandle, EntityHandle>;\n readonly diagnostics: readonly SceneHierarchyDiagnostic[];\n getParent(entity: EntityHandle): EntityHandle | undefined;\n}\n\ninterface HierarchyProjectionCacheEntry {\n readonly structureEpoch: number;\n readonly childOfChanges: Query;\n readonly snapshot: SceneHierarchySnapshot;\n}\n\n// A World can be observed by the transform system, renderer visibility, and\n// editor projections in the same frame. Keep one World-local projection so\n// those consumers do not each rescan every archetype. Structure changes and\n// the ChildOf component's own mutation token are the invalidation keys; the\n// global mutation epoch is intentionally too broad because animation and\n// runtime-only component writes may advance it every frame. Direct table\n// writes are internal-only and must not mutate authored hierarchy state.\nconst HIERARCHY_PROJECTION_CACHE = new WeakMap<World, HierarchyProjectionCacheEntry>();\n\nfunction createChildOfChangeQuery(world: World): Query {\n const result = world.query({ changed: [ChildOf] });\n if (!result.ok) throw result.error;\n return result.value;\n}\n\nfunction drainChanges(query: Query): boolean {\n let changed = false;\n for (const span of query.spans().unwrap()) changed ||= span.length > 0;\n return changed;\n}\n\nfunction diagnostic(\n code: SceneErrorCode,\n entity: EntityHandle,\n parent: EntityHandle,\n): SceneHierarchyDiagnostic {\n if (code === 'hierarchy-cycle') {\n return {\n code,\n expected: 'ChildOf parent edges form an acyclic live hierarchy',\n hint: 'remove one ChildOf edge from the reported cycle, then re-run the extract',\n detail: { entity, parent },\n };\n }\n return {\n code,\n expected: 'ChildOf.parent references a live entity in the same World',\n hint: 'remove the stale ChildOf component or restore the referenced parent in this World',\n detail: { entity, parent },\n };\n}\n\n/** Build the only World-local projection of ChildOf parent facts. */\nexport function projectHierarchy(world: World): SceneHierarchySnapshot {\n const cached = HIERARCHY_PROJECTION_CACHE.get(world);\n if (\n cached !== undefined &&\n cached.structureEpoch === world.getStructureEpoch() &&\n !drainChanges(cached.childOfChanges)\n ) {\n return cached.snapshot;\n }\n const liveEntities = new Set<EntityHandle>();\n const authoredParents = new Map<EntityHandle, EntityHandle>();\n\n const query = world.query({ read: [Entity], optional: [ChildOf] });\n if (query.ok) {\n for (const row of query.value) {\n liveEntities.add(row.entity);\n const parent = row.get(ChildOf)?.parent;\n if (parent !== undefined && parent !== null) authoredParents.set(row.entity, parent);\n }\n }\n\n const parentOf = new Map<EntityHandle, EntityHandle>();\n const diagnostics: SceneHierarchyDiagnostic[] = [];\n for (const [entity, parent] of authoredParents) {\n if (liveEntities.has(parent)) {\n parentOf.set(entity, parent);\n } else {\n diagnostics.push(diagnostic('hierarchy-broken', entity, parent));\n }\n }\n\n const state = new Map<EntityHandle, 0 | 1 | 2>();\n const stack: EntityHandle[] = [];\n const cycleMembers = new Set<EntityHandle>();\n const visit = (entity: EntityHandle): void => {\n const currentState = state.get(entity) ?? 0;\n if (currentState === 2) return;\n if (currentState === 1) {\n const cycleStart = stack.indexOf(entity);\n for (let index = cycleStart; index >= 0 && index < stack.length; index++) {\n const member = stack[index];\n if (member !== undefined) cycleMembers.add(member);\n }\n return;\n }\n\n state.set(entity, 1);\n stack.push(entity);\n const parent = parentOf.get(entity);\n if (parent !== undefined) visit(parent);\n stack.pop();\n state.set(entity, 2);\n };\n\n for (const entity of liveEntities) visit(entity);\n for (const entity of cycleMembers) {\n const parent = authoredParents.get(entity);\n if (parent !== undefined) diagnostics.push(diagnostic('hierarchy-cycle', entity, parent));\n parentOf.delete(entity);\n }\n\n diagnostics.sort((left, right) => {\n const entityDelta = (left.detail.entity as number) - (right.detail.entity as number);\n if (entityDelta !== 0) return entityDelta;\n return left.code.localeCompare(right.code);\n });\n\n const stableParentOf = new Map(parentOf);\n const stableDiagnostics = Object.freeze(diagnostics.slice());\n const snapshot: SceneHierarchySnapshot = {\n parentOf: stableParentOf,\n diagnostics: stableDiagnostics,\n getParent(entity: EntityHandle): EntityHandle | undefined {\n return stableParentOf.get(entity);\n },\n };\n const childOfChanges = createChildOfChangeQuery(world);\n drainChanges(childOfChanges);\n HIERARCHY_PROJECTION_CACHE.set(world, {\n structureEpoch: world.getStructureEpoch(),\n childOfChanges,\n snapshot,\n });\n return snapshot;\n}\n"],"mappings":";AAAA;AAAA,EAKE;AAAA,EACA;AAAA,OAKK;;;ACHA,SAAS,kCACd,eACA,QACA,kBACyB;AACzB,Q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;AACtC,UAAM,IAAI;AACV,UAAM,IAAI,QAAQ,CAAC;AAAA,EACrB;AAEA,aAAW,UAAU,aAAc,OAAM,MAAM;AAC/C,aAAW,UAAU,cAAc;AACjC,UAAM,SAAS,gBAAgB,IAAI,MAAM;AACzC,QAAI,WAAW,OAAW,aAAY,KAAK,WAAW,mBAAmB,QAAQ,MAAM,CAAC;AACxF,aAAS,OAAO,MAAM;AAAA,EACxB;AAEA,cAAY,KAAK,CAAC,MAAM,UAAU;AAChC,UAAM,cAAe,KAAK,OAAO,SAAqB,MAAM,OAAO;AACnE,QAAI,gBAAgB,EAAG,QAAO;AAC9B,WAAO,KAAK,KAAK,cAAc,MAAM,IAAI;AAAA,EAC3C,CAAC;AAED,QAAM,iBAAiB,IAAI,IAAI,QAAQ;AACvC,QAAM,oBAAoB,OAAO,OAAO,YAAY,MAAM,CAAC;AAC3D,QAAM,WAAmC;AAAA,IACvC,UAAU;AAAA,IACV,aAAa;AAAA,IACb,UAAU,QAAgD;AACxD,aAAO,eAAe,IAAI,MAAM;AAAA,IAClC;AAAA,EACF;AACA,QAAM,iBAAiB,yBAAyB,KAAK;AACrD,eAAa,cAAc;AAC3B,6BAA2B,IAAI,OAAO;AAAA,IACpC,gBAAgB,MAAM,kBAAkB;AAAA,IACxC;AAAA,IACA;AAAA,EACF,CAAC;AACD,SAAO;AACT;","names":["defineComponent","defineComponent","err","ok","err","ok","err","ok","err","ok","err","parts","slot","ok","classifyEntityField","remapEntityFieldValue","componentSchema","err","ok","PACK_ERROR_HINTS","ok","err","PACK_ERROR_HINTS","componentSchema","classifyEntityField","remapEntityFieldValue","value","ENTITY_NULL_RAW","err","ok","err","ok","world","bindingIndex","ENTITY_NULL_RAW","parentRaw","active"]}
1
+ {"version":3,"sources":["../src/assets/scene-decoder.ts","../src/instances/legacy.ts","../src/components/children.ts","../src/components/transform.ts","../src/collect-subtree.ts","../src/components/morph-weights.ts","../src/components/name.ts","../src/errors.ts","../src/instances/binding.ts","../src/instances/collect-profile.ts","../src/instances/externalization.ts","../src/instances/keyed.ts","../src/instances/scene-instances.ts","../src/instances/state.ts","../src/systems/propagate-transforms.ts","../src/plugin.ts","../src/systems/hierarchy-projection.ts"],"sourcesContent":["import {\n type AssetDecoder,\n type AssetDecoderContribution,\n type AssetKind,\n type AssetLoadError,\n err,\n ok,\n type Result,\n type SceneAsset,\n type SceneEntity,\n type SceneInstanceOverride,\n} from '@forgeax/engine-types';\nimport { normalizeLegacySceneAsset } from '../instances/legacy.js';\n\nexport const sceneAssetKind: AssetKind<SceneAsset, 'scene'> = {\n kind: 'scene',\n} as AssetKind<SceneAsset, 'scene'>;\n\nfunction invalidScene(guid: string, reason: string): Result<SceneAsset, AssetLoadError> {\n return err({\n code: 'asset-package-invalid',\n expected: 'a scene payload with keyed entities',\n hint: 'recook the SceneAsset and publish its complete envelope',\n detail: { guid, reason },\n });\n}\n\ntype SceneWireRefResult =\n | { readonly ok: true; readonly value: SceneAsset }\n | { readonly ok: false; readonly reason: string };\n\n// The Pack envelope owns refs[] while the decoded SceneAsset remains the\n// portable payload. Keep that wire-only fact beside the decoded object so the\n// World-local projection can interpret shared-field indices without putting a\n// component registry or World into the decoder contract.\nconst sceneWireRefs = new WeakMap<object, readonly string[]>();\n\n/** @internal Read the Pack refs[] retained for a decoded SceneAsset payload. */\nexport function sceneAssetWireRefs(asset: SceneAsset): readonly string[] | undefined {\n return sceneWireRefs.get(asset);\n}\n\nfunction resolveWireRef(\n refs: readonly string[],\n value: number,\n location: string,\n): { readonly ok: true; readonly value: string } | { readonly ok: false; readonly reason: string } {\n const guid = refs[value];\n if (!Number.isInteger(value) || value < 0 || guid === undefined) {\n return {\n ok: false,\n reason: `${location} references refs[${value}], but refs contains ${refs.length} entries`,\n };\n }\n return { ok: true, value: guid };\n}\n\nfunction resolveInstanceSource(\n source: unknown,\n refs: readonly string[],\n location: string,\n): { readonly ok: true; readonly value: string } | { readonly ok: false; readonly reason: string } {\n if (typeof source === 'string' && source.length > 0) return { ok: true, value: source };\n if (typeof source !== 'number' || !Number.isInteger(source)) {\n return { ok: false, reason: `${location} must be a GUID or refs index` };\n }\n return resolveWireRef(refs, source, location);\n}\n\nfunction resolveSkinGuids(\n skinGuids: readonly (number | string)[] | undefined,\n refs: readonly string[],\n):\n | { readonly ok: true; readonly value: readonly string[] | undefined }\n | { readonly ok: false; readonly reason: string } {\n if (skinGuids === undefined) return { ok: true, value: undefined };\n const resolved: string[] = [];\n for (let index = 0; index < skinGuids.length; index += 1) {\n const value = skinGuids[index];\n if (typeof value === 'string') {\n resolved.push(value);\n continue;\n }\n if (typeof value !== 'number' || !Number.isInteger(value)) {\n return { ok: false, reason: `skinGuids[${index}] is not a GUID or refs index` };\n }\n const ref = resolveWireRef(refs, value, `skinGuids[${index}]`);\n if (!ref.ok) return ref;\n resolved.push(ref.value);\n }\n return { ok: true, value: resolved };\n}\n\nfunction resolveSceneWireRefs(\n payload: { readonly entities: unknown; readonly skinGuids?: unknown },\n refs: readonly string[],\n): SceneWireRefResult {\n const normalized = normalizeLegacySceneAsset({ kind: 'scene', entities: payload.entities });\n const rawEntities = normalized.entities;\n if (rawEntities === null || typeof rawEntities !== 'object' || Array.isArray(rawEntities)) {\n return { ok: false, reason: 'entities must be a keyed object' };\n }\n const entities: Record<string, SceneEntity> = {};\n for (const [key, rawEntity] of Object.entries(rawEntities as Record<string, unknown>)) {\n const entity = rawEntity as\n | {\n readonly components?: unknown;\n readonly instance?: {\n readonly source?: unknown;\n readonly overrides?: unknown;\n };\n }\n | undefined;\n if (key.length === 0 || entity === undefined || typeof entity !== 'object') {\n return { ok: false, reason: `entities[${JSON.stringify(key)}] is malformed` };\n }\n if (\n entity.components === null ||\n typeof entity.components !== 'object' ||\n Array.isArray(entity.components)\n ) {\n return { ok: false, reason: `entities.${key}.components must be an object` };\n }\n const components: Record<string, Record<string, unknown>> = {};\n for (const [componentName, rawFields] of Object.entries(\n entity.components as Record<string, unknown>,\n )) {\n if (rawFields === null || typeof rawFields !== 'object' || Array.isArray(rawFields)) {\n return {\n ok: false,\n reason: `entities.${key}.components.${componentName} must be an object`,\n };\n }\n // Component schema lookup is World-local after the ECS core reduction.\n // The runtime projection owns the World-local schema and converts\n // authored GUID fields into World.sharedRefs handles. Keep this loader\n // boundary POD-only instead of consulting a removed process-global ECS\n // component registry.\n components[componentName] = { ...(rawFields as Record<string, unknown>) };\n }\n const instance = entity.instance;\n let resolvedInstance: SceneEntity['instance'];\n if (instance !== undefined) {\n if (instance === null || typeof instance !== 'object') {\n return { ok: false, reason: `entities.${key}.instance must be an object` };\n }\n const source = resolveInstanceSource(\n instance.source,\n refs,\n `entities.${key}.instance.source`,\n );\n if (!source.ok) return source;\n if (instance.overrides !== undefined && !Array.isArray(instance.overrides)) {\n return { ok: false, reason: `entities.${key}.instance.overrides must be an array` };\n }\n let overrides: NonNullable<SceneEntity['instance']>['overrides'] | undefined;\n if (instance.overrides === undefined) {\n overrides = undefined;\n } else {\n const resolvedOverrides: SceneInstanceOverride[] = [];\n for (const [index, rawOverride] of (instance.overrides as readonly unknown[]).entries()) {\n if (\n rawOverride === null ||\n typeof rawOverride !== 'object' ||\n Array.isArray(rawOverride) ||\n !Array.isArray((rawOverride as { readonly target?: unknown }).target) ||\n (rawOverride as { readonly target?: unknown[] }).target?.some(\n (part) => typeof part !== 'string' || part.length === 0,\n )\n ) {\n return {\n ok: false,\n reason: `entities.${key}.instance.overrides[${index}] is malformed`,\n };\n }\n const target = (rawOverride as { readonly target: readonly string[] }).target;\n const rawComponents = (rawOverride as { readonly components?: unknown }).components;\n if (\n rawComponents === null ||\n typeof rawComponents !== 'object' ||\n Array.isArray(rawComponents)\n ) {\n return {\n ok: false,\n reason: `entities.${key}.instance.overrides[${index}].components is malformed`,\n };\n }\n resolvedOverrides.push({\n target: [...target] as [string, ...string[]],\n components: rawComponents as SceneEntity['components'],\n });\n }\n overrides = resolvedOverrides;\n }\n resolvedInstance = {\n source: source.value,\n ...(overrides === undefined ? {} : { overrides }),\n };\n }\n entities[key] = {\n components,\n ...(resolvedInstance === undefined ? {} : { instance: resolvedInstance }),\n };\n }\n\n const skinGuids = resolveSkinGuids(\n Array.isArray(payload.skinGuids)\n ? (payload.skinGuids as readonly (number | string)[])\n : payload.skinGuids === undefined\n ? undefined\n : ([] as readonly (number | string)[]),\n refs,\n );\n if (!skinGuids.ok) return skinGuids;\n\n return {\n ok: true,\n value: {\n kind: 'scene',\n entities,\n ...(skinGuids.value === undefined ? {} : { skinGuids: skinGuids.value }),\n },\n };\n}\n\n/** Scene owns structural validation; World-local projection resolves shared refs. */\nexport const sceneAssetDecoder: AssetDecoder<SceneAsset> = {\n async decode({ envelope }): Promise<Result<SceneAsset, AssetLoadError>> {\n const payload = envelope.payload;\n if (\n payload.kind !== 'scene' ||\n payload.entities === null ||\n typeof payload.entities !== 'object'\n ) {\n return invalidScene(envelope.guid, 'scene payload is missing keyed entities');\n }\n const resolved = resolveSceneWireRefs(payload, envelope.refs);\n if (!resolved.ok) return invalidScene(envelope.guid, resolved.reason);\n sceneWireRefs.set(resolved.value, Object.freeze([...envelope.refs]));\n return ok(resolved.value);\n },\n};\n\nexport const sceneAssetContribution: AssetDecoderContribution<SceneAsset, 'scene'> = {\n kind: sceneAssetKind,\n decoder: sceneAssetDecoder,\n consumer: 'Scene',\n};\n","/**\n * Normalize the small set of SceneAsset fields emitted by the 0.1.27\n * ScriptablePack template before the current keyed runtime validates them.\n *\n * This is deliberately a boundary migration. Current authoring and runtime\n * types stay keyed and use `shadowFilter`; only old payloads carry numeric\n * ChildOf addresses or `pcfKernelSize`.\n */\nexport function migrateLegacySceneComponentFields(\n componentName: string,\n source: Record<string, unknown>,\n addressByLocalId?: ReadonlyMap<number, string>,\n): Record<string, unknown> {\n const fields = { ...source };\n const address = (value: unknown): unknown =>\n Number.isSafeInteger(value) ? (addressByLocalId?.get(value as number) ?? String(value)) : value;\n if (componentName === 'DirectionalLight' && Object.hasOwn(fields, 'pcfKernelSize')) {\n const kernel = fields.pcfKernelSize;\n const shadowFilter = kernel === 1 ? 1 : kernel === 3 ? 2 : kernel === 5 ? 3 : undefined;\n if (shadowFilter !== undefined && !Object.hasOwn(fields, 'shadowFilter')) {\n delete fields.pcfKernelSize;\n fields.shadowFilter = shadowFilter;\n }\n }\n if (componentName === 'ChildOf' && Number.isSafeInteger(fields.parent)) {\n fields.parent = address(fields.parent);\n }\n if (componentName === 'Children' && Array.isArray(fields.entities)) {\n fields.entities = fields.entities.map(address);\n }\n return fields;\n}\n\ninterface LegacySceneEntity {\n readonly localId?: unknown;\n readonly bindingKey?: unknown;\n readonly components?: unknown;\n readonly instance?: unknown;\n}\n\n/**\n * Lift the pre-keyed SceneAsset array into the current keyed shape.\n *\n * The 0.1.27 template used `localId` for storage and `bindingKey` for the\n * gameplay-facing names. Keeping the binding key is essential: the runtime\n * resolves `player`, `camera`, and joints by that name, not by the old number.\n * This function is intentionally structural and accepts `unknown` only at the\n * compatibility boundary; current authoring types remain keyed.\n */\nexport function normalizeLegacySceneAsset(\n scene: unknown,\n): import('@forgeax/engine-types').SceneAsset {\n if (scene === null || typeof scene !== 'object') return scene as never;\n const candidate = scene as { readonly entities?: unknown };\n if (!Array.isArray(candidate.entities))\n return scene as import('@forgeax/engine-types').SceneAsset;\n\n const rows = candidate.entities as readonly LegacySceneEntity[];\n const addressByLocalId = new Map<number, string>();\n const rowKeys: string[] = [];\n const used = new Set<string>();\n for (const [index, row] of rows.entries()) {\n const localId = Number.isSafeInteger(row?.localId) ? (row.localId as number) : index;\n const bindingKey =\n typeof row?.bindingKey === 'string' && row.bindingKey.length > 0\n ? row.bindingKey\n : String(localId);\n const key = used.has(bindingKey) ? String(localId) : bindingKey;\n used.add(key);\n addressByLocalId.set(localId, key);\n rowKeys.push(key);\n }\n\n const entities: Record<\n string,\n { readonly components: Record<string, Record<string, unknown>>; readonly instance?: unknown }\n > = {};\n for (const [index, row] of rows.entries()) {\n const key = rowKeys[index] as string;\n const rawComponents = row?.components;\n const components: Record<string, Record<string, unknown>> = {};\n if (\n rawComponents !== null &&\n typeof rawComponents === 'object' &&\n !Array.isArray(rawComponents)\n ) {\n for (const [componentName, rawFields] of Object.entries(\n rawComponents as Record<string, unknown>,\n )) {\n if (rawFields === null || typeof rawFields !== 'object' || Array.isArray(rawFields))\n continue;\n components[componentName] = migrateLegacySceneComponentFields(\n componentName,\n rawFields as Record<string, unknown>,\n addressByLocalId,\n );\n }\n }\n entities[key] = {\n components,\n ...(row?.instance === undefined ? {} : { instance: row.instance }),\n };\n }\n return {\n ...(scene as Record<string, unknown>),\n entities,\n } as import('@forgeax/engine-types').SceneAsset;\n}\n","// @forgeax/engine-runtime - Children (forward-list of child entities).\n//\n// Schema: 1 array<entity> field `entities` (variable-length, ECS-managed via\n// the BufferPool slot column + sidecar count column allocated by the ECS\n// relationship owner).\n//\n// feat-20260515-buffer-array-vocab-collapse M3 / w17:\n// the legacy `VarArrayView<Entity>` value-shape wrapper was retired in\n// favour of a direct `TypedArray` snapshot returned by `world.get`. AI users\n// read the engine-maintained list through the read-only `Uint32Array` snapshot:\n//\n// const snap = world.get(parent, Children).unwrap().entities;\n// const liveCount = snap.length;\n// for (let i = 0; i < liveCount; i++) { const child = snap[i]; ... }\n//\n// Snapshot length equals the live element count (sidecar count column owned\n// by the ECS layer); the public snapshot is detached and rematerialised on\n// every `world.get` (D-4 no-cache), so `fill` or index writes cannot mutate the\n// target. Internal relationship maintenance and Scene traversal borrow the\n// live array through the package-internal zero-copy seams instead.\n//\n// feat-20260531-ecs-relationship-abstraction-bidirectional-sync M4 / t20:\n// Children is the MIRROR side of the ChildOf relationship. Its schema is\n// unchanged (the `entities: 'array<entity>'` shape is exactly what the\n// relationship mirror contract requires), but the engine now maintains this\n// list automatically whenever ChildOf is added / removed / reparented on a\n// child entity (M2 bidirectional-sync hook on ChildOf). The prior OOS-10\n// \"AI users keep the two sides consistent themselves\" contract is retired:\n// `world.addComponent(child, ChildOf{parent})` appends `child` to\n// `parent.Children.entities`, `world.removeComponent` / reparent prunes it.\n// For the ChildOf hierarchy the engine owns consistency; no public target\n// write can diverge from the source relationship.\n//\n// feat-20260514-ecs-children-instances-managed-buffer-array M3 / w13 (kept\n// for context): migrated from the legacy `{ count: 'u32' }` advisory marker\n// to the real variable-length entity-array storage path.\n// - OOS-09 (prior loop): no `addChild` / `removeChild` / `removeChildren`\n// Commands API. Retired this feat: `world.addChild` / `world.removeChild`\n// / `world.reparent` ship in M3, plus the relationship hook above.\n// - Normal ChildOf child despawn invokes the source onRemove hook and\n// removes the child before the row is retired; parent despawn follows the\n// linkedSpawn cascade. A dangling u32 is therefore an explicitly malformed\n// internal fixture or a non-linked generic relationship, not a normal\n// ChildOf lifecycle result. Consumers still probe liveness before using a\n// handle and receive the structured ECS error for malformed state.\n//\n// charter mapping: proposition 2 (Bevy ChildOf+Children pair, holder\n// perspective) + proposition 3 (machine-readable schema:\n// `componentSchema(Children).entities === 'array<entity>'`) + proposition 4 (explicit\n// failure: dangling entries surface to the AI user via `world.get(parent, Entity)` liveness probe,\n// not silent drop) + proposition 5 (consistent abstraction: Children is the\n// generic relationship-mirror shape, not a ChildOf special case).\n\nimport { defineRelationship } from '@forgeax/engine-ecs';\nimport { Transform } from './transform';\n\n/**\n * Hierarchy forward-list of child entities.\n *\n * `entities` is a variable-length `array<entity>` field; each element is\n * an `Entity` u32 the ECS relationship owner materialized. The value returned\n * by `world.get(parent, Children).unwrap().entities` is a detached read-only\n * `Uint32Array` snapshot rematerialised fresh on every read (D-4 no-cache);\n * mutating the returned array cannot change ECS-owned storage, and the\n * snapshot's `length` equals the live element count. Internal Scene/ECS paths\n * use the package-internal zero-copy array seams instead of this snapshot.\n *\n * Invariants:\n * - `propagateTransforms` consumes Children from the ECS-owned materialized\n * buffer and expands each root parent-first. The forward list is also\n * available for AI-user traversal / debug / inspection.\n * - Children <-> ChildOf consistency is maintained by the engine via the\n * ChildOf `relationship` mirror hook (see ./child-of.ts): adding /\n * removing / reparenting ChildOf on a child auto-updates the parent's\n * `entities` list. AI users do not hand-sync the two sides for the\n * hierarchy.\n * - ChildOf's linked lifecycle keeps ordinary Children entries aligned: a\n * child despawn prunes its source slot and a parent despawn cascades. A\n * deliberately malformed/non-linked edge remains observable as a dead\n * handle and must be diagnosed through the structured error channel.\n *\n * @example Spawn a parent and two children via ChildOf (engine maintains Children):\n * const parent = world.spawn({ component: Transform, data: identityXf() }).unwrap();\n * const a = world.spawn(\n * { component: Transform, data: identityXf() },\n * { component: ChildOf, data: { parent } },\n * ).unwrap();\n * const b = world.spawn(\n * { component: Transform, data: identityXf() },\n * { component: ChildOf, data: { parent } },\n * ).unwrap();\n * // Read back via the read-only snapshot - engine appended a, b:\n * const snap = world.get(parent, Children).unwrap().entities;\n * for (let i = 0; i < snap.length; i++) {\n * const child = snap[i];\n * // ... consume; probe the handle before using it when reading a\n * // deliberately malformed/non-linked relationship.\n * }\n */\nexport const { source: ChildOf, target: Children } = defineRelationship({\n sourceName: 'ChildOf',\n sourceField: 'parent',\n targetName: 'Children',\n targetField: 'entities',\n // Every scene hierarchy node is spatial. Adding ChildOf therefore\n // materializes the local/derived transform pair at the same structural\n // boundary, so render- and scene-authored children cannot enter a frame\n // with an incomplete hierarchy node.\n sourceRequires: [Transform],\n exclusive: true,\n linkedSpawn: true,\n});\n","// @forgeax/engine-runtime - authored local transform and derived world output.\n\nimport { defineComponent } from '@forgeax/engine-ecs';\n\nconst IDENTITY_MAT4 = new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);\n\n/** Scene-owned derived world transform. Only TransformPropagation writes it. */\nexport const GlobalTransform = defineComponent(\n 'GlobalTransform',\n {\n world: { type: 'array<f32, 16>', default: IDENTITY_MAT4 },\n },\n { transient: true },\n);\n\n/**\n * Authored local position, rotation and scale columns.\n *\n * The ECS `requires` declaration is the generic structural invariant: callers\n * add `Transform`, while `GlobalTransform` is materialized once at spawn/add.\n */\nexport const Transform = defineComponent(\n 'Transform',\n {\n pos: { type: 'array<f32, 3>', default: new Float32Array([0, 0, 0]) },\n // Component order [x, y, z, w] is shared with glTF.\n quat: { type: 'array<f32, 4>', default: new Float32Array([0, 0, 0, 1]) },\n scale: { type: 'array<f32, 3>', default: new Float32Array([1, 1, 1]) },\n },\n { requires: [GlobalTransform] },\n);\n","// Scene-owned hierarchy traversal shared by scene collection and render hooks.\n\nimport type { EntityHandle, World } from '@forgeax/engine-ecs';\n\nimport { Children } from './components/children';\n\n/** Walk a Children hierarchy breadth-first, reusing an optional visited set. */\nexport function collectSubtree(\n world: World,\n spawnRoot: EntityHandle,\n visited?: Set<number>,\n): Set<number> {\n if (visited === undefined) visited = new Set<number>();\n if (visited.has(spawnRoot as number)) return visited;\n const queue: number[] = [spawnRoot as number];\n visited.add(spawnRoot as number);\n for (let cursor = 0; cursor < queue.length; cursor += 1) {\n const current = queue[cursor] as number;\n const children = world.get(current as EntityHandle, Children);\n if (!children.ok) continue;\n const entities = children.value.entities as ArrayLike<number>;\n for (let index = 0; index < entities.length; index += 1) {\n const child = entities[index] as number;\n if (visited.has(child)) continue;\n visited.add(child);\n queue.push(child);\n }\n }\n return visited;\n}\n","import { defineComponent } from '@forgeax/engine-ecs';\n\n/** Per-entity morph weights; length is validated against the mesh target count. */\nexport const MorphWeights = defineComponent('MorphWeights', {\n weights: { type: 'array<f32>' },\n});\n","// @forgeax/engine-runtime --- Name component (built-in identifier).\n//\n// Single-field minimal skeleton: { value: 'string' }. Bare 'string' schema\n// vocab keyword routes through ECS UniqueRefStore (D-R3 single-arm managed\n// dispatch); the read shape is a native JS string.\n//\n// Lives in `runtime` rather than `ecs` because Name is a built-in *component*,\n// not part of the ECS framework itself (it does not participate in archetype /\n// query / world mechanics like the essential `Entity` component does). Mirrors\n// Bevy's split: `Entity` lives in `bevy_ecs`; `Name` lives in `bevy_core`.\n//\n// Migrated from packages/ecs/src/name.ts by tweak-20260612-ecs-concept-compression\n// (architecture-principles.md §1 SSOT: Name's authoritative location is the\n// runtime built-in components surface, not the ECS framework barrel).\n//\n// Naming follows the Bevy-aligned convention locked by feat-20260513:\n// single-semantic component drops the 'Component' suffix (Transform / Camera\n// / DirectionalLight / Name).\n\nimport { defineComponent } from '@forgeax/engine-ecs';\n\nexport const Name = defineComponent('Name', { value: { type: 'string' } });\n","import type { EcsError, EntityHandle } from '@forgeax/engine-ecs';\n\nexport type SceneErrorCode = 'hierarchy-broken' | 'hierarchy-cycle';\n\n/** Scene-instantiation failures owned by the scene package. */\nexport type SceneInstanceErrorCode = 'component-not-defined' | 'scene-override-type-mismatch';\n\nexport { ComponentNotDefinedError } from '@forgeax/engine-ecs/projection';\n\n/** The structured ECS failure retained by a Scene derived-write diagnostic. */\nexport interface SceneErrorCause {\n readonly code: EcsError['code'];\n readonly expected?: string;\n readonly hint?: string;\n readonly detail?: unknown;\n}\n\n/** Location detail shared by hierarchy diagnostics and derived-write errors. */\nexport interface SceneHierarchyErrorDetail {\n readonly kind?: 'hierarchy';\n readonly entity: EntityHandle;\n readonly parent: EntityHandle;\n}\n\n/** A flat derived publication failure with its original ECS error intact. */\nexport interface SceneDerivedWriteErrorDetail {\n readonly kind: 'derived-write';\n readonly entity: EntityHandle;\n readonly parent: EntityHandle;\n readonly bindingIndex: number;\n readonly base: number;\n readonly start: number;\n readonly count: number;\n readonly cause: SceneErrorCause;\n}\n\nexport type SceneErrorDetail = SceneHierarchyErrorDetail | SceneDerivedWriteErrorDetail;\n\nexport class SceneError extends Error {\n readonly code: SceneErrorCode;\n readonly expected: string;\n readonly hint: string;\n readonly detail: SceneErrorDetail | undefined;\n\n constructor(args: {\n code: SceneErrorCode;\n expected: string;\n hint: string;\n detail?: SceneErrorDetail;\n }) {\n super(`[SceneError ${args.code}] expected: ${args.expected}; hint: ${args.hint}`);\n this.name = 'SceneError';\n this.code = args.code;\n this.expected = args.expected;\n this.hint = args.hint;\n this.detail = args.detail;\n }\n}\n","import type { EntityHandle } from '@forgeax/engine-ecs';\nimport type { SceneEntityAddress, SceneEntityRef } from '@forgeax/engine-types';\nimport { err, ok, type Result } from '@forgeax/engine-types';\n\nexport type { SceneEntityRef } from '@forgeax/engine-types';\n\nexport type SceneBindingError = {\n readonly code: 'scene-binding-missing' | 'scene-binding-wrong-instance';\n readonly expected: string;\n readonly hint: string;\n readonly detail: { readonly sceneSourceKey: string; readonly address: SceneEntityAddress };\n};\n\nexport type SceneBindingDeclarationError = {\n readonly code: 'scene-binding-duplicate' | 'scene-binding-source-missing';\n readonly expected: string;\n readonly hint: string;\n readonly detail: { readonly sceneSourceKey?: string; readonly address?: SceneEntityAddress };\n};\n\nexport function validateSceneEntityKeys(\n sceneSourceKey: string,\n entityKeys: readonly string[],\n): Result<readonly string[], SceneBindingDeclarationError> {\n if (sceneSourceKey.length === 0) {\n return err({\n code: 'scene-binding-source-missing',\n expected: 'a non-empty scene sourceKey',\n hint: 'declare the scene sourceKey in the author inventory',\n detail: {},\n });\n }\n const seen = new Set<string>();\n for (const entityKey of entityKeys) {\n if (entityKey.length === 0 || seen.has(entityKey)) {\n return err({\n code: 'scene-binding-duplicate',\n expected: 'unique non-empty entity keys within one scene',\n hint: 'rename the duplicate entity key in the scene producer',\n detail: { sceneSourceKey, address: entityKey },\n });\n }\n seen.add(entityKey);\n }\n return ok([...entityKeys]);\n}\n\nexport function sceneEntity(sceneSourceKey: string, address: SceneEntityAddress): SceneEntityRef {\n return { sceneSourceKey, address };\n}\n\n/** Stable map key shared by direct and nested SceneEntityRef addresses. */\nexport function sceneEntityAddressKey(address: SceneEntityAddress): string {\n if (typeof address === 'string') return `s:${JSON.stringify(address)}`;\n if (address.length === 1) return `s:${JSON.stringify(address[0] ?? '')}`;\n return `a:${JSON.stringify(address)}`;\n}\n\nexport function resolveSceneEntity(\n ref: SceneEntityRef,\n instance: {\n readonly sceneSourceKey: string;\n readonly bindings: ReadonlyMap<string, EntityHandle | number>;\n },\n): Result<EntityHandle | number, SceneBindingError> {\n if (ref.sceneSourceKey !== instance.sceneSourceKey) {\n return err({\n code: 'scene-binding-wrong-instance',\n expected: `scene instance ${ref.sceneSourceKey}`,\n hint: 'resolve the SceneEntityRef against its owning SceneInstance',\n detail: { sceneSourceKey: ref.sceneSourceKey, address: ref.address },\n });\n }\n const value = instance.bindings.get(sceneEntityAddressKey(ref.address));\n if (value === undefined) {\n return err({\n code: 'scene-binding-missing',\n expected: 'entity key declared by the scene producer',\n hint: 'declare the entity key in the scene producer before consuming it',\n detail: { sceneSourceKey: ref.sceneSourceKey, address: ref.address },\n });\n }\n return ok(value);\n}\n","/** Immutable Scene collection policy shared by runtime collectors. */\nexport interface SceneCollectProfile {\n readonly includeComponent: (componentName: string, transient: boolean) => boolean;\n readonly includeField: (componentName: string, fieldName: string, transient: boolean) => boolean;\n}\n\nexport const SCENE_COLLECT_PROFILE: SceneCollectProfile = Object.freeze({\n includeComponent: (_componentName: string, transient: boolean) => !transient,\n includeField: (_componentName: string, _fieldName: string, transient: boolean) => !transient,\n});\n","import type { AssetRef, SceneAsset, SceneInstanceOverride } from '@forgeax/engine-types';\nimport { err, ok, type Result } from '@forgeax/engine-types';\nimport { migrateLegacySceneComponentFields, normalizeLegacySceneAsset } from './legacy.js';\n\nexport type SceneComponentSchemaResolver = (\n componentName: string,\n) => Readonly<Record<string, string>> | undefined;\n\nexport interface SceneExternalizationError {\n readonly field: string;\n readonly value: unknown;\n}\n\nexport interface ExternalizedSceneAsset {\n readonly payload: Record<string, unknown>;\n readonly refs: readonly AssetRef[];\n}\n\nfunction sharedKind(type: string | undefined): 'one' | 'many' | undefined {\n if (type?.startsWith('shared<')) return 'one';\n if (type?.startsWith('array<shared<')) return 'many';\n return undefined;\n}\n\ninterface RefContext {\n readonly refs: AssetRef[];\n readonly indexByGuid: Map<string, number>;\n}\n\nfunction addRef(\n context: RefContext,\n guid: string,\n sourceField: NonNullable<AssetRef['sourceField']>,\n sceneEntityKey?: string,\n): number {\n const prior = context.indexByGuid.get(guid);\n if (prior !== undefined) return prior;\n const index = context.refs.length;\n context.refs.push({\n guid,\n sourceField,\n ...(sceneEntityKey === undefined ? {} : { sceneEntityKey }),\n } as AssetRef);\n context.indexByGuid.set(guid, index);\n return index;\n}\n\nfunction externalizeFields(\n componentName: string,\n source: Record<string, unknown>,\n resolveSchema: SceneComponentSchemaResolver,\n context: RefContext,\n sceneEntityKey: string | undefined,\n): Record<string, unknown> {\n const schema = resolveSchema(componentName);\n const fields: Record<string, unknown> = {};\n for (const [fieldName, value] of Object.entries(\n migrateLegacySceneComponentFields(componentName, source),\n )) {\n if (value === undefined) continue;\n const kind = sharedKind(schema?.[fieldName]);\n if (kind === 'one' && typeof value === 'string') {\n fields[fieldName] = addRef(context, value, { componentName, fieldName }, sceneEntityKey);\n } else if (kind === 'many' && Array.isArray(value)) {\n fields[fieldName] = value.map((item, arrayIndex) =>\n typeof item === 'string'\n ? addRef(context, item, { componentName, fieldName, arrayIndex }, sceneEntityKey)\n : item,\n );\n } else {\n fields[fieldName] = value;\n }\n }\n return fields;\n}\n\nfunction externalizeOverride(\n override: SceneInstanceOverride,\n resolveSchema: SceneComponentSchemaResolver,\n context: RefContext,\n sceneEntityKey: string,\n): SceneInstanceOverride {\n const components: Record<string, Record<string, unknown>> = {};\n for (const [componentName, rawFields] of Object.entries(override.components)) {\n components[componentName] = externalizeFields(\n componentName,\n { ...(rawFields as Record<string, unknown>) },\n resolveSchema,\n context,\n sceneEntityKey,\n );\n }\n return {\n target: [...override.target],\n components,\n };\n}\n\n/** Project a keyed SceneAsset's shared asset fields into a payload plus refs. */\nexport function externalizeSceneAsset(\n scene: SceneAsset,\n resolveSchema: SceneComponentSchemaResolver,\n): Result<ExternalizedSceneAsset, SceneExternalizationError> {\n const normalized = normalizeLegacySceneAsset(scene);\n const context: RefContext = { refs: [], indexByGuid: new Map() };\n const entities: Record<string, Record<string, unknown>> = {};\n for (const [key, entity] of Object.entries(normalized.entities)) {\n const components: Record<string, Record<string, unknown>> = {};\n for (const [componentName, raw] of Object.entries(entity.components)) {\n const source = raw as Record<string, unknown> | undefined;\n if (source === undefined) continue;\n components[componentName] = externalizeFields(\n componentName,\n source,\n resolveSchema,\n context,\n key,\n );\n }\n const instance = entity.instance;\n entities[key] = {\n components,\n ...(instance === undefined\n ? {}\n : {\n instance: {\n source: addRef(\n context,\n instance.source,\n { componentName: 'SceneInstance', fieldName: 'source' },\n key,\n ),\n ...(instance.overrides === undefined\n ? {}\n : {\n overrides: instance.overrides.map((override) =>\n externalizeOverride(override, resolveSchema, context, key),\n ),\n }),\n },\n }),\n };\n }\n\n for (const [arrayIndex, guid] of (normalized.skinGuids ?? []).entries()) {\n if (typeof guid !== 'string') return err({ field: 'skinGuids', value: guid });\n addRef(context, guid, { componentName: '<scene>', fieldName: 'skinGuids', arrayIndex });\n }\n return ok({\n payload: {\n kind: 'scene',\n entities,\n ...(normalized.skinGuids === undefined\n ? {}\n : {\n skinGuids: normalized.skinGuids.map((guid) => context.indexByGuid.get(guid) as number),\n }),\n },\n refs: context.refs,\n });\n}\n","import type { Component, World } from '@forgeax/engine-ecs';\nimport { classifyEntityField, remapEntityFieldValue } from '@forgeax/engine-ecs/externalization';\nimport { componentSchema } from '@forgeax/engine-ecs/internal';\nimport type {\n ComponentValuesMap,\n LocalEntityId,\n SceneAsset,\n SceneEntityAddress,\n} from '@forgeax/engine-types';\nimport {\n err,\n type Handle,\n ok,\n PACK_ERROR_HINTS,\n type Result,\n type SceneEntity,\n} from '@forgeax/engine-types';\nimport { migrateLegacySceneComponentFields, normalizeLegacySceneAsset } from './legacy.js';\nimport type { MountOverride, SceneInstanceMount } from './runtime-types.js';\n\n/** Numeric representation used only inside the Scene runtime. */\nexport interface CompiledSceneEntity {\n readonly localId: LocalEntityId;\n readonly components: Partial<ComponentValuesMap>;\n}\n\nexport interface CompiledSceneAsset {\n readonly kind: 'scene';\n readonly entities: readonly CompiledSceneEntity[];\n readonly mounts?: readonly SceneInstanceMount[];\n readonly skinGuids?: readonly string[];\n}\n\nexport interface CompiledSceneResult {\n readonly asset: CompiledSceneAsset;\n readonly keyByLocalId: ReadonlyMap<number, string>;\n readonly mountKeyByLocalId: ReadonlyMap<number, string>;\n /** Private slots that attach directly to this scene's synthetic root. */\n readonly rootLocalIds: readonly number[];\n /** Effective private ChildOf edges, including nested scene attachment. */\n readonly hierarchyParentByLocalId: ReadonlyMap<number, number>;\n readonly resolveAddress: (address: unknown, field?: string) => number | undefined;\n}\n\nexport interface KeyedSceneCompileContext {\n readonly resolveSource: (\n source: string,\n parent: Handle<'SceneAsset', 'shared'>,\n ) => Result<Handle<'SceneAsset', 'shared'>, unknown>;\n readonly resolveAsset: (handle: Handle<'SceneAsset', 'shared'>) => Result<SceneAsset, unknown>;\n readonly stack: ReadonlySet<number>;\n}\n\nfunction fail(reason: string, detail: Record<string, unknown> = {}): Result<never, unknown> {\n return err({\n code: 'asset-package-invalid',\n expected: 'a keyed SceneAsset with valid entity and instance addresses',\n hint: 'repair the SceneAsset source and recook the asset',\n detail: { reason, ...detail },\n });\n}\n\nfunction keyList(entities: Readonly<Record<string, SceneEntity>>): string[] {\n return Object.keys(entities).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));\n}\n\nfunction addressParts(value: unknown): readonly string[] | undefined {\n if (typeof value === 'string' && value.length > 0) return [value];\n // ScriptablePack 0.1.27 serialized ChildOf/Children addresses as numeric\n // local IDs. Accept that legacy wire form only at this compiler boundary;\n // the authoring contract remains string keyed.\n if (Number.isSafeInteger(value)) return [String(value)];\n if (!Array.isArray(value) || value.length === 0) return undefined;\n if (!value.every((part) => typeof part === 'string' && part.length > 0)) return undefined;\n return value as readonly string[];\n}\n\nfunction fieldRemap(\n world: World,\n componentName: string,\n fields: Record<string, unknown>,\n resolveAddress: (address: unknown, field: string) => number | undefined,\n entityKey?: string,\n): Result<Record<string, unknown>, unknown> {\n const token = world.components.resolve(componentName);\n if (token === undefined) return fail('unknown component', { component: componentName });\n const schema = componentSchema(token) as Record<string, string>;\n const out: Record<string, unknown> = {};\n for (const [fieldName, value] of Object.entries(\n migrateLegacySceneComponentFields(componentName, fields),\n )) {\n const fieldType = schema[fieldName];\n if (fieldType === undefined) {\n return fail('unknown component field', {\n component: componentName,\n field: fieldName,\n ...(entityKey === undefined ? {} : { entity: entityKey }),\n });\n }\n const kind = classifyEntityField(token as Component, fieldName);\n if (kind === null) {\n out[fieldName] = value;\n continue;\n }\n const remap = (address: number): number =>\n resolveAddress(address, `${componentName}.${fieldName}`) ?? address;\n // The keyed authoring model uses string addresses for scalar entity fields\n // and an address per element for array<entity>. The ECS kernel still gets\n // numeric local slots, so conversion is complete before spawn.\n if (kind.isArray) {\n if (!Array.isArray(value))\n return fail('array entity field is not an array', {\n component: componentName,\n field: fieldName,\n });\n const numeric: number[] = [];\n for (const item of value) {\n const parts = addressParts(item);\n if (parts === undefined)\n return fail('invalid entity address', {\n component: componentName,\n field: fieldName,\n address: item,\n });\n const slot = resolveAddress(parts, `${componentName}.${fieldName}`);\n if (slot === undefined)\n return fail('missing entity address target', {\n component: componentName,\n field: fieldName,\n address: parts,\n });\n numeric.push(slot);\n }\n out[fieldName] = remapEntityFieldValue(numeric, kind, remap);\n continue;\n }\n if (value === null) {\n out[fieldName] = null;\n continue;\n }\n const parts = addressParts(value);\n if (parts === undefined)\n return fail('invalid entity address', {\n component: componentName,\n field: fieldName,\n address: value,\n });\n const slot = resolveAddress(parts, `${componentName}.${fieldName}`);\n if (slot === undefined)\n return fail('missing entity address target', {\n component: componentName,\n field: fieldName,\n address: parts,\n });\n out[fieldName] = remapEntityFieldValue(slot, kind, remap);\n }\n return ok(out);\n}\n\n/**\n * Compile keyed author data to the private numeric Scene representation. The\n * compiler establishes every local and nested address before the caller starts\n * spawning entities, so malformed references and recursive instances cannot\n * leave a partially usable World projection.\n */\nexport function compileKeyedSceneAsset(\n world: World,\n handle: Handle<'SceneAsset', 'shared'>,\n asset: SceneAsset,\n context: KeyedSceneCompileContext,\n): Result<CompiledSceneResult, unknown> {\n asset = normalizeLegacySceneAsset(asset);\n if (\n asset.kind !== 'scene' ||\n asset.entities === null ||\n typeof asset.entities !== 'object' ||\n Array.isArray(asset.entities)\n ) {\n return fail('entities must be a keyed object');\n }\n const currentRaw = Number(handle);\n const activeStack = context.stack.has(currentRaw)\n ? context.stack\n : new Set([...context.stack, currentRaw]);\n const keys = keyList(asset.entities);\n if (keys.some((key) => key.length === 0)) return fail('entity keys must be non-empty');\n\n const ownKeys = keys.filter((key) => asset.entities[key]?.instance === undefined);\n const instanceKeys = keys.filter((key) => asset.entities[key]?.instance !== undefined);\n const ownSlotByKey = new Map<string, number>();\n const instanceSlotByKey = new Map<string, number>();\n const keyByLocalId = new Map<number, string>();\n for (let index = 0; index < ownKeys.length; index += 1) {\n const key = ownKeys[index] as string;\n ownSlotByKey.set(key, index);\n keyByLocalId.set(index, key);\n }\n for (let index = 0; index < instanceKeys.length; index += 1) {\n const key = instanceKeys[index] as string;\n const slot = ownKeys.length + index;\n instanceSlotByKey.set(key, slot);\n keyByLocalId.set(slot, key);\n }\n\n const childCompiled = new Map<\n string,\n { handle: Handle<'SceneAsset', 'shared'>; compiled: CompiledSceneResult }\n >();\n for (const key of instanceKeys) {\n const declaration = asset.entities[key]?.instance;\n if (\n declaration === undefined ||\n typeof declaration.source !== 'string' ||\n declaration.source.length === 0\n ) {\n return fail('instance source must be a non-empty GUID', { entity: key });\n }\n const childHandle = context.resolveSource(declaration.source, handle);\n if (!childHandle.ok) return childHandle;\n const childRaw = Number(childHandle.value);\n if (activeStack.has(childRaw)) {\n return err({\n code: 'pack-cyclic-reference',\n expected: 'acyclic SceneAsset instance graph',\n hint: PACK_ERROR_HINTS['pack-cyclic-reference'],\n detail: {\n code: 'pack-cyclic-reference',\n kind: 'mount-asset',\n cycle: [...activeStack, childRaw].map(String),\n },\n });\n }\n const childAsset = context.resolveAsset(childHandle.value);\n if (!childAsset.ok) return childAsset;\n const childContext: KeyedSceneCompileContext = {\n ...context,\n stack: activeStack,\n };\n const compiled = compileKeyedSceneAsset(\n world,\n childHandle.value,\n childAsset.value,\n childContext,\n );\n if (!compiled.ok) return compiled;\n childCompiled.set(key, { handle: childHandle.value, compiled: compiled.value });\n }\n\n const mountKeyByLocalId = new Map<number, string>();\n const mounts: SceneInstanceMount[] = [];\n let nextMemberFirst = ownKeys.length + instanceKeys.length;\n for (let index = 0; index < instanceKeys.length; index += 1) {\n const key = instanceKeys[index] as string;\n const slot = instanceSlotByKey.get(key) as number;\n const child = childCompiled.get(key) as {\n handle: Handle<'SceneAsset', 'shared'>;\n compiled: CompiledSceneResult;\n };\n const node = asset.entities[key] as SceneEntity;\n mountKeyByLocalId.set(slot, key);\n mounts.push({\n localId: slot as LocalEntityId,\n source: Number(child.handle),\n memberFirst: nextMemberFirst as LocalEntityId,\n memberCount:\n child.compiled.asset.entities.length +\n (child.compiled.asset.mounts?.length ?? 0) +\n (child.compiled.asset.mounts ?? []).reduce((sum, mount) => sum + mount.memberCount, 0),\n ...(Object.keys(node.components).length > 0 ? { components: node.components } : {}),\n });\n nextMemberFirst += mounts[index]?.memberCount ?? 0;\n }\n\n const mountByKey = new Map<string, SceneInstanceMount>();\n for (const mount of mounts)\n mountByKey.set(mountKeyByLocalId.get(Number(mount.localId)) as string, mount);\n\n const resolveInChild = (\n childResult: CompiledSceneResult,\n value: unknown,\n _field?: string,\n ): number | undefined => {\n const parts = addressParts(value);\n if (parts === undefined) return undefined;\n return childResult.resolveAddress(parts);\n };\n\n const resolveAddress = (value: unknown, field?: string): number | undefined => {\n const parts = addressParts(value);\n if (parts === undefined) return undefined;\n const first = parts[0];\n if (first === undefined) return undefined;\n const own = ownSlotByKey.get(first) ?? instanceSlotByKey.get(first);\n if (own !== undefined && parts.length === 1) return own;\n const mount = mountByKey.get(first);\n if (mount === undefined) return undefined;\n const child = childCompiled.get(first);\n if (child === undefined) return undefined;\n const childSlot = resolveInChild(child.compiled, parts.slice(1), field);\n return childSlot === undefined ? undefined : (mount.memberFirst as number) + childSlot;\n };\n\n // Instance entities carry their own authored components. They occupy the\n // mount slot in the private representation, so run the same schema driven\n // conversion as ordinary entities before any spawn occurs.\n for (const key of instanceKeys) {\n const node = asset.entities[key] as SceneEntity;\n const mount = mountByKey.get(key) as SceneInstanceMount;\n const convertedFields = Object.fromEntries(\n Object.entries(node.components).map(([componentName, raw]) => [\n componentName,\n fieldRemap(\n world,\n componentName,\n { ...(raw as Record<string, unknown>) },\n resolveAddress,\n key,\n ),\n ]),\n ) as Record<string, Result<Record<string, unknown>, unknown>>;\n const bad = Object.values(convertedFields).find((result) => !result.ok);\n if (bad !== undefined && !bad.ok) return bad;\n const components: Record<string, Record<string, unknown>> = {};\n for (const [componentName, result] of Object.entries(convertedFields)) {\n if (!result.ok) return result;\n components[componentName] = result.value;\n }\n const index = mounts.findIndex((item) => item.localId === mount.localId);\n if (index >= 0) {\n const childOf = components.ChildOf?.parent;\n // An instance declaration's ChildOf belongs to the private mount slot,\n // whose deferred parent wiring runs after own entities exist. Keeping it\n // inside mount.components would remap the parent before that slot is\n // live and silently lose the authored hierarchy edge.\n if (typeof childOf === 'number') {\n const { ChildOf: _ignored, ...mountComponents } = components;\n void _ignored;\n mounts[index] = { ...mount, components: mountComponents, parent: childOf as LocalEntityId };\n } else {\n mounts[index] = { ...mount, components };\n }\n }\n }\n\n const converted: CompiledSceneEntity[] = [];\n for (const key of ownKeys) {\n const node = asset.entities[key] as SceneEntity;\n const components: Record<string, Record<string, unknown>> = {};\n for (const [componentName, raw] of Object.entries(node.components)) {\n const convertedFields = fieldRemap(\n world,\n componentName,\n { ...(raw as Record<string, unknown>) },\n resolveAddress,\n key,\n );\n if (!convertedFields.ok) return convertedFields;\n components[componentName] = convertedFields.value;\n }\n converted.push({ localId: ownSlotByKey.get(key) as LocalEntityId, components });\n }\n\n // Convert ordered child-relative overrides into the private field patch\n // representation. Values resolve in the declaring parent namespace.\n // A component declaration that is absent on the target is represented as one\n // component-add override; an existing component stays field-granular so an\n // override cannot erase fields that were not mentioned by the author.\n const childHasComponent = (\n result: CompiledSceneResult,\n target: number,\n componentName: string,\n ): boolean => {\n const own = result.asset.entities.find((entity) => Number(entity.localId) === target);\n if (own !== undefined && own.components[componentName] !== undefined) return true;\n const mount = result.asset.mounts?.find((entry) => Number(entry.localId) === target);\n return mount?.components?.[componentName] !== undefined;\n };\n for (const key of instanceKeys) {\n const node = asset.entities[key] as SceneEntity;\n const declaration = node.instance as NonNullable<SceneEntity['instance']>;\n const mount = mountByKey.get(key) as SceneInstanceMount;\n const child = childCompiled.get(key) as { compiled: CompiledSceneResult };\n const childSlot = (target: SceneEntityAddress): number | undefined =>\n resolveInChild(child.compiled, target, `${key}.instance`);\n const overrides: MountOverride[] = [];\n for (const override of declaration.overrides ?? []) {\n const target = childSlot(override.target);\n if (target === undefined)\n return fail('instance override target does not exist', {\n entity: key,\n target: override.target,\n });\n for (const [componentName, fields] of Object.entries(override.components)) {\n const convertedFields = fieldRemap(\n world,\n componentName,\n { ...(fields as Record<string, unknown>) },\n resolveAddress,\n `${key}.instance.${override.target.join('.')}`,\n );\n if (!convertedFields.ok) return convertedFields;\n if (!childHasComponent(child.compiled, target, componentName)) {\n overrides.push({\n localId: ((mount.memberFirst as number) + target) as LocalEntityId,\n comp: componentName,\n value: convertedFields.value,\n });\n } else {\n overrides.push(\n ...Object.entries(convertedFields.value).map(([field, value]) => ({\n localId: ((mount.memberFirst as number) + target) as LocalEntityId,\n comp: componentName,\n field,\n value,\n })),\n );\n }\n }\n }\n if (overrides.length > 0) {\n const index = mounts.findIndex((item) => item.localId === mount.localId);\n const existing = mounts[index];\n if (index >= 0 && existing !== undefined) mounts[index] = { ...existing, overrides };\n }\n }\n\n const rootLocalIds: number[] = [\n ...convertedRootLocalIds(converted),\n ...mounts.filter((mount) => mount.parent === undefined).map((mount) => Number(mount.localId)),\n ];\n\n // Validate the authored hierarchy using the same keyed address resolver that\n // will be used for component fields. General component reference cycles are\n // legal; only ChildOf cycles are rejected before any spawn.\n const hierarchyParentByLocalId = new Map<number, number>();\n for (const node of converted) {\n const parent = node.components.ChildOf?.parent;\n if (typeof parent === 'number' && parent >= 0) {\n hierarchyParentByLocalId.set(Number(node.localId), parent);\n }\n }\n for (const mount of mounts) {\n if (mount.parent !== undefined) {\n hierarchyParentByLocalId.set(Number(mount.localId), mount.parent);\n }\n const key = mountKeyByLocalId.get(Number(mount.localId));\n const child = key === undefined ? undefined : childCompiled.get(key);\n if (child !== undefined) {\n for (const [childLocalId, childParent] of child.compiled.hierarchyParentByLocalId) {\n hierarchyParentByLocalId.set(\n Number(mount.memberFirst) + childLocalId,\n Number(mount.memberFirst) + childParent,\n );\n }\n for (const childRoot of child.compiled.rootLocalIds) {\n hierarchyParentByLocalId.set(Number(mount.memberFirst) + childRoot, Number(mount.localId));\n }\n }\n for (const override of mount.overrides ?? []) {\n if (override.comp !== 'ChildOf') continue;\n if (override.field === 'parent' && typeof override.value === 'number') {\n hierarchyParentByLocalId.set(Number(override.localId), override.value);\n } else if (\n override.field === undefined &&\n typeof override.value === 'object' &&\n override.value !== null\n ) {\n const parentValue = (override.value as Record<string, unknown>).parent;\n if (typeof parentValue === 'number') {\n hierarchyParentByLocalId.set(Number(override.localId), parentValue);\n }\n }\n }\n }\n for (const start of hierarchyParentByLocalId.keys()) {\n const seen = new Set<number>();\n let current: number | undefined = start;\n while (current !== undefined && hierarchyParentByLocalId.has(current)) {\n if (seen.has(current))\n return fail('hierarchy cycle', { entity: keyByLocalId.get(start), address: [...seen] });\n seen.add(current);\n current = hierarchyParentByLocalId.get(current);\n }\n }\n\n return ok({\n asset: {\n kind: 'scene',\n entities: converted,\n ...(mounts.length > 0 ? { mounts } : {}),\n ...(asset.skinGuids === undefined ? {} : { skinGuids: asset.skinGuids }),\n },\n keyByLocalId,\n mountKeyByLocalId,\n rootLocalIds,\n hierarchyParentByLocalId,\n resolveAddress,\n });\n}\n\nfunction convertedRootLocalIds(nodes: readonly CompiledSceneEntity[]): number[] {\n return nodes\n .filter((node) => node.components.ChildOf === undefined)\n .map((node) => Number(node.localId));\n}\n","// @forgeax/engine-scene — scene instantiation and instance-state subsystem.\n\nimport {\n type Component,\n type ComponentData,\n type ComponentSchema,\n type EcsError,\n ENTITY_NULL_RAW,\n type EntityHandle,\n type InputShapeOf,\n type ShapeOf,\n type World,\n} from '@forgeax/engine-ecs';\nimport { classifyEntityField, remapEntityFieldValue } from '@forgeax/engine-ecs/externalization';\nimport { componentSchema } from '@forgeax/engine-ecs/internal';\nimport { fillComponentDefaults, StaleEntityError } from '@forgeax/engine-ecs/projection';\nimport type {\n Handle,\n LocalEntityId,\n PackErrorCode,\n PackErrorDetail,\n SceneAsset,\n SceneEntityAddress,\n SceneEntityRef,\n} from '@forgeax/engine-types';\nimport {\n err,\n ok,\n PACK_ERROR_HINTS,\n type Result,\n toUnique,\n unwrapHandle,\n} from '@forgeax/engine-types';\nimport { ComponentNotDefinedError } from '../errors';\nimport { resolveSceneEntity, sceneEntityAddressKey } from './binding.js';\nimport {\n type CompiledSceneAsset,\n type CompiledSceneEntity,\n compileKeyedSceneAsset,\n} from './keyed.js';\nimport type { MountOverride, SceneInstanceMount } from './runtime-types.js';\nimport {\n isPrimitiveScalarFieldType,\n mountOverrideStateKey,\n primitiveJsType,\n type SceneInstanceStatePayload,\n sceneWorldState,\n} from './state.js';\n\nexport type { SceneInstanceStatePayload } from './state.js';\n\nconst entityIndex = (entity: EntityHandle): number => (entity as number) & 0x00ffffff;\nconst entityGeneration = (entity: EntityHandle): number => ((entity as number) >>> 24) & 0xff;\n\n/**\n * Legacy diagnostic shape retained on the scene-instantiation result for\n * non-blocking runtime observations. SceneAsset schema violations are\n * rejected by the keyed compiler before this result is produced; no authored\n * unknown-field record is emitted by the current path.\n *\n * const r = worldInstantiateScene(world, handle);\n * if (r.ok) for (const d of r.value.diagnostics)\n * console.warn('scene diagnostic', d);\n *\n * Direct `world.spawn` / `world.addComponent` / `Commands.spawn` remain\n * fail-fast with `SpawnDataUnknownFieldError`.\n */\nexport type SceneInstantiateDiagnostic = {\n /** Component name associated with the observation. */\n readonly component: string;\n /** Field associated with the observation. */\n readonly field: string;\n /** LocalEntityId within the owning SceneAsset, when applicable. */\n readonly localId: number;\n};\n\n/**\n * Success value of `worldInstantiateScene`. `root` is the synthetic scene-root\n * EntityHandle (carries `SceneInstance`); `diagnostics` contains only\n * non-blocking runtime observations. Schema-invalid authored fields fail before\n * an entity is created.\n */\nexport type SceneInstantiateOk = {\n readonly root: EntityHandle;\n readonly diagnostics: readonly SceneInstantiateDiagnostic[];\n};\n\n/**\n * Success value of `worldInstantiateSceneFlat` — the \"edit the scene itself\"\n * primitive. Unlike `instantiateScene`, NO synthetic SceneInstance root is\n * minted and NO `ChildOf` is forced onto top-level members: the scene's own\n * entities become plain top-level world entities whose hierarchy is exactly\n * their authored `ChildOf` (an entity with no `ChildOf` stays a root). `roots`\n * is the set of those top-level handles (own rootless entities + top-level\n * mount carriers). Nested prefabs inside the scene STILL materialise as their\n * own SceneInstance anchors (charter P4: instance == entity-with-SceneInstance)\n * — only THIS scene is flat.\n */\nexport type SceneInstantiateFlatOk = {\n readonly roots: EntityHandle[];\n /**\n * All mount carrier entities spawned while flattening this scene. These are\n * separate from `roots`: carriers with an authored parent are not roots,\n * but still delimit a nested prefab subtree for post-spawn hooks.\n */\n readonly mountEntities: EntityHandle[];\n readonly diagnostics: readonly SceneInstantiateDiagnostic[];\n};\n\n/**\n * @internal Intermediate produced by `_spawnSceneMembers` and consumed by both\n * the anchor finisher (`_instantiateSceneAsset`) and the flat finisher\n * (`_instantiateSceneAssetFlat`). Holds everything the shared member-spawn\n * (mounts recursion + own-entity spawn + deferred owned-parent wiring) computes,\n * before either finisher decides whether to wrap the members in a synthetic\n * SceneInstance root.\n */\nexport interface SceneMembersSpawn {\n /** LocalEntityId → live Entity u32 (ENTITY_NULL_RAW for unspawned slots). */\n readonly mapping: Uint32Array;\n /** Reverse map live Entity → LocalEntityId for override / detach bookkeeping. */\n readonly entityToLocalId: Map<EntityHandle, LocalEntityId>;\n /** Own entities that carried no `ChildOf` — the scene's authored top-level roots. */\n readonly rootEntities: EntityHandle[];\n /** Mount carriers whose `mount.parent === undefined` (default-parented). */\n readonly mountEntitiesNeedingRootParent: EntityHandle[];\n /** Every mount carrier spawned by this scene, including explicitly parented carriers. */\n readonly mountEntities: EntityHandle[];\n /**\n * The child anchor and mapping for each mount. Flat scene opening has no\n * outer SceneInstance state to own parent-namespace mount overrides, so it\n * records those overrides on this child anchor after the shared spawn pass.\n */\n readonly mountInstances: readonly {\n readonly mount: SceneInstanceMount;\n readonly root: EntityHandle;\n readonly mapping: Uint32Array;\n readonly key?: string;\n }[];\n /** `entities.length + mounts + Σ memberCount`, captured at instantiate-time. */\n readonly totalSlots: number;\n}\n\n/**\n * Populate the instance binding projection from the private numeric mapping.\n * The authored key remains the only lookup identity: nested instance paths are\n * represented as the same string/tuple key accepted by `SceneEntityRef`, while\n * the numeric mapping stays local to the Scene owner.\n */\nfunction collectSceneEntityBindings(\n world: World,\n root: EntityHandle,\n prefix: readonly string[],\n bindings: Map<string, EntityHandle>,\n visited = new Set<number>(),\n): void {\n const rootRaw = root as unknown as number;\n if (visited.has(rootRaw)) return;\n visited.add(rootRaw);\n const state = worldResolveSceneInstanceStatePayload(world, root);\n if (!state.ok) return;\n const sceneInstance = world.components.resolve('SceneInstance');\n if (sceneInstance === undefined) return;\n const component = world.get(root, sceneInstance);\n if (!component.ok) return;\n const mapping = (component.value as unknown as { mapping: ArrayLike<number> }).mapping;\n for (const [slot, key] of state.value.keyByLocalId) {\n const raw = mapping[slot];\n if (raw === undefined || raw === ENTITY_NULL_RAW) continue;\n const address: SceneEntityAddress =\n prefix.length === 0 ? key : ([...prefix, key] as unknown as [string, ...string[]]);\n bindings.set(sceneEntityAddressKey(address), raw as unknown as EntityHandle);\n }\n for (const childRoot of state.value.mountRoots) {\n const childState = worldResolveSceneInstanceStatePayload(world, childRoot);\n const childKey = childState.ok ? childState.value.instanceKey : undefined;\n if (childKey === undefined) continue;\n collectSceneEntityBindings(world, childRoot, [...prefix, childKey], bindings, visited);\n }\n}\n\nexport type SceneAssetResolver = (\n source: number | string,\n parentHandle: Handle<'SceneAsset', 'shared'>,\n) => Result<Handle<'SceneAsset', 'shared'>, unknown>;\n\n/** @internal */\nexport function worldSetSceneAssetResolver(world: World, resolver: SceneAssetResolver): void {\n sceneWorldState(world).resolver = resolver;\n}\n\n/** @internal */\nexport function worldGetSceneAssetResolver(world: World): SceneAssetResolver | null {\n return sceneWorldState(world).resolver as SceneAssetResolver | null;\n}\n\n/**\n * Materialise a SceneAsset (and any nested SceneAsset references via\n * `mounts[]`) into live entities. Returns the synthetic root Entity that\n * carries the `SceneInstance` ECS component (charter P4: instance ==\n * entity-with-SceneInstance).\n *\n * Recursion path is closed inside `_instantiateSceneRec(handle, parent,\n * stack)` (D-3); cycle detection is fail-fast `pack-cyclic-reference +\n * detail.kind:'mount-asset'` (D-1 mirror, plan-strategy §D-3). The\n * caller-supplied `parent` flows to the synthetic root's `ChildOf` so the\n * full sub-tree attaches under the AI user's host entity.\n *\n * @example\n * const r = worldInstantiateScene(world, handle);\n * if (!r.ok) return r;\n * const { root, diagnostics } = r.value;\n * for (const d of diagnostics) // non-blocking runtime observations\n * console.warn('scene diagnostic', d);\n * const inst = world.get(root, SceneInstance).value;\n * const member = inst.mapping[0]; // first member entity\n */\nexport function worldInstantiateScene(\n world: World,\n handle: Handle<'SceneAsset', 'shared'>,\n parent?: EntityHandle,\n sceneSourceKey?: string,\n): Result<SceneInstantiateOk, EcsError> {\n const stack = new Set<number>();\n // Keep the existing result shape for non-blocking runtime observations. The\n // keyed compiler rejects schema-invalid authoring data before spawning.\n const diagnostics: SceneInstantiateDiagnostic[] = [];\n const r = worldInstantiateSceneRec(\n world,\n handle,\n parent,\n stack,\n diagnostics,\n undefined,\n sceneSourceKey,\n );\n if (!r.ok) return r;\n return ok({ root: r.value, diagnostics });\n}\n\n/**\n * Materialise a projected `SceneAsset` payload without exposing the temporary\n * shared-ref handle to the caller. The World remains the owner of both the\n * handle and the instantiated SceneInstance: the producer grant is released\n * after the SceneInstance retains its source, including when instantiation\n * fails. This is the payload-shaped counterpart to `worldInstantiateScene` for\n * hosts that load a SceneAsset directly from the Engine AssetRegistry.\n */\nexport function worldInstantiateScenePayload(\n world: World,\n asset: SceneAsset,\n parent?: EntityHandle,\n): Result<SceneInstantiateOk, EcsError> {\n const handle = world.allocSharedRef('SceneAsset', asset);\n try {\n return worldInstantiateScene(world, handle, parent);\n } finally {\n // The SceneInstance source column retains the handle on success. On a\n // failed materialisation there should be no remaining holder; either way\n // release the producer grant owned by this convenience entrypoint.\n world.sharedRefs.release(handle);\n }\n}\n\n/**\n * Materialise a SceneAsset FLAT — the \"edit the scene itself\" primitive.\n * Unlike `instantiateScene`, this mints NO synthetic SceneInstance root and\n * forces NO `ChildOf` onto top-level members: the scene's own entities become\n * plain top-level world entities whose hierarchy is exactly their authored\n * `ChildOf` (an entity with no `ChildOf` is a root). Use this to OPEN a scene\n * for editing; use `instantiateScene` (anchor) at runtime / for nested\n * prefabs where an instance boundary + override isolation is wanted.\n *\n * Nested prefabs referenced via `mounts[]` STILL materialise as their own\n * SceneInstance anchors (charter P4 preserved) — only THIS top scene is flat.\n *\n * @example\n * const r = worldInstantiateSceneFlat(world, handle);\n * if (!r.ok) return r;\n * const { roots, diagnostics } = r.value; // roots = top-level handles\n */\nexport function worldInstantiateSceneFlat(\n world: World,\n handle: Handle<'SceneAsset', 'shared'>,\n): Result<SceneInstantiateFlatOk, EcsError> {\n const stack = new Set<number>();\n const diagnostics: SceneInstantiateDiagnostic[] = [];\n const handleKey = unwrapHandle(handle);\n const resolved = worldResolveSceneAsset(world, handle);\n if (!resolved.ok) return resolved;\n stack.add(handleKey);\n let r: Result<{ roots: EntityHandle[]; mountEntities: EntityHandle[] }, EcsError>;\n try {\n r = worldInstantiateSceneAssetFlat(world, handle, resolved.value, stack, diagnostics);\n } finally {\n stack.delete(handleKey);\n }\n if (!r.ok) return r;\n return ok({ ...r.value, diagnostics });\n}\n/**\n * @internal Recursive helper carrying the cycle-detection stack. Sugar /\n * other public callers must not see this mechanic — use `instantiateScene`\n * (D-3 / charter P1).\n */\nexport function worldInstantiateSceneRec(\n world: World,\n handle: Handle<'SceneAsset', 'shared'>,\n parent: EntityHandle | undefined,\n stack: Set<number>,\n diagnostics: SceneInstantiateDiagnostic[],\n instanceKey?: string,\n sceneSourceKey?: string,\n): Result<EntityHandle, EcsError> {\n const handleKey = unwrapHandle(handle);\n if (stack.has(handleKey)) {\n const cycleArr: string[] = [];\n for (const k of stack) cycleArr.push(String(k));\n cycleArr.push(String(handleKey));\n const detail: PackErrorDetail = {\n code: 'pack-cyclic-reference',\n kind: 'mount-asset',\n cycle: cycleArr,\n };\n return err({\n code: 'pack-cyclic-reference' as PackErrorCode,\n expected: 'acyclic SceneAsset mount graph',\n hint: PACK_ERROR_HINTS['pack-cyclic-reference'],\n detail,\n } as unknown as EcsError);\n }\n const resolved = worldResolveSceneAsset(world, handle);\n if (!resolved.ok) return resolved;\n const asset = resolved.value;\n stack.add(handleKey);\n try {\n return worldInstantiateSceneAsset(\n world,\n handle,\n asset,\n parent,\n stack,\n diagnostics,\n instanceKey,\n sceneSourceKey,\n );\n } finally {\n stack.delete(handleKey);\n }\n}\n/**\n * @internal Resolve a SceneAsset handle through the SharedRefStore.\n * The handle u32 is the SharedRefStore slot id (`world.allocSharedRef\n * ('SceneAsset', asset)` is the producer; rc starts at 1, the SceneInstance\n * spawn retains to rc=2 in M4 / w13). Errors propagate as EcsError so the\n * instantiateScene chain returns a single closed union.\n */\nexport function worldResolveSceneAsset(\n world: World,\n handle: Handle<'SceneAsset', 'shared'>,\n): Result<SceneAsset, EcsError> {\n const r = world.sharedRefs.resolve(handle);\n if (!r.ok) {\n return err(r.error as unknown as EcsError);\n }\n return ok(r.value as SceneAsset);\n}\n/**\n * @internal Spawn one SceneAsset's members — the shared body of both scene\n * finishers. Recurses into `mounts[]` (each nested prefab becomes its own\n * SceneInstance anchor), spawns `entities[]` honouring their authored\n * `ChildOf`, and wires deferred owned-parent mount edges. Does NOT create a\n * synthetic root or force any `ChildOf` — that is the caller's (finisher's)\n * job. `_instantiateSceneRec` owns cycle bookkeeping.\n */\nexport function worldSpawnSceneMembers(\n world: World,\n handle: Handle<'SceneAsset', 'shared'>,\n asset: CompiledSceneAsset,\n stack: Set<number>,\n diagnostics: SceneInstantiateDiagnostic[],\n mountKeys?: ReadonlyMap<number, string>,\n): Result<SceneMembersSpawn, EcsError> {\n const sceneInstanceToken = world.components.resolve('SceneInstance');\n if (sceneInstanceToken === undefined) {\n return err(new ComponentNotDefinedError('SceneInstance'));\n }\n const childOfToken = world.components.resolve('ChildOf');\n // ChildOf is optional — only needed if the asset declares ChildOf or a\n // caller-supplied parent must be wired. If absent and we need it, we\n // fail-fast at the wiring site below.\n\n const ownEntities = asset.entities;\n const ownMounts = asset.mounts ?? [];\n const memberSum = ownMounts.reduce((s, m) => s + m.memberCount, 0);\n const countBaseline = ownEntities.length + ownMounts.length + memberSum;\n // C-R1 (studio-issues #6): mapping table must be sized to maxLocalId+1,\n // not to the entity count. An editor scene may have non-contiguous\n // localIds (deleted entities leave gaps); sizing to count means any\n // localId >= count is a silent Uint32Array OOB no-op -> entity spawns\n // but is unreachable by localId -> users report \"character can't move\".\n // Take the max of count-baseline and id-range so both packed and\n // sparse scenes work without over-allocation in the common case.\n let maxLocalId = ownEntities.reduce((m, e) => Math.max(m, e.localId as unknown as number), -1);\n for (const mount of ownMounts) {\n maxLocalId = Math.max(maxLocalId, mount.localId as unknown as number);\n const last = (mount.memberFirst as unknown as number) + mount.memberCount - 1;\n maxLocalId = Math.max(maxLocalId, last);\n }\n const totalSlots = Math.max(countBaseline, maxLocalId + 1);\n\n // R2/Bonus: namespace-overlap fail-fast (AC-05 /\n // pack-mount-localid-overlap). Each LocalEntityId in\n // [0, totalSlots) must be claimed by exactly one of:\n // - entities[i].localId\n // - mounts[i].localId\n // - mounts[i] window slot (memberFirst .. memberFirst+memberCount-1)\n // Overlap or duplicate claim => fail-fast with the offending localIds\n // and human-readable origin labels.\n {\n const claims = new Map<number, string>();\n const overlapLids = new Set<number>();\n const overlapSources: string[] = [];\n const claim = (lid: number, src: string): void => {\n const prior = claims.get(lid);\n if (prior !== undefined) {\n if (!overlapLids.has(lid)) {\n overlapLids.add(lid);\n overlapSources.push(prior);\n overlapSources.push(src);\n } else {\n overlapSources.push(src);\n }\n return;\n }\n claims.set(lid, src);\n };\n for (const ent of ownEntities) {\n claim(ent.localId as unknown as number, `entities[${ent.localId as unknown as number}]`);\n }\n for (const mount of ownMounts) {\n const mLid = mount.localId as unknown as number;\n claim(mLid, `mount[${mLid}]`);\n const first = mount.memberFirst as unknown as number;\n for (let k = 0; k < mount.memberCount; k += 1) {\n claim(first + k, `mount[${mLid}].member[${k}]`);\n }\n }\n if (overlapLids.size > 0) {\n const overlapping = Array.from(overlapLids).sort((a, b) => a - b);\n return err({\n code: 'pack-mount-localid-overlap' as PackErrorCode,\n expected: 'each LocalEntityId claimed by exactly one entity or mount slot',\n hint: PACK_ERROR_HINTS['pack-mount-localid-overlap'],\n detail: {\n code: 'pack-mount-localid-overlap',\n overlapping,\n sources: overlapSources,\n } as PackErrorDetail,\n } as unknown as EcsError);\n }\n }\n\n // Slot table: indexed by LocalEntityId; populated as entities / mounts /\n // members are spawned. mapping[localId] = encoded Entity u32. Unspawned\n // slots hold ENTITY_NULL_RAW (0xffffffff) — NOT 0, because a fresh World's\n // first spawn encodes to gen=0+idx=0=raw 0, which is a valid Entity. The\n // remap path in `_buildSceneEntityComponentDatas` distinguishes the two\n // (live=ENTITY_NULL_RAW => parent unspawned at remap time => surface as\n // null sentinel; live=any other u32 => valid live Entity, including 0).\n const mapping = new Uint32Array(totalSlots).fill(ENTITY_NULL_RAW);\n const entityToLocalId = new Map<EntityHandle, LocalEntityId>();\n const rootEntities: EntityHandle[] = [];\n const mountEntities: EntityHandle[] = [];\n // R2/B-1: mount entities whose `mount.parent === undefined` need their\n // ChildOf wired to the outer synthetic root (this scene's root). Step 5\n // does the wiring once the synthetic root entity is materialised; we\n // collect them here in step 1.\n const mountEntitiesNeedingRootParent: EntityHandle[] = [];\n // D-8 (feat-20260707): mount entities whose `mount.parent` points at an\n // OWNED entity slot are wired AFTER step 2 spawns the owned entities —\n // mounts are processed first (step 1), so the owned parent slot is still\n // ENTITY_NULL_RAW at mount-processing time. Same deferred-wiring shape as\n // mountEntitiesNeedingRootParent: register [mountEntity, parentSlot] here,\n // wire ChildOf once the slot is live. Without this the edge was silently\n // dropped, and the mount carrier stayed unreachable from its owned parent.\n const mountEntitiesNeedingDeferredParent: Array<[EntityHandle, number]> = [];\n const mountInstances: Array<{\n readonly mount: SceneInstanceMount;\n readonly root: EntityHandle;\n readonly mapping: Uint32Array;\n }> = [];\n\n // 1. Recurse into mounts[] FIRST so the mount-window slots\n // (`mount.localId` + `[memberFirst, memberFirst+memberCount)`) are\n // populated before any owned entity tries to remap a LocalEntityId\n // pointing into the mount window (AC-24 cross-boundary reference).\n for (const mount of ownMounts) {\n // R2/B-3 + R2/B-4: validate overrides BEFORE child resolution so a\n // malformed override fails fast without observable side-effects.\n const overrideValidationRes = worldValidateMountOverrides(world, mount);\n if (!overrideValidationRes.ok) {\n return overrideValidationRes;\n }\n\n // Spawn the mount entity (carries mount.components).\n const mountLid = mount.localId as unknown as number;\n const mountSpawnRes = worldSpawnMountEntity(world, mount, mapping, diagnostics);\n if (!mountSpawnRes.ok) return mountSpawnRes;\n const mountEntity = mountSpawnRes.value;\n mountEntities.push(mountEntity);\n mapping[mountLid] = mountEntity as unknown as number;\n\n // Resolve mount.source -> child SceneAsset handle.\n const childHandleRes = worldResolveMountSource(world, mount.source, handle);\n if (!childHandleRes.ok) return childHandleRes;\n const childHandle = childHandleRes.value;\n\n // Recursively instantiate the child. Its synthetic root attaches as a\n // child of the mount entity; runtime observations share the same result\n // accumulator and bubble to the top-level instance.\n const childRes = worldInstantiateSceneRec(\n world,\n childHandle,\n mountEntity,\n stack,\n diagnostics,\n mountKeys?.get(mountLid),\n );\n if (!childRes.ok) return childRes;\n\n // R2/B-2: cross-check mount.memberCount === child.totalSlots BEFORE\n // copying the mount window. The child SceneInstance.mapping length is\n // the authoritative `totalSlots` of the child. AC-04 / requirements\n // S-5 mandate fail-fast at runtime for this disagreement.\n const childInstRes = world.get(childRes.value, sceneInstanceToken);\n if (!childInstRes.ok) return childInstRes;\n const childMapping = (childInstRes.value as unknown as { mapping: Uint32Array }).mapping;\n mountInstances.push({\n mount,\n root: childRes.value,\n mapping: childMapping,\n ...(mountKeys?.get(mountLid) === undefined ? {} : { key: mountKeys.get(mountLid) }),\n });\n if (childMapping.length !== mount.memberCount) {\n return err({\n code: 'pack-mount-count-mismatch' as PackErrorCode,\n expected: 'mount.memberCount === child SceneAsset totalSlots',\n hint: PACK_ERROR_HINTS['pack-mount-count-mismatch'],\n detail: {\n code: 'pack-mount-count-mismatch',\n mountLocalId: mountLid,\n declared: mount.memberCount,\n actual: childMapping.length,\n } as PackErrorDetail,\n } as unknown as EcsError);\n }\n\n // Pull the child's mapping into our parent window. Default unset slots\n // to ENTITY_NULL_RAW so downstream \"live\" checks distinguish them from\n // the first Entity (gen=0+idx=0 encodes to raw u32 0).\n const window = mount.memberCount;\n for (let k = 0; k < window; k += 1) {\n mapping[(mount.memberFirst as unknown as number) + k] = childMapping[k] ?? ENTITY_NULL_RAW;\n }\n\n // Apply mount.overrides at instantiate-time (AC-19).\n // Each override.localId addresses a slot in *this* (parent) namespace\n // (R2/F-8 cement: parent-namespace + memberFirst+offset addressing).\n // The state map will be populated below with these overrides — but we\n // must also write the value through to the live entity column so the\n // readback invariant holds.\n // Mount-entity itself never has children attached by the caller other\n // than via the recursive child; nothing else to wire here.\n if (childOfToken !== undefined) {\n if (mount.parent !== undefined) {\n // Reparent the mount-entity ChildOf to the caller-specified parent.\n const parentSlot = mount.parent as unknown as number;\n const parentEntity = mapping[parentSlot];\n if (parentEntity !== undefined && parentEntity !== ENTITY_NULL_RAW) {\n const r = world.addComponent(mountEntity, {\n component: childOfToken,\n data: { parent: parentEntity } as never,\n });\n if (!r.ok) {\n // ChildOf may already be present from layer-1; reparent via set.\n const set = world.set(mountEntity, childOfToken, {\n parent: parentEntity,\n } as never);\n if (!set.ok) return set as Result<SceneMembersSpawn, EcsError>;\n }\n } else {\n // D-8: the owned parent slot is not spawned yet (owned entities\n // spawn in step 2, after this mount loop). Defer the ChildOf wire\n // to step 2's tail once mapping[parentSlot] is live.\n mountEntitiesNeedingDeferredParent.push([mountEntity, parentSlot]);\n }\n } else {\n // R2/B-1: default semantic — mount.parent === undefined wires the\n // mount entity ChildOf to *this* scene's synthetic root (created\n // in step 3 below). Defer the actual wire to step 5 after the\n // synthetic root spawn; record the mount entity here.\n mountEntitiesNeedingRootParent.push(mountEntity);\n }\n }\n }\n\n // 2. Spawn entities[] entities. Topo-sort by ChildOf so parents are\n // spawned before children (so localId remap can read mapping live).\n // This runs AFTER mount processing (step 1) so cross-boundary\n // `ChildOf {parent: <mount-window-localId>}` references resolve\n // correctly (AC-24).\n const order = sceneTopoSort(ownEntities);\n for (const idx of order) {\n const node = ownEntities[idx];\n if (node === undefined) continue;\n const lid = node.localId as unknown as number;\n const compDataRes = worldBuildSceneEntityComponentDatas(world, node, mapping, diagnostics);\n if (!compDataRes.ok) return compDataRes;\n const sp = (world.spawn as (...c: ComponentData[]) => Result<EntityHandle, EcsError>)(\n ...compDataRes.value,\n );\n if (!sp.ok) return sp as Result<SceneMembersSpawn, EcsError>;\n const e = sp.value;\n mapping[lid] = e as unknown as number;\n entityToLocalId.set(e, lid as unknown as LocalEntityId);\n if (node.components.ChildOf === undefined) {\n rootEntities.push(e);\n }\n }\n\n // 2b. D-8 (feat-20260707): wire deferred owned-parent mount ChildOf edges.\n // Owned entities are now live (step 2 above), so mapping[parentSlot]\n // resolves. Same shape as the mountEntitiesNeedingRootParent wiring in\n // step 5. The relationship mirror hook (relationshipOnInsert) pushes the\n // carrier into the owned parent's Children mirror automatically.\n if (childOfToken !== undefined) {\n for (const [mountEntity, parentSlot] of mountEntitiesNeedingDeferredParent) {\n const parentEntity = mapping[parentSlot];\n if (parentEntity === undefined || parentEntity === ENTITY_NULL_RAW) continue;\n const set = world.set(mountEntity, childOfToken, { parent: parentEntity } as never);\n if (!set.ok) {\n const r = world.addComponent(mountEntity, {\n component: childOfToken,\n data: { parent: parentEntity } as never,\n });\n if (!r.ok) return r as Result<SceneMembersSpawn, EcsError>;\n }\n }\n }\n\n return ok({\n mapping,\n entityToLocalId,\n rootEntities,\n mountEntitiesNeedingRootParent,\n mountEntities,\n mountInstances,\n totalSlots,\n });\n}\n/**\n * @internal Spawn one SceneAsset's entities + apply mounts recursively, then\n * wrap them in a synthetic SceneInstance root (the anchor). This is the\n * runtime / Play / nested-mount finisher (charter P4: instance ==\n * entity-with-SceneInstance). Caller (`_instantiateSceneRec`) owns cycle\n * bookkeeping.\n */\nexport function worldInstantiateSceneAsset(\n world: World,\n handle: Handle<'SceneAsset', 'shared'>,\n asset: SceneAsset,\n parent: EntityHandle | undefined,\n stack: Set<number>,\n diagnostics: SceneInstantiateDiagnostic[],\n instanceKey?: string,\n sceneSourceKey?: string,\n): Result<EntityHandle, EcsError> {\n const sceneInstanceToken = world.components.resolve('SceneInstance');\n if (sceneInstanceToken === undefined) {\n return err(new ComponentNotDefinedError('SceneInstance'));\n }\n const childOfToken = world.components.resolve('ChildOf');\n\n const compiled = compileKeyedSceneAsset(world, handle, asset, {\n resolveSource: (source, parentHandle) => worldResolveMountSource(world, source, parentHandle),\n resolveAsset: (childHandle) => worldResolveSceneAsset(world, childHandle),\n stack,\n });\n if (!compiled.ok) return err(compiled.error as EcsError);\n const compiledAsset = compiled.value.asset;\n const membersRes = worldSpawnSceneMembers(\n world,\n handle,\n compiledAsset,\n stack,\n diagnostics,\n compiled.value.mountKeyByLocalId,\n );\n if (!membersRes.ok) return membersRes;\n const { mapping, entityToLocalId, rootEntities, mountEntitiesNeedingRootParent, totalSlots } =\n membersRes.value;\n const { mountInstances } = membersRes.value;\n const ownMounts = compiledAsset.mounts ?? [];\n\n // 3. Spawn the synthetic root entity carrying SceneInstance.\n // First alloc the state ref so the SceneInstance.state column has a\n // live u32; then attach SceneInstance to a fresh entity.\n let stateRef: Handle<'SceneInstanceState', 'unique'>;\n stateRef = world.allocUniqueRef('SceneInstanceState', null, () => {\n sceneWorldState(world).statePayloads.delete(Number(stateRef));\n });\n // Spawn the root with SceneInstance component, mapping snapshot, and\n // state ref. The mapping is a Uint32Array (array<entity> field shape).\n // Convert mapping Uint32Array to plain number[] for spawn write — the\n // ECS array<entity> arm copies element-by-element and accepts both, but\n // the plain-array form sidesteps a Uint32Array.length=0 corner case\n // observed during M2 testing where a non-empty Uint32Array was written\n // as if empty (suspect: archetype write-array dispatch on instanceof\n // Array vs TypedArray).\n const mappingPlain: number[] = Array.from(mapping);\n // The synthetic root is the ChildOf parent of every owned root entity\n // (step 5 below) and may itself become a ChildOf parent of a caller-\n // supplied `parent` chain. propagateTransforms expands the ECS-maintained\n // Children lists parent-first and treats a parent missing Transform\n // as `hierarchy-broken`, so the synthetic root must carry Transform\n // (identity TRS via layer-2 defaults) when Transform is defined.\n const rootComponents: ComponentData[] = [\n {\n component: sceneInstanceToken,\n data: {\n source: handle,\n mapping: mappingPlain,\n state: stateRef,\n } as never,\n },\n ];\n const transformToken = world.components.resolve('Transform');\n if (transformToken !== undefined) {\n rootComponents.push({\n component: transformToken,\n data: {} as never,\n });\n }\n const rootSpawn = (world.spawn as (...c: ComponentData[]) => Result<EntityHandle, EcsError>)(\n ...rootComponents,\n );\n if (!rootSpawn.ok) {\n return rootSpawn;\n }\n const rootEntity = rootSpawn.value;\n\n // 4. Build SceneInstanceState payload + register it in the UniqueRefStore\n // under the same handle. We use the public `_setUniqueRefPayload`\n // helper (added below) so the alloc -> populate sequence stays atomic.\n const overrides = new Map<LocalEntityId, Map<string, MountOverride>>();\n for (const mount of ownMounts) {\n for (const ov of mount.overrides ?? []) {\n // feat-20260713 M2 / w8: `MountOverride.field` is optional (add-or-patch\n // discriminant carried by the shape itself). Record the override into\n // the SceneInstanceState map keyed by comp (no field) or comp:field\n // (field-patch), then apply it to the live member column via the shared\n // add-or-patch helper.\n const lid = ov.localId as unknown as LocalEntityId;\n let fieldMap = overrides.get(lid);\n if (fieldMap === undefined) {\n fieldMap = new Map();\n overrides.set(lid, fieldMap);\n }\n fieldMap.set(mountOverrideStateKey(ov), ov);\n // Apply override to the live member entity column.\n const memberEntityRaw = mapping[lid as unknown as number];\n if (memberEntityRaw !== undefined && memberEntityRaw !== ENTITY_NULL_RAW) {\n const memberEntity = memberEntityRaw as unknown as EntityHandle;\n const applyRes = worldApplyMountOverride(\n world,\n memberEntity,\n worldRemapMountOverride(world, ov, mapping),\n );\n if (!applyRes.ok) {\n return applyRes as Result<EntityHandle, EcsError>;\n }\n }\n }\n }\n\n const detached = new Set<LocalEntityId>();\n const bindings = new Map<string, EntityHandle>();\n const state: Record<string, unknown> = {\n source: handle,\n ...(sceneSourceKey === undefined ? {} : { sceneSourceKey }),\n keyByLocalId: new Map(compiled.value.keyByLocalId),\n ...(instanceKey === undefined ? {} : { instanceKey }),\n bindings,\n entityToLocalId,\n detachedLocalIds: detached,\n // Convert overrides Map<LocalEntityId, Map<string, MountOverride>>\n // into Map<LocalEntityId, Map<string, SceneInstanceOverrideRecord>>\n overrides: worldMountOverridesToStateMap(overrides),\n rootEntities,\n mountRoots: mountInstances.map(({ root }) => root),\n totalSlots,\n mountTimeOverrides: ownMounts.flatMap((m) => m.overrides ?? []),\n };\n // Stuff the state into the UniqueRefStore under the existing slot. We\n // re-use the slot we allocated above by writing directly into the\n // payloads map via a `_setUniqueRefPayload` shim.\n worldSetUniqueRefPayload(world, stateRef, state);\n // Populate direct and nested keyed addresses only after this root state is\n // visible. Child SceneInstance states were published by the recursive spawn\n // above, so the same walk can project the complete address closure.\n collectSceneEntityBindings(world, rootEntity, [], bindings);\n\n // 5. Wire ChildOf for every owned root entity (no ChildOf at layer-1)\n // to the synthetic root.\n if (childOfToken !== undefined) {\n for (const rootE of rootEntities) {\n const has = world.get(rootE, childOfToken);\n if (!has.ok) {\n // No ChildOf yet — attach to synthetic root.\n const r = world.addComponent(rootE, {\n component: childOfToken,\n data: { parent: rootEntity } as never,\n });\n if (!r.ok) return r as Result<EntityHandle, EcsError>;\n }\n }\n // R2/B-1: wire mount entities with default `mount.parent === undefined`\n // to this scene's synthetic root. _spawnMountEntity may have attached a\n // placeholder ChildOf {parent: ENTITY_NULL_RAW} when mount.components\n // was empty; overwrite via set so the ChildOf chain meshRenderer ->\n // childSyntheticRoot -> mountEntity -> outerSyntheticRoot resolves\n // through Transform-bearing parents (AC-16 / requirements S-7).\n for (const mountE of mountEntitiesNeedingRootParent) {\n const set = world.set(mountE, childOfToken, { parent: rootEntity } as never);\n if (!set.ok) {\n const r = world.addComponent(mountE, {\n component: childOfToken,\n data: { parent: rootEntity } as never,\n });\n if (!r.ok) return r as Result<EntityHandle, EcsError>;\n }\n }\n // Caller-supplied parent: synthetic root's ChildOf -> parent.\n if (parent !== undefined) {\n const r = world.addComponent(rootEntity, {\n component: childOfToken,\n data: { parent } as never,\n });\n if (!r.ok) return r as Result<EntityHandle, EcsError>;\n }\n }\n\n return ok(rootEntity);\n}\n/**\n * @internal Flat finisher — spawn one SceneAsset's members WITHOUT wrapping\n * them in a synthetic SceneInstance root and WITHOUT forcing `ChildOf` onto\n * top-level members. Used for \"opening a scene to edit\": the scene's own\n * entities become plain top-level world entities whose hierarchy is exactly\n * their authored `ChildOf`. Nested prefabs inside still materialise as their\n * own SceneInstance anchors (the mount recursion in `_spawnSceneMembers` is\n * always anchored). Returns the top-level handles (own rootless entities +\n * top-level mount carriers).\n */\nexport function worldInstantiateSceneAssetFlat(\n world: World,\n handle: Handle<'SceneAsset', 'shared'>,\n asset: SceneAsset,\n stack: Set<number>,\n diagnostics: SceneInstantiateDiagnostic[],\n): Result<{ roots: EntityHandle[]; mountEntities: EntityHandle[] }, EcsError> {\n const compiled = compileKeyedSceneAsset(world, handle, asset, {\n resolveSource: (source, parentHandle) => worldResolveMountSource(world, source, parentHandle),\n resolveAsset: (childHandle) => worldResolveSceneAsset(world, childHandle),\n stack,\n });\n if (!compiled.ok) return err(compiled.error as EcsError);\n const membersRes = worldSpawnSceneMembers(\n world,\n handle,\n compiled.value.asset,\n stack,\n diagnostics,\n compiled.value.mountKeyByLocalId,\n );\n if (!membersRes.ok) return membersRes;\n const { rootEntities, mountEntitiesNeedingRootParent, mountEntities, mountInstances } =\n membersRes.value;\n const childOfToken = world.components.resolve('ChildOf');\n\n // Apply parent mount overrides to the live columns and record them on the\n // nested child anchor. Flat mode has no outer SceneInstance state; without\n // this hand-authored mounts[].overrides affect the live value but disappear\n // from the child state, so Gateway re-open cannot discover or revert them.\n for (const { mount, root, mapping: childMapping } of mountInstances) {\n const childStateRes = worldGetSceneInstanceState(world, root);\n if (!childStateRes.ok) return childStateRes;\n for (const ov of mount.overrides ?? []) {\n const childLocalId =\n (ov.localId as unknown as number) - (mount.memberFirst as unknown as number);\n const memberEntityRaw = childMapping[childLocalId];\n if (memberEntityRaw === undefined || memberEntityRaw === ENTITY_NULL_RAW) continue;\n const memberEntity = memberEntityRaw as unknown as EntityHandle;\n const applyRes = worldApplyMountOverride(\n world,\n memberEntity,\n worldRemapMountOverride(world, ov, childMapping),\n );\n if (!applyRes.ok) {\n return applyRes as Result<\n { roots: EntityHandle[]; mountEntities: EntityHandle[] },\n EcsError\n >;\n }\n let fieldMap = childStateRes.value.overrides.get(childLocalId as LocalEntityId);\n if (fieldMap === undefined) {\n fieldMap = new Map();\n childStateRes.value.overrides.set(childLocalId as LocalEntityId, fieldMap);\n }\n fieldMap.set(mountOverrideStateKey(ov), {\n comp: ov.comp,\n ...(ov.field === undefined ? {} : { field: ov.field }),\n value: ov.value,\n });\n }\n }\n\n // Default-parented mount carriers (`mount.parent === undefined`) would, in\n // anchor mode, attach to the synthetic root. Flat mode has none, so they\n // stay top-level. `_spawnMountEntity` may have left a placeholder\n // `ChildOf {parent: ENTITY_NULL_RAW}` (rare: mount with no components AND\n // Transform unregistered) — strip it so the carrier is a genuine root.\n if (childOfToken !== undefined) {\n for (const mountE of mountEntitiesNeedingRootParent) {\n const co = world.get(mountE, childOfToken);\n if (co.ok && (co.value as { parent: number }).parent === ENTITY_NULL_RAW) {\n world.removeComponent(mountE, childOfToken);\n }\n }\n }\n\n return ok({ roots: [...rootEntities, ...mountEntitiesNeedingRootParent], mountEntities });\n}\n/** @internal Build ComponentData[] for one SceneEntity, remapping localIds.\n *\n * SceneAsset payloads use the same schema contract as explicit ECS writes.\n * Unknown fields fail before the first entity is spawned, with the component\n * schema's structured error. The source object is never mutated.\n */\nexport function worldBuildSceneEntityComponentDatas(\n world: World,\n node: CompiledSceneEntity,\n mapping: Uint32Array,\n _diagnostics: SceneInstantiateDiagnostic[],\n): Result<ComponentData[], EcsError> {\n const out: ComponentData[] = [];\n const nodeLocalId = node.localId as unknown as number;\n for (const compName of Object.keys(node.components)) {\n const token = world.components.resolve(compName);\n if (token === undefined) {\n return err(new ComponentNotDefinedError(compName));\n }\n const raw = node.components[compName] ?? {};\n const schema = componentSchema(token) as Record<string, string>;\n const remappedRaw: Record<string, unknown> = {};\n for (const fieldName of Object.keys(raw)) {\n const fieldType = schema[fieldName];\n // Do not mutate the source `raw`. SceneAsset compilation normally catches\n // this earlier; this guard keeps the private numeric projection fail-fast\n // for callers that provide a precompiled asset.\n if (fieldType === undefined) {\n return err({\n code: 'spawn-data-unknown-field',\n expected: `field name in {${Object.keys(schema).sort().join(', ')}}`,\n hint: `unknown field '${fieldName}' on component '${compName}' at scene localId ${nodeLocalId}`,\n detail: {\n component: compName,\n field: fieldName,\n entity: nodeLocalId,\n knownFields: Object.keys(schema).sort(),\n },\n } as unknown as EcsError);\n }\n const value = (raw as Record<string, unknown>)[fieldName];\n const kind = classifyEntityField(token, fieldName);\n if (kind !== null) {\n // Entity / array<entity> field — remap through the shared kernel.\n // localId -> live Entity. Slots not yet spawned hold ENTITY_NULL_RAW.\n const sceneRemap = (localId: number): number => {\n if (localId < 0 || localId >= mapping.length) return ENTITY_NULL_RAW;\n const live = mapping[localId];\n return live === undefined || live === ENTITY_NULL_RAW ? ENTITY_NULL_RAW : live;\n };\n remappedRaw[fieldName] = remapEntityFieldValue(value, kind, sceneRemap);\n } else {\n remappedRaw[fieldName] = value;\n }\n }\n const filled = fillComponentDefaults(token, remappedRaw);\n out.push({ component: token, data: filled as never });\n }\n return ok(out);\n}\n\n/**\n * Resolve the private local-slot values produced by keyed SceneAsset\n * compilation before an instance override is written to a live ECS row.\n * Override references are authored in the declaring parent namespace, while\n * `worldApplyMountOverride` deliberately accepts ordinary live component data.\n */\nfunction worldRemapMountOverride(\n world: World,\n override: MountOverride,\n mapping: Uint32Array,\n): MountOverride {\n const token = world.components.resolve(override.comp);\n if (token === undefined) return override;\n const remapField = (field: string, value: unknown): unknown => {\n const kind = classifyEntityField(token as Component, field);\n if (kind === null) return value;\n const toLive = (slot: number): number => {\n if (slot < 0 || slot >= mapping.length) return ENTITY_NULL_RAW;\n return mapping[slot] ?? ENTITY_NULL_RAW;\n };\n return remapEntityFieldValue(value, kind, toLive);\n };\n if (override.field !== undefined) {\n return { ...override, value: remapField(override.field, override.value) };\n }\n if (\n typeof override.value !== 'object' ||\n override.value === null ||\n Array.isArray(override.value)\n ) {\n return override;\n }\n const value: Record<string, unknown> = {};\n for (const [field, fieldValue] of Object.entries(override.value as Record<string, unknown>)) {\n value[field] = remapField(field, fieldValue);\n }\n return { ...override, value };\n}\n\n/**\n * @internal feat-20260713 M2 / w8: apply one MountOverride to a live member\n * entity column. The `field?` shape is the add-or-patch discriminant:\n *\n * - `field` present -> PATCH one field: `world.set(member, comp, {[field]:\n * value})`. Omitted fields keep their authored / existing values.\n * - `field` absent -> ADD/UPSERT the whole component: `value` is the\n * per-field value map for `comp`. When the member already carries `comp`\n * it is upserted (set-over each supplied field + schema defaults for the\n * omitted ones — the whole component is rewritten from the value map +\n * defaults, never a `component-already-present` error). When absent it is\n * added fresh via `addComponent` (fillComponentDefaults fills omitted\n * fields). The value-map is fed through `fillComponentDefaults` so the\n * add and upsert paths write byte-identical rows.\n *\n * Component registration + value-key validation happened at\n * `_validateMountOverrides` (fail-fast before any spawn); by this point the\n * comp resolves through the World-local catalog and the value keys are schema-valid.\n * still guards defensively (an unregistered comp is a no-op skip, matching\n * the prior field-patch behaviour). Returns the underlying set / addComponent\n * Result so a shared-field value gate (D-4) or any other write error\n * propagates unchanged.\n */\nexport function worldApplyMountOverride(\n world: World,\n member: EntityHandle,\n ov: MountOverride,\n): Result<void, EcsError> {\n const ovToken = world.components.resolve(ov.comp);\n if (ovToken === undefined) return ok(undefined);\n if (ov.field !== undefined) {\n // PATCH one field.\n return world.set(member, ovToken, { [ov.field]: ov.value } as never);\n }\n // ADD/UPSERT the whole component. Fill omitted fields from the schema so\n // add and upsert produce identical rows (upsert = full rewrite from the\n // value map + defaults).\n const rawValue = (ov.value ?? {}) as Record<string, unknown>;\n const filled = fillComponentDefaults(ovToken as Component, rawValue);\n const has = world.get(member, ovToken);\n if (has.ok) {\n // Already present -> upsert (set every filled field, no duplicate error).\n return world.set(member, ovToken, filled as never);\n }\n return world.addComponent(member, { component: ovToken, data: filled as never });\n}\n/**\n * @internal R2/B-3 + R2/B-4: validate `mount.overrides[]` BEFORE any\n * spawn so a malformed override fails fast with no observable side\n * effects (charter P3 explicit-failure). Two checks:\n *\n * 1. `override.localId` must address a slot inside the parent-namespace\n * member window `[memberFirst, memberFirst + memberCount)` (AC-06).\n * 2. `override.field` must exist in the resolved component schema\n * (AC-07). When the component is unregistered we cannot validate the\n * field shape; let the existing fall-through path proceed (the\n * catalog guard inside the override-application loop\n * will skip the write).\n */\nexport function worldValidateMountOverrides(\n world: World,\n mount: SceneInstanceMount,\n): Result<void, EcsError> {\n const overrides = mount.overrides;\n if (overrides === undefined) return ok(undefined);\n const memberFirst = mount.memberFirst as unknown as number;\n const memberCount = mount.memberCount;\n const memberLast = memberFirst + memberCount;\n const mountLid = mount.localId as unknown as number;\n for (const ov of overrides) {\n const ovLid = ov.localId as unknown as number;\n // R2/B-3: parent-namespace check — override.localId must lie in the\n // member window [memberFirst, memberFirst + memberCount).\n if (ovLid < memberFirst || ovLid >= memberLast) {\n return err({\n code: 'pack-mount-override-localid-out-of-range' as PackErrorCode,\n expected: `override.localId in [${memberFirst}, ${memberLast})`,\n hint: PACK_ERROR_HINTS['pack-mount-override-localid-out-of-range'],\n detail: {\n code: 'pack-mount-override-localid-out-of-range',\n overrideLocalId: ovLid,\n mountLocalId: mountLid,\n memberCount,\n } as PackErrorDetail,\n } as unknown as EcsError);\n }\n // feat-20260713 M2 / w8: double-branch schema check.\n // - field-patch form (field present): the component (when registered)\n // must declare `override.field` in its schema (R2/B-4, unchanged).\n // - component-add form (field absent): the component MUST be registered\n // (component-not-defined otherwise) AND every key in the value map\n // must be a schema field (pack-mount-override-unknown-field).\n const ovToken = world.components.resolve(ov.comp);\n if (ov.field !== undefined) {\n if (ovToken !== undefined) {\n const schema = componentSchema(ovToken) as Record<string, unknown>;\n if (!(ov.field in schema)) {\n return err({\n code: 'pack-mount-override-unknown-field' as PackErrorCode,\n expected: `override.field defined on component '${ov.comp}'`,\n hint: PACK_ERROR_HINTS['pack-mount-override-unknown-field'],\n detail: {\n code: 'pack-mount-override-unknown-field',\n comp: ov.comp,\n field: ov.field,\n mountLocalId: mountLid,\n } as PackErrorDetail,\n } as unknown as EcsError);\n }\n }\n } else {\n // component-add form: comp must be registered so we can validate + apply\n // the whole component (add/upsert needs the schema).\n if (ovToken === undefined) {\n return err(new ComponentNotDefinedError(ov.comp));\n }\n const schema = componentSchema(ovToken) as Record<string, unknown>;\n const valueMap = (ov.value ?? {}) as Record<string, unknown>;\n for (const key of Object.keys(valueMap)) {\n if (!(key in schema)) {\n return err({\n code: 'pack-mount-override-unknown-field' as PackErrorCode,\n expected: `override.value keys defined on component '${ov.comp}'`,\n hint: PACK_ERROR_HINTS['pack-mount-override-unknown-field'],\n detail: {\n code: 'pack-mount-override-unknown-field',\n comp: ov.comp,\n field: key,\n mountLocalId: mountLid,\n } as PackErrorDetail,\n } as unknown as EcsError);\n }\n }\n }\n }\n return ok(undefined);\n}\n/** @internal Spawn the mount-entity slot carrying mount.components (if any).\n *\n * R2/B-1: the mount entity is a structural intermediate in the ChildOf\n * chain `cube -> innerSyntheticRoot -> mountEntity -> outerSyntheticRoot`,\n * so it MUST carry Transform whenever Transform is registered (mirrors\n * the D-V-0 synthetic-root invariant). Otherwise propagateTransforms\n * expanding the chain hits a Transform-less parent and emits per-frame\n * `RhiError(hierarchy-broken)` (verify R1 root cause of the\n * hello-scene-nesting demo black frames).\n */\nexport function worldSpawnMountEntity(\n world: World,\n mount: SceneInstanceMount,\n mapping: Uint32Array,\n diagnostics: SceneInstantiateDiagnostic[],\n): Result<EntityHandle, EcsError> {\n const fakeNode: CompiledSceneEntity = {\n localId: mount.localId,\n components: mount.components ?? {},\n };\n const cdRes = worldBuildSceneEntityComponentDatas(world, fakeNode, mapping, diagnostics);\n if (!cdRes.ok) return cdRes;\n // R2/B-1: ensure Transform is attached so propagateTransforms can expand\n // through this entity. Layer-2 defaults supply identity TRS; the\n // mount.components overlay (when present and including Transform) takes\n // precedence and is already in cdRes.value.\n const transformToken = world.components.resolve('Transform');\n if (transformToken !== undefined) {\n const hasTransform = cdRes.value.some((c) => c.component === transformToken);\n if (!hasTransform) {\n cdRes.value.push({ component: transformToken, data: {} as never });\n }\n }\n if (cdRes.value.length === 0) {\n // Mount has no components AND Transform is unregistered (rare unit-\n // test path). Fall back to the placeholder ChildOf so the spawn has\n // a real archetype. Step 5 overwrites this placeholder.\n const childOfToken = world.components.resolve('ChildOf');\n if (childOfToken === undefined) {\n return err(new ComponentNotDefinedError('ChildOf'));\n }\n cdRes.value.push({\n component: childOfToken,\n data: { parent: ENTITY_NULL_RAW } as never,\n });\n }\n return (world.spawn as (...c: ComponentData[]) => Result<EntityHandle, EcsError>)(...cdRes.value);\n}\n/** @internal Resolve mount.source through the wired SceneAssetResolver. */\nexport function worldResolveMountSource(\n world: World,\n source: number | string,\n parentHandle: Handle<'SceneAsset', 'shared'>,\n): Result<Handle<'SceneAsset', 'shared'>, EcsError> {\n const resolver = worldGetSceneAssetResolver(world);\n if (resolver === null) {\n return err({\n code: 'stale-entity' as const,\n expected: 'wired SceneAssetResolver (auto-wired by engine.assets.instantiate)',\n hint:\n 'engine.assets.instantiate sugar wires this for you; ' +\n 'call worldSetSceneAssetResolver before nested scene expansion.',\n detail: { entity: 0, slot: 0, generation: 0 },\n } as unknown as EcsError);\n }\n const r = resolver(source, parentHandle);\n if (!r.ok) {\n // Resolver carries `unknown` err (loose contract — engine-runtime may\n // wire any shape); narrow back to EcsError here at the boundary.\n return err(r.error as EcsError);\n }\n return ok(r.value);\n}\n/** @internal Convert mount.overrides Map shape to the SceneInstanceState shape.\n *\n * feat-20260713 M1 / w4: `field` is optional (add-or-patch discriminant). In\n * M1 only the field-patch form reaches this builder (the component-add form\n * fails fast in the apply loops); the record type stays `field?: string` so\n * the M2 add path can flow through untouched. `exactOptionalPropertyTypes`\n * forbids writing an explicit `field: undefined`, so omit the key when absent.\n */\nexport function worldMountOverridesToStateMap(\n src: Map<LocalEntityId, Map<string, MountOverride>>,\n): Map<LocalEntityId, Map<string, { comp: string; field?: string; value: unknown }>> {\n const out = new Map<\n LocalEntityId,\n Map<string, { comp: string; field?: string; value: unknown }>\n >();\n for (const [lid, fields] of src) {\n const m = new Map<string, { comp: string; field?: string; value: unknown }>();\n for (const [k, v] of fields) {\n m.set(k, {\n comp: v.comp,\n value: v.value,\n ...(v.field !== undefined ? { field: v.field } : {}),\n });\n }\n out.set(lid, m);\n }\n return out;\n}\n/** @internal Set the payload of an already-allocated SceneInstance state ref. */\nexport function worldSetUniqueRefPayload<T>(\n world: World,\n handle: Handle<string, 'unique'>,\n payload: T,\n): void {\n sceneWorldState(world).statePayloads.set(Number(handle), payload);\n}\n\n/**\n * @internal Resolve the SceneInstanceState payload behind the\n * `SceneInstance.state` ref column on `root`. Returns Err when `root`\n * does not carry SceneInstance or the ref slot is dead.\n */\nexport function worldResolveSceneInstanceStatePayload(\n world: World,\n root: EntityHandle,\n): Result<SceneInstanceStatePayload, EcsError> {\n const sceneInstanceToken = world.components.resolve('SceneInstance');\n if (sceneInstanceToken === undefined) {\n return err(new ComponentNotDefinedError('SceneInstance'));\n }\n const r = world.get(root, sceneInstanceToken);\n if (!r.ok) return r;\n const stateRefRaw = (r.value as unknown as { state: number }).state;\n const stateRefHandle = toUnique<'SceneInstanceState'>(stateRefRaw);\n const payload = sceneWorldState(world).statePayloads.get(Number(stateRefHandle));\n if (payload === undefined) {\n return err(\n new StaleEntityError(root as unknown as number, entityIndex(root), entityGeneration(root), {\n operation: 'resolveSceneInstanceState',\n component: 'SceneInstance',\n expectedGeneration: entityGeneration(root),\n actualGeneration: entityGeneration(root),\n }),\n );\n }\n return ok(payload as SceneInstanceStatePayload);\n}\n/**\n * Public sugar — get the SceneInstanceState payload (Map / Set view) for\n * `root`. Equivalent to `world.get(root, SceneInstance)` followed by a\n * managed-ref resolution; provided so AI users do not have to learn the\n * `ref<T>` slot resolution mechanic for the common read path.\n */\nexport function worldGetSceneInstanceState(\n world: World,\n root: EntityHandle,\n): Result<SceneInstanceStatePayload, EcsError> {\n return worldResolveSceneInstanceStatePayload(world, root);\n}\n\n/** Resolve a generated SceneEntityRef against one concrete SceneInstance. */\nexport function worldResolveSceneEntity(\n world: World,\n root: EntityHandle,\n ref: SceneEntityRef,\n): Result<EntityHandle, EcsError> {\n const state = worldResolveSceneInstanceStatePayload(world, root);\n if (!state.ok) return state;\n // Anonymous POD scenes remain addressable with an explicit empty source key.\n // Never let the caller supply the identity used for the comparison: that\n // would make an anonymous instance accept a fabricated persistent ref.\n const resolved = resolveSceneEntity(ref, {\n sceneSourceKey: state.value.sceneSourceKey ?? '',\n bindings: state.value.bindings,\n });\n if (!resolved.ok) return err(resolved.error as unknown as EcsError);\n return ok(resolved.value as EntityHandle);\n}\n/**\n * Despawn a SceneInstance root + all its members. `opts.keepDetached`\n * preserves members marked via `worldDetachSceneMember` (plan-strategy\n * §D-5). Returns the count of entities actually despawned (root + each\n * non-detached member).\n *\n * For a plain entity (no SceneInstance), behaviour matches\n * `world.despawn(entity)` followed by `despawnDescendants(entity)` — i.e.\n * `keepDetached` is a no-op.\n */\nexport function worldDespawnScene(\n world: World,\n root: EntityHandle,\n opts?: { keepDetached?: boolean },\n): Result<number, EcsError> {\n const dRes = worldDespawnDescendants(world, root, opts);\n if (!dRes.ok) return dRes;\n const drop = world.despawn(root);\n if (!drop.ok) return drop;\n return ok(dRes.value + 1);\n}\n/**\n * Despawn every descendant of `root` reachable through Children mirror /\n * SceneInstance.mapping. `opts.keepDetached` is honoured only when `root`\n * carries a SceneInstance (otherwise the option is ignored — there is no\n * detached set on a plain entity).\n *\n * Returns the count of entities despawned. The `root` itself is NOT\n * despawned (that is `despawnScene`'s extra step).\n */\nexport function worldDespawnDescendants(\n world: World,\n root: EntityHandle,\n opts?: { keepDetached?: boolean },\n): Result<number, EcsError> {\n let detached: Set<LocalEntityId> | null = null;\n let entityToLocalId: Map<EntityHandle, LocalEntityId> | null = null;\n if (opts?.keepDetached === true) {\n const stateRes = worldResolveSceneInstanceStatePayload(world, root);\n if (stateRes.ok) {\n detached = stateRes.value.detachedLocalIds;\n entityToLocalId = stateRes.value.entityToLocalId;\n }\n }\n let count = 0;\n // Collect descendants first (DFS via iterDescendants) to avoid mutating\n // while iterating. SceneInstance.mapping also owns members that may not be\n // reachable through a Children mirror in a partially registered host. The\n // nested anchor list closes that same ownership boundary for mounted scenes.\n const list: EntityHandle[] = [];\n const seen = new Set<number>();\n const collect = (anchor: EntityHandle): void => {\n for (const e of world.iterDescendants(anchor)) {\n const raw = e as unknown as number;\n if (!seen.has(raw)) {\n seen.add(raw);\n list.push(e);\n }\n }\n const stateRes = worldResolveSceneInstanceStatePayload(world, anchor);\n if (!stateRes.ok) return;\n for (const e of stateRes.value.entityToLocalId.keys()) {\n const raw = e as unknown as number;\n if (!seen.has(raw)) {\n seen.add(raw);\n list.push(e);\n }\n }\n for (const nestedRoot of stateRes.value.mountRoots) {\n const raw = nestedRoot as unknown as number;\n if (seen.has(raw)) continue;\n seen.add(raw);\n list.push(nestedRoot);\n collect(nestedRoot);\n }\n };\n collect(root);\n const childOfToken = world.components.resolve('ChildOf');\n // ChildOf uses linkedSpawn, so a parent-first pass would recursively retire\n // its children before this function can count them. Sort the ownership set\n // by its live ChildOf depth instead of relying on mirror traversal order;\n // nested SceneInstance roots are siblings of their mount carrier in the\n // flattened traversal but parents of the mounted members.\n const owned = new Set(list.map((entity) => Number(entity)));\n const ownedDepth = (entity: EntityHandle): number => {\n if (childOfToken === undefined) return 0;\n let current = entity;\n let depth = 0;\n const visited = new Set<number>();\n while (!visited.has(Number(current))) {\n visited.add(Number(current));\n const parentRes = world.get(current, childOfToken);\n if (!parentRes.ok) break;\n const parent = (parentRes.value as { parent: EntityHandle }).parent;\n if (!owned.has(Number(parent))) break;\n depth += 1;\n current = parent;\n }\n return depth;\n };\n list.sort((a, b) => ownedDepth(b) - ownedDepth(a));\n for (const e of list) {\n if (detached !== null) {\n const lid = entityToLocalId?.get(e);\n if (lid !== undefined && detached.has(lid)) {\n if (childOfToken !== undefined) {\n world.removeComponent(e, childOfToken);\n }\n continue;\n }\n }\n const r = world.despawn(e);\n if (!r.ok) {\n if (r.error.code === 'stale-entity') continue;\n return r;\n }\n count += 1;\n }\n return ok(count);\n}\n/**\n * Write a runtime override to a member entity belonging to `root`. Routes\n * through `world.set(member, comp, { [field]: value })` after an entity-\n * scope guard so cross-instance writes fail-fast. Type-mismatch surfaces\n * `EcsErrorCode = 'scene-override-type-mismatch'` (D-9).\n */\nexport function worldSetSceneOverride<S extends ComponentSchema>(\n world: World,\n root: EntityHandle,\n member: EntityHandle,\n component: Component<string, S>,\n field: keyof ShapeOf<S> & string,\n value: unknown,\n): Result<void, EcsError> {\n const stateRes = worldResolveSceneInstanceStatePayload(world, root);\n if (!stateRes.ok) return stateRes;\n const state = stateRes.value;\n const lid = state.entityToLocalId.get(member);\n if (lid === undefined) {\n return err(\n new StaleEntityError(\n member as unknown as number,\n entityIndex(member),\n entityGeneration(member),\n {\n operation: 'setSceneOverride',\n component: component.name,\n expectedGeneration: entityGeneration(member),\n actualGeneration: entityGeneration(member),\n },\n ),\n );\n }\n // Type guard: only check primitive scalar field types where we can\n // narrow `typeof`; ref / handle / entity / array / buffer fields skip\n // (write would surface a deeper error from set).\n const schemaType = (componentSchema(component) as Record<string, string>)[field];\n if (schemaType !== undefined && isPrimitiveScalarFieldType(schemaType)) {\n const expectJsType = primitiveJsType(schemaType);\n const actualJsType = typeof value;\n if (expectJsType !== actualJsType) {\n return err({\n code: 'scene-override-type-mismatch' as const,\n expected: `value typeof === ${expectJsType}`,\n hint:\n `setSceneOverride(${component.name}.${field}) expected ${expectJsType}, ` +\n `got ${actualJsType}; coerce or pick a different override path.`,\n detail: {\n code: 'scene-override-type-mismatch' as const,\n comp: component.name,\n field: field as string,\n expectedType: schemaType,\n actualType: actualJsType,\n },\n } as unknown as EcsError);\n }\n }\n const setRes = world.set(member, component, { [field]: value } as Partial<InputShapeOf<S>>);\n if (!setRes.ok) return setRes;\n // Record into state.overrides\n let fieldMap = state.overrides.get(lid);\n if (fieldMap === undefined) {\n fieldMap = new Map();\n state.overrides.set(lid, fieldMap);\n }\n fieldMap.set(`${component.name}:${field}`, {\n comp: component.name,\n field: field as string,\n value,\n });\n return ok(undefined);\n}\n/**\n * Drop a runtime override (and any mount-time override for the same\n * (member, comp, field) triple); roll the live column value back to the\n * source SceneAsset's layer-1 explicit value (M2 v1 — M3+ widens to layer\n * 2/3 defaults via fillComponentDefaults).\n */\nexport function worldRemoveSceneOverride<S extends ComponentSchema>(\n world: World,\n root: EntityHandle,\n member: EntityHandle,\n component: Component<string, S>,\n field: keyof ShapeOf<S> & string,\n): Result<void, EcsError> {\n const stateRes = worldResolveSceneInstanceStatePayload(world, root);\n if (!stateRes.ok) return stateRes;\n const state = stateRes.value;\n const lid = state.entityToLocalId.get(member);\n if (lid === undefined) return ok(undefined);\n const fieldMap = state.overrides.get(lid);\n if (fieldMap !== undefined) {\n fieldMap.delete(`${component.name}:${field}`);\n if (fieldMap.size === 0) state.overrides.delete(lid);\n }\n // Look up the source SceneAsset layer-1 value.\n const assetRes = worldResolveSceneAsset(world, state.source);\n if (!assetRes.ok) return assetRes;\n const key = state.keyByLocalId.get(lid as unknown as number);\n const node = key === undefined ? undefined : assetRes.value.entities[key];\n const layer1 = node?.components[component.name] as Record<string, unknown> | undefined;\n if (layer1 !== undefined && field in layer1) {\n const r = world.set(member, component, { [field]: layer1[field] } as Partial<InputShapeOf<S>>);\n if (!r.ok) return r;\n }\n return ok(undefined);\n}\n/** Mark a member entity detached. Idempotent (set semantics). */\nexport function worldDetachSceneMember(\n world: World,\n root: EntityHandle,\n member: EntityHandle,\n): Result<void, EcsError> {\n const sceneInstanceToken = world.components.resolve('SceneInstance');\n if (sceneInstanceToken === undefined) {\n return err(new ComponentNotDefinedError('SceneInstance'));\n }\n const stateRes = worldResolveSceneInstanceStatePayload(world, root);\n if (!stateRes.ok) return stateRes;\n const state = stateRes.value;\n const lid = state.entityToLocalId.get(member);\n if (lid === undefined) return ok(undefined);\n state.detachedLocalIds.add(lid);\n return ok(undefined);\n}\n/** Clear a detached mark. Idempotent (set semantics). */\nexport function worldReattachSceneMember(\n world: World,\n root: EntityHandle,\n member: EntityHandle,\n): Result<void, EcsError> {\n const stateRes = worldResolveSceneInstanceStatePayload(world, root);\n if (!stateRes.ok) return stateRes;\n const state = stateRes.value;\n const lid = state.entityToLocalId.get(member);\n if (lid === undefined) return ok(undefined);\n state.detachedLocalIds.delete(lid);\n return ok(undefined);\n}\n/**\n * Get the SceneAsset handle a SceneInstance root was instantiated from.\n * Returns Err on a plain entity (no SceneInstance component).\n */\nexport function worldGetSceneAssetForInstance(\n world: World,\n root: EntityHandle,\n): Result<Handle<'SceneAsset', 'shared'>, EcsError> {\n const stateRes = worldResolveSceneInstanceStatePayload(world, root);\n if (!stateRes.ok) return stateRes;\n return ok(stateRes.value.source);\n}\n\n/**\n * Topological sort over the implicit ChildOf graph (parents before children).\n * Cycle-free input always covers all n nodes; cyclic input emits whatever was\n * reachable from indegree-0 (the fallback caller handles cycle reporting via\n * `pack-cyclic-reference` at the upstream scanner / runtime path).\n */\nfunction sceneTopoSort(nodes: readonly CompiledSceneEntity[]): readonly number[] {\n const n = nodes.length;\n const childrenOf: number[][] = Array.from({ length: n }, () => []);\n const indeg = new Uint32Array(n);\n const localIdToIdx = new Map<number, number>();\n for (let i = 0; i < n; i += 1) {\n const node = nodes[i];\n if (node === undefined) continue;\n localIdToIdx.set(node.localId as unknown as number, i);\n }\n for (let i = 0; i < n; i += 1) {\n const node = nodes[i];\n if (node === undefined) continue;\n const child = node.components.ChildOf;\n if (child === undefined) continue;\n const p = (child as Record<string, unknown>).parent;\n if (typeof p === 'number') {\n const parentIdx = localIdToIdx.get(p);\n if (parentIdx !== undefined && parentIdx !== i) {\n childrenOf[parentIdx]?.push(i);\n indeg[i] = (indeg[i] ?? 0) + 1;\n }\n }\n }\n const order: number[] = [];\n const queue: number[] = [];\n for (let i = 0; i < n; i += 1) if ((indeg[i] ?? 0) === 0) queue.push(i);\n while (queue.length > 0) {\n const head = queue.shift();\n if (head === undefined) break;\n order.push(head);\n for (const c of childrenOf[head] ?? []) {\n indeg[c] = (indeg[c] ?? 0) - 1;\n if ((indeg[c] ?? 0) === 0) queue.push(c);\n }\n }\n // Append any nodes left unvisited (defensive — cycle would surface here).\n for (let i = 0; i < n; i += 1) {\n if (!order.includes(i) && nodes[i] !== undefined) order.push(i);\n }\n return order;\n}\n","import type { EntityHandle, World } from '@forgeax/engine-ecs';\nimport type { Handle, LocalEntityId } from '@forgeax/engine-types';\nimport type { MountOverride } from './runtime-types.js';\n\n/** Internal state retained by a SceneInstance root. */\nexport interface SceneInstanceStatePayload {\n readonly source: Handle<'SceneAsset', 'shared'>;\n readonly sceneSourceKey?: string;\n /** Authored key for each private numeric slot, retained for collection. */\n readonly keyByLocalId: Map<number, string>;\n /** Authored key of this instance when it is nested in a parent scene. */\n readonly instanceKey?: string;\n readonly bindings: Map<string, EntityHandle>;\n readonly entityToLocalId: Map<EntityHandle, LocalEntityId>;\n readonly detachedLocalIds: Set<LocalEntityId>;\n readonly overrides: Map<\n LocalEntityId,\n Map<string, { readonly comp: string; readonly field?: string; readonly value: unknown }>\n >;\n readonly rootEntities: EntityHandle[];\n readonly mountRoots: EntityHandle[];\n readonly totalSlots: number;\n readonly mountTimeOverrides: readonly MountOverride[];\n}\n\nexport interface SceneWorldState {\n resolver: unknown;\n readonly statePayloads: Map<number, unknown>;\n}\n\nconst sceneWorldStates = new WeakMap<World, SceneWorldState>();\n\nexport function sceneWorldState(world: World): SceneWorldState {\n const current = sceneWorldStates.get(world);\n if (current !== undefined) return current;\n const created: SceneWorldState = { resolver: null, statePayloads: new Map<number, unknown>() };\n sceneWorldStates.set(world, created);\n return created;\n}\n\nexport function mountOverrideStateKey(ov: MountOverride): string {\n return ov.field !== undefined ? `${ov.comp}:${ov.field}` : ov.comp;\n}\n\nexport function isPrimitiveScalarFieldType(fieldType: string): boolean {\n if (\n fieldType === 'f32' ||\n fieldType === 'f64' ||\n fieldType === 'u32' ||\n fieldType === 'i32' ||\n fieldType === 'u8' ||\n fieldType === 'i8' ||\n fieldType === 'u16' ||\n fieldType === 'i16' ||\n fieldType === 'bool' ||\n fieldType === 'string'\n ) {\n return true;\n }\n return fieldType.startsWith('enum<');\n}\n\nexport function primitiveJsType(fieldType: string): string {\n if (fieldType === 'bool') return 'boolean';\n if (fieldType === 'string') return 'string';\n return 'number';\n}\n","import {\n defineSystem,\n defineSystemSet,\n type EcsError,\n ENTITY_NULL_RAW,\n type EntityHandle,\n FixedUpdate,\n type Query,\n type SystemHandle,\n Update,\n type World,\n} from '@forgeax/engine-ecs';\nimport {\n type DerivedColumnBinding,\n type DerivedRangeCursor,\n type DerivedRangeWriter,\n getDerivedWriter,\n} from '@forgeax/engine-ecs/internal';\nimport { worldRead } from '@forgeax/engine-ecs/world-read';\nimport { type Mat4, mat4 } from '@forgeax/engine-math';\nimport { err, ok, type Result } from '@forgeax/engine-types';\nimport { ChildOf } from '../components/child-of';\nimport { Children } from '../components/children';\nimport { GlobalTransform, Transform } from '../components/transform';\nimport { SceneError } from '../errors';\n\nexport const PROPAGATE_TRANSFORMS_SYSTEM = 'propagateTransforms' as const;\nexport const PROPAGATE_TRANSFORMS_FIXED_SYSTEM = 'propagateTransformsFixed' as const;\nexport const TransformSet = defineSystemSet({ name: 'transform' });\nexport const TransformFixedSet = defineSystemSet({ name: 'transform-fixed' });\n\n/**\n * Optional, test-owned counters for the parent-first executor. The counters\n * are disabled unless a caller brackets a run with begin/end; production\n * propagation therefore pays only one predictable branch per instrumented\n * event. They are deliberately not a second execution state or a public\n * dirty/cache contract.\n */\nexport interface TransformPropagationTrace {\n hierarchyRootInvocations: number;\n hierarchyRootCursorReuses: number;\n hierarchyRootCursorAllocations: number;\n hierarchyEntityLookups: number;\n hierarchyRowsEvaluated: number;\n hierarchyEdgesVisited: number;\n hierarchyPublishedRows: number;\n hierarchyPublishedRuns: number;\n hierarchyResidualParentProbes: number;\n flatStructuralRootRows: number;\n}\n\nlet propagationTrace: TransformPropagationTrace | undefined;\nlet hierarchyRootCursorAllocationCount = 0;\nlet propagationTraceRootCursorAllocationStart = 0;\n\nfunction createHierarchyRootCursor(): DerivedRangeCursor {\n hierarchyRootCursorAllocationCount += 1;\n return { bindingIndex: -1, row: -1 };\n}\n\nexport function beginTransformPropagationTrace(): void {\n propagationTraceRootCursorAllocationStart = hierarchyRootCursorAllocationCount;\n propagationTrace = {\n hierarchyRootInvocations: 0,\n hierarchyRootCursorReuses: 0,\n hierarchyRootCursorAllocations: 0,\n hierarchyEntityLookups: 0,\n hierarchyRowsEvaluated: 0,\n hierarchyEdgesVisited: 0,\n hierarchyPublishedRows: 0,\n hierarchyPublishedRuns: 0,\n hierarchyResidualParentProbes: 0,\n flatStructuralRootRows: 0,\n };\n}\n\nexport function endTransformPropagationTrace(): TransformPropagationTrace {\n const trace = propagationTrace;\n propagationTrace = undefined;\n const rootCursorAllocations =\n hierarchyRootCursorAllocationCount - propagationTraceRootCursorAllocationStart;\n propagationTraceRootCursorAllocationStart = hierarchyRootCursorAllocationCount;\n if (trace !== undefined) {\n trace.hierarchyRootCursorAllocations = rootCursorAllocations;\n return trace;\n }\n return {\n hierarchyRootInvocations: 0,\n hierarchyRootCursorReuses: 0,\n hierarchyRootCursorAllocations: 0,\n hierarchyEntityLookups: 0,\n hierarchyRowsEvaluated: 0,\n hierarchyEdgesVisited: 0,\n hierarchyPublishedRows: 0,\n hierarchyPublishedRuns: 0,\n hierarchyResidualParentProbes: 0,\n flatStructuralRootRows: 0,\n };\n}\n\nfunction countPropagation(name: keyof TransformPropagationTrace): void {\n const trace = propagationTrace;\n if (trace !== undefined) trace[name] += 1;\n}\n\ninterface Scratch {\n position: Float32Array;\n rotation: Float32Array;\n scale: Float32Array;\n local: Mat4;\n parent: Mat4;\n candidate: Mat4;\n hierarchyStackEntities: EntityHandle[];\n hierarchyStackChildren: number[];\n hierarchyProbeEntities: EntityHandle[];\n hierarchyCurrentCursor: DerivedRangeCursor;\n hierarchyParentCursor: DerivedRangeCursor;\n hierarchyChildCursor: DerivedRangeCursor;\n hierarchyResidualCursor: DerivedRangeCursor;\n hierarchyResidualParentCursor: DerivedRangeCursor;\n hierarchyRootCursor: DerivedRangeCursor;\n hierarchyStates: Uint8Array[];\n hierarchyChanged: Uint8Array[];\n hierarchyBindingTables: number[];\n hierarchyBindingRows: number[];\n flatChanged: Uint8Array[];\n flatBindingTables: number[];\n flatBindingRows: number[];\n flatStructureEpoch: number;\n hierarchyStructureEpoch: number;\n dirtyTransforms?: Query<readonly [typeof Transform]>;\n dirtyParents?: Query<readonly [typeof ChildOf]>;\n dirtyGlobals?: Query<readonly [typeof GlobalTransform]>;\n flatQuery?: FlatQuery;\n hierarchyQuery?: HierarchyQuery;\n transformQuery?: TransformQuery;\n hierarchyWriter?: HierarchyWriter;\n transformWriter?: TransformWriter;\n missingGlobalQuery?: MissingGlobalQuery;\n missingTransformQuery?: MissingTransformQuery;\n}\n\ntype FlatQuery = Query<readonly [typeof Transform], readonly [typeof GlobalTransform]>;\ntype HierarchyQuery = Query<\n readonly [typeof Transform, typeof ChildOf],\n readonly [typeof GlobalTransform]\n>;\ntype TransformQuery = Query<readonly [typeof Transform], readonly [typeof GlobalTransform]>;\ntype HierarchyWriter = DerivedRangeWriter<\n typeof Transform | typeof ChildOf,\n typeof GlobalTransform\n>;\ntype TransformWriter = DerivedRangeWriter<typeof Transform, typeof GlobalTransform>;\ntype HierarchyBinding = DerivedColumnBinding<\n typeof Transform | typeof ChildOf,\n typeof GlobalTransform\n>;\ntype TransformBinding = DerivedColumnBinding<typeof Transform, typeof GlobalTransform>;\ntype MissingGlobalQuery = Query<readonly [], readonly [], readonly []>;\ntype MissingTransformQuery = Query<readonly [], readonly [], readonly []>;\n\ninterface RegistrationLease {\n refs: number;\n}\n\nconst SCRATCH = new WeakMap<World, Scratch>();\nconst REGISTRATION_LEASES = new WeakMap<World, RegistrationLease>();\n\nfunction pairError(entity: EntityHandle, expected: string): Result<void, SceneError> {\n return err(\n new SceneError({\n code: 'hierarchy-broken',\n expected,\n hint: 'attach both Transform and GlobalTransform at scene authoring or import time, then retry propagation',\n detail: { entity, parent: entity },\n }),\n );\n}\n\nfunction ensureQueries(world: World, scratch: Scratch): Result<void, SceneError> {\n if (\n scratch.flatQuery !== undefined &&\n scratch.hierarchyQuery !== undefined &&\n scratch.transformQuery !== undefined &&\n scratch.hierarchyWriter !== undefined &&\n scratch.transformWriter !== undefined &&\n scratch.missingGlobalQuery !== undefined &&\n scratch.missingTransformQuery !== undefined\n ) {\n return ok(undefined);\n }\n const flatOutput = world.query({\n read: [Transform],\n write: [GlobalTransform],\n without: [ChildOf],\n changed: [Transform],\n });\n scratch.dirtyTransforms ??= world.query({ read: [Transform], changed: [Transform] }).unwrap();\n scratch.dirtyParents ??= world.query({ read: [ChildOf], changed: [ChildOf] }).unwrap();\n scratch.dirtyGlobals ??= world\n .query({ read: [GlobalTransform], changed: [GlobalTransform] })\n .unwrap();\n const hierarchy = world.query({ read: [Transform, ChildOf], write: [GlobalTransform] });\n const transform = world.query({ read: [Transform], write: [GlobalTransform] });\n const missingGlobal = world.query({ with: [Transform], without: [GlobalTransform] });\n const missingTransform = world.query({ with: [GlobalTransform], without: [Transform] });\n if (\n !flatOutput.ok ||\n !hierarchy.ok ||\n !transform.ok ||\n !missingGlobal.ok ||\n !missingTransform.ok\n ) {\n return pairError(0 as EntityHandle, 'valid Transform and GlobalTransform pair queries');\n }\n const hierarchyWriter = getDerivedWriter(hierarchy.value, GlobalTransform);\n const transformWriter = getDerivedWriter(transform.value, GlobalTransform);\n if (!hierarchyWriter.ok || !transformWriter.ok) {\n return pairError(0 as EntityHandle, 'dense Transform and ChildOf derived bindings');\n }\n scratch.flatQuery = flatOutput.value as FlatQuery;\n scratch.hierarchyQuery = hierarchy.value as HierarchyQuery;\n scratch.transformQuery = transform.value as TransformQuery;\n scratch.hierarchyWriter = hierarchyWriter.value as HierarchyWriter;\n scratch.transformWriter = transformWriter.value as TransformWriter;\n scratch.missingGlobalQuery = missingGlobal.value as MissingGlobalQuery;\n scratch.missingTransformQuery = missingTransform.value as MissingTransformQuery;\n return ok(undefined);\n}\n\nfunction validateTransformPairs(world: World, scratch: Scratch): Result<void, SceneError> {\n const queryResult = ensureQueries(world, scratch);\n if (!queryResult.ok) return queryResult;\n const missingGlobal = scratch.missingGlobalQuery;\n const missingTransform = scratch.missingTransformQuery;\n if (missingGlobal === undefined || missingTransform === undefined) {\n return pairError(0 as EntityHandle, 'valid Transform and GlobalTransform pair queries');\n }\n for (const row of missingGlobal) {\n return pairError(row.entity, 'each Transform entity to carry a GlobalTransform pair');\n }\n for (const row of missingTransform) {\n return pairError(row.entity, 'each GlobalTransform entity to carry a Transform pair');\n }\n return ok(undefined);\n}\n\nfunction scratchFor(world: World): Scratch {\n const existing = SCRATCH.get(world);\n if (existing !== undefined) return existing;\n const created = {\n position: new Float32Array(3),\n rotation: new Float32Array(4),\n scale: new Float32Array(3),\n local: mat4.create(),\n parent: mat4.create(),\n candidate: mat4.create(),\n hierarchyStackEntities: [] as EntityHandle[],\n hierarchyStackChildren: [] as number[],\n hierarchyProbeEntities: [] as EntityHandle[],\n hierarchyCurrentCursor: { bindingIndex: -1, row: -1 },\n hierarchyParentCursor: { bindingIndex: -1, row: -1 },\n hierarchyChildCursor: { bindingIndex: -1, row: -1 },\n hierarchyResidualCursor: { bindingIndex: -1, row: -1 },\n hierarchyResidualParentCursor: { bindingIndex: -1, row: -1 },\n hierarchyRootCursor: createHierarchyRootCursor(),\n hierarchyStates: [],\n hierarchyChanged: [],\n hierarchyBindingTables: [],\n hierarchyBindingRows: [],\n flatChanged: [],\n flatBindingTables: [],\n flatBindingRows: [],\n flatStructureEpoch: -1,\n hierarchyStructureEpoch: -1,\n };\n SCRATCH.set(world, created);\n return created;\n}\n\nfunction composeColumns(\n position: ArrayLike<number>,\n rotation: ArrayLike<number>,\n scale: ArrayLike<number>,\n out: Mat4,\n scratch: Scratch,\n positionStart = 0,\n rotationStart = 0,\n): void {\n scratch.position[0] = position[positionStart] ?? 0;\n scratch.position[1] = position[positionStart + 1] ?? 0;\n scratch.position[2] = position[positionStart + 2] ?? 0;\n scratch.rotation[0] = rotation[rotationStart] ?? 0;\n scratch.rotation[1] = rotation[rotationStart + 1] ?? 0;\n scratch.rotation[2] = rotation[rotationStart + 2] ?? 0;\n scratch.rotation[3] = rotation[rotationStart + 3] ?? 1;\n scratch.scale[0] = scale[positionStart] ?? 1;\n scratch.scale[1] = scale[positionStart + 1] ?? 1;\n scratch.scale[2] = scale[positionStart + 2] ?? 1;\n mat4.compose(out, scratch.position, scratch.rotation, scratch.scale);\n}\n\nfunction composeFlatColumns(\n positions: ArrayLike<number>,\n rotations: ArrayLike<number>,\n scales: ArrayLike<number>,\n worlds: Float32Array,\n count: number,\n): void {\n for (let row = 0; row < count; row += 1) {\n const position = row * 3;\n const rotation = row * 4;\n const world = row * 16;\n const x = rotations[rotation] ?? 0;\n const y = rotations[rotation + 1] ?? 0;\n const z = rotations[rotation + 2] ?? 0;\n const w = rotations[rotation + 3] ?? 1;\n const x2 = x + x;\n const y2 = y + y;\n const z2 = z + z;\n const xx = x * x2;\n const xy = x * y2;\n const xz = x * z2;\n const yy = y * y2;\n const yz = y * z2;\n const zz = z * z2;\n const wx = w * x2;\n const wy = w * y2;\n const wz = w * z2;\n const sx = scales[position] ?? 1;\n const sy = scales[position + 1] ?? 1;\n const sz = scales[position + 2] ?? 1;\n\n worlds[world] = (1 - (yy + zz)) * sx;\n worlds[world + 1] = (xy + wz) * sx;\n worlds[world + 2] = (xz - wy) * sx;\n worlds[world + 3] = 0;\n worlds[world + 4] = (xy - wz) * sy;\n worlds[world + 5] = (1 - (xx + zz)) * sy;\n worlds[world + 6] = (yz + wx) * sy;\n worlds[world + 7] = 0;\n worlds[world + 8] = (xz + wy) * sz;\n worlds[world + 9] = (yz - wx) * sz;\n worlds[world + 10] = (1 - (xx + yy)) * sz;\n worlds[world + 11] = 0;\n worlds[world + 12] = positions[position] ?? 0;\n worlds[world + 13] = positions[position + 1] ?? 0;\n worlds[world + 14] = positions[position + 2] ?? 0;\n worlds[world + 15] = 1;\n }\n}\n\nfunction propagateFlat(world: World, scratch: Scratch): Result<void, SceneError> {\n const query = scratch.flatQuery;\n if (query === undefined)\n return err(\n new SceneError({\n code: 'hierarchy-broken',\n expected: 'a valid changed Transform write query',\n hint: 'register the scene components before running TransformPropagation',\n }),\n );\n const spans = query.spans();\n if (!spans.ok) return pairError(0 as EntityHandle, 'dense numeric Transform spans');\n let bindingIndex = 0;\n try {\n for (const span of spans.value) {\n const local = span.get(Transform);\n const world = span.mut(GlobalTransform).world;\n composeFlatColumns(local.pos, local.quat, local.scale, world, span.length);\n bindingIndex += 1;\n }\n } catch (cause) {\n const error = cause as EcsError;\n return err(derivedWriteError(error, bindingIndex));\n }\n\n // A structural relation change can turn an unchanged Transform row into a\n // flat root (most importantly ChildOf removal). The changed Transform query\n // above cannot observe that transition, so once per structure epoch scan the\n // already-bound numeric Transform rows and publish only differing roots.\n const transformWriter = scratch.transformWriter;\n if (transformWriter === undefined) {\n return pairError(0 as EntityHandle, 'dense Transform and GlobalTransform derived bindings');\n }\n const transformBindings = transformWriter.bindings as readonly TransformBinding[];\n const structureEpoch = world.getStructureEpoch();\n if (scratch.flatStructureEpoch === structureEpoch) return ok(undefined);\n\n ensureFlatBuffers(scratch, transformBindings);\n resetFlatBuffers(scratch);\n for (let bindingIndex = 0; bindingIndex < transformBindings.length; bindingIndex += 1) {\n const binding = transformBindings[bindingIndex];\n const changed = scratch.flatChanged[bindingIndex];\n if (binding === undefined || changed === undefined) continue;\n for (let row = 0; row < binding.rowCapacity; row += 1) {\n const entity = (binding.entities[row] ?? 0) as EntityHandle;\n const parentRaw = world[worldRead].getFieldValue(entity, ChildOf, 'parent');\n if (parentRaw !== undefined && parentRaw !== ENTITY_NULL_RAW) continue;\n countPropagation('flatStructuralRootRows');\n composeBindingRow(binding, row, undefined, 0, scratch, changed);\n }\n }\n for (let bindingIndex = 0; bindingIndex < transformBindings.length; bindingIndex += 1) {\n const changed = scratch.flatChanged[bindingIndex];\n if (changed === undefined) continue;\n const published = transformWriter.publishChangedRows(bindingIndex, changed);\n if (!published.ok) return err(derivedWriteError(published.error, bindingIndex));\n }\n scratch.flatStructureEpoch = structureEpoch;\n return ok(undefined);\n}\n\ninterface TransformColumnShape {\n readonly pos: ArrayLike<number>;\n readonly quat: ArrayLike<number>;\n readonly scale: ArrayLike<number>;\n}\n\ninterface OutputColumnShape {\n readonly world: Float32Array;\n}\n\ninterface HierarchyColumnShape extends TransformColumnShape {\n readonly parent: ArrayLike<number>;\n}\n\nfunction transformColumns(binding: TransformBinding | HierarchyBinding): TransformColumnShape {\n return binding.read as unknown as TransformColumnShape;\n}\n\nfunction hierarchyColumns(binding: HierarchyBinding): HierarchyColumnShape {\n return binding.read as unknown as HierarchyColumnShape;\n}\n\nfunction worldColumn(binding: TransformBinding | HierarchyBinding): Float32Array {\n return (binding.write as unknown as OutputColumnShape).world;\n}\n\nfunction hierarchyError(\n code: 'hierarchy-broken' | 'hierarchy-cycle',\n entity: EntityHandle,\n parent: EntityHandle,\n expected: string,\n hint: string,\n): SceneError {\n return new SceneError({ code, expected, hint, detail: { entity, parent } });\n}\n\nfunction writeCandidate(\n binding: TransformBinding | HierarchyBinding,\n row: number,\n candidate: Mat4,\n changed: Uint8Array,\n): void {\n const worlds = worldColumn(binding);\n const base = row * 16;\n for (let index = 0; index < 16; index += 1) {\n if (worlds[base + index] !== candidate[index]) {\n worlds.set(candidate, base);\n changed[row] = 1;\n return;\n }\n }\n}\n\nfunction composeBindingRow(\n binding: TransformBinding | HierarchyBinding,\n row: number,\n parentBinding: TransformBinding | undefined,\n parentRow: number,\n scratch: Scratch,\n changed: Uint8Array,\n): void {\n // Hierarchy bindings carry the parent column; flat structural-root repair\n // uses the same numeric kernel but is intentionally counted separately.\n if ('parent' in (binding.read as object)) countPropagation('hierarchyRowsEvaluated');\n const local = transformColumns(binding);\n const offset = row * 3;\n composeColumns(local.pos, local.quat, local.scale, scratch.local, scratch, offset, row * 4);\n if (parentBinding === undefined) {\n scratch.candidate.set(scratch.local);\n } else {\n const parentWorld = worldColumn(parentBinding);\n const parentOffset = parentRow * 16;\n for (let index = 0; index < 16; index += 1) {\n scratch.parent[index] = parentWorld[parentOffset + index] ?? 0;\n }\n // Column-major composition is intentionally identical to the previous\n // matrix path: Global = Parent * Local, with no TRS decomposition.\n mat4.multiply(scratch.candidate, scratch.parent, scratch.local);\n }\n writeCandidate(binding, row, scratch.candidate, changed);\n}\n\nfunction ensureHierarchyBuffers(scratch: Scratch, bindings: readonly HierarchyBinding[]): void {\n let same = scratch.hierarchyBindingTables.length === bindings.length;\n if (same) {\n for (let index = 0; index < bindings.length; index += 1) {\n const binding = bindings[index];\n if (\n binding === undefined ||\n scratch.hierarchyBindingTables[index] !== binding.tableId ||\n scratch.hierarchyBindingRows[index] !== binding.rowCapacity\n ) {\n same = false;\n break;\n }\n }\n }\n if (same) return;\n scratch.hierarchyBindingTables = bindings.map((binding) => binding.tableId);\n scratch.hierarchyBindingRows = bindings.map((binding) => binding.rowCapacity);\n scratch.hierarchyStates = bindings.map((binding) => new Uint8Array(binding.rowCapacity));\n scratch.hierarchyChanged = bindings.map((binding) => new Uint8Array(binding.rowCapacity));\n}\n\nfunction resetHierarchyBuffers(scratch: Scratch): void {\n for (let index = 0; index < scratch.hierarchyStates.length; index += 1) {\n scratch.hierarchyStates[index]?.fill(0);\n scratch.hierarchyChanged[index]?.fill(0);\n }\n}\n\nfunction ensureFlatBuffers(scratch: Scratch, bindings: readonly TransformBinding[]): void {\n let same = scratch.flatBindingTables.length === bindings.length;\n if (same) {\n for (let index = 0; index < bindings.length; index += 1) {\n const binding = bindings[index];\n if (\n binding === undefined ||\n scratch.flatBindingTables[index] !== binding.tableId ||\n scratch.flatBindingRows[index] !== binding.rowCapacity\n ) {\n same = false;\n break;\n }\n }\n }\n if (same) return;\n scratch.flatBindingTables = bindings.map((binding) => binding.tableId);\n scratch.flatBindingRows = bindings.map((binding) => binding.rowCapacity);\n scratch.flatChanged = bindings.map((binding) => new Uint8Array(binding.rowCapacity));\n}\n\nfunction resetFlatBuffers(scratch: Scratch): void {\n for (const changed of scratch.flatChanged) changed.fill(0);\n}\n\nfunction derivedWriteError(cause: EcsError, bindingIndex: number): SceneError {\n return new SceneError({\n code: 'hierarchy-broken',\n expected: 'derived GlobalTransform range publication to succeed',\n hint: cause.hint ?? 'retry propagation on a healthy World',\n detail: {\n kind: 'derived-write',\n entity: 0 as EntityHandle,\n parent: 0 as EntityHandle,\n bindingIndex,\n base: 0,\n start: 0,\n count: 0,\n cause,\n },\n });\n}\n\nfunction findHierarchyLocation(\n writer: HierarchyWriter,\n bindings: readonly HierarchyBinding[],\n entity: EntityHandle,\n cursor: DerivedRangeCursor,\n): HierarchyBinding | undefined {\n countPropagation('hierarchyEntityLookups');\n if (!writer.locateEntity(entity, cursor)) return undefined;\n return bindings[cursor.bindingIndex];\n}\n\nfunction findTransformLocation(\n writer: TransformWriter,\n bindings: readonly TransformBinding[],\n entity: EntityHandle,\n cursor: DerivedRangeCursor,\n): TransformBinding | undefined {\n countPropagation('hierarchyEntityLookups');\n if (!writer.locateEntity(entity, cursor)) return undefined;\n return bindings[cursor.bindingIndex];\n}\n\nfunction countPublishedRows(changed: Uint8Array): void {\n const trace = propagationTrace;\n if (trace === undefined) return;\n let runOpen = false;\n for (let row = 0; row < changed.length; row += 1) {\n if ((changed[row] ?? 0) !== 0) {\n trace.hierarchyPublishedRows += 1;\n if (!runOpen) {\n trace.hierarchyPublishedRuns += 1;\n runOpen = true;\n }\n } else {\n runOpen = false;\n }\n }\n}\n\nfunction noteHierarchyError(current: SceneError | undefined, next: SceneError): SceneError {\n if (current === undefined) return next;\n const currentEntity = Number(current.detail?.entity ?? Number.MAX_SAFE_INTEGER);\n const nextEntity = Number(next.detail?.entity ?? Number.MAX_SAFE_INTEGER);\n return nextEntity < currentEntity ||\n (nextEntity === currentEntity && next.code.localeCompare(current.code) < 0)\n ? next\n : current;\n}\n\nfunction composeLocalHierarchyEntity(\n writer: HierarchyWriter,\n bindings: readonly HierarchyBinding[],\n entity: EntityHandle,\n scratch: Scratch,\n changed: Uint8Array[],\n): boolean {\n const cursor = scratch.hierarchyCurrentCursor;\n const binding = findHierarchyLocation(writer, bindings, entity, cursor);\n if (binding === undefined) return false;\n composeBindingRow(\n binding,\n cursor.row,\n undefined,\n 0,\n scratch,\n changed[cursor.bindingIndex] as Uint8Array,\n );\n const states = scratch.hierarchyStates[cursor.bindingIndex];\n if (states !== undefined) states[cursor.row] = 3;\n return true;\n}\n\nfunction handleActiveCycle(\n repeated: EntityHandle,\n stackEntities: EntityHandle[],\n stackChildren: number[],\n writer: HierarchyWriter,\n bindings: readonly HierarchyBinding[],\n scratch: Scratch,\n changed: Uint8Array[],\n report: (error: SceneError) => void,\n): void {\n let cycleStart = -1;\n for (let index = 0; index < stackEntities.length; index += 1) {\n if (stackEntities[index] === repeated) {\n cycleStart = index;\n break;\n }\n }\n if (cycleStart < 0) return;\n const repeatedCursor: DerivedRangeCursor = { bindingIndex: -1, row: -1 };\n const repeatedBinding = findHierarchyLocation(writer, bindings, repeated, repeatedCursor);\n const repeatedParent =\n repeatedBinding === undefined\n ? repeated\n : ((hierarchyColumns(repeatedBinding).parent[repeatedCursor.row] ??\n ENTITY_NULL_RAW) as number as EntityHandle);\n report(\n hierarchyError(\n 'hierarchy-cycle',\n repeated,\n repeatedParent,\n 'a parent-before-child Transform hierarchy',\n 'repair the ChildOf cycle and retry TransformPropagation',\n ),\n );\n for (let index = cycleStart; index < stackEntities.length; index += 1) {\n const cycleEntity = stackEntities[index];\n if (cycleEntity === undefined) continue;\n composeLocalHierarchyEntity(writer, bindings, cycleEntity, scratch, changed);\n stackChildren[index] = 0;\n }\n}\n\nfunction walkChildren(\n world: World,\n root: EntityHandle,\n writer: HierarchyWriter,\n bindings: readonly HierarchyBinding[],\n transformWriter: TransformWriter,\n transformBindings: readonly TransformBinding[],\n scratch: Scratch,\n report: (error: SceneError) => void,\n allowCompletedRoot: boolean,\n refresh = false,\n): void {\n countPropagation('hierarchyRootInvocations');\n const stackEntities = scratch.hierarchyStackEntities;\n const stackChildren = scratch.hierarchyStackChildren;\n stackEntities.length = 0;\n stackChildren.length = 0;\n\n if (allowCompletedRoot) {\n // Residual recovery may be entered once for each member of a malformed\n // parent path. State 4 means a previous fallback walk already expanded\n // this root and all reachable Children edges, so do not repeat that\n // subtree for every cycle member.\n const rootCursor = scratch.hierarchyRootCursor;\n const rootBinding = findHierarchyLocation(writer, bindings, root, rootCursor);\n if (rootBinding !== undefined) {\n const state = scratch.hierarchyStates[rootCursor.bindingIndex]?.[rootCursor.row] ?? 0;\n if (state === 4) return;\n }\n } else {\n // This cursor is scratch-owned and reused for every root. A root walk is\n // a hot invocation; allocating a cursor here would scale object churn with\n // the number of roots even after all bindings have warmed.\n const rootCursor = scratch.hierarchyRootCursor;\n countPropagation('hierarchyRootCursorReuses');\n const rootBinding = findHierarchyLocation(writer, bindings, root, rootCursor);\n if (rootBinding !== undefined) {\n const state = scratch.hierarchyStates[rootCursor.bindingIndex]?.[rootCursor.row] ?? 0;\n if (state !== 0 && !refresh) return;\n }\n }\n stackEntities.push(root);\n stackChildren.push(-1);\n\n const currentCursor = scratch.hierarchyCurrentCursor;\n const parentCursor = scratch.hierarchyParentCursor;\n const childCursor = scratch.hierarchyChildCursor;\n while (stackEntities.length > 0) {\n const top = stackEntities.length - 1;\n const current = stackEntities[top];\n if (current === undefined) {\n stackEntities.pop();\n stackChildren.pop();\n continue;\n }\n const hierarchyBinding = findHierarchyLocation(writer, bindings, current, currentCursor);\n const nextChild = stackChildren[top] ?? -1;\n if (nextChild < 0) {\n if (hierarchyBinding !== undefined) {\n if (refresh) {\n const states = scratch.hierarchyStates[currentCursor.bindingIndex];\n if (states !== undefined) states[currentCursor.row] = 0;\n }\n const state = scratch.hierarchyStates[currentCursor.bindingIndex]?.[currentCursor.row] ?? 0;\n if (state === 0) {\n const states = scratch.hierarchyStates[currentCursor.bindingIndex];\n if (states !== undefined) states[currentCursor.row] = 1;\n const parentRaw = (hierarchyColumns(hierarchyBinding).parent[currentCursor.row] ??\n ENTITY_NULL_RAW) as number;\n let completed = false;\n if (parentRaw === ENTITY_NULL_RAW) {\n composeBindingRow(\n hierarchyBinding,\n currentCursor.row,\n undefined,\n 0,\n scratch,\n scratch.hierarchyChanged[currentCursor.bindingIndex] as Uint8Array,\n );\n completed = true;\n } else {\n const parent = parentRaw as EntityHandle;\n const parentBinding = findTransformLocation(\n transformWriter,\n transformBindings,\n parent,\n parentCursor,\n );\n const parentHierarchy = findHierarchyLocation(writer, bindings, parent, childCursor);\n if (parentBinding === undefined) {\n report(\n hierarchyError(\n 'hierarchy-broken',\n current,\n parent,\n 'each ChildOf parent to carry Transform and GlobalTransform',\n 'repair the missing parent pair before retrying propagation',\n ),\n );\n composeBindingRow(\n hierarchyBinding,\n currentCursor.row,\n undefined,\n 0,\n scratch,\n scratch.hierarchyChanged[currentCursor.bindingIndex] as Uint8Array,\n );\n completed = true;\n } else if (parentHierarchy !== undefined) {\n const parentState =\n scratch.hierarchyStates[childCursor.bindingIndex]?.[childCursor.row] ?? 0;\n if (parentState === 1) {\n handleActiveCycle(\n parent,\n stackEntities,\n stackChildren,\n writer,\n bindings,\n scratch,\n scratch.hierarchyChanged,\n report,\n );\n completed = true;\n } else if (parentState === 0) {\n report(\n hierarchyError(\n 'hierarchy-broken',\n current,\n parent,\n 'Children to enumerate every parent-before-child edge',\n 'repair the Children mirror and retry TransformPropagation',\n ),\n );\n composeBindingRow(\n hierarchyBinding,\n currentCursor.row,\n undefined,\n 0,\n scratch,\n scratch.hierarchyChanged[currentCursor.bindingIndex] as Uint8Array,\n );\n completed = true;\n } else {\n composeBindingRow(\n hierarchyBinding,\n currentCursor.row,\n parentBinding,\n parentCursor.row,\n scratch,\n scratch.hierarchyChanged[currentCursor.bindingIndex] as Uint8Array,\n );\n completed = true;\n }\n } else {\n composeBindingRow(\n hierarchyBinding,\n currentCursor.row,\n parentBinding,\n parentCursor.row,\n scratch,\n scratch.hierarchyChanged[currentCursor.bindingIndex] as Uint8Array,\n );\n completed = true;\n }\n }\n if (completed && states !== undefined && states[currentCursor.row] === 1) {\n states[currentCursor.row] = 2;\n }\n }\n }\n stackChildren[top] = 0;\n continue;\n }\n\n const childrenLength = world[worldRead].getArrayLength(current, Children, 'entities') ?? 0;\n if (nextChild >= childrenLength) {\n stackEntities.pop();\n stackChildren.pop();\n if (allowCompletedRoot) {\n const completedCursor = scratch.hierarchyResidualCursor;\n const completedBinding = findHierarchyLocation(writer, bindings, current, completedCursor);\n const completedStates =\n completedBinding === undefined\n ? undefined\n : scratch.hierarchyStates[completedCursor.bindingIndex];\n if (completedStates !== undefined && completedStates[completedCursor.row] === 3) {\n completedStates[completedCursor.row] = 4;\n }\n }\n continue;\n }\n stackChildren[top] = nextChild + 1;\n countPropagation('hierarchyEdgesVisited');\n const childRaw = world[worldRead].getArrayElement(current, Children, 'entities', nextChild);\n if (childRaw === undefined || childRaw === ENTITY_NULL_RAW) {\n report(\n hierarchyError(\n 'hierarchy-broken',\n current,\n current,\n 'Children.entities to contain live child handles',\n 'repair the Children mirror and retry TransformPropagation',\n ),\n );\n continue;\n }\n const child = childRaw as EntityHandle;\n const childBinding = findHierarchyLocation(writer, bindings, child, childCursor);\n if (childBinding === undefined) {\n report(\n hierarchyError(\n 'hierarchy-broken',\n child,\n current,\n 'each Children entry to carry Transform, GlobalTransform, and ChildOf',\n 'repair the child component pair before retrying propagation',\n ),\n );\n continue;\n }\n const childParent = (hierarchyColumns(childBinding).parent[childCursor.row] ??\n ENTITY_NULL_RAW) as number;\n const childState = scratch.hierarchyStates[childCursor.bindingIndex]?.[childCursor.row] ?? 0;\n if (childParent !== (current as number)) {\n // Leave an unvisited child for the residual row-state pass. That pass\n // can classify the complete path (including a rootless cycle) without\n // emitting a premature mirror error that would hide the cycle cause.\n if (childState === 0) continue;\n report(\n hierarchyError(\n 'hierarchy-broken',\n child,\n current,\n 'Children and ChildOf to describe the same parent',\n 'repair the relationship mirror and retry TransformPropagation',\n ),\n );\n continue;\n }\n if (childState === 1) {\n handleActiveCycle(\n child,\n stackEntities,\n stackChildren,\n writer,\n bindings,\n scratch,\n scratch.hierarchyChanged,\n report,\n );\n } else if (childState === 0 || refresh) {\n stackEntities.push(child);\n stackChildren.push(-1);\n }\n }\n}\n\nfunction fallbackResidualPath(\n world: World,\n path: readonly EntityHandle[],\n writer: HierarchyWriter,\n bindings: readonly HierarchyBinding[],\n transformWriter: TransformWriter,\n transformBindings: readonly TransformBinding[],\n scratch: Scratch,\n report: (error: SceneError) => void,\n): void {\n // Root traversal owns the normal path. A residual path is necessarily a\n // malformed Children projection (or a rootless cycle); cut the complete\n // path to local roots in one pass so no stale GlobalTransform survives the\n // diagnostic. Keeping the path as an explicit work list also makes this\n // recovery O(path length), rather than repeatedly searching parent chains.\n for (const entity of path) {\n composeLocalHierarchyEntity(writer, bindings, entity, scratch, scratch.hierarchyChanged);\n }\n for (const entity of path) {\n walkChildren(\n world,\n entity,\n writer,\n bindings,\n transformWriter,\n transformBindings,\n scratch,\n report,\n true,\n );\n }\n}\n\nfunction resolveResidualPath(\n world: World,\n entity: EntityHandle,\n writer: HierarchyWriter,\n bindings: readonly HierarchyBinding[],\n transformWriter: TransformWriter,\n transformBindings: readonly TransformBinding[],\n scratch: Scratch,\n report: (error: SceneError) => void,\n): void {\n const path = scratch.hierarchyProbeEntities;\n path.length = 0;\n const cursor = scratch.hierarchyResidualCursor;\n const parentTransformCursor = scratch.hierarchyParentCursor;\n const parentHierarchyCursor = scratch.hierarchyResidualParentCursor;\n let current = entity;\n while (true) {\n countPropagation('hierarchyResidualParentProbes');\n const binding = findHierarchyLocation(writer, bindings, current, cursor);\n if (binding === undefined) break;\n const states = scratch.hierarchyStates[cursor.bindingIndex];\n const state = states?.[cursor.row] ?? 0;\n if (state !== 0) {\n const columns = hierarchyColumns(binding);\n const parentRaw = (columns.parent[cursor.row] ?? ENTITY_NULL_RAW) as number;\n report(\n hierarchyError(\n 'hierarchy-cycle',\n current,\n parentRaw === ENTITY_NULL_RAW ? current : (parentRaw as EntityHandle),\n 'a parent-before-child Transform hierarchy',\n 'repair the ChildOf cycle and retry TransformPropagation',\n ),\n );\n fallbackResidualPath(\n world,\n path,\n writer,\n bindings,\n transformWriter,\n transformBindings,\n scratch,\n report,\n );\n return;\n }\n\n if (states !== undefined) states[cursor.row] = 1;\n path.push(current);\n const parentRaw = (hierarchyColumns(binding).parent[cursor.row] ?? ENTITY_NULL_RAW) as number;\n if (parentRaw === ENTITY_NULL_RAW) {\n // Every null-parent row is enumerated as a root above. Reaching one\n // here means the materialized Children graph failed to expose the\n // parent-first edge; preserve the explicit malformed-graph error.\n report(\n hierarchyError(\n 'hierarchy-broken',\n current,\n current,\n 'Children to enumerate every parent-before-child edge',\n 'repair the Children mirror and retry TransformPropagation',\n ),\n );\n fallbackResidualPath(\n world,\n path,\n writer,\n bindings,\n transformWriter,\n transformBindings,\n scratch,\n report,\n );\n return;\n }\n\n const parent = parentRaw as EntityHandle;\n const parentTransform = findTransformLocation(\n transformWriter,\n transformBindings,\n parent,\n parentTransformCursor,\n );\n const parentHierarchy = findHierarchyLocation(writer, bindings, parent, parentHierarchyCursor);\n if (parentHierarchy === undefined) {\n report(\n hierarchyError(\n 'hierarchy-broken',\n current,\n parent,\n parentTransform === undefined\n ? 'each ChildOf parent to carry Transform and GlobalTransform'\n : 'Children to enumerate every parent-before-child edge',\n parentTransform === undefined\n ? 'repair the missing parent pair before retrying propagation'\n : 'repair the Children mirror and retry TransformPropagation',\n ),\n );\n fallbackResidualPath(\n world,\n path,\n writer,\n bindings,\n transformWriter,\n transformBindings,\n scratch,\n report,\n );\n return;\n }\n\n const parentState =\n scratch.hierarchyStates[parentHierarchyCursor.bindingIndex]?.[parentHierarchyCursor.row] ?? 0;\n if (parentState === 0) {\n current = parent;\n continue;\n }\n if (parentState === 1) {\n report(\n hierarchyError(\n 'hierarchy-cycle',\n parent,\n current,\n 'a parent-before-child Transform hierarchy',\n 'repair the ChildOf cycle and retry TransformPropagation',\n ),\n );\n } else {\n report(\n hierarchyError(\n 'hierarchy-broken',\n current,\n parent,\n 'Children to enumerate every parent-before-child edge',\n 'repair the Children mirror and retry TransformPropagation',\n ),\n );\n }\n fallbackResidualPath(\n world,\n path,\n writer,\n bindings,\n transformWriter,\n transformBindings,\n scratch,\n report,\n );\n return;\n }\n}\n\nfunction propagateHierarchy(\n world: World,\n scratch: Scratch,\n globalEdited: boolean,\n): Result<void, SceneError> {\n const hierarchyWriter = scratch.hierarchyWriter;\n const transformWriter = scratch.transformWriter;\n if (hierarchyWriter === undefined || transformWriter === undefined) {\n return err(\n new SceneError({\n code: 'hierarchy-broken',\n expected: 'paired Transform and GlobalTransform derived bindings',\n hint: 'register the scene components before running TransformPropagation',\n }),\n );\n }\n const hierarchyBindings = hierarchyWriter.bindings as readonly HierarchyBinding[];\n const transformBindings = transformWriter.bindings as readonly TransformBinding[];\n if (hierarchyBindings.length === 0) {\n // Keep the flat-only lane independent: it must not allocate hierarchy\n // markers or scan every Transform row merely to prove that no ChildOf\n // archetype exists.\n scratch.hierarchyBindingTables.length = 0;\n scratch.hierarchyBindingRows.length = 0;\n scratch.hierarchyStates.length = 0;\n scratch.hierarchyChanged.length = 0;\n scratch.hierarchyStructureEpoch = world.getStructureEpoch();\n return ok(undefined);\n }\n const dirty = new Set<EntityHandle>();\n for (const row of scratch.dirtyTransforms ?? []) dirty.add(row.entity);\n let rebuild = scratch.hierarchyStructureEpoch !== world.getStructureEpoch();\n for (const _row of scratch.dirtyParents ?? []) rebuild = true;\n rebuild ||= globalEdited;\n if (!rebuild && dirty.size === 0) return ok(undefined);\n ensureHierarchyBuffers(scratch, hierarchyBindings);\n if (rebuild) resetHierarchyBuffers(scratch);\n else for (const changed of scratch.hierarchyChanged) changed.fill(0);\n let firstError: SceneError | undefined;\n const report = (error: SceneError): void => {\n firstError = noteHierarchyError(firstError, error);\n };\n\n if (!rebuild) {\n // The previous successful structural pass proved the parent graph. Only\n // highest dirty ancestors need execution; clean parents retain valid worlds.\n for (const entity of dirty) {\n let parent = world[worldRead].getFieldValue(entity, ChildOf, 'parent');\n let covered = false;\n while (parent !== undefined && parent !== ENTITY_NULL_RAW) {\n if (dirty.has(parent as EntityHandle)) {\n covered = true;\n break;\n }\n parent = world[worldRead].getFieldValue(parent as EntityHandle, ChildOf, 'parent');\n }\n if (!covered)\n walkChildren(\n world,\n entity,\n hierarchyWriter,\n hierarchyBindings,\n transformWriter,\n transformBindings,\n scratch,\n report,\n false,\n true,\n );\n }\n } else {\n // Start only at actual roots (flat Transform rows and null-parent\n // ChildOf rows). Descendants are discovered exclusively through the ECS\n // materialized Children lists, so every normal frame is parent-first and\n // linear in rows plus relationship edges.\n for (const binding of transformBindings) {\n const entities = binding.entities;\n for (let row = 0; row < binding.rowCapacity; row += 1) {\n const entity = (entities[row] ?? 0) as EntityHandle;\n const parentRaw = world[worldRead].getFieldValue(entity, ChildOf, 'parent');\n if (parentRaw === undefined || parentRaw === ENTITY_NULL_RAW) {\n walkChildren(\n world,\n entity,\n hierarchyWriter,\n hierarchyBindings,\n transformWriter,\n transformBindings,\n scratch,\n report,\n false,\n );\n }\n }\n }\n\n // Any remaining hierarchy row is either behind a malformed/missing mirror\n // edge or belongs to a rootless cycle. Follow each residual parent chain\n // once with the same row-state machine (not a per-node parent search), then\n // cut that complete residual path to local space. This keeps malformed\n // coverage linear in residual rows and edges while normal frames remain\n // exclusively Children-driven.\n for (let bindingIndex = 0; bindingIndex < hierarchyBindings.length; bindingIndex += 1) {\n const binding = hierarchyBindings[bindingIndex];\n if (binding === undefined) continue;\n const entities = binding.entities;\n const states = scratch.hierarchyStates[bindingIndex];\n for (let row = 0; row < binding.rowCapacity; row += 1) {\n if ((states?.[row] ?? 0) !== 0) continue;\n const entity = (entities[row] ?? 0) as EntityHandle;\n resolveResidualPath(\n world,\n entity,\n hierarchyWriter,\n hierarchyBindings,\n transformWriter,\n transformBindings,\n scratch,\n report,\n );\n }\n }\n }\n\n for (let bindingIndex = 0; bindingIndex < hierarchyBindings.length; bindingIndex += 1) {\n const changed = scratch.hierarchyChanged[bindingIndex];\n if (changed === undefined) continue;\n countPublishedRows(changed);\n const published = hierarchyWriter.publishChangedRows(bindingIndex, changed);\n if (!published.ok) {\n const cause = published.error as EcsError;\n report(derivedWriteError(cause, bindingIndex));\n }\n }\n scratch.hierarchyStructureEpoch = firstError === undefined ? world.getStructureEpoch() : -1;\n return firstError === undefined ? ok(undefined) : err(firstError);\n}\n\nexport function propagateTransforms(world: World): Result<void, SceneError> {\n const scratch = scratchFor(world);\n const pairs = validateTransformPairs(world, scratch);\n if (!pairs.ok) return pairs;\n let globalEdited = false;\n for (const _span of scratch.dirtyGlobals?.spans().unwrap() ?? []) globalEdited = true;\n const flat = propagateFlat(world, scratch);\n if (!flat.ok) return flat;\n const hierarchy = propagateHierarchy(world, scratch, globalEdited);\n // Consume our own derived publications, while preserving later external edits.\n for (const _span of scratch.dirtyGlobals?.spans().unwrap() ?? []) {\n /* observation only */\n }\n return hierarchy;\n}\n\nexport const PropagateTransforms: SystemHandle<readonly []> = defineSystem({\n name: PROPAGATE_TRANSFORMS_SYSTEM,\n queries: [],\n fn: (world) => {\n const result = propagateTransforms(world);\n if (!result.ok) throw result.error;\n },\n});\n\nexport const PropagateTransformsFixed: SystemHandle<readonly []> = defineSystem({\n name: PROPAGATE_TRANSFORMS_FIXED_SYSTEM,\n queries: [],\n fn: PropagateTransforms.fn,\n});\n\nexport function registerPropagateTransforms(\n world: World,\n options: { beforeSystemName?: string } = {},\n): () => void {\n const existing = REGISTRATION_LEASES.get(world);\n if (existing !== undefined) {\n existing.refs += 1;\n let active = true;\n return () => {\n if (!active) return;\n active = false;\n existing.refs -= 1;\n if (existing.refs === 0) {\n world.removeSystem(FixedUpdate, PROPAGATE_TRANSFORMS_FIXED_SYSTEM);\n world.removeSystem(Update, PROPAGATE_TRANSFORMS_SYSTEM);\n REGISTRATION_LEASES.delete(world);\n SCRATCH.delete(world);\n }\n };\n }\n if (options.beforeSystemName === undefined) {\n world.addSystems(Update, TransformSet, [PropagateTransforms]).unwrap();\n } else {\n world\n .addSystems(Update, TransformSet, [\n {\n name: PROPAGATE_TRANSFORMS_SYSTEM,\n queries: [],\n fn: PropagateTransforms.fn,\n before: [options.beforeSystemName],\n },\n ])\n .unwrap();\n }\n world.addSystems(FixedUpdate, TransformFixedSet, [PropagateTransformsFixed]).unwrap();\n REGISTRATION_LEASES.set(world, { refs: 1 });\n let active = true;\n return () => {\n if (!active) return;\n active = false;\n const lease = REGISTRATION_LEASES.get(world);\n if (lease === undefined) return;\n lease.refs -= 1;\n if (lease.refs !== 0) return;\n world.removeSystem(FixedUpdate, PROPAGATE_TRANSFORMS_FIXED_SYSTEM);\n world.removeSystem(Update, PROPAGATE_TRANSFORMS_SYSTEM);\n REGISTRATION_LEASES.delete(world);\n SCRATCH.delete(world);\n };\n}\n","import type { Component, World } from '@forgeax/engine-ecs';\nimport type { Plugin } from '@forgeax/engine-plugin';\nimport { ChildOf } from './components/child-of';\nimport { Children } from './components/children';\nimport { MorphWeights } from './components/morph-weights';\nimport { Name } from './components/name';\nimport { GlobalTransform, Transform } from './components/transform';\nimport { registerPropagateTransforms } from './systems/propagate-transforms';\n\nconst SCENE_COMPONENTS: readonly Component[] = [\n ChildOf,\n Children,\n MorphWeights,\n Name,\n Transform,\n GlobalTransform,\n];\n\nfunction registerSceneComponents(world: World): () => void {\n const leases = SCENE_COMPONENTS.map((component) => world.components.register(component).unwrap());\n return () => {\n for (let index = leases.length - 1; index >= 0; index -= 1) leases[index]?.dispose();\n };\n}\n\nexport function scenePlugin(): Plugin {\n return {\n name: 'scene',\n inject: ['world'],\n apply(ctx) {\n ctx.effect(() => registerSceneComponents(ctx.world), 'scene/components');\n ctx.effect(() => registerPropagateTransforms(ctx.world), 'scene/propagate-transforms');\n },\n };\n}\n","import { Entity, type EntityHandle, type Query, type World } from '@forgeax/engine-ecs';\nimport { ChildOf } from '../components/child-of';\nimport type { SceneErrorCode, SceneErrorDetail } from '../errors';\n\nexport interface SceneHierarchyDiagnostic {\n readonly code: SceneErrorCode;\n readonly expected: string;\n readonly hint: string;\n readonly detail: SceneErrorDetail;\n}\n\nexport interface SceneHierarchySnapshot {\n readonly parentOf: ReadonlyMap<EntityHandle, EntityHandle>;\n readonly diagnostics: readonly SceneHierarchyDiagnostic[];\n getParent(entity: EntityHandle): EntityHandle | undefined;\n}\n\ninterface HierarchyProjectionCacheEntry {\n readonly structureEpoch: number;\n readonly childOfChanges: Query;\n readonly snapshot: SceneHierarchySnapshot;\n}\n\n// A World can be observed by the transform system, renderer visibility, and\n// editor projections in the same frame. Keep one World-local projection so\n// those consumers do not each rescan every archetype. Structure changes and\n// the ChildOf component's own mutation token are the invalidation keys; the\n// global mutation epoch is intentionally too broad because animation and\n// runtime-only component writes may advance it every frame. Direct table\n// writes are internal-only and must not mutate authored hierarchy state.\nconst HIERARCHY_PROJECTION_CACHE = new WeakMap<World, HierarchyProjectionCacheEntry>();\n\nfunction createChildOfChangeQuery(world: World): Query {\n const result = world.query({ changed: [ChildOf] });\n if (!result.ok) throw result.error;\n return result.value;\n}\n\nfunction drainChanges(query: Query): boolean {\n let changed = false;\n for (const span of query.spans().unwrap()) changed ||= span.length > 0;\n return changed;\n}\n\nfunction diagnostic(\n code: SceneErrorCode,\n entity: EntityHandle,\n parent: EntityHandle,\n): SceneHierarchyDiagnostic {\n if (code === 'hierarchy-cycle') {\n return {\n code,\n expected: 'ChildOf parent edges form an acyclic live hierarchy',\n hint: 'remove one ChildOf edge from the reported cycle, then re-run the extract',\n detail: { entity, parent },\n };\n }\n return {\n code,\n expected: 'ChildOf.parent references a live entity in the same World',\n hint: 'remove the stale ChildOf component or restore the referenced parent in this World',\n detail: { entity, parent },\n };\n}\n\n/** Build the only World-local projection of ChildOf parent facts. */\nexport function projectHierarchy(world: World): SceneHierarchySnapshot {\n const cached = HIERARCHY_PROJECTION_CACHE.get(world);\n if (\n cached !== undefined &&\n cached.structureEpoch === world.getStructureEpoch() &&\n !drainChanges(cached.childOfChanges)\n ) {\n return cached.snapshot;\n }\n const liveEntities = new Set<EntityHandle>();\n const authoredParents = new Map<EntityHandle, EntityHandle>();\n\n const query = world.query({ read: [Entity], optional: [ChildOf] });\n if (query.ok) {\n for (const row of query.value) {\n liveEntities.add(row.entity);\n const parent = row.get(ChildOf)?.parent;\n if (parent !== undefined && parent !== null) authoredParents.set(row.entity, parent);\n }\n }\n\n const parentOf = new Map<EntityHandle, EntityHandle>();\n const diagnostics: SceneHierarchyDiagnostic[] = [];\n for (const [entity, parent] of authoredParents) {\n if (liveEntities.has(parent)) {\n parentOf.set(entity, parent);\n } else {\n diagnostics.push(diagnostic('hierarchy-broken', entity, parent));\n }\n }\n\n const state = new Map<EntityHandle, 0 | 1 | 2>();\n const stack: EntityHandle[] = [];\n const cycleMembers = new Set<EntityHandle>();\n const visit = (entity: EntityHandle): void => {\n const currentState = state.get(entity) ?? 0;\n if (currentState === 2) return;\n if (currentState === 1) {\n const cycleStart = stack.indexOf(entity);\n for (let index = cycleStart; index >= 0 && index < stack.length; index++) {\n const member = stack[index];\n if (member !== undefined) cycleMembers.add(member);\n }\n return;\n }\n\n state.set(entity, 1);\n stack.push(entity);\n const parent = parentOf.get(entity);\n if (parent !== undefined) visit(parent);\n stack.pop();\n state.set(entity, 2);\n };\n\n for (const entity of liveEntities) visit(entity);\n for (const entity of cycleMembers) {\n const parent = authoredParents.get(entity);\n if (parent !== undefined) diagnostics.push(diagnostic('hierarchy-cycle', entity, parent));\n parentOf.delete(entity);\n }\n\n diagnostics.sort((left, right) => {\n const entityDelta = (left.detail.entity as number) - (right.detail.entity as number);\n if (entityDelta !== 0) return entityDelta;\n return left.code.localeCompare(right.code);\n });\n\n const stableParentOf = new Map(parentOf);\n const stableDiagnostics = Object.freeze(diagnostics.slice());\n const snapshot: SceneHierarchySnapshot = {\n parentOf: stableParentOf,\n diagnostics: stableDiagnostics,\n getParent(entity: EntityHandle): EntityHandle | undefined {\n return stableParentOf.get(entity);\n },\n };\n const childOfChanges = createChildOfChangeQuery(world);\n drainChanges(childOfChanges);\n HIERARCHY_PROJECTION_CACHE.set(world, {\n structureEpoch: world.getStructureEpoch(),\n childOfChanges,\n snapshot,\n });\n return snapshot;\n}\n"],"mappings":";AAAA;AAAA,EAKE;AAAA,EACA;AAAA,OAKK;;;ACHA,SAAS,kCACd,eACA,QACA,kBACyB;AACzB,QAAM,SAAS,EAAE,GAAG,OAAO;AAC3B,QAAM,UAAU,CAAC,UACf,OAAO,cAAc,KAAK,IAAK,kBAAkB,IAAI,KAAe,KAAK,OAAO,KAAK,IAAK;AAC5F,MAAI,kBAAkB,sBAAsB,OAAO,OAAO,QAAQ,eAA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AAK;AAC1B,YAAI,WAAW,OAAW,cAAa,IAAI,MAAM;AAAA,MACnD;AACA;AAAA,IACF;AAEA,UAAM,IAAI,QAAQ,CAAC;AACnB,UAAM,KAAK,MAAM;AACjB,UAAM,SAAS,SAAS,IAAI,MAAM;AAClC,QAAI,WAAW,OAAW,OAAM,MAAM;AACtC,UAAM,IAAI;AACV,UAAM,IAAI,QAAQ,CAAC;AAAA,EACrB;AAEA,aAAW,UAAU,aAAc,OAAM,MAAM;AAC/C,aAAW,UAAU,cAAc;AACjC,UAAM,SAAS,gBAAgB,IAAI,MAAM;AACzC,QAAI,WAAW,OAAW,aAAY,KAAK,WAAW,mBAAmB,QAAQ,MAAM,CAAC;AACxF,aAAS,OAAO,MAAM;AAAA,EACxB;AAEA,cAAY,KAAK,CAAC,MAAM,UAAU;AAChC,UAAM,cAAe,KAAK,OAAO,SAAqB,MAAM,OAAO;AACnE,QAAI,gBAAgB,EAAG,QAAO;AAC9B,WAAO,KAAK,KAAK,cAAc,MAAM,IAAI;AAAA,EAC3C,CAAC;AAED,QAAM,iBAAiB,IAAI,IAAI,QAAQ;AACvC,QAAM,oBAAoB,OAAO,OAAO,YAAY,MAAM,CAAC;AAC3D,QAAM,WAAmC;AAAA,IACvC,UAAU;AAAA,IACV,aAAa;AAAA,IACb,UAAU,QAAgD;AACxD,aAAO,eAAe,IAAI,MAAM;AAAA,IAClC;AAAA,EACF;AACA,QAAM,iBAAiB,yBAAyB,KAAK;AACrD,eAAa,cAAc;AAC3B,6BAA2B,IAAI,OAAO;AAAA,IACpC,gBAAgB,MAAM,kBAAkB;AAAA,IACxC;AAAA,IACA;AAAA,EACF,CAAC;AACD,SAAO;AACT;","names":["defineComponent","defineComponent","err","ok","err","ok","err","ok","err","ok","err","parts","slot","ok","classifyEntityField","remapEntityFieldValue","componentSchema","err","ok","PACK_ERROR_HINTS","ok","err","PACK_ERROR_HINTS","componentSchema","classifyEntityField","remapEntityFieldValue","value","ENTITY_NULL_RAW","err","ok","err","ok","world","bindingIndex","ENTITY_NULL_RAW","parentRaw","active"]}