@forgeax/engine-render 0.1.27 → 0.1.29
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +842 -124
- package/dist/assembly/atmosphere-shader-prewarm.d.ts +6 -0
- package/dist/assembly/atmosphere-shader-prewarm.d.ts.map +1 -0
- package/dist/assembly/dynamic-geometry-host.d.ts +52 -0
- package/dist/assembly/dynamic-geometry-host.d.ts.map +1 -0
- package/dist/assembly/dynamic-geometry-runtime.d.ts +20 -0
- package/dist/assembly/dynamic-geometry-runtime.d.ts.map +1 -0
- package/dist/assembly/factory.d.ts +3 -1
- package/dist/assembly/factory.d.ts.map +1 -1
- package/dist/assembly/gpu-driven-owner.d.ts +10 -0
- package/dist/assembly/gpu-driven-owner.d.ts.map +1 -0
- package/dist/assembly/host-contract.d.ts +19 -0
- package/dist/assembly/host-contract.d.ts.map +1 -1
- package/dist/assembly/material/assembly.d.ts +7 -0
- package/dist/assembly/material/assembly.d.ts.map +1 -1
- package/dist/assembly/material-shader-policy.d.ts +3 -1
- package/dist/assembly/material-shader-policy.d.ts.map +1 -1
- package/dist/assembly/recovery/failure-location.d.ts +12 -0
- package/dist/assembly/recovery/failure-location.d.ts.map +1 -0
- package/dist/assembly/recovery/renderer-recover.d.ts +6 -4
- package/dist/assembly/recovery/renderer-recover.d.ts.map +1 -1
- package/dist/assembly/renderer-facade.d.ts.map +1 -1
- package/dist/assembly/renderer-feature-inspection.d.ts +5 -0
- package/dist/assembly/renderer-feature-inspection.d.ts.map +1 -0
- package/dist/assembly/renderer-frame-transaction.d.ts +19 -0
- package/dist/assembly/renderer-frame-transaction.d.ts.map +1 -1
- package/dist/assembly/renderer-helpers.d.ts +3 -0
- package/dist/assembly/renderer-helpers.d.ts.map +1 -1
- package/dist/assembly/renderer-inspection.d.ts +4 -0
- package/dist/assembly/renderer-inspection.d.ts.map +1 -1
- package/dist/assembly/shader-prewarm-policy.d.ts +6 -0
- package/dist/assembly/shader-prewarm-policy.d.ts.map +1 -1
- package/dist/assembly/skin-palette-owner.d.ts +8 -0
- package/dist/assembly/skin-palette-owner.d.ts.map +1 -0
- package/dist/assembly/ssr-shader-prewarm.d.ts +6 -0
- package/dist/assembly/ssr-shader-prewarm.d.ts.map +1 -0
- package/dist/assembly/webgpu-device-loss.d.ts +15 -0
- package/dist/assembly/webgpu-device-loss.d.ts.map +1 -0
- package/dist/assembly/webgpu-pbr-ready.d.ts +38 -0
- package/dist/assembly/webgpu-pbr-ready.d.ts.map +1 -0
- package/dist/assembly/webgpu-ready-mipmap.d.ts +11 -0
- package/dist/assembly/webgpu-ready-mipmap.d.ts.map +1 -0
- package/dist/assembly/webgpu-ready.d.ts +7 -3
- package/dist/assembly/webgpu-ready.d.ts.map +1 -1
- package/dist/assembly/webgpu-renderer-bootstrap.d.ts +10 -0
- package/dist/assembly/webgpu-renderer-bootstrap.d.ts.map +1 -0
- package/dist/assembly/webgpu-renderer-contract.d.ts +62 -0
- package/dist/assembly/webgpu-renderer-contract.d.ts.map +1 -0
- package/dist/assembly/webgpu-renderer-guards.d.ts +9 -0
- package/dist/assembly/webgpu-renderer-guards.d.ts.map +1 -0
- package/dist/assembly/webgpu-renderer-observation.d.ts +6 -0
- package/dist/assembly/webgpu-renderer-observation.d.ts.map +1 -0
- package/dist/assembly/webgpu-renderer-recovery-failure.d.ts +12 -0
- package/dist/assembly/webgpu-renderer-recovery-failure.d.ts.map +1 -0
- package/dist/assembly/webgpu-renderer.d.ts +7 -141
- package/dist/assembly/webgpu-renderer.d.ts.map +1 -1
- package/dist/assembly/webgpu-vertex-layouts.d.ts +28 -84
- package/dist/assembly/webgpu-vertex-layouts.d.ts.map +1 -1
- package/dist/authoring.mjs +3 -3
- package/dist/{chunk-ADHHVYLW.mjs → chunk-33XZFTQU.mjs} +245 -39
- package/dist/chunk-33XZFTQU.mjs.map +1 -0
- package/dist/{chunk-GF523LHF.mjs → chunk-BLXGONR2.mjs} +30 -12
- package/dist/chunk-BLXGONR2.mjs.map +1 -0
- package/dist/{chunk-KM2NOX2I.mjs → chunk-BQVQOQJH.mjs} +958 -254
- package/dist/chunk-BQVQOQJH.mjs.map +1 -0
- package/dist/{chunk-HKXTW355.mjs → chunk-BTWH7BP4.mjs} +386 -17
- package/dist/chunk-BTWH7BP4.mjs.map +1 -0
- package/dist/{chunk-TMIASV2N.mjs → chunk-FUODTTIA.mjs} +3934 -676
- package/dist/chunk-FUODTTIA.mjs.map +1 -0
- package/dist/{chunk-FJ6P52EE.mjs → chunk-ILQ5MEZF.mjs} +3 -17
- package/dist/chunk-ILQ5MEZF.mjs.map +1 -0
- package/dist/{chunk-E34VL5VI.mjs → chunk-JQTSEI3Z.mjs} +3 -3
- package/dist/{chunk-E34VL5VI.mjs.map → chunk-JQTSEI3Z.mjs.map} +1 -1
- package/dist/{chunk-GE3SDD72.mjs → chunk-NICXSHAT.mjs} +16 -38
- package/dist/chunk-NICXSHAT.mjs.map +1 -0
- package/dist/{chunk-ZZ4YQ474.mjs → chunk-NRNXBLIJ.mjs} +577 -7
- package/dist/chunk-NRNXBLIJ.mjs.map +1 -0
- package/dist/{chunk-JDWARUOI.mjs → chunk-PA5DRJNI.mjs} +17 -3
- package/dist/chunk-PA5DRJNI.mjs.map +1 -0
- package/dist/{chunk-XDP6XE5V.mjs → chunk-S4DNKQYQ.mjs} +1118 -446
- package/dist/chunk-S4DNKQYQ.mjs.map +1 -0
- package/dist/components/camera.d.ts +62 -2
- package/dist/components/camera.d.ts.map +1 -1
- package/dist/components/index.d.ts +1 -0
- package/dist/components/index.d.ts.map +1 -1
- package/dist/components/instances.d.ts +6 -20
- package/dist/components/instances.d.ts.map +1 -1
- package/dist/components/scene-instance.d.ts +2 -1
- package/dist/components/scene-instance.d.ts.map +1 -1
- package/dist/components/screen-space-reflection.d.ts +14 -0
- package/dist/components/screen-space-reflection.d.ts.map +1 -0
- package/dist/construct-renderer.mjs +13805 -7186
- package/dist/construct-renderer.mjs.map +1 -1
- package/dist/device/gpu-residency.d.ts +11 -17
- package/dist/device/gpu-residency.d.ts.map +1 -1
- package/dist/device/mesh-residency-lifetime.d.ts +21 -0
- package/dist/device/mesh-residency-lifetime.d.ts.map +1 -0
- package/dist/dynamic-geometry.d.ts +125 -0
- package/dist/dynamic-geometry.d.ts.map +1 -0
- package/dist/environment/background.d.ts +6 -0
- package/dist/environment/background.d.ts.map +1 -0
- package/dist/errors/gpu-driven.d.ts +6 -3
- package/dist/errors/gpu-driven.d.ts.map +1 -1
- package/dist/errors/render.d.ts +7 -4
- package/dist/errors/render.d.ts.map +1 -1
- package/dist/extract/camera.d.ts.map +1 -1
- package/dist/extract/gpu-driven.d.ts +33 -3
- package/dist/extract/gpu-driven.d.ts.map +1 -1
- package/dist/features/host.d.ts +23 -1
- package/dist/features/host.d.ts.map +1 -1
- package/dist/features/noise-texture.d.ts +17 -0
- package/dist/features/noise-texture.d.ts.map +1 -0
- package/dist/features/plan.d.ts +83 -2
- package/dist/features/plan.d.ts.map +1 -1
- package/dist/features/prepared-gpu-work.d.ts +37 -4
- package/dist/features/prepared-gpu-work.d.ts.map +1 -1
- package/dist/features/prepared-graphics-store.d.ts.map +1 -1
- package/dist/features/prepared-graphics.d.ts +5 -0
- package/dist/features/prepared-graphics.d.ts.map +1 -1
- package/dist/features/render-graph-compute.d.ts +5 -3
- package/dist/features/render-graph-compute.d.ts.map +1 -1
- package/dist/features/render-graph-contribution.d.ts +11 -3
- package/dist/features/render-graph-contribution.d.ts.map +1 -1
- package/dist/features/render-graph-raster.d.ts +19 -3
- package/dist/features/render-graph-raster.d.ts.map +1 -1
- package/dist/features/types.d.ts +11 -0
- package/dist/features/types.d.ts.map +1 -1
- package/dist/fullscreen-post-process-pass.d.ts +2 -0
- package/dist/fullscreen-post-process-pass.d.ts.map +1 -1
- package/dist/gpu-driven/batch-topology.d.ts +34 -1
- package/dist/gpu-driven/batch-topology.d.ts.map +1 -1
- package/dist/gpu-driven/pbr-program.d.ts +10 -0
- package/dist/gpu-driven/pbr-program.d.ts.map +1 -0
- package/dist/gpu-driven/prepared-draw.d.ts.map +1 -1
- package/dist/gpu-driven/production-raster.d.ts +144 -23
- package/dist/gpu-driven/production-raster.d.ts.map +1 -1
- package/dist/gpu-driven/shadow-views.d.ts +126 -0
- package/dist/gpu-driven/shadow-views.d.ts.map +1 -0
- package/dist/gpu-driven/view-gpu.d.ts +18 -2
- package/dist/gpu-driven/view-gpu.d.ts.map +1 -1
- package/dist/gpu-scene-schema.d.ts +2 -8
- package/dist/gpu-scene-schema.d.ts.map +1 -1
- package/dist/gpu-scene.d.ts +14 -0
- package/dist/gpu-scene.d.ts.map +1 -1
- package/dist/gpu-texture-usage.d.ts +1 -0
- package/dist/gpu-texture-usage.d.ts.map +1 -1
- package/dist/hdrp-buffers.d.ts +6 -0
- package/dist/hdrp-buffers.d.ts.map +1 -1
- package/dist/ibl/frame-resources.d.ts +8 -0
- package/dist/ibl/frame-resources.d.ts.map +1 -0
- package/dist/ibl/skylight-bind-group.d.ts.map +1 -1
- package/dist/index.d.ts +21 -8
- package/dist/index.d.ts.map +1 -1
- package/dist/index.mjs +8 -7
- package/dist/index.mjs.map +1 -1
- package/dist/inspection-types.d.ts +164 -0
- package/dist/inspection-types.d.ts.map +1 -1
- package/dist/instances-derived-bounds.d.ts +11 -0
- package/dist/instances-derived-bounds.d.ts.map +1 -1
- package/dist/instances.d.ts +89 -44
- package/dist/instances.d.ts.map +1 -1
- package/dist/internal.d.ts +3 -0
- package/dist/internal.d.ts.map +1 -1
- package/dist/internal.mjs +118 -10
- package/dist/internal.mjs.map +1 -1
- package/dist/lifecycle.d.ts +2 -1
- package/dist/lifecycle.d.ts.map +1 -1
- package/dist/material-row.d.ts +5 -0
- package/dist/material-row.d.ts.map +1 -0
- package/dist/materials.d.ts +15 -0
- package/dist/materials.d.ts.map +1 -1
- package/dist/pbr-pipeline.d.ts +21 -5
- package/dist/pbr-pipeline.d.ts.map +1 -1
- package/dist/pipeline/standard-forward-lane.d.ts.map +1 -1
- package/dist/pipeline/standard-output/auto-exposure/capability.d.ts +12 -0
- package/dist/pipeline/standard-output/auto-exposure/capability.d.ts.map +1 -0
- package/dist/pipeline/standard-output/auto-exposure/gpu.d.ts +70 -0
- package/dist/pipeline/standard-output/auto-exposure/gpu.d.ts.map +1 -0
- package/dist/pipeline/standard-output/auto-exposure/graph.d.ts +75 -0
- package/dist/pipeline/standard-output/auto-exposure/graph.d.ts.map +1 -0
- package/dist/pipeline/standard-output/auto-exposure/inspection.d.ts +111 -0
- package/dist/pipeline/standard-output/auto-exposure/inspection.d.ts.map +1 -0
- package/dist/pipeline/standard-output/auto-exposure/oracle.d.ts +16 -0
- package/dist/pipeline/standard-output/auto-exposure/oracle.d.ts.map +1 -0
- package/dist/pipeline/standard-output/auto-exposure/preset.d.ts +14 -0
- package/dist/pipeline/standard-output/auto-exposure/preset.d.ts.map +1 -0
- package/dist/pipeline/standard-output/auto-exposure/state.d.ts +46 -0
- package/dist/pipeline/standard-output/auto-exposure/state.d.ts.map +1 -0
- package/dist/pipeline/standard-output/color-transform.d.ts +27 -0
- package/dist/pipeline/standard-output/color-transform.d.ts.map +1 -0
- package/dist/pipeline/standard-output/graph.d.ts +15 -0
- package/dist/pipeline/standard-output/graph.d.ts.map +1 -0
- package/dist/pipeline/standard-output/lut-admission.d.ts +29 -0
- package/dist/pipeline/standard-output/lut-admission.d.ts.map +1 -0
- package/dist/pipeline/standard-output/lut-gpu.d.ts +48 -0
- package/dist/pipeline/standard-output/lut-gpu.d.ts.map +1 -0
- package/dist/pipeline/standard-output/lut-state.d.ts +68 -0
- package/dist/pipeline/standard-output/lut-state.d.ts.map +1 -0
- package/dist/pipeline/standard-output/resources.d.ts +10 -0
- package/dist/pipeline/standard-output/resources.d.ts.map +1 -0
- package/dist/pipeline/standard-output/types.d.ts +39 -0
- package/dist/pipeline/standard-output/types.d.ts.map +1 -0
- package/dist/pipeline/standard-pipeline.d.ts.map +1 -1
- package/dist/pipeline/standard-post.d.ts +2 -2
- package/dist/pipeline/standard-post.d.ts.map +1 -1
- package/dist/pipeline-builder.d.ts +2 -1
- package/dist/pipeline-builder.d.ts.map +1 -1
- package/dist/pipeline-spec-types.d.ts +4 -0
- package/dist/pipeline-spec-types.d.ts.map +1 -1
- package/dist/pipeline-spec.d.ts +1 -9
- package/dist/pipeline-spec.d.ts.map +1 -1
- package/dist/points-lines/standard-owner.d.ts +1 -1
- package/dist/points-lines/standard-owner.d.ts.map +1 -1
- package/dist/prepare/prepared-graphics-resolver.d.ts +6 -1
- package/dist/prepare/prepared-graphics-resolver.d.ts.map +1 -1
- package/dist/record/dynamic-geometry-consumption.d.ts +15 -0
- package/dist/record/dynamic-geometry-consumption.d.ts.map +1 -0
- package/dist/record/frame-lighting.d.ts +3 -3
- package/dist/record/frame-lighting.d.ts.map +1 -1
- package/dist/record/frame-snapshot.d.ts +106 -5
- package/dist/record/frame-snapshot.d.ts.map +1 -1
- package/dist/record/frame-targets.d.ts.map +1 -1
- package/dist/record/frame.d.ts +39 -4
- package/dist/record/frame.d.ts.map +1 -1
- package/dist/record/main-pass-geometry.d.ts +7 -8
- package/dist/record/main-pass-geometry.d.ts.map +1 -1
- package/dist/record/main-pass-material.d.ts +38 -1
- package/dist/record/main-pass-material.d.ts.map +1 -1
- package/dist/record/main-pass-sprite-draws.d.ts +2 -10
- package/dist/record/main-pass-sprite-draws.d.ts.map +1 -1
- package/dist/record/main-pass.d.ts +12 -2
- package/dist/record/main-pass.d.ts.map +1 -1
- package/dist/record/mesh-ssbo.d.ts +15 -6
- package/dist/record/mesh-ssbo.d.ts.map +1 -1
- package/dist/record/prepared-material-bindings.d.ts +19 -0
- package/dist/record/prepared-material-bindings.d.ts.map +1 -0
- package/dist/record/recovery-pipeline.d.ts +2 -9
- package/dist/record/recovery-pipeline.d.ts.map +1 -1
- package/dist/record/render-context.d.ts +76 -26
- package/dist/record/render-context.d.ts.map +1 -1
- package/dist/record/shadow-pass.d.ts +62 -7
- package/dist/record/shadow-pass.d.ts.map +1 -1
- package/dist/record/skybox-post-pass.d.ts +1 -1
- package/dist/record/skybox-post-pass.d.ts.map +1 -1
- package/dist/record/typed-frame-graph.d.ts +35 -7
- package/dist/record/typed-frame-graph.d.ts.map +1 -1
- package/dist/record/view-ubo.d.ts +1 -0
- package/dist/record/view-ubo.d.ts.map +1 -1
- package/dist/recovery/render-system-candidate.d.ts +10 -2
- package/dist/recovery/render-system-candidate.d.ts.map +1 -1
- package/dist/recovery/render-system-roots.d.ts +11 -0
- package/dist/recovery/render-system-roots.d.ts.map +1 -0
- package/dist/recovery/types.d.ts +76 -0
- package/dist/recovery/types.d.ts.map +1 -0
- package/dist/reflection/record-owner.d.ts +0 -2
- package/dist/reflection/record-owner.d.ts.map +1 -1
- package/dist/render-contract.d.ts +185 -30
- package/dist/render-contract.d.ts.map +1 -1
- package/dist/render-graph-primitives.d.ts +1 -0
- package/dist/render-graph-primitives.d.ts.map +1 -1
- package/dist/render-pipeline.d.ts +64 -5
- package/dist/render-pipeline.d.ts.map +1 -1
- package/dist/render-system-extract-tail.d.ts +7 -5
- package/dist/render-system-extract-tail.d.ts.map +1 -1
- package/dist/render-system-extract.d.ts +101 -41
- package/dist/render-system-extract.d.ts.map +1 -1
- package/dist/render-system-projections.d.ts +22 -0
- package/dist/render-system-projections.d.ts.map +1 -0
- package/dist/render-system.d.ts +34 -77
- package/dist/render-system.d.ts.map +1 -1
- package/dist/scene/render-scene-types.d.ts +14 -7
- package/dist/scene/render-scene-types.d.ts.map +1 -1
- package/dist/scene/render-scene.d.ts +29 -11
- package/dist/scene/render-scene.d.ts.map +1 -1
- package/dist/scene/shadow-visibility.d.ts +5 -0
- package/dist/scene/shadow-visibility.d.ts.map +1 -0
- package/dist/ssr/admission.d.ts +70 -1
- package/dist/ssr/admission.d.ts.map +1 -1
- package/dist/ssr/compose.d.ts +13 -0
- package/dist/ssr/compose.d.ts.map +1 -0
- package/dist/ssr/errors.d.ts +35 -0
- package/dist/ssr/errors.d.ts.map +1 -1
- package/dist/ssr/graph.d.ts +60 -0
- package/dist/ssr/graph.d.ts.map +1 -0
- package/dist/ssr/history.d.ts +97 -0
- package/dist/ssr/history.d.ts.map +1 -0
- package/dist/ssr/hiz.d.ts +37 -0
- package/dist/ssr/hiz.d.ts.map +1 -0
- package/dist/ssr/inspection.d.ts +42 -0
- package/dist/ssr/inspection.d.ts.map +1 -0
- package/dist/ssr/resources.d.ts +58 -0
- package/dist/ssr/resources.d.ts.map +1 -0
- package/dist/ssr/temporal.d.ts +38 -0
- package/dist/ssr/temporal.d.ts.map +1 -0
- package/dist/systems/skin-palette-allocator.d.ts +32 -10
- package/dist/systems/skin-palette-allocator.d.ts.map +1 -1
- package/dist/systems/skin-palette-types.d.ts +15 -0
- package/dist/systems/skin-palette-types.d.ts.map +1 -1
- package/dist/systems/transparent-dispatch.d.ts +9 -0
- package/dist/systems/transparent-dispatch.d.ts.map +1 -0
- package/dist/targets/material-source.d.ts +7 -0
- package/dist/targets/material-source.d.ts.map +1 -1
- package/dist/temporal/frame-coordinator.d.ts +7 -0
- package/dist/temporal/frame-coordinator.d.ts.map +1 -1
- package/dist/temporal/gpu.d.ts +8 -0
- package/dist/temporal/gpu.d.ts.map +1 -1
- package/dist/temporal/history.d.ts.map +1 -1
- package/dist/temporal/index.mjs +6 -6
- package/dist/temporal/inspection.d.ts.map +1 -1
- package/dist/temporal/standard-scene-data.d.ts +2 -1
- package/dist/temporal/standard-scene-data.d.ts.map +1 -1
- package/dist/temporal/temporal-view.d.ts +2 -0
- package/dist/temporal/temporal-view.d.ts.map +1 -1
- package/dist/typed-render-graph-primitives.d.ts +35 -1
- package/dist/typed-render-graph-primitives.d.ts.map +1 -1
- package/dist/typed-shadow-passes.d.ts +3 -1
- package/dist/typed-shadow-passes.d.ts.map +1 -1
- package/dist/volume/temporal.d.ts +6 -0
- package/dist/volume/temporal.d.ts.map +1 -1
- package/package.json +21 -20
- package/src/__tests__/auto-exposure-gpu-evidence.ts +291 -0
- package/src/__tests__/auto-exposure-inspection.unit.test.ts +80 -0
- package/src/__tests__/auto-exposure-transaction.integration.test.ts +99 -0
- package/src/__tests__/auto-exposure.browser.test.ts +33 -0
- package/src/__tests__/auto-exposure.dawn.test.ts +33 -0
- package/src/__tests__/detached-inspection.integration.test.ts +5 -0
- package/src/__tests__/device-scope-lifecycle.unit.test.ts +18 -0
- package/src/__tests__/device-scope-stale-matrix.unit.test.ts +18 -0
- package/src/__tests__/docs-gate-green.unit.test.ts +3 -3
- package/src/__tests__/dynamic-geometry-host.unit.test.ts +1123 -0
- package/src/__tests__/dynamic-geometry.unit.test.ts +233 -0
- package/src/__tests__/factory-contract.integration.test.ts +73 -22
- package/src/__tests__/fallback-row-stride-surface.unit.test.ts +19 -0
- package/src/__tests__/feature-depth-input.dawn.test.ts +121 -0
- package/src/__tests__/feature-noise.unit.test.ts +38 -0
- package/src/__tests__/fixtures/taa-resolve-pinned-baseline.wgsl +301 -0
- package/src/__tests__/frame-camera-selection.unit.test.ts +131 -0
- package/src/__tests__/frame-plan-contract.unit.test.ts +24 -0
- package/src/__tests__/frame-targets.unit.test.ts +24 -0
- package/src/__tests__/fullscreen-feature-plan.unit.test.ts +3 -0
- package/src/__tests__/gpu-driven-baseline.characterization.test.ts +79 -0
- package/src/__tests__/gpu-driven-batch-topology-pbr.unit.test.ts +287 -6
- package/src/__tests__/gpu-driven-indirect-raster-evidence.ts +122 -142
- package/src/__tests__/gpu-driven-indirect-raster.browser.test.ts +10 -1
- package/src/__tests__/gpu-driven-lod-cache.unit.test.ts +264 -0
- package/src/__tests__/gpu-driven-mesh-world-identity.unit.test.ts +349 -0
- package/src/__tests__/gpu-driven-pbr.dawn.test.ts +1417 -0
- package/src/__tests__/gpu-driven-pbr.integration.test.ts +21 -0
- package/src/__tests__/gpu-driven-production-fixture.ts +96 -0
- package/src/__tests__/gpu-driven-production.integration.test.ts +1075 -93
- package/src/__tests__/gpu-driven-scaling.unit.test.ts +1 -3
- package/src/__tests__/gpu-driven-shadow-views.browser.test.ts +63 -0
- package/src/__tests__/gpu-driven-shadow-views.dawn.test.ts +294 -0
- package/src/__tests__/gpu-driven-shadow-views.integration.test.ts +97 -0
- package/src/__tests__/gpu-driven-shadow-views.unit.test.ts +168 -0
- package/src/__tests__/gpu-driven-skin-contract.test-d.ts +11 -0
- package/src/__tests__/gpu-driven-view-gpu-evidence.ts +72 -20
- package/src/__tests__/gpu-driven-view-graph.integration.test.ts +30 -9
- package/src/__tests__/gpu-driven-view.unit.test.ts +159 -52
- package/src/__tests__/gpu-pass-timing.browser.test.ts +6 -1
- package/src/__tests__/gpu-resource-store-stride.unit.test.ts +42 -0
- package/src/__tests__/gpu-scene-render-graph-gpu.ts +19 -5
- package/src/__tests__/gpu-scene.dawn.test.ts +40 -13
- package/src/__tests__/gpu-scene.unit.test.ts +559 -33
- package/src/__tests__/instances-culling.integration.test.ts +36 -10
- package/src/__tests__/instances-derived-bounds.unit.test.ts +54 -0
- package/src/__tests__/instances-store.unit.test.ts +242 -39
- package/src/__tests__/ktx2-basis-gpu-consumer.dawn.test.ts +6 -0
- package/src/__tests__/lighting-scene-roundtrip.integration.test.ts +13 -16
- package/src/__tests__/lut-lkg-transaction.integration.test.ts +122 -0
- package/src/__tests__/material-contract-inventory.unit.test.ts +5 -6
- package/src/__tests__/material-dispatch-shader-id.unit.test.ts +51 -0
- package/src/__tests__/material-lane-selection.unit.test.ts +60 -0
- package/src/__tests__/material-numeric-upload.unit.test.ts +53 -0
- package/src/__tests__/material-texture-handles.unit.test.ts +18 -0
- package/src/__tests__/material-texture-source.unit.test.ts +87 -0
- package/src/__tests__/materials-authoring-validation.unit.test.ts +41 -0
- package/src/__tests__/materials-standard-contract.unit.test.ts +52 -2
- package/src/__tests__/mesh-buffer-usage-surface.unit.test.ts +4 -0
- package/src/__tests__/mesh-submission-lifetime.unit.test.ts +53 -0
- package/src/__tests__/normal-fallback.dawn.test.ts +122 -0
- package/src/__tests__/particle-material-input-layout.unit.test.ts +104 -0
- package/src/__tests__/physical-clearcoat.integration.test.ts +37 -3
- package/src/__tests__/pipeline-texture-specialization.unit.test.ts +138 -0
- package/src/__tests__/point-shadow-inspection.unit.test.ts +2 -0
- package/src/__tests__/prepared-gpu-driven-pbr-contract.test-d.ts +31 -0
- package/src/__tests__/prepared-gpu-driven-pbr-contract.unit.test.ts +39 -0
- package/src/__tests__/prepared-gpu-driven-pbr.integration.test.ts +35 -4
- package/src/__tests__/prepared-graphics-capability.unit.test.ts +21 -0
- package/src/__tests__/prepared-graphics-pipeline-warmup.unit.test.ts +6 -2
- package/src/__tests__/profiler-phase-catalog.test.ts +5 -0
- package/src/__tests__/public-surface.test-d.ts +3 -0
- package/src/__tests__/recovery-candidate-prepare.contract.test.ts +30 -12
- package/src/__tests__/reflection-fallback-async-publication.unit.test.ts +104 -0
- package/src/__tests__/reflection-probe-record-owner.characterization.unit.test.ts +2 -1
- package/src/__tests__/render-error-code-owner.test-d.ts +4 -0
- package/src/__tests__/render-error-detail-ssot.test-d.ts +22 -0
- package/src/__tests__/render-error-exhaustive.test-d.ts +15 -0
- package/src/__tests__/render-feature-gpu-work.integration.test.ts +285 -2
- package/src/__tests__/render-feature-plan.unit.test.ts +245 -0
- package/src/__tests__/render-feature-shadow-order.unit.test.ts +228 -0
- package/src/__tests__/render-feature-zero-work.unit.test.ts +35 -1
- package/src/__tests__/render-graph-fallback.integration.test.ts +2 -2
- package/src/__tests__/render-owner-cohesion.unit.test.ts +55 -0
- package/src/__tests__/render-scene-mixed-updates.integration.test.ts +426 -0
- package/src/__tests__/render-scene-projection.unit.test.ts +914 -23
- package/src/__tests__/render-scene-resource-updates.integration.test.ts +214 -0
- package/src/__tests__/render-scene-skin-lifecycle.integration.test.ts +173 -0
- package/src/__tests__/render-scene-temporal-retry.unit.test.ts +133 -0
- package/src/__tests__/render-target-material-source.test-d.ts +27 -3
- package/src/__tests__/renderer-factory-material-contract.unit.test.ts +61 -1
- package/src/__tests__/renderer-frame-transaction.integration.test.ts +923 -5
- package/src/__tests__/shader-manifest-fixture.ts +39 -0
- package/src/__tests__/skin-motion-regression.unit.test.ts +0 -33
- package/src/__tests__/skin-palette-persistent.integration.test.ts +28 -0
- package/src/__tests__/skin-palette-persistent.unit.test.ts +247 -0
- package/src/__tests__/skinned-shadow-caster.test.ts +118 -14
- package/src/__tests__/specular-environment-scale.dawn.test.ts +156 -0
- package/src/__tests__/ssr-admission-matrix.integration.test.ts +7 -1
- package/src/__tests__/ssr-confidence-compose.unit.test.ts +84 -0
- package/src/__tests__/ssr-coordinate-oracle.unit.test.ts +28 -0
- package/src/__tests__/ssr-format-probe-gating.integration.test.ts +82 -0
- package/src/__tests__/ssr-gpu-dispatch.browser.test.ts +91 -0
- package/src/__tests__/ssr-gpu-dispatch.dawn.test.ts +112 -0
- package/src/__tests__/ssr-gpu-dispatch.ts +946 -0
- package/src/__tests__/ssr-graph-topology.unit.test.ts +104 -0
- package/src/__tests__/ssr-history-filter.dawn.test.ts +198 -0
- package/src/__tests__/ssr-hit-color.dawn.test.ts +273 -0
- package/src/__tests__/ssr-hiz-odd-reduction.dawn.test.ts +569 -0
- package/src/__tests__/ssr-hiz-rescue.dawn.test.ts +279 -0
- package/src/__tests__/ssr-hiz.browser.test.ts +150 -0
- package/src/__tests__/ssr-hiz.dawn.test.ts +150 -0
- package/src/__tests__/ssr-hiz.unit.test.ts +56 -0
- package/src/__tests__/ssr-inspection.unit.test.ts +105 -0
- package/src/__tests__/ssr-memory-budget.unit.test.ts +45 -0
- package/src/__tests__/ssr-performance-sequence-aggregation.unit.test.ts +15 -0
- package/src/__tests__/ssr-public-surface.test-d.ts +37 -0
- package/src/__tests__/ssr-receiver-coverage.dawn.test.ts +387 -0
- package/src/__tests__/ssr-reflection-mip-reducer.dawn.test.ts +309 -0
- package/src/__tests__/ssr-reprojection-probe.ts +90 -0
- package/src/__tests__/ssr-roughness-mip.dawn.test.ts +163 -0
- package/src/__tests__/ssr-shader-prewarm.unit.test.ts +59 -0
- package/src/__tests__/ssr-spatial.integration.test.ts +141 -0
- package/src/__tests__/ssr-stable-lattice.dawn.test.ts +475 -0
- package/src/__tests__/ssr-temporal-history.unit.test.ts +202 -0
- package/src/__tests__/ssr-texel-crossing.dawn.test.ts +448 -0
- package/src/__tests__/ssr-zero-work.integration.test.ts +87 -0
- package/src/__tests__/standard-cluster-variant-resolution.unit.test.ts +44 -12
- package/src/__tests__/standard-clustered-pipeline.unit.test.ts +29 -0
- package/src/__tests__/standard-output-chain-contract.unit.test.ts +99 -0
- package/src/__tests__/standard-output-chain.integration.test.ts +73 -0
- package/src/__tests__/standard-output-gpu-evidence.ts +205 -0
- package/src/__tests__/standard-output.browser.test.ts +15 -0
- package/src/__tests__/standard-output.dawn.test.ts +15 -0
- package/src/__tests__/standard-pbr-artifact-assembly.unit.test.ts +38 -0
- package/src/__tests__/standard-pipeline.integration.test.ts +320 -3
- package/src/__tests__/standard-profile-oracle.unit.test.ts +22 -0
- package/src/__tests__/standard-surface-lighting.unit.test.ts +41 -0
- package/src/__tests__/standard-texture-specialization.dawn.test.ts +141 -0
- package/src/__tests__/surface-adjacent-regressions.integration.test.ts +6 -3
- package/src/__tests__/taa-coverage-edge.dawn.test.ts +193 -0
- package/src/__tests__/taa-history-clipping.dawn.test.ts +328 -0
- package/src/__tests__/taa-neighborhood-equivalence.dawn.test.ts +778 -0
- package/src/__tests__/taa-stability-feedback.browser.test.ts +23 -0
- package/src/__tests__/taa-stability-feedback.dawn.test.ts +68 -0
- package/src/__tests__/taa-stability-feedback.ts +341 -0
- package/src/__tests__/temporal-history-lifecycle.unit.test.ts +49 -7
- package/src/__tests__/temporal-reset-matrix.unit.test.ts +9 -0
- package/src/__tests__/temporal-transaction.integration.test.ts +28 -0
- package/src/__tests__/texture-usage-surface.unit.test.ts +4 -2
- package/src/__tests__/typed-pipeline-topology.unit.test.ts +109 -4
- package/src/__tests__/typed-scene-pass-material-cache.integration.test.ts +126 -0
- package/src/__tests__/vertex-layouts-ssot.unit.test.ts +47 -0
- package/src/__tests__/visibility-extract.perf.test.ts +20 -8
- package/src/__tests__/visibility-instances.integration.test.ts +19 -7
- package/src/__tests__/visibility-producer-matrix.integration.test.ts +20 -9
- package/src/assembly/atmosphere-shader-prewarm.ts +38 -0
- package/src/assembly/dynamic-geometry-host.ts +887 -0
- package/src/assembly/dynamic-geometry-runtime.ts +71 -0
- package/src/assembly/factory.ts +4 -0
- package/src/assembly/gpu-driven-owner.ts +29 -0
- package/src/assembly/host-contract.ts +36 -0
- package/src/assembly/material/assembly.ts +38 -0
- package/src/assembly/material-shader-policy.ts +71 -28
- package/src/assembly/recovery/failure-location.ts +62 -0
- package/src/assembly/recovery/renderer-recover.ts +19 -17
- package/src/assembly/renderer-facade.ts +29 -0
- package/src/assembly/renderer-feature-inspection.ts +13 -0
- package/src/assembly/renderer-frame-transaction.ts +63 -0
- package/src/assembly/renderer-helpers.ts +26 -0
- package/src/assembly/renderer-inspection.ts +6 -0
- package/src/assembly/shader-prewarm-policy.ts +32 -0
- package/src/assembly/skin-palette-owner.ts +21 -0
- package/src/assembly/ssr-shader-prewarm.ts +41 -0
- package/src/assembly/webgpu-device-loss.ts +75 -0
- package/src/assembly/webgpu-pbr-ready.ts +232 -0
- package/src/assembly/webgpu-ready-mipmap.ts +26 -0
- package/src/assembly/webgpu-ready.ts +142 -121
- package/src/assembly/webgpu-renderer-bootstrap.ts +85 -0
- package/src/assembly/webgpu-renderer-contract.ts +69 -0
- package/src/assembly/webgpu-renderer-guards.ts +32 -0
- package/src/assembly/webgpu-renderer-observation.ts +43 -0
- package/src/assembly/webgpu-renderer-recovery-failure.ts +62 -0
- package/src/assembly/webgpu-renderer.ts +675 -614
- package/src/assembly/webgpu-vertex-layouts.ts +233 -87
- package/src/components/__tests__/camera-exposure.contract.unit.test.ts +153 -0
- package/src/components/camera.ts +287 -7
- package/src/components/index.ts +1 -0
- package/src/components/instances.ts +45 -18
- package/src/components/scene-instance.ts +2 -1
- package/src/components/screen-space-reflection.ts +21 -0
- package/src/components/sprite-animation.ts +3 -3
- package/src/components/sprite-instances.ts +1 -1
- package/src/device/gpu-residency.ts +96 -93
- package/src/device/mesh-residency-lifetime.ts +73 -0
- package/src/dynamic-geometry.ts +736 -0
- package/src/environment/background.ts +263 -0
- package/src/errors/gpu-driven.ts +39 -5
- package/src/errors/render.ts +27 -3
- package/src/extract/camera.ts +26 -1
- package/src/extract/gpu-driven.ts +185 -10
- package/src/features/host.ts +237 -19
- package/src/features/noise-texture.ts +91 -0
- package/src/features/plan.ts +553 -24
- package/src/features/prepared-gpu-work.ts +631 -49
- package/src/features/prepared-graphics-store.ts +31 -0
- package/src/features/prepared-graphics.ts +5 -0
- package/src/features/render-graph-compute.ts +41 -8
- package/src/features/render-graph-contribution.ts +141 -3
- package/src/features/render-graph-raster.ts +143 -30
- package/src/features/types.ts +11 -0
- package/src/fullscreen-post-process-pass.ts +3 -0
- package/src/gpu-driven/batch-topology.ts +424 -102
- package/src/gpu-driven/pbr-program.ts +31 -0
- package/src/gpu-driven/prepared-draw.ts +29 -4
- package/src/gpu-driven/production-raster.ts +2267 -694
- package/src/gpu-driven/shadow-views.ts +539 -0
- package/src/gpu-driven/view-gpu.ts +188 -41
- package/src/gpu-scene-schema.ts +52 -11
- package/src/gpu-scene.ts +186 -99
- package/src/gpu-texture-usage.ts +1 -0
- package/src/hdrp-buffers.ts +72 -36
- package/src/ibl/frame-resources.ts +38 -0
- package/src/ibl/skylight-bind-group.ts +5 -4
- package/src/index.ts +125 -1
- package/src/inspection-types.ts +191 -0
- package/src/instances-derived-bounds.ts +258 -34
- package/src/instances.ts +459 -150
- package/src/internal.ts +22 -0
- package/src/lifecycle.ts +2 -0
- package/src/material-row.ts +145 -0
- package/src/materials.ts +44 -8
- package/src/pbr-pipeline.ts +159 -17
- package/src/pipeline/standard-forward-lane.ts +52 -24
- package/src/pipeline/standard-output/__tests__/lut-admission.unit.test.ts +103 -0
- package/src/pipeline/standard-output/auto-exposure/__tests__/capability.unit.test.ts +40 -0
- package/src/pipeline/standard-output/auto-exposure/__tests__/gpu.contract.unit.test.ts +125 -0
- package/src/pipeline/standard-output/auto-exposure/__tests__/graph.contract.unit.test.ts +94 -0
- package/src/pipeline/standard-output/auto-exposure/__tests__/oracle.test.ts +108 -0
- package/src/pipeline/standard-output/auto-exposure/__tests__/preset.test.ts +26 -0
- package/src/pipeline/standard-output/auto-exposure/capability.ts +38 -0
- package/src/pipeline/standard-output/auto-exposure/gpu.ts +567 -0
- package/src/pipeline/standard-output/auto-exposure/graph.ts +221 -0
- package/src/pipeline/standard-output/auto-exposure/inspection.ts +231 -0
- package/src/pipeline/standard-output/auto-exposure/oracle.ts +291 -0
- package/src/pipeline/standard-output/auto-exposure/preset.ts +28 -0
- package/src/pipeline/standard-output/auto-exposure/state.ts +156 -0
- package/src/pipeline/standard-output/color-transform.ts +124 -0
- package/src/pipeline/standard-output/graph.ts +139 -0
- package/src/pipeline/standard-output/lut-admission.ts +121 -0
- package/src/pipeline/standard-output/lut-gpu.ts +399 -0
- package/src/pipeline/standard-output/lut-state.ts +176 -0
- package/src/pipeline/standard-output/resources.ts +121 -0
- package/src/pipeline/standard-output/types.ts +58 -0
- package/src/pipeline/standard-pipeline.ts +192 -59
- package/src/pipeline/standard-post.ts +186 -27
- package/src/pipeline-builder.ts +16 -6
- package/src/pipeline-spec-types.ts +4 -0
- package/src/pipeline-spec.ts +37 -29
- package/src/points-lines/standard-owner.ts +6 -14
- package/src/prepare/prepared-graphics-resolver.ts +9 -2
- package/src/record/__tests__/material-slot-plan.unit.test.ts +48 -0
- package/src/record/__tests__/mesh-ssbo.unit.test.ts +40 -1
- package/src/record/__tests__/recovery-pipeline.unit.test.ts +2 -29
- package/src/record/__tests__/sprite-material-abi.unit.test.ts +36 -5
- package/src/record/__tests__/typed-frame-graph-plan.unit.test.ts +45 -0
- package/src/record/__tests__/view-ubo-layout.unit.test.ts +5 -0
- package/src/record/dynamic-geometry-consumption.ts +59 -0
- package/src/record/frame-lighting.ts +12 -11
- package/src/record/frame-snapshot.ts +133 -23
- package/src/record/frame-targets.ts +9 -0
- package/src/record/frame.ts +727 -133
- package/src/record/main-pass-geometry.ts +162 -98
- package/src/record/main-pass-material.ts +115 -26
- package/src/record/main-pass-sprite-draws.ts +18 -107
- package/src/record/main-pass.ts +78 -8
- package/src/record/material-uniforms.ts +1 -1
- package/src/record/mesh-ssbo.ts +59 -15
- package/src/record/prepared-material-bindings.ts +234 -0
- package/src/record/recovery-pipeline.ts +59 -136
- package/src/record/render-context.ts +92 -22
- package/src/record/shadow-pass.ts +1231 -209
- package/src/record/skybox-post-pass.ts +14 -3
- package/src/record/typed-frame-graph.ts +1006 -53
- package/src/record/view-ubo.ts +11 -0
- package/src/recovery/render-system-candidate.ts +90 -66
- package/src/recovery/render-system-roots.ts +113 -0
- package/src/recovery/types.ts +77 -0
- package/src/reflection/record-owner.ts +26 -54
- package/src/render-contract.ts +219 -25
- package/src/render-graph-primitives.ts +6 -2
- package/src/render-pipeline.ts +70 -1
- package/src/render-system-extract-tail.ts +409 -160
- package/src/render-system-extract.ts +376 -102
- package/src/render-system-projections.ts +241 -0
- package/src/render-system.ts +692 -791
- package/src/scene/render-scene-types.ts +13 -4
- package/src/scene/render-scene.ts +569 -355
- package/src/scene/shadow-visibility.ts +21 -0
- package/src/ssr/admission.ts +380 -14
- package/src/ssr/compose.ts +144 -0
- package/src/ssr/errors.ts +48 -0
- package/src/ssr/graph.ts +777 -0
- package/src/ssr/history.ts +436 -0
- package/src/ssr/hiz.ts +124 -0
- package/src/ssr/inspection.ts +124 -0
- package/src/ssr/resources.ts +202 -0
- package/src/ssr/temporal.ts +164 -0
- package/src/systems/skin-palette-allocator.ts +495 -148
- package/src/systems/skin-palette-types.ts +17 -0
- package/src/systems/transparent-dispatch.ts +90 -0
- package/src/targets/material-source.ts +34 -0
- package/src/temporal/coverage.ts +1 -1
- package/src/temporal/frame-coordinator.ts +23 -2
- package/src/temporal/gpu.ts +74 -12
- package/src/temporal/history.ts +3 -1
- package/src/temporal/inspection.ts +2 -1
- package/src/temporal/standard-scene-data.ts +3 -1
- package/src/temporal/temporal-view.ts +3 -0
- package/src/transmission/__tests__/standard-transmission.dawn.test.ts +204 -139
- package/src/typed-render-graph-primitives.ts +266 -74
- package/src/typed-shadow-passes.ts +122 -12
- package/src/volume/temporal.ts +10 -0
- package/dist/chunk-ADHHVYLW.mjs.map +0 -1
- package/dist/chunk-FJ6P52EE.mjs.map +0 -1
- package/dist/chunk-GE3SDD72.mjs.map +0 -1
- package/dist/chunk-GF523LHF.mjs.map +0 -1
- package/dist/chunk-HKXTW355.mjs.map +0 -1
- package/dist/chunk-JDWARUOI.mjs.map +0 -1
- package/dist/chunk-KM2NOX2I.mjs.map +0 -1
- package/dist/chunk-TMIASV2N.mjs.map +0 -1
- package/dist/chunk-XDP6XE5V.mjs.map +0 -1
- package/dist/chunk-ZZ4YQ474.mjs.map +0 -1
- package/src/__tests__/instances-world-ownership.integration.test.ts +0 -62
- package/src/scene/__tests__/changed-block-summary.candidate.test.ts +0 -36
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/inspection-types.ts","../src/prepare/extended-lighting/state.ts","../src/scene/visibility/occlusion-query-pool.ts","../src/scene/visibility/occlusion-pass.ts","../src/scene/visibility/types.ts","../src/scene/visibility/occlusion-runtime.ts","../src/environment/signature.ts","../src/extract/environment.ts","../src/environment/frame.ts","../src/extract/directional-shadow-projection.ts","../src/errors/gpu-driven.ts","../src/gpu-driven/prepared-draw.ts","../src/extract/gpu-driven.ts","../src/glyph-text-layout-system.ts","../src/instances-derived-bounds.ts","../src/points-lines/bounds.ts","../src/prepare/extended-lighting/spot-modifiers.ts","../src/render-system-extract-tail.ts","../src/render-system-extract.ts","../src/scene/probe-blend.ts"],"names":["failure","RhiErrorClass","err","valid","sorted","ok","input","layout","materialId","cameraOwnerFrame","mat4","resolveAssetHandle","toShared","lightViewProj","box3","vec3","routeWorldError","pass","AssetGuid","derive","projectMaterialParametersToParamSchema","walkMaterialPassesOverSharedRefs","materialValuesToLinearRuntime","Transform","G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W,IAAA,EAAM,UAAA,EAAY,KAAA,CAAM,aAAA,EAAc,CAAA;AACzD,IAAA,IAAA,CAAK,mBAAA,GAAsB,OAAA;AAC3B,IAAA,IAAA,CAAK,gBAAA,GAAmB,kBAAA;AACxB,IAAA,OAAO,MAAA;AAAA,EACT;AACF","file":"chunk-XDP6XE5V.mjs","sourcesContent":["/**\n * Renderer-owned inspection PODs. Keeping these projections free of renderer\n * implementation imports prevents the observation contract from reopening the\n * extract/record dependency graph.\n */\n\nimport type { DirectionalShadowFilterLabel } from './components/directional-shadow-filter';\nimport type { PointsLinesInspection } from './points-lines/inspection';\nimport type { LodOcclusionInspection } from './scene/visibility/inspection';\nimport type { SsrAdmissionIdentity } from './ssr/identity';\n\nexport type {\n LodOcclusionInspection,\n LodOcclusionInspectionRow,\n LodOcclusionWorldAttribution,\n LodOcclusionWorldInspection,\n} from './scene/visibility/inspection';\n\nexport interface LodOcclusionInspectionSummary extends LodOcclusionInspection {\n readonly timing?: {\n readonly medianUs: number;\n readonly p95Us: number;\n readonly samples: number;\n };\n}\n\n/**\n * SSR M0 inspection is a detached projection of the consumer admission\n * result. The admission owner remains in `ssr/admission`; this re-export\n * keeps inspection callers on the same typed identity and status vocabulary.\n */\nexport type {\n SsrAdmissionBudget,\n SsrAdmissionResult,\n SsrAdmissionWork,\n SsrDependenciesInspection,\n SsrFormatReceipt,\n SsrReflectionFallbackReceipt,\n SsrTemporalReceipt,\n} from './ssr/admission';\nexport type {\n SsrAdmissionError,\n SsrAdmissionErrorCode,\n SsrAdmissionErrorDetail,\n SsrOwnerRecoveryAction,\n} from './ssr/errors';\nexport type { SsrAdmissionIdentity } from './ssr/identity';\n\nexport interface LightInspectionInput {\n readonly generation: number;\n readonly candidate: string | undefined;\n readonly accepted: string | undefined;\n readonly lastKnownGood: string | undefined;\n readonly failure: string | undefined;\n readonly failureKeys: readonly string[];\n readonly resourceCount: number;\n readonly uploadBytes: number;\n}\n\nexport type LightInspection = Readonly<LightInspectionInput>;\n\nexport function projectLightInspection(input: LightInspectionInput): LightInspection {\n return Object.freeze({\n generation: input.generation,\n candidate: input.candidate,\n accepted: input.accepted,\n lastKnownGood: input.lastKnownGood,\n failure: input.failure,\n failureKeys: [...input.failureKeys],\n resourceCount: input.resourceCount,\n uploadBytes: input.uploadBytes,\n });\n}\n\nexport function lightInspectionIdentity(topology: string, generation: number): string {\n return `${topology}:generation-${generation}`;\n}\n\nexport type BloomGraphStatus = 'empty' | 'valid' | 'invalid';\n\nexport interface BloomInspection {\n readonly graphStatus: BloomGraphStatus;\n readonly enabled: boolean;\n readonly targetCount: number;\n readonly targetBytes: number;\n readonly resourceCount: number;\n readonly passCount: number;\n readonly encodeCount: number;\n readonly bindGroupCount: number;\n readonly uploadCount: number;\n readonly residentChildBytes: number;\n readonly generation: number;\n readonly state: 'off' | 'active' | 'retiring';\n}\nexport type { TransmissionInspection } from './transmission/inspection';\n\nexport interface BatchTopologyInspection {\n readonly revision: number;\n readonly batchCount: number;\n readonly candidateCount: number;\n readonly rebuilds: number;\n readonly patches: number;\n readonly ineligible: number;\n}\n\nexport interface ProbeBlendRecordInspection {\n readonly objectKey: number;\n readonly generation: number;\n readonly localBlendFraction: number;\n readonly shPreblend: readonly number[];\n readonly byteLength: number;\n readonly candidate: boolean;\n readonly accepted: boolean;\n readonly lastKnownGood: boolean;\n readonly sentinel: string | undefined;\n readonly probeBlendIndex: number;\n readonly contributors: readonly {\n readonly identity: string;\n readonly distance: number;\n readonly radius: number;\n readonly coverage: number;\n readonly q: number;\n readonly qHat: number;\n readonly alpha: number;\n }[];\n readonly qHatSum: number;\n readonly rStar: number;\n readonly fallbackReason: string | undefined;\n}\n\nexport interface ProbeSkyInspection {\n readonly available: boolean;\n readonly identity: string | undefined;\n readonly sourceKey: string | undefined;\n readonly irradiance: readonly [number, number, number];\n readonly fallbackReason: string | undefined;\n}\n\nexport interface ProbeBlendInspection {\n readonly activeContributorCount: number;\n readonly admittedProbeCount: number;\n readonly coverage: number;\n readonly skyResidualFraction: number;\n readonly finite: boolean;\n readonly errorCode: 'capacity-exceeded' | 'invalid-admitted-prefix' | undefined;\n readonly records: readonly ProbeBlendRecordInspection[];\n readonly sky: ProbeSkyInspection;\n readonly dirtyVisitCount: number;\n readonly dirtyReasons: readonly string[];\n readonly receipt: {\n readonly activeIdentities: readonly string[];\n readonly admittedIdentities: readonly string[];\n readonly rejectedIdentities: readonly string[];\n readonly stableOrder: readonly string[];\n readonly capacity: number;\n readonly scaleRadius: number;\n readonly finite: boolean;\n readonly overflowReason: 'active-count-exceeds-capacity' | undefined;\n };\n}\n\nexport interface GpuSceneTableInspection {\n readonly capacity: number;\n readonly bytes: number;\n}\n\ntype GpuSceneTableName = 'primitive' | 'instance' | 'transform' | 'drawTemplate' | 'material';\n\nexport interface GpuSceneInspection {\n readonly capacity: number;\n readonly tables: Readonly<Record<GpuSceneTableName, GpuSceneTableInspection>>;\n readonly uploadRanges: number;\n readonly uploadBytes: number;\n readonly capacityGrows: number;\n readonly fullRebuilds: number;\n readonly clearedSlots: number;\n readonly noChangeFrames: number;\n}\n\nexport interface GpuDrivenProductionInspection {\n readonly gpuOwnedSnapshotsMaterialized: number;\n readonly filteredPlanBuilds: number;\n readonly gpuOwnedEntityCount: number;\n readonly candidateUploadBytes: number;\n readonly batchUploadBytes: number;\n readonly viewConstantsUploadBytes: number;\n readonly batchBindGroupCreates: number;\n readonly viewBindGroupCreates: number;\n readonly topologyRevision: number | undefined;\n readonly validatedGpuOwnedRows: number;\n readonly cpuFallbackDrawItems: number;\n /** Index work accumulated by the real GPU LOD selector for the last submit. */\n readonly geometryWork: number;\n /** Level-0 index work for the same selected candidates. */\n readonly rootGeometryWork: number;\n /** `1 - geometryWork / rootGeometryWork` when the root denominator is non-zero. */\n readonly geometryWorkReduction: number;\n /** Number of selector batches in the last filtered production plan. */\n readonly batchCount: number;\n /** Number of non-zero-capacity indirect raster commands actually encoded. */\n readonly indirectDrawCount: number;\n}\n\nexport type DirectionalShadowEffectiveProfile =\n | 'off'\n | DirectionalShadowFilterLabel\n | 'rhi-null-structural';\n\nexport type DirectionalShadowProfile = 'off' | DirectionalShadowFilterLabel;\n\nexport interface DirectionalShadowInspectionError {\n readonly code: string;\n readonly expected: string;\n readonly hint: string;\n readonly detail?: unknown;\n}\n\n/** Bounded, detached Directional shadow facts for AI-readable inspection. */\nexport interface DirectionalShadowInspection {\n readonly requested: DirectionalShadowProfile;\n readonly effective: DirectionalShadowEffectiveProfile;\n readonly status: 'accepted' | 'fallback' | 'rejected';\n readonly fallbackReason?: 'webgl2-unsupported' | 'rhi-null-structural' | 'candidate-failed';\n readonly lastKnownGood: boolean;\n readonly pixelEvidence: 'available' | 'not-available';\n readonly cascadeCount: number;\n readonly mapSize: number;\n readonly atlasBytes: number;\n readonly writerPasses: number;\n readonly blockerTaps: number;\n readonly filterTapUpperBound: number;\n readonly seamTapUpperBound: number;\n readonly shadowAngularRadius: number | undefined;\n readonly maxPenumbraTexels: number | undefined;\n readonly deviceGeneration: number;\n readonly graphGeneration: number;\n readonly error?: DirectionalShadowInspectionError;\n}\n\nexport type ReflectionProbeSelectionInspection =\n | { readonly kind: 'probe'; readonly worldId: number; readonly entityKey: number }\n | { readonly kind: 'skylight' };\n\nexport type ReflectionFallbackSource = 'probe' | 'skylight' | 'neutral';\n\nexport type ReflectionFallbackState = 'candidate' | 'active' | 'lkg' | 'neutral' | 'unavailable';\n\n/** Detached committed fallback facts; never exposes a live GPU handle. */\nexport interface ReflectionFallbackReceipt {\n /** Device-scope owner that identifies the renderer transaction. */\n readonly rendererId?: string;\n /** Stable producer identity for this detached projection. */\n readonly producerId?: string;\n /** Stable main-pass renderable identity, when this is a per-renderable row. */\n readonly renderableKey?: string;\n /** Stable producer source identity, never a physical resource handle. */\n readonly sourceKey?: string;\n /** Frame number that produced this detached receipt. */\n readonly frameId?: number;\n readonly source: ReflectionFallbackSource;\n readonly sourceGeneration: number;\n readonly projectionGeneration: number;\n readonly deviceGeneration: number;\n readonly state: ReflectionFallbackState;\n readonly candidateVisible: false;\n readonly coverage: number;\n readonly extent?: readonly [number, number, number];\n readonly brdfSignature: string;\n /** Exact host identity of the detached producer transaction, when bound. */\n readonly identity?: SsrAdmissionIdentity;\n}\n\n/**\n * One completed readback for the frame-owned fallback attachment.\n *\n * This is an aggregate attachment fact, not a per-renderable row. Row\n * receipts deliberately carry source/coverage identity only, so one pixel\n * cannot be mistaken for every renderable's BRDF result.\n */\nexport interface ReflectionFallbackReadbackReceipt {\n readonly rendererId: string;\n readonly producerId: string;\n readonly frameId: number;\n readonly deviceGeneration: number;\n readonly graphGeneration: number;\n readonly textureIdentity: number;\n readonly format: string;\n readonly size: { readonly width: number; readonly height: number };\n readonly linearHdr: readonly [number, number, number, number];\n readonly readbackHash: string;\n readonly readbackStatus: 'complete';\n}\n\nexport type ReflectionFallbackFailureStage =\n | 'prepare'\n | 'filter'\n | 'build'\n | 'encode'\n | 'finish'\n | 'submit'\n | 'completion';\n\nexport type ReflectionFallbackRecoveryAction =\n | 'use-LKG'\n | 'use-Skylight'\n | 'use-neutral'\n | 'recapture'\n | 'rebuild'\n | 'retry';\n\nexport interface ReflectionFallbackInspection {\n readonly receipt: ReflectionFallbackReceipt;\n readonly failureStage?: ReflectionFallbackFailureStage;\n readonly failureCode?: string;\n readonly expected?: string;\n readonly detail?: Readonly<Record<string, unknown>>;\n readonly recoveryAction: ReflectionFallbackRecoveryAction;\n}\n\nexport interface ReflectionProbeInspection {\n readonly selection: ReflectionProbeSelectionInspection;\n readonly factCount: number;\n readonly acceptedCount: number;\n readonly activeCount: number;\n readonly rawFacesCaptured: number;\n readonly filteredStepsCompleted: number;\n readonly filteredMipLevels: readonly number[];\n readonly scheduledRawFaces: number;\n readonly scheduledFilteredSteps: number;\n readonly pipelineReady: boolean;\n readonly pipelineWarmupAttempts: number;\n readonly pipelineWarmupFailure?: string;\n readonly reflectionFallback: ReflectionFallbackReceipt;\n /** Latest bounded fallback failure and owner-directed recovery action. */\n readonly reflectionFallbackInspection: ReflectionFallbackInspection;\n /** Bounded per-renderable projections; no live graph resources are included. */\n readonly reflectionFallbacks?: readonly ReflectionFallbackReceipt[];\n /** Completed frame attachment readback; separate from per-renderable rows. */\n readonly reflectionFallbackReadback?: ReflectionFallbackReadbackReceipt;\n}\n\n/** Detached semantic descriptor for the Standard scene-temporal producer. */\nexport interface TemporalTargetInspection {\n readonly identity: 'standard-scene-temporal';\n readonly producerId: 'forgeax::standard::scene-data';\n readonly schema: 'forgeax::scene-data::temporal-v1';\n readonly targetCount: 1;\n readonly descriptor: {\n readonly format: 'rgba16float';\n readonly width: number;\n readonly height: number;\n readonly sampleCount: 1;\n readonly bytes: number;\n };\n}\n\n/** Detached, bounded Motion Blur facts; no graph, device, target, or history handle. */\nexport type MotionBlurInspectionStatus = 'off' | 'active' | 'reset' | 'invalid';\n\nexport interface MotionBlurInspection {\n readonly enabled: boolean;\n readonly status: MotionBlurInspectionStatus;\n readonly shutterAngle: number;\n readonly maxRadiusPixels: number;\n readonly sampleCount: number;\n readonly temporalDemand: 'none' | 'scene-data-temporal-v1';\n readonly passName: 'motion-blur';\n readonly historyWrites: 0;\n readonly lastFailure?: 'invalid-params' | 'scene-data-unavailable';\n}\n\nexport type RenderSceneResyncReason =\n | 'attach'\n | 'asset-catalog-changed'\n | 'shared-ref-changed'\n | 'unsupported-change'\n | 'non-rigid-lane'\n | 'explicit-invalidate';\n\nexport interface PersistentRenderSceneInspection {\n readonly worldEntitiesScanned: number;\n readonly fullRebuilds: number;\n readonly noChangeFrames: number;\n readonly deltaFrames: number;\n readonly transformUpdates: number;\n readonly lastResyncReason: RenderSceneResyncReason | undefined;\n readonly projectionRecords: number;\n /** Numeric probe ownership facts; no GPU handles or object graph references. */\n readonly probeBlend?: ProbeBlendInspection;\n readonly topology: BatchTopologyInspection;\n readonly gpu:\n | { readonly status: 'inactive' }\n | { readonly status: 'unsupported'; readonly reason: 'storage-buffer-unavailable' }\n | ({ readonly status: 'resident' } & GpuSceneInspection)\n | { readonly status: 'rebuild-pending' }\n | { readonly status: 'error' };\n /** Bounded retained authoring observations; no graph or backend handles. */\n readonly pointsLines: readonly PointsLinesInspection[];\n}\n\nexport type RenderSceneInspection = PersistentRenderSceneInspection & {\n readonly gpuDriven: GpuDrivenProductionInspection;\n};\n","import type { LightResourceUnavailableError } from '../../errors/render';\nimport {\n type LightInspection,\n lightInspectionIdentity,\n projectLightInspection,\n} from '../../inspection-types';\nimport type { ExtendedLightingResourceCandidate } from './resources';\n\nexport type ExtendedLightingResourceStatus = 'empty' | 'candidate' | 'accepted';\n\nexport interface ExtendedLightingState {\n readonly enabled: boolean;\n readonly generation: number;\n readonly status: ExtendedLightingResourceStatus;\n readonly candidate: ExtendedLightingResourceCandidate | undefined;\n readonly accepted: ExtendedLightingResourceCandidate | undefined;\n readonly lastKnownGood: ExtendedLightingResourceCandidate | undefined;\n readonly resourceCount: number;\n readonly descriptorBytes: number;\n readonly uploadCount: number;\n readonly passCount: number;\n readonly bindGroupCount: number;\n readonly failure: LightResourceUnavailableError | undefined;\n readonly failureKeys: readonly string[];\n}\n\nexport function createExtendedLightingState(generation: number): ExtendedLightingState {\n return {\n enabled: false,\n generation,\n status: 'empty',\n candidate: undefined,\n accepted: undefined,\n lastKnownGood: undefined,\n resourceCount: 0,\n descriptorBytes: 0,\n uploadCount: 0,\n passCount: 0,\n bindGroupCount: 0,\n failure: undefined,\n failureKeys: [],\n };\n}\n\nexport function promoteExtendedLightingCandidate(\n state: ExtendedLightingState,\n candidate: ExtendedLightingResourceCandidate | undefined,\n): ExtendedLightingState {\n if (candidate === undefined) return state;\n return {\n ...state,\n enabled: true,\n generation: candidate.generation,\n status: 'accepted',\n candidate: undefined,\n accepted: candidate,\n lastKnownGood: candidate,\n resourceCount: 4,\n descriptorBytes: candidate.descriptorBytes,\n uploadCount: candidate.uploadCount,\n };\n}\n\nexport function recordExtendedLightingFailure(\n state: ExtendedLightingState,\n failure: LightResourceUnavailableError,\n): ExtendedLightingState {\n const key = `${failure.detail.entity}:${failure.detail.feature}:${failure.detail.generation}`;\n if (state.failureKeys.includes(key)) return state;\n return {\n ...state,\n failure,\n failureKeys: [...state.failureKeys, key],\n };\n}\n\nexport function projectExtendedLightingInspection(state: ExtendedLightingState): LightInspection {\n const identity = (candidate: ExtendedLightingResourceCandidate | undefined) =>\n candidate === undefined\n ? undefined\n : lightInspectionIdentity(candidate.topology, candidate.generation);\n return projectLightInspection({\n generation: state.generation,\n candidate: identity(state.candidate),\n accepted: identity(state.accepted),\n lastKnownGood: identity(state.lastKnownGood),\n failure: state.failure?.code,\n failureKeys: state.failureKeys,\n resourceCount: state.resourceCount,\n uploadBytes: state.descriptorBytes,\n });\n}\n","export const OCCLUSION_QUERY_PAGE_COUNT = 3;\nexport const OCCLUSION_QUERY_PAGE_INDEX_LIMIT = 4096;\nexport const OCCLUSION_QUERY_RESULT_BYTES = 8;\nexport const OCCLUSION_QUERY_PAGE_BYTES =\n OCCLUSION_QUERY_PAGE_INDEX_LIMIT * OCCLUSION_QUERY_RESULT_BYTES;\n\nexport interface OcclusionQueryIdentity {\n readonly viewKey: string;\n readonly attachmentId: string;\n readonly deviceGeneration: number;\n readonly worldGeneration: number;\n readonly primitiveSlot: number;\n readonly slotGeneration: number;\n}\n\nexport interface OcclusionQueryReservation extends OcclusionQueryIdentity {\n readonly pageIndex: number;\n readonly queryIndex: number;\n readonly reservationId: number;\n}\n\nexport interface OcclusionQueryTicket extends OcclusionQueryIdentity {\n readonly pageIndex: number;\n readonly queryIndex: number;\n readonly reservationId: number;\n readonly submissionGeneration: number;\n}\n\nexport interface OcclusionQueryPoolInspection {\n readonly pageCount: number;\n readonly pageIndexLimit: number;\n readonly resolveBytes: number;\n readonly stagingBytes: number;\n readonly availablePages: number;\n readonly inFlight: number;\n readonly disposed: boolean;\n}\n\nexport interface OcclusionQueryCompletion {\n readonly status: 'accepted' | 'stale';\n /** M3 transport never suppresses a draw; M4 owns confidence policy. */\n readonly visible: true;\n}\n\ninterface PageState {\n readonly index: number;\n nextQueryIndex: number;\n pendingCount: number;\n inFlightCount: number;\n}\n\nfunction identityKey(identity: OcclusionQueryIdentity): string {\n return [\n identity.viewKey,\n identity.attachmentId,\n identity.deviceGeneration,\n identity.worldGeneration,\n identity.primitiveSlot,\n identity.slotGeneration,\n ].join('|');\n}\n\n/** Renderer-owned bounded query transport; it contains no visibility policy. */\nexport class OcclusionQueryPool {\n private readonly pages: PageState[] = Array.from(\n { length: OCCLUSION_QUERY_PAGE_COUNT },\n (_, index) => ({ index, nextQueryIndex: 0, pendingCount: 0, inFlightCount: 0 }),\n );\n private readonly pending = new Map<number, OcclusionQueryReservation>();\n private readonly tickets = new Map<number, OcclusionQueryTicket>();\n private nextReservationId = 1;\n private disposed = false;\n\n reserve(identity: OcclusionQueryIdentity): OcclusionQueryReservation | undefined {\n if (this.disposed) return undefined;\n const page = this.pages.find(\n (candidate) =>\n candidate.inFlightCount === 0 &&\n candidate.nextQueryIndex < OCCLUSION_QUERY_PAGE_INDEX_LIMIT,\n );\n if (page === undefined || page.nextQueryIndex >= OCCLUSION_QUERY_PAGE_INDEX_LIMIT) {\n return undefined;\n }\n const reservation = Object.freeze({\n ...identity,\n pageIndex: page.index,\n queryIndex: page.nextQueryIndex,\n reservationId: this.nextReservationId++,\n });\n page.nextQueryIndex += 1;\n page.pendingCount += 1;\n this.pending.set(reservation.reservationId, reservation);\n return reservation;\n }\n\n publish(\n reservation: OcclusionQueryReservation,\n result: { readonly submitted: boolean; readonly submissionGeneration: number },\n ): OcclusionQueryTicket | undefined {\n const pending = this.pending.get(reservation.reservationId);\n if (pending === undefined || this.disposed) {\n return undefined;\n }\n // A failed shared submit leaves the reservation retryable but does not\n // count as in-flight work and never publishes a completion ticket.\n if (!result.submitted) return undefined;\n this.pending.delete(reservation.reservationId);\n const page = this.pages[pending.pageIndex];\n if (page !== undefined) {\n page.pendingCount = Math.max(0, page.pendingCount - 1);\n page.inFlightCount += 1;\n }\n const ticket = Object.freeze({ ...pending, submissionGeneration: result.submissionGeneration });\n this.tickets.set(ticket.reservationId, ticket);\n return ticket;\n }\n\n /** Return an unsubmitted reservation to its bounded page. */\n cancel(reservation: OcclusionQueryReservation): boolean {\n const pending = this.pending.get(reservation.reservationId);\n if (pending === undefined) return false;\n this.pending.delete(reservation.reservationId);\n const page = this.pages[pending.pageIndex];\n if (page !== undefined) {\n page.pendingCount = Math.max(0, page.pendingCount - 1);\n this.releasePage(pending.pageIndex);\n }\n return true;\n }\n\n complete(ticket: OcclusionQueryTicket, _samples: number): OcclusionQueryCompletion {\n const current = this.tickets.get(ticket.reservationId);\n if (current !== undefined) {\n this.tickets.delete(ticket.reservationId);\n const page = this.pages[current.pageIndex];\n if (page !== undefined) page.inFlightCount = Math.max(0, page.inFlightCount - 1);\n this.releasePage(current.pageIndex);\n }\n if (this.disposed || current === undefined || identityKey(current) !== identityKey(ticket)) {\n return { status: 'stale', visible: true };\n }\n return { status: 'accepted', visible: true };\n }\n\n inspect(): OcclusionQueryPoolInspection {\n return {\n pageCount: OCCLUSION_QUERY_PAGE_COUNT,\n pageIndexLimit: OCCLUSION_QUERY_PAGE_INDEX_LIMIT,\n resolveBytes: OCCLUSION_QUERY_PAGE_BYTES,\n stagingBytes: OCCLUSION_QUERY_PAGE_BYTES,\n availablePages: this.disposed\n ? 0\n : this.pages.filter(\n (page) =>\n page.inFlightCount === 0 && page.nextQueryIndex < OCCLUSION_QUERY_PAGE_INDEX_LIMIT,\n ).length,\n inFlight: this.tickets.size,\n disposed: this.disposed,\n };\n }\n\n dispose(): void {\n this.disposed = true;\n this.pending.clear();\n this.tickets.clear();\n for (const page of this.pages) {\n page.pendingCount = 0;\n page.inFlightCount = 0;\n }\n }\n\n private releasePage(pageIndex: number): void {\n const page = this.pages[pageIndex];\n if (page !== undefined && page.pendingCount === 0 && page.inFlightCount === 0) {\n page.nextQueryIndex = 0;\n }\n }\n}\n","export interface OcclusionBounds {\n readonly min: readonly [number, number, number];\n readonly max: readonly [number, number, number];\n}\n\nexport interface OcclusionPassIdentity {\n readonly primitiveSlot: number;\n readonly slotGeneration: number;\n}\n\nexport interface OcclusionPassPlan {\n readonly after: string;\n readonly depth: { readonly resource: string; readonly usage: 'depth-read-only' };\n readonly color: { readonly resource: string; readonly usage: 'not-written' };\n readonly proxyBounds: OcclusionBounds;\n readonly queryIndex: number;\n readonly identity?: OcclusionPassIdentity;\n readonly resolve: { readonly queryIndex: number; readonly bytes: number };\n readonly copy: { readonly asynchronous: true; readonly bytes: number };\n readonly writesColor: false;\n readonly writesDepth: false;\n readonly submitCount: 1;\n readonly mapSameFrame: false;\n}\n\nexport interface OcclusionPassInput {\n readonly opaquePass: string;\n readonly depthResource: string;\n readonly colorResource: string;\n readonly bounds: OcclusionBounds | undefined;\n readonly queryIndex: number;\n readonly identity?: OcclusionPassIdentity;\n readonly transparent?: boolean;\n readonly deformed?: boolean;\n}\n\nexport interface OcclusionQueryResources {\n readonly pageIndex: number;\n readonly querySet: QuerySet;\n readonly resolveBuffer: Buffer;\n readonly stagingBuffer: Buffer;\n}\n\nexport function createOcclusionQueryResources(\n device: RhiDevice,\n pageIndex: number,\n): Result<OcclusionQueryResources, RhiError> {\n const querySet = device.createQuerySet({\n label: `occlusion-page-${pageIndex}`,\n type: 'occlusion',\n count: OCCLUSION_QUERY_PAGE_INDEX_LIMIT,\n });\n if (!querySet.ok) return querySet;\n const resolveBuffer = device.createBuffer({\n label: `occlusion-page-${pageIndex}-resolve`,\n size: OCCLUSION_QUERY_PAGE_BYTES,\n usage: GPU_BUFFER_USAGE_QUERY_RESOLVE | GPU_BUFFER_USAGE_COPY_SRC,\n });\n if (!resolveBuffer.ok) {\n device.destroyQuerySet(querySet.value);\n return resolveBuffer;\n }\n const stagingBuffer = device.createBuffer({\n label: `occlusion-page-${pageIndex}-staging`,\n size: OCCLUSION_QUERY_PAGE_BYTES,\n usage: GPU_BUFFER_USAGE_MAP_READ | GPU_BUFFER_USAGE_COPY_DST,\n });\n if (!stagingBuffer.ok) {\n device.destroyBuffer(resolveBuffer.value);\n device.destroyQuerySet(querySet.value);\n return stagingBuffer;\n }\n return ok({\n pageIndex,\n querySet: querySet.value,\n resolveBuffer: resolveBuffer.value,\n stagingBuffer: stagingBuffer.value,\n });\n}\n\n/** Records resolve and copy only; caller owns one shared encoder and submit. */\nexport function recordOcclusionResolve(\n encoder: RhiCommandEncoder,\n resources: OcclusionQueryResources,\n firstQuery: number,\n queryCount: number,\n): Result<void, RhiError> {\n if (\n !Number.isSafeInteger(firstQuery) ||\n !Number.isSafeInteger(queryCount) ||\n firstQuery < 0 ||\n queryCount <= 0 ||\n firstQuery + queryCount > OCCLUSION_QUERY_PAGE_INDEX_LIMIT\n ) {\n return err(\n new RhiErrorClass({\n code: 'webgpu-runtime-error',\n expected: 'query range stays within one 4096-index page',\n hint: 'allocate a bounded page before recording occlusion resolve',\n }),\n );\n }\n const resolved = encoder.resolveQuerySet(\n resources.querySet,\n firstQuery,\n queryCount,\n resources.resolveBuffer,\n 0,\n );\n if (!resolved.ok) return resolved;\n encoder.copyBufferToBuffer(resources.resolveBuffer, resources.stagingBuffer, queryCount * 8);\n return ok(undefined);\n}\n\nfunction finiteBounds(bounds: OcclusionBounds | undefined): bounds is OcclusionBounds {\n if (bounds === undefined) return false;\n return [...bounds.min, ...bounds.max].every((value) => Number.isFinite(value));\n}\n\n/** Creates only the transport plan; confidence remains owned by visibility facet/M4. */\nexport function buildOcclusionPassPlan(input: OcclusionPassInput): OcclusionPassPlan | undefined {\n if (\n input.transparent === true ||\n input.deformed === true ||\n !finiteBounds(input.bounds) ||\n !Number.isSafeInteger(input.queryIndex) ||\n input.queryIndex < 0\n ) {\n return undefined;\n }\n return Object.freeze({\n after: input.opaquePass,\n depth: { resource: input.depthResource, usage: 'depth-read-only' as const },\n color: { resource: input.colorResource, usage: 'not-written' as const },\n proxyBounds: input.bounds,\n queryIndex: input.queryIndex,\n ...(input.identity === undefined ? {} : { identity: Object.freeze({ ...input.identity }) }),\n resolve: { queryIndex: input.queryIndex, bytes: 8 },\n copy: { asynchronous: true as const, bytes: 8 },\n writesColor: false as const,\n writesDepth: false as const,\n submitCount: 1 as const,\n mapSameFrame: false as const,\n });\n}\n\nimport type {\n Buffer,\n QuerySet,\n Result,\n RhiCommandEncoder,\n RhiDevice,\n RhiError,\n} from '@forgeax/engine-rhi';\nimport { err, ok, RhiError as RhiErrorClass } from '@forgeax/engine-rhi';\nimport {\n GPU_BUFFER_USAGE_COPY_DST,\n GPU_BUFFER_USAGE_COPY_SRC,\n GPU_BUFFER_USAGE_MAP_READ,\n GPU_BUFFER_USAGE_QUERY_RESOLVE,\n} from '../../gpu-usage';\nimport {\n OCCLUSION_QUERY_PAGE_BYTES,\n OCCLUSION_QUERY_PAGE_INDEX_LIMIT,\n} from './occlusion-query-pool';\n","/** Closed view roles used by the renderer-owned visibility facet. */\nexport type VisibilityViewRole = 'main' | 'shadow' | 'reflection' | 'probe';\n\nexport interface ViewKey {\n readonly attachmentId: string;\n readonly cameraEntity: number;\n readonly viewRole: VisibilityViewRole;\n readonly viewGeneration: number;\n}\n\nexport interface PrimitiveKey {\n readonly attachmentId: string;\n readonly worldGeneration: number;\n readonly primitiveSlot: number;\n readonly slotGeneration: number;\n}\n\nexport interface VisibilityCandidate {\n readonly level: number;\n readonly confidence: number;\n}\n\nexport interface VisibilityFacetInspection {\n readonly owner: 'persistent-render-scene';\n readonly activeViews: number;\n readonly facetRows: number;\n}\n\nexport interface VisibilityFacetInput {\n readonly view: ViewKey;\n readonly primitive: PrimitiveKey;\n readonly epoch: number;\n readonly candidate: VisibilityCandidate;\n}\n\nexport function viewKeyId(key: ViewKey): string {\n return `${key.attachmentId}:${key.cameraEntity}:${key.viewRole}:${key.viewGeneration}`;\n}\n\nexport function primitiveKeyId(key: PrimitiveKey): string {\n return `${key.attachmentId}:${key.worldGeneration}:${key.primitiveSlot}:${key.slotGeneration}`;\n}\n\nexport function viewKey(input: ViewKey): ViewKey {\n return Object.freeze({ ...input });\n}\n\nexport function primitiveKey(input: PrimitiveKey): PrimitiveKey {\n return Object.freeze({ ...input });\n}\n","import type {\n Buffer,\n QuerySet,\n RenderPipeline,\n Result,\n RhiCommandEncoder,\n RhiDevice,\n RhiError,\n RhiRenderPassEncoder,\n} from '@forgeax/engine-rhi';\nimport { err, ok, RhiError as RhiErrorClass } from '@forgeax/engine-rhi';\nimport {\n GPU_BUFFER_USAGE_COPY_DST,\n GPU_BUFFER_USAGE_MAP_READ,\n GPU_BUFFER_USAGE_VERTEX,\n} from '../../gpu-usage';\nimport type { PipelineBuilderShaderModuleFactory } from '../../pipeline-builder';\nimport type { VisibilityBudget } from './budget';\nimport type { VisibilityFacetStore } from './facet';\nimport {\n createOcclusionQueryResources,\n type OcclusionBounds,\n type OcclusionQueryResources,\n recordOcclusionResolve,\n} from './occlusion-pass';\nimport {\n OCCLUSION_QUERY_PAGE_INDEX_LIMIT,\n OcclusionQueryPool,\n type OcclusionQueryReservation,\n type OcclusionQueryTicket,\n} from './occlusion-query-pool';\nimport {\n type PrimitiveKey,\n primitiveKeyId,\n type ViewKey,\n type VisibilityCandidate,\n viewKeyId,\n} from './types';\n\nconst PROXY_VERTEX_FLOATS_PER_CANDIDATE = 36 * 4;\nconst PROXY_GEOMETRY_BYTES =\n OCCLUSION_QUERY_PAGE_INDEX_LIMIT * PROXY_VERTEX_FLOATS_PER_CANDIDATE * 4;\n\n/** @internal Deterministic producer hook; never configured by the player API. */\nexport interface OcclusionRuntimeTestHooks {\n readonly beforeMap?: () => Promise<void>;\n}\n\nlet runtimeTestHooks: OcclusionRuntimeTestHooks | undefined;\n\n/** @internal Used only by the production evidence falsification harness. */\nexport function setOcclusionRuntimeTestHooks(hooks: OcclusionRuntimeTestHooks | undefined): void {\n runtimeTestHooks = hooks;\n}\n\nexport interface OcclusionRuntimeCandidate {\n readonly view: ViewKey;\n readonly primitive: PrimitiveKey;\n readonly epoch: number;\n readonly bounds: OcclusionBounds;\n readonly candidate: VisibilityCandidate;\n readonly deviceGeneration: number;\n /** Clip-space triangles for the conservative bounds proxy. */\n readonly proxyVertices?: Float32Array;\n}\n\nexport interface OcclusionFrameProjection {\n readonly querySet: QuerySet;\n readonly queryIndex: number;\n readonly queryCount: number;\n readonly sampleCount: 1 | 4;\n readonly pageIndex: number;\n readonly reservationId: number;\n readonly encodeProxyBounds: (pass: RhiRenderPassEncoder) => Result<void, RhiError>;\n readonly beginCandidate: (pass: RhiRenderPassEncoder) => Result<void, RhiError>;\n readonly endCandidate: (pass: RhiRenderPassEncoder) => Result<void, RhiError>;\n readonly recordResolve: (encoder: RhiCommandEncoder) => Result<void, RhiError>;\n readonly commit: (\n submitted: boolean,\n submissionGeneration: number,\n profilePhase?: OcclusionProfilePhaseRunner,\n ) => void;\n}\n\nexport type OcclusionProfilePhaseRunner = <T>(\n phase: 'record/occlusion-query-submit' | 'record/occlusion-global-advance',\n action: () => T,\n) => T;\n\ninterface PendingFrame {\n readonly reservations: readonly OcclusionQueryReservation[];\n readonly resources: OcclusionQueryResources;\n readonly candidates: readonly OcclusionRuntimeCandidate[];\n readonly sampleCount: 1 | 4;\n endedCount: number;\n readonly proxyFloatCount: number;\n}\n\n/**\n * RenderSystem-owned query transport. It is deliberately the only bridge\n * between the logical pool, the typed graph raster pass, and facet completion.\n */\nexport class OcclusionRenderRuntime {\n private readonly pool = new OcclusionQueryPool();\n private readonly resources = new Map<number, OcclusionQueryResources>();\n private readonly activeCompletions = new Map<OcclusionQueryResources, Promise<void>>();\n private readonly retiredResources = new Set<OcclusionQueryResources>();\n /** Candidate descriptors are rebuilt only when the extracted frame changes. */\n private candidateSource: readonly OcclusionRuntimeCandidate[] | undefined;\n private validCandidates: readonly OcclusionRuntimeCandidate[] = [];\n private readonly candidateByKey = new Map<string, OcclusionRuntimeCandidate>();\n private lastPrepareUnavailable = false;\n private pendingFrame: PendingFrame | undefined;\n private disposed = false;\n private proxyBuffer: Buffer | undefined;\n private readonly proxyScratch: Float32Array;\n private proxyPipeline: RenderPipeline | undefined;\n private proxyPipelineSampleCount: 1 | 4 | undefined;\n private readonly queryLatencySamplesUs: number[] = [];\n private lastQueryLatencyUs = 0;\n private readonly projection: OcclusionFrameProjection;\n\n constructor(\n private readonly device: RhiDevice,\n private readonly facets: VisibilityFacetStore,\n private readonly shaderModuleFactory?: PipelineBuilderShaderModuleFactory,\n private readonly budget: VisibilityBudget = facets.visibilityBudget(),\n ) {\n const runtime = this;\n this.proxyScratch = new Float32Array(\n Math.min(this.budget.effectiveQueryBudget, OCCLUSION_QUERY_PAGE_INDEX_LIMIT) *\n PROXY_VERTEX_FLOATS_PER_CANDIDATE,\n );\n this.projection = {\n get querySet() {\n return runtime.pendingFrame?.resources.querySet as QuerySet;\n },\n get queryIndex() {\n return runtime.pendingFrame?.reservations[0]?.queryIndex ?? 0;\n },\n get queryCount() {\n return runtime.pendingFrame?.reservations.length ?? 0;\n },\n get sampleCount() {\n return runtime.pendingFrame?.sampleCount ?? 1;\n },\n get pageIndex() {\n return runtime.pendingFrame?.reservations[0]?.pageIndex ?? 0;\n },\n get reservationId() {\n return runtime.pendingFrame?.reservations[0]?.reservationId ?? 0;\n },\n encodeProxyBounds: (pass) => {\n const pending = runtime.pendingFrame;\n return pending === undefined\n ? err(runtimeError('the current RenderSystem frame owns the occlusion candidate'))\n : runtime.encodeProxyBounds(pass, pending);\n },\n beginCandidate: (pass) => {\n const pending = runtime.pendingFrame;\n if (pending === undefined || pending.endedCount >= pending.reservations.length) {\n return err(runtimeError('the current RenderSystem frame owns the occlusion candidate'));\n }\n return pass.beginOcclusionQuery(pending.reservations[pending.endedCount]?.queryIndex ?? 0);\n },\n endCandidate: (pass) => {\n const pending = runtime.pendingFrame;\n if (pending === undefined || pending.endedCount >= pending.reservations.length) {\n return err(runtimeError('the current RenderSystem frame owns the occlusion candidate'));\n }\n const ended = pass.endOcclusionQuery();\n if (ended.ok) pending.endedCount += 1;\n return ended;\n },\n recordResolve: (encoder) => {\n const pending = runtime.pendingFrame;\n if (pending === undefined || pending.endedCount !== pending.reservations.length) {\n return err(runtimeError('the real geometry pass must end its occlusion query first'));\n }\n return recordOcclusionResolve(\n encoder,\n pending.resources,\n pending.reservations[0]?.queryIndex ?? 0,\n pending.reservations.length,\n );\n },\n commit: (submitted, submissionGeneration, profilePhase) => {\n const pending = runtime.pendingFrame;\n if (pending !== undefined)\n runtime.commit(pending, submitted, submissionGeneration, profilePhase);\n },\n };\n }\n\n prepare(candidate: OcclusionRuntimeCandidate): OcclusionFrameProjection | undefined {\n // Keep the single-candidate helper useful for transport unit tests and\n // direct callers. The RenderSystem uses prepareBatch's facet-owned queue.\n return this.prepareBatch([candidate], 1, false);\n }\n\n prepareBatch(\n candidates: readonly OcclusionRuntimeCandidate[],\n sampleCount: 1 | 4 = 1,\n useReadyQueue = true,\n ): OcclusionFrameProjection | undefined {\n this.lastPrepareUnavailable = false;\n if (this.disposed || candidates.length === 0) return undefined;\n if (this.pendingFrame !== undefined) {\n this.lastPrepareUnavailable = true;\n return undefined;\n }\n if (this.candidateSource !== candidates) {\n this.candidateSource = candidates;\n this.candidateByKey.clear();\n const valid: OcclusionRuntimeCandidate[] = [];\n for (const candidate of candidates) {\n this.candidateByKey.set(candidateKey(candidate.view, candidate.primitive), candidate);\n if (finiteBounds(candidate.bounds)) valid.push(candidate);\n }\n this.validCandidates = valid;\n }\n const valid = this.validCandidates;\n if (valid.length === 0) return undefined;\n\n let selectedCandidates: OcclusionRuntimeCandidate[];\n if (!useReadyQueue) {\n selectedCandidates = valid.slice(0, this.budget.effectiveQueryBudget);\n } else {\n const firstView = valid[0]?.view;\n if (firstView === undefined) return undefined;\n selectedCandidates = [];\n for (const entry of this.facets.dequeueQueryCandidates(\n firstView,\n this.budget.effectiveQueryBudget,\n )) {\n const candidate = this.candidateByKey.get(candidateKey(entry.view, entry.primitive));\n if (candidate === undefined || !finiteBounds(candidate.bounds)) {\n this.facets.requeueQueryCandidate(entry.view, entry.primitive);\n continue;\n }\n selectedCandidates.push(candidate);\n }\n // No ready work is a normal bounded-query frame, not a transport error.\n if (selectedCandidates.length === 0) return undefined;\n }\n\n const reservations: OcclusionQueryReservation[] = [];\n let selectedCount = 0;\n while (selectedCount < selectedCandidates.length) {\n const candidate = selectedCandidates[selectedCount];\n if (candidate === undefined) break;\n const reservation = this.pool.reserve({\n viewKey: viewKeyId(candidate.view),\n attachmentId: candidate.view.attachmentId,\n deviceGeneration: candidate.deviceGeneration,\n worldGeneration: candidate.primitive.worldGeneration,\n primitiveSlot: candidate.primitive.primitiveSlot,\n slotGeneration: candidate.primitive.slotGeneration,\n });\n if (reservation === undefined) {\n this.lastPrepareUnavailable = true;\n break;\n }\n if (reservations.length > 0 && reservation.pageIndex !== reservations[0]?.pageIndex) {\n this.pool.cancel(reservation);\n this.lastPrepareUnavailable = true;\n break;\n }\n reservations.push(reservation);\n selectedCount += 1;\n if (reservations.length >= this.budget.effectiveQueryBudget) break;\n }\n if (reservations.length === 0) {\n for (const candidate of selectedCandidates) {\n if (useReadyQueue) this.facets.requeueQueryCandidate(candidate.view, candidate.primitive);\n }\n return undefined;\n }\n if (reservations.length < selectedCandidates.length) {\n for (const reservation of reservations) this.pool.cancel(reservation);\n for (const candidate of selectedCandidates) {\n if (useReadyQueue) this.facets.requeueQueryCandidate(candidate.view, candidate.primitive);\n }\n return undefined;\n }\n const resources = this.ensureResources(reservations[0]?.pageIndex ?? 0);\n if (resources === undefined) {\n for (const reservation of reservations) this.pool.cancel(reservation);\n this.lastPrepareUnavailable = true;\n for (const candidate of selectedCandidates) {\n if (useReadyQueue) this.facets.requeueQueryCandidate(candidate.view, candidate.primitive);\n }\n return undefined;\n }\n const selected = selectedCandidates;\n let proxyFloatCount = 0;\n for (const candidate of selected) {\n const vertices = candidate.proxyVertices;\n if (vertices === undefined) continue;\n if (proxyFloatCount + vertices.length > this.proxyScratch.length) {\n for (const reservation of reservations) this.pool.cancel(reservation);\n for (const queuedCandidate of selectedCandidates) {\n if (useReadyQueue) {\n this.facets.requeueQueryCandidate(queuedCandidate.view, queuedCandidate.primitive);\n }\n }\n this.lastPrepareUnavailable = true;\n return undefined;\n }\n this.proxyScratch.set(vertices, proxyFloatCount);\n proxyFloatCount += vertices.length;\n }\n const pending: PendingFrame = {\n reservations,\n resources,\n candidates: selected,\n sampleCount,\n endedCount: 0,\n proxyFloatCount,\n };\n this.pendingFrame = pending;\n return this.projection;\n }\n\n inspect(): ReturnType<OcclusionQueryPool['inspect']> {\n return this.pool.inspect();\n }\n\n get prepareUnavailable(): boolean {\n return this.lastPrepareUnavailable;\n }\n\n /** Map-only latency from the submitted query page; queue wait is excluded. */\n inspectQueryLatency(): { readonly median: number; readonly p95: number; readonly last: number } {\n if (this.queryLatencySamplesUs.length === 0) {\n return { median: 0, p95: 0, last: this.lastQueryLatencyUs };\n }\n const sorted = [...this.queryLatencySamplesUs].sort((left, right) => left - right);\n const rank = (percentile: number): number =>\n sorted[Math.max(0, Math.ceil(sorted.length * percentile) - 1)] ?? 0;\n return {\n median: rank(0.5),\n p95: rank(0.95),\n last: this.lastQueryLatencyUs,\n };\n }\n\n /**\n * Wait until query readbacks submitted before the current observation have\n * settled. The renderer receipt only fences command submission; query\n * completion also includes the asynchronous map/unmap transition. Keeping\n * that fence here makes `renderer.observe()` publish the latest visibility\n * result and measured map latency instead of racing the readback promise.\n */\n async waitForCompletions(): Promise<void> {\n // A submission callback can publish the next page while the previous\n // completion is settling. Drain until the map stays empty so observation\n // cannot return with a newer query still racing the inspection update.\n for (;;) {\n const completions = [...this.activeCompletions.values()];\n if (completions.length === 0) return;\n await Promise.all(completions);\n }\n }\n\n /** Count a successful frame for hidden rows that were not queried this frame. */\n advanceSuccessfulSubmit(submissionGeneration: number): void {\n this.facets.advanceSuccessfulSubmits(submissionGeneration);\n }\n\n dispose(): void {\n if (this.disposed) return;\n this.disposed = true;\n this.pool.dispose();\n for (const resource of this.resources.values()) {\n const completion = this.activeCompletions.get(resource);\n if (completion === undefined) {\n this.destroyResources(resource);\n } else {\n // A completion may still be awaiting mapAsync. Destroying its staging\n // buffer here makes Dawn report a use-after-destroy validation error.\n void completion.then(() => this.destroyResources(resource));\n }\n }\n this.resources.clear();\n if (this.proxyBuffer !== undefined) this.device.destroyBuffer(this.proxyBuffer);\n this.proxyBuffer = undefined;\n this.proxyPipeline = undefined;\n this.proxyPipelineSampleCount = undefined;\n this.candidateSource = undefined;\n this.validCandidates = [];\n this.candidateByKey.clear();\n this.lastPrepareUnavailable = false;\n this.pendingFrame = undefined;\n }\n\n private ensureResources(pageIndex: number): OcclusionQueryResources | undefined {\n const existing = this.resources.get(pageIndex);\n if (existing !== undefined) return existing;\n const created = createOcclusionQueryResources(this.device, pageIndex);\n if (!created.ok) return undefined;\n this.resources.set(pageIndex, created.value);\n return created.value;\n }\n\n private commit(\n pending: PendingFrame,\n submitted: boolean,\n submissionGeneration: number,\n profilePhase?: OcclusionProfilePhaseRunner,\n ): void {\n if (this.pendingFrame !== pending) return;\n this.pendingFrame = undefined;\n const tickets: OcclusionQueryTicket[] = [];\n const accepted =\n profilePhase === undefined\n ? this.publishAndApplySubmit(pending, submitted, submissionGeneration, tickets)\n : profilePhase('record/occlusion-query-submit', () =>\n this.publishAndApplySubmit(pending, submitted, submissionGeneration, tickets),\n );\n if (!accepted) {\n for (const reservation of pending.reservations) this.pool.cancel(reservation);\n for (const candidate of pending.candidates) {\n this.facets.applyConfidence(candidate.view, candidate.primitive, {\n type: 'failure',\n submissionGeneration,\n });\n }\n return;\n }\n\n if (profilePhase === undefined) {\n this.facets.advanceSuccessfulSubmits(submissionGeneration);\n } else {\n profilePhase('record/occlusion-global-advance', () =>\n this.facets.advanceSuccessfulSubmits(submissionGeneration),\n );\n }\n const completion = this.completeAfterSubmit(tickets, pending);\n this.activeCompletions.set(pending.resources, completion);\n void completion.then(() => {\n if (this.activeCompletions.get(pending.resources) === completion) {\n this.activeCompletions.delete(pending.resources);\n }\n });\n }\n\n private publishAndApplySubmit(\n pending: PendingFrame,\n submitted: boolean,\n submissionGeneration: number,\n tickets: OcclusionQueryTicket[],\n ): boolean {\n for (const reservation of pending.reservations) {\n const ticket = this.pool.publish(reservation, { submitted, submissionGeneration });\n if (ticket !== undefined) tickets.push(ticket);\n }\n if (!submitted || tickets.length !== pending.reservations.length) return false;\n const submitEvent = Object.freeze({ type: 'submit' as const, submissionGeneration });\n for (const candidate of pending.candidates) {\n this.facets.applyConfidence(candidate.view, candidate.primitive, submitEvent);\n }\n return true;\n }\n\n private destroyResources(resource: OcclusionQueryResources): void {\n if (this.retiredResources.has(resource)) return;\n this.retiredResources.add(resource);\n this.device.destroyBuffer(resource.resolveBuffer);\n this.device.destroyBuffer(resource.stagingBuffer);\n this.device.destroyQuerySet(resource.querySet);\n }\n\n private async completeAfterSubmit(\n tickets: readonly OcclusionQueryTicket[],\n pending: PendingFrame,\n ): Promise<void> {\n try {\n await this.device.queue.onSubmittedWorkDone();\n const mapStart = performance.now();\n await runtimeTestHooks?.beforeMap?.();\n const mapped = await pending.resources.stagingBuffer.mapAsync(\n GPU_BUFFER_USAGE_MAP_READ,\n 0,\n pending.reservations.length * 8,\n );\n if (!mapped.ok) throw mapped.error;\n // Inspection is a bounded integer POD; keep the real map-only duration\n // while rounding sub-microsecond timer noise at the transport boundary.\n this.lastQueryLatencyUs = Math.max(0, Math.round((performance.now() - mapStart) * 1000));\n this.queryLatencySamplesUs.push(this.lastQueryLatencyUs);\n if (this.queryLatencySamplesUs.length > 64) this.queryLatencySamplesUs.shift();\n const bytes = mapped.value.getMappedRange(0, pending.reservations.length * 8);\n if (!bytes.ok) throw bytes.error;\n // WebGPU detaches the mapped range when unmap() is called. Copy the\n // bounded query payload while it is still mapped, then release the\n // staging buffer before applying any facet mutations. Reading the view\n // after unmap would throw on real Dawn and turn every result into the\n // fail-open failure path (leaving candidates permanently visible).\n const data = new Uint8Array(bytes.value.slice(0));\n const dataView = new DataView(data.buffer);\n const firstQuery = pending.reservations[0]?.queryIndex ?? 0;\n mapped.value.unmap();\n for (let ticketIndex = tickets.length - 1; ticketIndex >= 0; ticketIndex -= 1) {\n const ticket = tickets[ticketIndex];\n if (ticket === undefined) continue;\n const candidateIndex = ticket.queryIndex - firstQuery;\n const samples = dataView.getUint32(candidateIndex * 8, true);\n const completion = this.pool.complete(ticket, samples);\n if (completion.status !== 'accepted') continue;\n const candidate = pending.candidates[candidateIndex];\n if (candidate === undefined) continue;\n this.facets.applyConfidence(candidate.view, candidate.primitive, {\n type: 'result',\n samples,\n submissionGeneration: ticket.submissionGeneration,\n });\n this.facets.applyCompletion(\n candidate.view,\n candidate.primitive,\n candidate.epoch,\n candidate.candidate,\n );\n }\n } catch {\n for (const ticket of tickets) {\n this.pool.complete(ticket, Number.NaN);\n const candidate =\n pending.candidates[ticket.queryIndex - (pending.reservations[0]?.queryIndex ?? 0)];\n if (candidate !== undefined) {\n this.facets.applyConfidence(candidate.view, candidate.primitive, {\n type: 'failure',\n submissionGeneration: ticket.submissionGeneration,\n });\n }\n }\n }\n }\n\n private encodeProxyBounds(\n pass: RhiRenderPassEncoder,\n pending: PendingFrame,\n ): Result<void, RhiError> {\n if (pending.proxyFloatCount === 0) {\n return err(runtimeError('every occlusion candidate needs conservative proxy geometry'));\n }\n const pipeline = this.ensureProxyPipeline(pending.sampleCount);\n if (pipeline === undefined) {\n // RhiNull has no shader-module factory. It still records the complete\n // query fan-out structurally so lifecycle and identity tests exercise\n // the same bounded transport; real backends take the mesh path below.\n for (const reservation of pending.reservations) {\n const began = pass.beginOcclusionQuery(reservation.queryIndex);\n if (!began.ok) return began;\n const ended = pass.endOcclusionQuery();\n if (!ended.ok) return ended;\n }\n pending.endedCount = pending.reservations.length;\n return ok(undefined);\n }\n const buffer = this.ensureProxyBuffer(pending.proxyFloatCount * Float32Array.BYTES_PER_ELEMENT);\n if (buffer === undefined) {\n return err(runtimeError('the backend must allocate the bounded proxy geometry buffer'));\n }\n const uploaded = this.device.queue.writeBuffer(\n buffer,\n 0,\n this.proxyScratch.subarray(0, pending.proxyFloatCount),\n );\n if (!uploaded.ok) return uploaded;\n pass.setPipeline(pipeline);\n pass.setVertexBuffer(0, buffer);\n let vertexOffset = 0;\n for (let index = 0; index < pending.reservations.length; index += 1) {\n const vertices = pending.candidates[index]?.proxyVertices;\n if (vertices === undefined || vertices.length === 0) continue;\n const began = pass.beginOcclusionQuery(pending.reservations[index]?.queryIndex ?? 0);\n if (!began.ok) return began;\n pass.draw(vertices.length / 4, 1, vertexOffset / 4, 0);\n const ended = pass.endOcclusionQuery();\n if (!ended.ok) return ended;\n vertexOffset += vertices.length;\n }\n pending.endedCount = pending.reservations.length;\n return ok(undefined);\n }\n\n private ensureProxyBuffer(byteLength: number): Buffer | undefined {\n if (this.proxyBuffer !== undefined) return this.proxyBuffer;\n const created = this.device.createBuffer({\n label: 'occlusion-bounds-proxy-geometry',\n size: Math.max(16, PROXY_GEOMETRY_BYTES, byteLength),\n usage: GPU_BUFFER_USAGE_VERTEX | GPU_BUFFER_USAGE_COPY_DST,\n });\n if (!created.ok) return undefined;\n this.proxyBuffer = created.value;\n return created.value;\n }\n\n private ensureProxyPipeline(sampleCount: 1 | 4): RenderPipeline | undefined {\n if (this.proxyPipelineSampleCount === sampleCount && this.proxyPipeline !== undefined) {\n return this.proxyPipeline;\n }\n if (this.shaderModuleFactory === undefined) return undefined;\n const module = this.shaderModuleFactory.createShaderModule({\n label: 'occlusion-bounds-proxy',\n code: PROXY_BOUNDS_WGSL,\n });\n if (!module.ok) return undefined;\n const created = this.device.createRenderPipeline({\n label: 'occlusion-bounds-proxy',\n layout: 'auto',\n vertex: {\n module: module.value,\n entryPoint: 'vs_main',\n buffers: [\n {\n arrayStride: 16,\n stepMode: 'vertex',\n attributes: [{ shaderLocation: 0, offset: 0, format: 'float32x4' }],\n },\n ],\n },\n // The proxy is recorded in the typed main pass, whose color attachment\n // remains RGBA16Float. Keep the pass compatible while suppressing all\n // color writes; occlusion only consumes depth samples.\n fragment: {\n module: module.value,\n entryPoint: 'fs_main',\n targets: [{ format: 'rgba16float', writeMask: 0 }],\n },\n primitive: { topology: 'triangle-list' },\n depthStencil: {\n format: 'depth24plus-stencil8',\n depthWriteEnabled: false,\n depthCompare: 'less-equal',\n },\n multisample: { count: sampleCount },\n });\n if (!created.ok) return undefined;\n this.proxyPipeline = created.value;\n this.proxyPipelineSampleCount = sampleCount;\n return created.value;\n }\n}\n\nconst PROXY_BOUNDS_WGSL = `\n@vertex\nfn vs_main(@location(0) position: vec4f) -> @builtin(position) vec4f {\n return position;\n}\n@fragment\nfn fs_main() -> @location(0) vec4f {\n return vec4f(0.0);\n}\n`;\n\nfunction candidateKey(view: ViewKey, primitive: PrimitiveKey): string {\n return `${viewKeyId(view)}|${primitiveKeyId(primitive)}`;\n}\n\nfunction finiteBounds(bounds: OcclusionBounds): boolean {\n return [...bounds.min, ...bounds.max].every((value) => Number.isFinite(value));\n}\n\nfunction runtimeError(hint: string): RhiError {\n return new RhiErrorClass({\n code: 'webgpu-runtime-error',\n expected: 'RenderSystem owns one active occlusion candidate for the shared frame',\n hint,\n });\n}\n","import type { EnvironmentCandidate, FogCandidate } from '../extract/environment';\n\nexport interface EnvironmentSignatureInput {\n readonly environments: readonly EnvironmentCandidate[];\n readonly fogs: readonly FogCandidate[];\n readonly suns: readonly {\n readonly entityKey: number;\n readonly direction: readonly [number, number, number];\n readonly color: readonly [number, number, number];\n readonly intensity: number;\n }[];\n}\n\nexport interface EnvironmentFactSignatures {\n readonly environmentSignature: string;\n readonly fogSignature: string;\n readonly signature: string;\n}\n\nfunction sorted<T extends { readonly entityKey: number }>(items: readonly T[]): readonly T[] {\n return [...items].sort((left, right) => left.entityKey - right.entityKey);\n}\n\n/** Derive a deterministic source signature without retaining GPU objects. */\nexport function environmentSignature(input: EnvironmentSignatureInput): string {\n return JSON.stringify({\n environments: sorted(input.environments),\n fogs: sorted(input.fogs),\n suns: sorted(input.suns),\n });\n}\n\n/** Signature for Environment and Sun facts, excluding the independent Fog channel. */\nexport function environmentOnlySignature(input: EnvironmentSignatureInput): string {\n return JSON.stringify({\n environments: sorted(input.environments),\n suns: sorted(input.suns),\n });\n}\n\n/** Signature for the independent Fog channel. */\nexport function fogOnlySignature(input: Pick<EnvironmentSignatureInput, 'fogs'>): string {\n return JSON.stringify({ fogs: sorted(input.fogs) });\n}\n\n/** Build all frame signatures from one immutable source fact set. */\nexport function environmentFactSignatures(\n input: EnvironmentSignatureInput,\n): EnvironmentFactSignatures {\n return {\n environmentSignature: environmentOnlySignature(input),\n fogSignature: fogOnlySignature(input),\n signature: environmentSignature(input),\n };\n}\n","import type { World } from '@forgeax/engine-ecs';\nimport { err, ok, type Result } from '@forgeax/engine-types';\nimport { environmentFactSignatures } from '../environment/signature';\nimport {\n AtmosphereInvalidParameterError,\n type AtmosphereParameterRange,\n EnvironmentSourceConflictError,\n FogCardinalityError,\n type RenderError,\n} from '../errors/render';\nimport type { TemporalView } from '../temporal/view';\n\n/** The retained projection's environment extraction owner. */\nexport interface EnvironmentExtractionContext {\n readonly resourceOwner: number;\n readonly world: World;\n}\n\n/** Keep environment reads at the resource-owner frame boundary. */\nexport function createEnvironmentExtractionContext(\n world: World,\n resourceOwner: number,\n): EnvironmentExtractionContext {\n return Object.freeze({ world, resourceOwner });\n}\n\nexport type EnvironmentCandidate =\n | { readonly kind: 'image'; readonly entityKey: number; readonly sourceKey: string }\n | {\n readonly kind: 'atmosphere';\n readonly entityKey: number;\n readonly sourceKey: string;\n readonly atmosphere: AtmosphereParameters;\n };\n\nexport interface AtmosphereParameters {\n readonly turbidity: number;\n readonly rayleigh: number;\n readonly mieCoefficient: number;\n readonly mieDirectionalG: number;\n readonly sunAngularRadius: number;\n}\n\n/** Shared CPU contract for values accepted by the atmosphere shaders. */\nexport const ATMOSPHERE_PARAMETER_RANGES: Readonly<\n Record<keyof AtmosphereParameters, AtmosphereParameterRange>\n> = Object.freeze({\n turbidity: Object.freeze({ min: 1, max: 20 }),\n rayleigh: Object.freeze({ min: 0, max: Number.POSITIVE_INFINITY }),\n mieCoefficient: Object.freeze({ min: 0, max: Number.POSITIVE_INFINITY }),\n mieDirectionalG: Object.freeze({ min: 0, max: 0.999 }),\n sunAngularRadius: Object.freeze({ min: 0, max: Number.POSITIVE_INFINITY }),\n});\n\nexport interface FogCandidate {\n readonly entityKey: number;\n readonly color: readonly [number, number, number];\n readonly density: number;\n readonly heightFalloff: number;\n readonly maxOpacity: number;\n}\n\nexport type EnvironmentSource =\n | { readonly kind: 'none' }\n | {\n readonly kind: 'image';\n readonly entityKey: number;\n readonly sourceKey: string;\n }\n | {\n readonly kind: 'atmosphere';\n readonly entityKey: number;\n readonly sourceKey: string;\n readonly atmosphere: AtmosphereParameters;\n };\n\nexport interface FogFrame extends FogCandidate {}\n\nexport interface FogParameterIssue {\n readonly field: string;\n readonly value: number;\n readonly expected: string;\n}\n\n/** Structured failure retained when an invalid Fog update falls back to LKG. */\nexport interface FogSelectionFailure {\n readonly code: string;\n readonly expected: string;\n readonly hint: string;\n readonly detail: Readonly<Record<string, unknown>>;\n}\n\nexport interface EnvironmentFrame {\n readonly source: EnvironmentSource;\n /** Descriptor of the real environment resource adopted for this frame. */\n readonly resourceDescriptor?: Readonly<{\n readonly width: number;\n readonly height: number;\n readonly bytesPerPixel: number;\n }>;\n readonly fog: FogFrame | undefined;\n readonly environmentSignature: string;\n readonly fogSignature: string;\n readonly signature: string;\n readonly revision: number;\n}\n\nexport interface FramePlan {\n readonly environment: EnvironmentFrame;\n readonly temporal: TemporalView;\n}\n\nfunction freezeFog(candidate: FogCandidate): FogFrame {\n return Object.freeze({\n ...candidate,\n color: Object.freeze([...candidate.color] as unknown as FogFrame['color']),\n });\n}\n\n/** Validate the bounded Fog domain once for every frame-selection producer. */\nexport function validateFogParameters(candidate: FogCandidate): FogParameterIssue | undefined {\n if (candidate.color.length !== 3) {\n return {\n field: 'color',\n value: candidate.color.length,\n expected: 'exactly three finite channels in [0, 1]',\n };\n }\n for (let index = 0; index < candidate.color.length; index += 1) {\n const value = candidate.color[index];\n if (value === undefined || !Number.isFinite(value) || value < 0 || value > 1) {\n return {\n field: `color[${index}]`,\n value: value ?? Number.NaN,\n expected: 'a finite number in [0, 1]',\n };\n }\n }\n if (!Number.isFinite(candidate.density) || candidate.density < 0) {\n return { field: 'density', value: candidate.density, expected: 'a finite number >= 0' };\n }\n if (!Number.isFinite(candidate.heightFalloff) || candidate.heightFalloff < 0) {\n return {\n field: 'heightFalloff',\n value: candidate.heightFalloff,\n expected: 'a finite number >= 0',\n };\n }\n if (\n !Number.isFinite(candidate.maxOpacity) ||\n candidate.maxOpacity < 0 ||\n candidate.maxOpacity > 1\n ) {\n return {\n field: 'maxOpacity',\n value: candidate.maxOpacity,\n expected: 'a finite number in [0, 1]',\n };\n }\n return undefined;\n}\n\nfunction freezeAtmosphere(parameters: AtmosphereParameters): AtmosphereParameters {\n return Object.freeze({ ...parameters });\n}\n\n/** Return the first invalid analytic atmosphere field at the extraction boundary. */\nexport function validateAtmosphereParameters(\n parameters: AtmosphereParameters,\n): AtmosphereInvalidParameterError | undefined {\n for (const field of Object.keys(ATMOSPHERE_PARAMETER_RANGES) as (keyof AtmosphereParameters)[]) {\n const value = parameters[field];\n const range = ATMOSPHERE_PARAMETER_RANGES[field];\n if (!Number.isFinite(value) || value < range.min || value > range.max) {\n return new AtmosphereInvalidParameterError(field, value, range);\n }\n }\n return undefined;\n}\n\n/** Select immutable environment and independent Fog facts at the frame boundary. */\nexport function selectEnvironmentFrame(\n candidates: readonly EnvironmentCandidate[],\n fogCandidates: readonly FogCandidate[],\n): Result<EnvironmentFrame, RenderError> {\n if (candidates.length > 1) {\n return err(\n new EnvironmentSourceConflictError(\n candidates.map(({ kind, entityKey, sourceKey }) => ({ kind, entityKey, sourceKey })),\n ),\n );\n }\n if (fogCandidates.length > 1) return err(new FogCardinalityError(fogCandidates.length));\n const candidate = candidates[0];\n if (candidate?.kind === 'atmosphere') {\n const invalid = validateAtmosphereParameters(candidate.atmosphere);\n if (invalid !== undefined) return err(invalid);\n }\n const source: EnvironmentSource =\n candidate === undefined\n ? { kind: 'none' }\n : candidate.kind === 'atmosphere'\n ? {\n kind: 'atmosphere',\n entityKey: candidate.entityKey,\n sourceKey: candidate.sourceKey,\n atmosphere: freezeAtmosphere(candidate.atmosphere),\n }\n : {\n kind: 'image',\n entityKey: candidate.entityKey,\n sourceKey: candidate.sourceKey,\n };\n const fog = fogCandidates[0] === undefined ? undefined : freezeFog(fogCandidates[0]);\n const signatures = environmentFactSignatures({\n environments: candidate === undefined ? [] : [candidate],\n fogs: fogCandidates,\n suns: [],\n });\n return ok(\n Object.freeze({\n source: Object.freeze(source),\n fog,\n ...signatures,\n revision: 0,\n }),\n );\n}\n","import { err, ok, type Result } from '@forgeax/engine-types';\nimport { EnvironmentSourceConflictError, FogCardinalityError } from '../errors/render';\nimport type {\n EnvironmentCandidate,\n EnvironmentFrame,\n EnvironmentSource,\n FogCandidate,\n FogFrame,\n} from '../extract/environment';\nimport { validateAtmosphereParameters, validateFogParameters } from '../extract/environment';\nimport { environmentFactSignatures } from './signature';\n\nexport type { EnvironmentCandidate, EnvironmentFrame, EnvironmentSource, FogCandidate, FogFrame };\n\n/** Producer-local fallback while replacement environment storage is uninitialized. */\nexport const SKYLIGHT_RECOVERY_FALLBACK = Object.freeze({\n kind: 'skylight',\n active: false,\n} as const);\n\nexport interface SunCandidate {\n readonly entityKey: number;\n readonly direction: readonly [number, number, number];\n readonly color: readonly [number, number, number];\n readonly intensity: number;\n}\n\nexport interface EnvironmentSelectionInput {\n readonly environments: readonly EnvironmentCandidate[];\n readonly fogs: readonly FogCandidate[];\n readonly suns: readonly SunCandidate[];\n readonly lane: 'direct' | 'clustered';\n}\n\nexport interface EnvironmentSelectionParameterDetail {\n readonly field: string;\n readonly value: number;\n}\n\nexport class EnvironmentSelectionParameterError extends Error {\n readonly code = 'environment-selection-invalid' as const;\n readonly expected: string;\n readonly hint: string;\n readonly detail: EnvironmentSelectionParameterDetail;\n\n constructor(field: string, value: number, expected: string) {\n super(`environment selection field ${field} is invalid`);\n this.name = 'EnvironmentSelectionParameterError';\n this.expected = expected;\n this.hint = `set ${field} to a finite value satisfying ${expected}`;\n this.detail = { field, value };\n }\n}\n\nexport interface SunCardinalityDetail {\n readonly field: 'sun';\n readonly value: number;\n}\n\nexport class SunCardinalityError extends Error {\n readonly code = 'sun-cardinality' as const;\n readonly expected = 'atmosphere has exactly one sun owner';\n readonly hint = 'add exactly one DirectionalLight sun for the atmosphere owner';\n readonly detail: SunCardinalityDetail;\n\n constructor(value: number) {\n super(`atmosphere sun cardinality is ${value}`);\n this.name = 'SunCardinalityError';\n this.detail = { field: 'sun', value };\n }\n}\n\nexport interface EnvironmentSelectionErrorDetail {\n readonly owners?: readonly {\n readonly kind: 'image' | 'atmosphere';\n readonly entityKey: number;\n readonly sourceKey: string;\n }[];\n readonly field?: string;\n readonly value?: number;\n readonly count?: number;\n}\n\nexport interface EnvironmentSelectionError {\n readonly code:\n | 'environment-source-conflict'\n | 'fog-cardinality'\n | 'environment-selection-invalid'\n | 'atmosphere-invalid-parameter'\n | 'sun-cardinality';\n readonly expected: string;\n readonly hint: string;\n readonly detail: EnvironmentSelectionErrorDetail;\n}\n\nexport interface SelectedEnvironmentFrame extends EnvironmentFrame {\n readonly sun: SunCandidate | undefined;\n readonly lane: 'direct' | 'clustered';\n}\n\nfunction freezeCandidate<T extends object>(candidate: T): T {\n return Object.freeze(candidate);\n}\n\nfunction freezeFog(candidate: FogCandidate): FogFrame {\n return Object.freeze({\n ...candidate,\n color: Object.freeze([...candidate.color] as unknown as FogFrame['color']),\n });\n}\n\n/** Select one immutable frame fact set for both Standard lighting lanes. */\nexport function selectEnvironment(\n input: EnvironmentSelectionInput,\n): Result<SelectedEnvironmentFrame, EnvironmentSelectionError> {\n if (input.environments.length > 1) {\n return err(\n new EnvironmentSourceConflictError(\n [...input.environments]\n .sort((left, right) => left.entityKey - right.entityKey)\n .map(({ kind, entityKey, sourceKey }) => ({ kind, entityKey, sourceKey })),\n ),\n );\n }\n if (input.fogs.length > 1) return err(new FogCardinalityError(input.fogs.length));\n const selectedFog = input.fogs[0];\n if (selectedFog !== undefined) {\n const issue = validateFogParameters(selectedFog);\n if (issue !== undefined) {\n return err(new EnvironmentSelectionParameterError(issue.field, issue.value, issue.expected));\n }\n }\n const selected = input.environments[0];\n if (selected?.kind === 'atmosphere') {\n const invalid = validateAtmosphereParameters(selected.atmosphere);\n if (invalid !== undefined) return err(invalid);\n }\n if (selected?.kind === 'atmosphere' && input.suns.length !== 1) {\n return err(new SunCardinalityError(input.suns.length));\n }\n const source: EnvironmentSource =\n selected === undefined\n ? { kind: 'none' }\n : selected.kind === 'atmosphere'\n ? {\n kind: 'atmosphere',\n entityKey: selected.entityKey,\n sourceKey: selected.sourceKey,\n atmosphere: Object.freeze({ ...selected.atmosphere }),\n }\n : {\n kind: 'image',\n entityKey: selected.entityKey,\n sourceKey: selected.sourceKey,\n };\n const sun = input.suns[0] === undefined ? undefined : freezeCandidate({ ...input.suns[0] });\n const fog = selectedFog === undefined ? undefined : freezeFog(selectedFog);\n const signatureInput = {\n environments: selected === undefined ? [] : [selected],\n fogs: selectedFog === undefined ? [] : [selectedFog],\n suns: input.suns,\n };\n const signatures = environmentFactSignatures(signatureInput);\n const result = {\n source: Object.freeze(source),\n fog,\n ...signatures,\n revision: 0,\n sun,\n } as SelectedEnvironmentFrame;\n Object.defineProperty(result, 'lane', { value: input.lane, enumerable: false });\n return ok(Object.freeze(result));\n}\n","// @forgeax/engine-render - Directional CSM projection owner.\n\nimport type { DirectionalShadowQuality } from '../components/directional-shadow-filter';\nimport { directionalShadowQualityFromF32 } from '../components/directional-shadow-filter';\n\n/** Light-space bounds produced by one existing orthographic CSM fit. */\nexport interface DirectionalShadowCascadeFit {\n readonly split: number;\n readonly minX: number;\n readonly maxX: number;\n readonly minY: number;\n readonly maxY: number;\n readonly minZ: number;\n readonly maxZ: number;\n}\n\n/** Host projection sent to the shared View UBO. */\nexport interface DirectionalShadowProjection {\n readonly splitPlanes: Float32Array;\n readonly directionalShadowQuality: DirectionalShadowQuality;\n}\n\n/**\n * Project accepted Directional author facts and the existing CSM fit into the\n * shared split vec4 lanes. `.x` is the split, `.y` is world units per texel,\n * `.z` is the light-space depth span, and `.w` is reserved for the ABI.\n */\nexport function projectDirectionalShadow(\n fits: readonly DirectionalShadowCascadeFit[],\n mapSize: number,\n shadowFilter: number,\n shadowAngularRadius: number,\n maxPenumbraTexels: number,\n): DirectionalShadowProjection | undefined {\n if (!Number.isFinite(mapSize) || mapSize < 1) return undefined;\n const directionalShadowQuality = directionalShadowQualityFromF32(\n shadowFilter,\n shadowAngularRadius,\n maxPenumbraTexels,\n );\n if (directionalShadowQuality === undefined) return undefined;\n\n const splitPlanes = new Float32Array(16);\n for (let index = 0; index < fits.length && index < 4; index += 1) {\n const fit = fits[index];\n if (fit === undefined) continue;\n const width = Math.abs(fit.maxX - fit.minX);\n const height = Math.abs(fit.maxY - fit.minY);\n const depth = Math.abs(fit.maxZ - fit.minZ);\n const worldUnitsPerTexel = Math.max(width, height, Number.EPSILON) / mapSize;\n const lightDepthWorldSpan = Math.max(depth, Number.EPSILON);\n if (!Number.isFinite(worldUnitsPerTexel) || !Number.isFinite(lightDepthWorldSpan)) {\n return undefined;\n }\n const lane = index * 4;\n splitPlanes[lane] = fit.split;\n splitPlanes[lane + 1] = worldUnitsPerTexel;\n splitPlanes[lane + 2] = lightDepthWorldSpan;\n }\n return { splitPlanes, directionalShadowQuality };\n}\n","import type { MaterialShaderArtifactReceipt } from '@forgeax/engine-shader';\n\nexport type GpuDrivenPreparationErrorCode =\n | 'missing-material-receipt'\n | 'missing-uv'\n | 'reflection-mismatch'\n | 'vertex-input-mismatch'\n | 'alpha-mask-mismatch'\n | 'resource-not-ready'\n | 'stale-generation'\n | 'skin-receipt-mismatch';\n\nexport type GpuDrivenPreparationReason =\n | 'material-receipt-missing'\n | 'uv-set-missing'\n | 'reflection-receipt-mismatch'\n | 'vertex-semantic-mismatch'\n | 'alpha-mask-receipt-missing'\n | 'material-resource-missing'\n | 'generation-stale'\n | 'skin-address-missing';\n\nexport interface GpuDrivenPreparationErrorDetail {\n readonly reason: GpuDrivenPreparationReason;\n readonly owner: 'material' | 'geometry' | 'skin' | 'generation';\n readonly expected?: string;\n readonly actual?: string;\n readonly expectedGeneration?: number;\n readonly actualGeneration?: number;\n}\n\nconst ERROR_POLICY: Readonly<\n Record<GpuDrivenPreparationErrorCode, { readonly expected: string; readonly hint: string }>\n> = {\n 'missing-material-receipt': {\n expected: 'a producer-owned Standard PBR material receipt is present',\n hint: 'cook and load the Standard PBR artifact, then retry preparation',\n },\n 'missing-uv': {\n expected: 'the geometry exposes every UV set named by the material receipt',\n hint: 'repair the geometry UV semantic or route the draw to the CPU semantic lane',\n },\n 'reflection-mismatch': {\n expected: 'the loaded reflection receipt matches the artifact layout identity',\n hint: 'rebuild the material artifact and reflection from one source, then retry',\n },\n 'vertex-input-mismatch': {\n expected: 'geometry vertex semantics match the material reflection receipt',\n hint: 'repair the geometry vertex semantic layout or route the draw to the CPU lane',\n },\n 'alpha-mask-mismatch': {\n expected: 'the Alpha Mask cutoff is present in the material receipt',\n hint: 'declare alphaCutoff in the Standard PBR material schema and recook it',\n },\n 'resource-not-ready': {\n expected: 'all material resource slots have resolved handles',\n hint: 'resolve the declared texture and sampler resources before recording',\n },\n 'stale-generation': {\n expected: 'receipt and prepared inputs belong to the requested generation',\n hint: 'discard stale GPU facts, rebuild the producer receipt, and retry the same draw',\n },\n 'skin-receipt-mismatch': {\n expected: 'skinned geometry has a current palette address receipt',\n hint: 'rebuild the Skin palette receipt for this generation before recording',\n },\n};\n\nexport class GpuDrivenPreparationError extends Error {\n readonly code: GpuDrivenPreparationErrorCode;\n readonly expected: string;\n readonly hint: string;\n readonly detail: GpuDrivenPreparationErrorDetail;\n\n constructor(code: GpuDrivenPreparationErrorCode, detail: GpuDrivenPreparationErrorDetail) {\n const policy = ERROR_POLICY[code];\n super(`[GpuDrivenPreparationError ${code}] ${policy.expected}`);\n this.name = 'GpuDrivenPreparationError';\n this.code = code;\n this.expected = policy.expected;\n this.hint = policy.hint;\n this.detail = detail;\n }\n}\n\nexport interface GpuDrivenPreparedMaterial {\n readonly receipt: MaterialShaderArtifactReceipt;\n readonly resourceSlots: MaterialShaderArtifactReceipt['resourceSlots'];\n readonly uvSets: MaterialShaderArtifactReceipt['uvSets'];\n readonly vertexInputs: MaterialShaderArtifactReceipt['vertexInputs'];\n readonly alphaMask: MaterialShaderArtifactReceipt['alphaMask'];\n}\n","import type {\n MaterialShaderArtifact,\n MaterialShaderArtifactReceipt,\n MaterialShaderVertexInput,\n} from '@forgeax/engine-shader';\nimport type { PrimitiveTopology } from '@forgeax/engine-types';\nimport {\n GpuDrivenPreparationError,\n type GpuDrivenPreparationErrorDetail,\n} from '../errors/gpu-driven';\nimport type { RenderableSnapshot } from '../render-system-extract';\n\nexport interface GpuDrivenGeometryReceipt {\n readonly identity: string;\n readonly vertexInputs: readonly MaterialShaderVertexInput[];\n readonly topology: PrimitiveTopology;\n readonly indexed: boolean;\n}\n\nexport interface GpuDrivenSkinReceipt {\n readonly identity: string;\n readonly generation: number;\n readonly group: number;\n readonly binding: number;\n readonly byteOffset: number;\n}\n\nexport interface PreparedGpuDrivenDraw {\n readonly identity: {\n readonly material: string;\n readonly geometry: string;\n readonly deformation: 'rigid' | 'skin';\n };\n readonly receiptGeneration: number;\n readonly directEntry: string;\n readonly sceneIndexEntry: string;\n readonly materialRow: MaterialShaderArtifactReceipt['materialRow'];\n readonly resourceSlots: MaterialShaderArtifactReceipt['resourceSlots'];\n readonly uvSets: MaterialShaderArtifactReceipt['uvSets'];\n readonly vertexInputs: MaterialShaderArtifactReceipt['vertexInputs'];\n readonly alphaMask: MaterialShaderArtifactReceipt['alphaMask'];\n readonly skinPaletteAddress: MaterialShaderArtifactReceipt['skinPaletteAddress'];\n readonly topology: PrimitiveTopology;\n readonly indexed: boolean;\n readonly first: number;\n readonly count: number;\n readonly baseVertex: number;\n}\n\n/** Exact extracted draw range consumed by the preparation owner. */\nexport interface GpuDrivenDrawRange {\n readonly kind: 'indexed' | 'non-indexed';\n readonly first: number;\n readonly count: number;\n readonly baseVertex: number;\n readonly topology: PrimitiveTopology;\n}\n\nexport interface PrepareGpuDrivenDrawInput {\n readonly snapshot: RenderableSnapshot;\n readonly artifact: MaterialShaderArtifact;\n readonly geometry: GpuDrivenGeometryReceipt;\n readonly generation: number;\n /** The submesh draw currently being prepared; never infer draw zero. */\n readonly draw: GpuDrivenDrawRange;\n readonly skinReceipt?: GpuDrivenSkinReceipt;\n}\n\nfunction failure(\n code: ConstructorParameters<typeof GpuDrivenPreparationError>[0],\n detail: GpuDrivenPreparationErrorDetail,\n): { readonly ok: false; readonly error: GpuDrivenPreparationError } {\n return { ok: false, error: new GpuDrivenPreparationError(code, detail) };\n}\n\nfunction sameVertexInputs(\n expected: readonly MaterialShaderVertexInput[],\n actual: readonly MaterialShaderVertexInput[],\n): boolean {\n return (\n expected.length === actual.length &&\n expected.every(\n (input, index) =>\n input.semantic === actual[index]?.semantic &&\n input.location === actual[index]?.location &&\n input.format === actual[index]?.format,\n )\n );\n}\n\nfunction hasMaterialResources(\n snapshot: RenderableSnapshot,\n receipt: MaterialShaderArtifactReceipt,\n) {\n const textures = snapshot.material.textureHandles;\n const samplers = snapshot.material.samplerHandles;\n return receipt.resourceSlots.every((slot) => {\n const handles = slot.kind === 'texture' ? textures : samplers;\n return handles?.has(slot.parameter) === true;\n });\n}\n\nexport function prepareGpuDrivenDraw(\n input: PrepareGpuDrivenDrawInput,\n):\n | { readonly ok: true; readonly value: PreparedGpuDrivenDraw }\n | { readonly ok: false; readonly error: GpuDrivenPreparationError } {\n const receipt = input.artifact.receipt;\n if (receipt === undefined) {\n return failure('missing-material-receipt', {\n reason: 'material-receipt-missing',\n owner: 'material',\n expected: 'MaterialShaderArtifact.receipt',\n });\n }\n if (receipt.generation !== input.generation) {\n return failure('stale-generation', {\n reason: 'generation-stale',\n owner: 'generation',\n expectedGeneration: input.generation,\n actualGeneration: receipt.generation,\n });\n }\n if (receipt.reflection.layoutIdentity !== input.artifact.layoutIdentity) {\n return failure('reflection-mismatch', {\n reason: 'reflection-receipt-mismatch',\n owner: 'material',\n expected: input.artifact.layoutIdentity,\n actual: receipt.reflection.layoutIdentity,\n });\n }\n if (receipt.uvSets.some((uv) => uv.set > 0) && input.geometry.vertexInputs.length < 3) {\n return failure('missing-uv', {\n reason: 'uv-set-missing',\n owner: 'geometry',\n expected: `${receipt.uvSets.length} material UV sets`,\n actual: `${input.geometry.vertexInputs.filter((vertex) => vertex.semantic.startsWith('uv')).length} geometry UV sets`,\n });\n }\n if (!sameVertexInputs(receipt.vertexInputs, input.geometry.vertexInputs)) {\n return failure('vertex-input-mismatch', {\n reason: 'vertex-semantic-mismatch',\n owner: 'geometry',\n expected: receipt.vertexInputs.map((input) => input.semantic).join(','),\n actual: input.geometry.vertexInputs.map((input) => input.semantic).join(','),\n });\n }\n if (receipt.alphaMask.cutoff.length === 0) {\n return failure('alpha-mask-mismatch', {\n reason: 'alpha-mask-receipt-missing',\n owner: 'material',\n expected: 'alphaMask.cutoff',\n });\n }\n if (!hasMaterialResources(input.snapshot, receipt)) {\n return failure('resource-not-ready', {\n reason: 'material-resource-missing',\n owner: 'material',\n expected: receipt.resourceSlots.map((slot) => slot.parameter).join(','),\n });\n }\n const deformation = input.snapshot.skin === undefined ? 'rigid' : 'skin';\n if (deformation === 'skin') {\n if (input.skinReceipt === undefined || receipt.skinPaletteAddress === undefined) {\n return failure('skin-receipt-mismatch', {\n reason: 'skin-address-missing',\n owner: 'skin',\n expected: 'skinPaletteAddress and skinReceipt',\n });\n }\n if (\n input.skinReceipt.generation !== input.generation ||\n input.skinReceipt.group !== receipt.skinPaletteAddress.group ||\n input.skinReceipt.binding !== receipt.skinPaletteAddress.binding\n ) {\n return failure('skin-receipt-mismatch', {\n reason: 'skin-address-missing',\n owner: 'skin',\n expected: `${receipt.skinPaletteAddress.group}:${receipt.skinPaletteAddress.binding}@${input.generation}`,\n actual: `${input.skinReceipt.group}:${input.skinReceipt.binding}@${input.skinReceipt.generation}`,\n });\n }\n }\n return {\n ok: true,\n value: {\n identity: {\n material: input.artifact.material,\n geometry: input.geometry.identity,\n deformation,\n },\n receiptGeneration: receipt.generation,\n directEntry: receipt.directEntry,\n sceneIndexEntry: receipt.sceneIndexEntry,\n materialRow: receipt.materialRow,\n resourceSlots: receipt.resourceSlots,\n uvSets: receipt.uvSets,\n vertexInputs: receipt.vertexInputs,\n alphaMask: receipt.alphaMask,\n skinPaletteAddress: receipt.skinPaletteAddress,\n topology: input.draw.topology,\n indexed: input.draw.kind === 'indexed',\n first: input.draw.first,\n count: input.draw.count,\n baseVertex: input.draw.baseVertex,\n },\n };\n}\n","import type { MaterialShaderArtifact } from '@forgeax/engine-shader';\nimport type { MeshAsset } from '@forgeax/engine-types';\nimport {\n type GpuDrivenDrawRange,\n type PreparedGpuDrivenDraw,\n type PrepareGpuDrivenDrawInput,\n prepareGpuDrivenDraw,\n} from '../gpu-driven/prepared-draw';\nimport type { MaterialSnapshot } from '../render-system-extract';\n\nexport {\n GpuDrivenPreparationError,\n type GpuDrivenPreparationErrorCode,\n type GpuDrivenPreparationErrorDetail,\n type GpuDrivenPreparationReason,\n} from '../errors/gpu-driven';\nexport {\n type GpuDrivenDrawRange,\n type GpuDrivenGeometryReceipt,\n type GpuDrivenSkinReceipt,\n type PreparedGpuDrivenDraw,\n type PrepareGpuDrivenDrawInput,\n prepareGpuDrivenDraw,\n} from '../gpu-driven/prepared-draw';\n\nexport interface GpuDrivenDrawSnapshot {\n readonly kind: GpuDrivenDrawRange['kind'];\n readonly first: GpuDrivenDrawRange['first'];\n readonly count: GpuDrivenDrawRange['count'];\n readonly baseVertex: GpuDrivenDrawRange['baseVertex'];\n readonly materialSlot: number;\n readonly topology: GpuDrivenDrawRange['topology'];\n readonly pipelineClass: string;\n readonly materialResourceClass: string;\n /** Producer-owned prepared ABI facts used by the PBR GPU lane. */\n readonly prepared?: PreparedGpuDrivenDraw;\n}\n\n/**\n * Resolves prepared facts once at extract time; record never re-reads assets.\n * The resolver surfaces UV, reflection, vertex, alpha, resource, and\n * generation failures as GpuDrivenPreparationError before recording.\n */\nexport function resolvePreparedGpuDrivenDraw(input: PrepareGpuDrivenDrawInput):\n | { readonly ok: true; readonly value: PreparedGpuDrivenDraw }\n | {\n readonly ok: false;\n readonly error: import('../errors/gpu-driven').GpuDrivenPreparationError;\n } {\n return prepareGpuDrivenDraw(input);\n}\n\n/** Keeps the artifact type visible at this owner boundary for contract checks. */\nexport type PreparedGpuDrivenArtifact = MaterialShaderArtifact;\n\n/**\n * Derives the resource identity consumed by the existing GPU-driven batch\n * owner. The extract stage is the only place that resolves material values;\n * this helper keeps the batch adapter from re-reading assets later.\n */\nexport function gpuDrivenMaterialResourceClass(material: MaterialSnapshot): string {\n const textures = [...(material.textureHandles?.entries() ?? [])]\n .map(([name, handle]) => [name, Number(handle)] as const)\n .sort(([left], [right]) => left.localeCompare(right));\n const samplers = [...(material.samplerHandles?.entries() ?? [])]\n .map(([name, handle]) => [name, Number(handle)] as const)\n .sort(([left], [right]) => left.localeCompare(right));\n return JSON.stringify({\n textures,\n samplers,\n video: [...(material.videoTextureFields?.keys() ?? [])].sort(),\n });\n}\n\n/**\n * Projects already-resolved mesh facts into the existing GPU-driven draw\n * snapshot. No World or AssetRegistry access is permitted at this boundary.\n */\nexport function buildGpuDrivenDraws(input: {\n readonly submeshes: readonly MeshAsset['submeshes'][number][];\n readonly indexed: boolean;\n readonly materials: readonly MaterialSnapshot[];\n readonly fallbackMaterial: MaterialSnapshot;\n readonly prepare?: (\n draw: GpuDrivenDrawSnapshot,\n material: MaterialSnapshot,\n ) => PreparedGpuDrivenDraw | undefined;\n}): GpuDrivenDrawSnapshot[] {\n let nonIndexedFirst = 0;\n return input.submeshes.flatMap((submesh) => {\n const drawMaterial = input.materials[submesh.materialSlot] ?? input.fallbackMaterial;\n const first = input.indexed ? submesh.indexOffset : nonIndexedFirst;\n nonIndexedFirst += submesh.vertexCount;\n if (drawMaterial.transparent === true) return [];\n const draw: GpuDrivenDrawSnapshot = {\n kind: input.indexed ? ('indexed' as const) : ('non-indexed' as const),\n first,\n count: input.indexed ? submesh.indexCount : submesh.vertexCount,\n baseVertex: 0,\n materialSlot: submesh.materialSlot,\n topology: submesh.topology,\n pipelineClass: `${drawMaterial.materialShaderId ?? 'forgeax::default-unlit'}|${submesh.topology}|${JSON.stringify(drawMaterial.renderState ?? null)}`,\n materialResourceClass: gpuDrivenMaterialResourceClass(drawMaterial),\n };\n const prepared = input.prepare?.(draw, drawMaterial);\n return [prepared === undefined ? draw : { ...draw, prepared }];\n });\n}\n","// @forgeax/engine-runtime - glyphTextLayoutSystem\n// (feat-20260531-world-space-msdf-text-rendering M4 / w18).\n//\n// The named ECS system that turns `GlyphText` authoring data into a rendered\n// world-space label (plan-strategy D-2). A Renderer attaches it to World's\n// internal render-derived phase,\n// so a freshly-spawned `GlyphText` entity gains its `MeshFilter` +\n// `MeshRenderer` before final publication resolves transforms and the same frame's\n// read-only render walk reaches it. Per `GlyphText` entity:\n//\n// 1. First observation (entity has no `MeshFilter`): resolve the FontAsset,\n// run `layoutGlyphText` (w15) + `bakeGlyphMesh` (w17), then attach\n// `MeshFilter` + `MeshRenderer` (AC-07). The attach uses the same\n// immediate `world.addComponent` path as `spriteAnimationTickSystem`'s\n// auto-add (the system runs ahead of the render walk in the same frame).\n// 2. Dirty (text / fontSize / color changed since last bake): re-layout and\n// `updateMesh` IN PLACE (plan-strategy D-1) -- never re-`register`, never\n// re-attach. The AssetRegistry size stays constant (AC-08; avoids the\n// unbounded growth R-1 would otherwise cause).\n//\n// D-8 concurrency: at most 8 distinct FontAsset handles may be active in one\n// frame. The system resets the per-frame tracker (resetFontConcurrency) at the\n// top and tracks each distinct font; the 9th distinct font surfaces a\n// structured `TextError('font-concurrency-exceeded')` (it does NOT silently\n// evict the oldest font).\n//\n// The system does NOT modify `pick.ts` (D-5): the baked mesh carries a local\n// AABB and the entity carries MeshFilter + MeshRenderer + Transform, so the\n// existing `pick()` raycast walk catches it for free.\n\nimport { resolveAssetHandle } from '@forgeax/engine-assets-runtime';\nimport type { EntityHandle, World } from '@forgeax/engine-ecs';\nimport { PROCEDURAL_FLOATS_PER_VERTEX } from '@forgeax/engine-geometry';\nimport {\n bakeGlyphMesh,\n conservativeCubeAabb,\n layoutGlyphText,\n resetFontConcurrency,\n trackFontConcurrency,\n} from '@forgeax/engine-graphics-extras';\nimport type { FontAsset, Handle, MaterialAsset, MeshAsset, Submesh } from '@forgeax/engine-types';\nimport { err, ok, type Result, TextError, toShared, unpackSlot } from '@forgeax/engine-types';\nimport { MeshFilter, MeshRenderer } from './components';\nimport { GlyphText } from './components/glyph-text';\nimport type { GpuResidencyCache } from './device/gpu-residency';\n\n// Per-entity bake bookkeeping: the baked mesh handle id + the authoring\n// signature it was baked from. A WeakMap owns one cache per World and each\n// entry is bounded by entity slot while retaining the full generation-bearing\n// EntityHandle, so slot reuse replaces stale state instead of aliasing it or\n// growing one historical entry per generation.\ninterface BakeRecord {\n readonly meshHandle: Handle<'MeshAsset', 'shared'>;\n signature: string;\n /** The MeshRenderer.material handle assigned on first observation. */\n readonly materialHandle: Handle<'MaterialAsset', 'shared'>;\n}\ninterface BakeCacheEntry {\n readonly handle: EntityHandle;\n readonly record: BakeRecord;\n}\nlet bakeCache = new WeakMap<World, Map<number, BakeCacheEntry>>();\n\n// One current material producer handle per GlyphText entity slot. Continuous\n// tint edits replace and release the previous producer instead of growing a\n// historical color-key cache.\nlet materialCache = new WeakMap<World, Map<number, Handle<'MaterialAsset', 'shared'>>>();\nlet liveGlyphSlots = new WeakMap<World, Set<number>>();\n\nfunction entitySlot(entity: EntityHandle): number {\n return unpackSlot(entity as number);\n}\n\n/** Clear the per-entity bake + per-font material caches (test isolation). */\nexport function resetGlyphBakeCache(): void {\n bakeCache = new WeakMap();\n materialCache = new WeakMap();\n liveGlyphSlots = new WeakMap();\n}\n\nfunction worldBakeCache(world: World): Map<number, BakeCacheEntry> {\n let cache = bakeCache.get(world);\n if (cache === undefined) {\n cache = new Map();\n bakeCache.set(world, cache);\n }\n return cache;\n}\n\nfunction worldMaterialCache(world: World): Map<number, Handle<'MaterialAsset', 'shared'>> {\n let cache = materialCache.get(world);\n if (cache === undefined) {\n cache = new Map();\n materialCache.set(world, cache);\n }\n return cache;\n}\n\n/** Release renderer-derived producer refs at GlyphText removal time. */\nfunction releaseGlyphProducers(world: World, entity: EntityHandle): void {\n const slot = entitySlot(entity);\n const bake = bakeCache.get(world)?.get(slot);\n if (bake?.handle === entity) {\n world.sharedRefs.release(bake.record.meshHandle);\n bakeCache.get(world)?.delete(slot);\n }\n const material = materialCache.get(world)?.get(slot);\n if (material !== undefined) {\n world.sharedRefs.release(material);\n materialCache.get(world)?.delete(slot);\n }\n}\n\n/** Remove stale renderer-derived state when a previously baked font is rejected. */\nfunction clearRejectedGlyphState(world: World, entity: EntityHandle): void {\n const slot = entitySlot(entity);\n const bake = bakeCache.get(world)?.get(slot);\n if (bake?.handle !== entity) return;\n\n // These components are owned by this system only when the matching bake\n // record exists. Removing them before releasing the producer refs leaves no\n // stale draw/material handles and lets the next valid frame take the normal\n // first-observation path.\n if (world.get(entity, MeshFilter).ok) world.removeComponent(entity, MeshFilter);\n if (world.get(entity, MeshRenderer).ok) world.removeComponent(entity, MeshRenderer);\n releaseGlyphProducers(world, entity);\n}\n\n// Premultiplied-alpha blend (mirrors the sprite path, plan D-7). The\n// `forgeax::msdf-text` fragment emits premultiplied RGB so the over-composite\n// math (`dst' = src + dst * (1 - src.a)`) is direct. The pass rides the\n// Transparent queue (3000) so text composites after opaque geometry while\n// honoring depth occlusion (depthCompare less-equal, depthWrite off via the\n// material-shader pipeline render state).\nconst MSDF_TEXT_BLEND = {\n color: { srcFactor: 'one', dstFactor: 'one-minus-src-alpha', operation: 'add' },\n alpha: { srcFactor: 'one', dstFactor: 'one-minus-src-alpha', operation: 'add' },\n} as const;\n\ninterface GlyphTextData {\n readonly fontHandle: number;\n readonly text: string;\n readonly fontSize: number;\n // feat-20260709 M3: color collapsed into one inline array<f32,4>; the\n // world.get read path materialises it as a Float32Array (color[0..3] = rgba).\n readonly color: ArrayLike<number>;\n}\n\n/** @internal archetype-walk view (same shape reached for in render-system-extract). */\n/**\n * Lay out + bake every `GlyphText` entity, attaching MeshFilter + MeshRenderer\n * on first observation and re-baking in place on a text / size / color change.\n *\n * @param world The ECS world holding the GlyphText entities.\n * @returns `ok(void)` on a clean pass, or `err(TextError)` carrying the FIRST\n * structured failure (currently only `font-concurrency-exceeded`). Healthy\n * entities observed before the failing one are still baked.\n */\nexport function glyphTextLayoutSystem(\n world: World,\n gpuStore: GpuResidencyCache,\n): Result<void, TextError> {\n resetFontConcurrency();\n\n // No GlyphText entity in this World -> empty query -> no-op pass. The\n // ECS query is the single owner of component presence and entity iteration;\n // the renderer does not reach into archetype storage internals.\n const entities = collectGlyphEntities(world);\n const live = liveGlyphSlots.get(world) ?? new Set<number>();\n live.clear();\n for (const entity of entities) live.add(entitySlot(entity));\n liveGlyphSlots.set(world, live);\n for (const entry of worldBakeCache(world).values()) {\n if (!live.has(entitySlot(entry.handle))) releaseGlyphProducers(world, entry.handle);\n }\n\n let firstError: TextError | null = null;\n for (const entity of entities) {\n const error = processEntity(world, gpuStore, entity);\n if (error !== null && firstError === null) firstError = error;\n }\n\n if (firstError !== null) return err(firstError);\n return ok(undefined);\n}\n\n/** Collect every Entity handle carrying GlyphText (single archetype walk). */\nfunction collectGlyphEntities(world: World): EntityHandle[] {\n const entities: EntityHandle[] = [];\n const query = world.query({ read: [GlyphText] }).unwrap();\n for (const row of query) {\n entities.push(row.entity);\n }\n return entities;\n}\n\n/**\n * Process one GlyphText entity. Returns a TextError when the concurrency limit\n * is exceeded after clearing stale derived state; returns null otherwise.\n */\nfunction processEntity(\n world: World,\n gpuStore: GpuResidencyCache,\n entity: EntityHandle,\n): TextError | null {\n const gtRes = world.get(entity, GlyphText);\n if (!gtRes.ok) return null;\n const gt = gtRes.value;\n\n // Unresolved font handle (zero sentinel) -> skip (entity not yet wired).\n if (gt.fontHandle === 0) return null;\n\n // D-8 concurrency: track this distinct font; the 9th throws a TextError.\n try {\n trackFontConcurrency(gt.fontHandle);\n } catch (e) {\n if (e instanceof TextError) {\n clearRejectedGlyphState(world, entity);\n return e;\n }\n throw e;\n }\n\n const fontRes = resolveAssetHandle<FontAsset>(world, asFontHandle(gt.fontHandle));\n if (!fontRes.ok) return null; // font not registered yet -> skip silently\n const font = fontRes.value;\n\n const signature = signatureOf(gt);\n const entityCache = worldBakeCache(world);\n const slot = entitySlot(entity);\n const cachedEntry = entityCache.get(slot);\n if (cachedEntry !== undefined && cachedEntry.handle !== entity) {\n world.sharedRefs.release(cachedEntry.record.meshHandle);\n const staleMaterial = worldMaterialCache(world).get(slot);\n if (staleMaterial !== undefined) {\n world.sharedRefs.release(staleMaterial);\n worldMaterialCache(world).delete(slot);\n }\n entityCache.delete(slot);\n }\n const cached = cachedEntry?.handle === entity ? cachedEntry.record : undefined;\n\n // Dirty path: same entity already baked, but the authoring signature changed.\n if (cached !== undefined) {\n ensureGlyphMeshMaterialSlots(world, cached.meshHandle);\n if (cached.signature === signature) return null; // clean -> nothing to do\n const layout = layoutGlyphText(font, gt.text, gt.fontSize);\n // feat-20260601-device/gpu-residency-extraction M1: in-place GPU mesh update\n // moved to the store. The mesh became GPU-resident on the first render\n // frame's `ensureResident` pull; the dirty re-layout overwrites those\n // buffers in place (a no-op if not yet resident -- the next render's\n // ensureResident then uploads the latest registered POD).\n const meshHandle = cached.meshHandle;\n const submeshes = [\n {\n indexOffset: 0,\n indexCount: layout.indices.length,\n vertexCount: layout.vertices.length / PROCEDURAL_FLOATS_PER_VERTEX,\n topology: 'triangle-list',\n materialSlot: 0,\n },\n ] satisfies readonly Submesh[];\n // A dynamic label can begin empty, so its first bake has a degenerate AABB.\n // Keep the shared MeshAsset's culling/picking bounds in lockstep with the\n // dirty layout; otherwise the GPU buffers update but the render walk still\n // rejects the label as an empty mesh.\n const mesh = world.sharedRefs.resolve<'MeshAsset', MeshAsset>(meshHandle);\n if (mesh.ok) {\n const aabb = conservativeCubeAabb(layout.radius);\n // Keep both sides of the pull boundary coherent. A zero-glyph first\n // bake may have no resident GPU buffers yet, so updating only the GPU\n // store would lose the new text on the next ensureResident pull.\n Object.assign(mesh.value, {\n vertices: layout.vertices,\n indices: layout.indices,\n submeshes,\n materialSlots: [{ slotName: 'Default' }],\n aabb,\n });\n }\n gpuStore.updateMesh(meshHandle, layout.vertices, layout.indices, 0, submeshes);\n // A color change replaces the material payload at this entity's stable\n // derived slot and re-binds the new producer handle in place.\n const materialId = resolveTextMaterial(world, gt, font, slot);\n if (materialId !== cached.materialHandle) {\n world.set(entity, MeshRenderer, {\n materials: [materialId],\n });\n }\n entityCache.set(slot, {\n handle: entity,\n record: {\n meshHandle: cached.meshHandle,\n signature,\n materialHandle: materialId,\n },\n });\n return null;\n }\n\n // First-observation path. If this entity already carries a MeshFilter (e.g.\n // the bake cache was reset between frames), skip without re-baking. `world.get`\n // returns err(component-not-present) (never throws) when the column is absent,\n // so the column probe needs no registration guard (feat-20260602).\n const existingFilter = world.get(entity, MeshFilter);\n if (existingFilter.ok) {\n ensureGlyphMeshMaterialSlots(world, existingFilter.value.assetHandle);\n return null;\n }\n\n const layout = layoutGlyphText(font, gt.text, gt.fontSize);\n const bake = bakeGlyphMesh(world, layout);\n if (!bake.ok) return null; // register fail-fast (should not happen for w15 output)\n\n // F-1: resolve the entity-owned MSDF MaterialAsset so the\n // `forgeax::msdf-text` shader + atlas texture + sampler are bound to this\n // text entity (plan D-7). Without this the MeshRenderer would carry material\n // handle 0 -> default mid-grey unlit, and the atlas would never be sampled.\n const materialId = resolveTextMaterial(world, gt, font, slot);\n\n world.addComponent(entity, {\n component: MeshFilter,\n data: { assetHandle: bake.value.handle },\n });\n world.addComponent(entity, {\n component: MeshRenderer,\n data: { materials: [materialId] },\n });\n entityCache.set(slot, {\n handle: entity,\n record: {\n meshHandle: bake.value.handle,\n signature,\n materialHandle: materialId,\n },\n });\n return null;\n}\n\nexport function ensureGlyphMeshMaterialSlots(\n world: World,\n meshHandle: Handle<'MeshAsset', 'shared'>,\n): void {\n const mesh = world.sharedRefs.resolve<'MeshAsset', MeshAsset>(meshHandle);\n if (mesh.ok && !Array.isArray(mesh.value.materialSlots)) {\n Object.assign(mesh.value, { materialSlots: [{ slotName: 'Default' }] });\n }\n}\n\n/**\n * Build the MSDF text MaterialAsset for one World/entity slot and\n * return its raw unmanaged handle id. The material carries a single\n * Transparent-queue pass on the `forgeax::msdf-text` shader with premultiplied\n * blend, and values binding the tint color, packed atlas distance data, and an\n * embedded atlas texture reference (the record stage supplies the sampler).\n * HDR tint components (>1) flow through unchanged so bloom-enabled cameras\n * pick up bright text (AC-12).\n */\nfunction resolveTextMaterial(\n world: World,\n gt: GlyphTextData,\n font: FontAsset,\n slot: number,\n): Handle<'MaterialAsset', 'shared'> {\n const cache = worldMaterialCache(world);\n const material = {\n kind: 'material',\n passes: [\n {\n name: 'text',\n program: { module: 'forgeax::msdf-text' },\n renderState: {\n ...{\n blend: MSDF_TEXT_BLEND as never,\n cullMode: 'none',\n depthWriteEnabled: false,\n depthCompare: 'less-equal',\n },\n tags: { LightMode: 'Forward' },\n queue: 3000,\n },\n },\n ],\n values: {\n tintColor: [gt.color[0] ?? 1, gt.color[1] ?? 1, gt.color[2] ?? 1, gt.color[3] ?? 1],\n distanceRange: [\n font.common.distanceRange,\n font.common.atlasWidth,\n font.common.atlasHeight,\n 0,\n ],\n baseColorTexture: { texture: font.atlas },\n },\n parameters: [\n { name: 'tintColor', type: 'color', default: [1, 1, 1, 1] },\n { name: 'distanceRange', type: 'vec4', default: [4, 512, 512, 0] },\n { name: 'baseColorTexture', type: 'texture' },\n { name: 'metallicRoughnessTexture', type: 'texture', optional: true },\n { name: 'normalTexture', type: 'texture', optional: true },\n ],\n } satisfies MaterialAsset;\n const id = world.allocSharedRef('MaterialAsset', material);\n const previous = cache.get(slot);\n cache.set(slot, id);\n if (previous !== undefined && previous !== id) {\n world.sharedRefs.release(previous);\n }\n return id;\n}\n\nfunction signatureOf(gt: GlyphTextData): string {\n return `${gt.fontHandle}|${gt.fontSize}|${gt.text}|${gt.color[0]},${gt.color[1]},${gt.color[2]},${gt.color[3]}`;\n}\n\n// Handle bridges: GlyphText.fontHandle / cached mesh ids are packed u32 values;\n// AssetRegistry expects branded Handles. The brand is a compile-time phantom\n// (runtime value is the raw number), so a cast is the canonical bridge\n// (mirrors pick.ts toShared).\nfunction asFontHandle(raw: number): Handle<'FontAsset', 'shared'> {\n return toShared<'FontAsset'>(raw);\n}\n","import { box3, type Mat4Like, mat4 } from '@forgeax/engine-math';\n\n/**\n * Inputs owned by the render extract/persistent-scene boundary. Bounds are\n * deliberately derived here instead of being added to the author-facing\n * `Instances` component or written back to a Pack asset.\n */\nexport interface DerivedInstancesUnionBoundsInput {\n readonly meshAabb: ArrayLike<number> | undefined;\n readonly entityWorld: ArrayLike<number>;\n readonly transforms: ArrayLike<number> | undefined;\n}\n\n/**\n * Renderer-owned cache key. Each generation is supplied by the owner that can\n * observe that mutation: mesh/AABB publication, entity world transform, and\n * the packed instance matrix array respectively.\n */\nexport interface InstanceBoundsCacheKey {\n /** Optional scene/world scope for composite scenes; omitted for standalone tests. */\n readonly worldId?: number;\n readonly entityKey: number;\n readonly meshGeneration: number;\n readonly transformGeneration: number;\n readonly matrixGeneration: number;\n}\n\nexport type InstanceBoundsCacheInput = InstanceBoundsCacheKey & DerivedInstancesUnionBoundsInput;\n\n/**\n * Stable bitwise fingerprint for detached numeric facts used by the cache.\n * Float32 bits are hashed rather than decimal text so a real matrix/AABB\n * change invalidates the projection without keeping another mutable ledger.\n */\nexport function fingerprintNumericArray(values: ArrayLike<number>): number {\n let hash = 0x811c9dc5;\n const scalar = new Float32Array(1);\n const bits = new Uint32Array(scalar.buffer);\n for (let index = 0; index < values.length; index += 1) {\n scalar[0] = Number(values[index]);\n hash = Math.imul(hash ^ (bits[0] ?? 0), 0x01000193) >>> 0;\n }\n return hash >>> 0;\n}\n\nfunction finiteAabb(aabb: ArrayLike<number> | undefined): aabb is ArrayLike<number> {\n if (aabb === undefined || aabb.length < 6) return false;\n const minX = aabb[0] as number;\n const minY = aabb[1] as number;\n const minZ = aabb[2] as number;\n const maxX = aabb[3] as number;\n const maxY = aabb[4] as number;\n const maxZ = aabb[5] as number;\n return (\n Number.isFinite(minX) &&\n Number.isFinite(minY) &&\n Number.isFinite(minZ) &&\n Number.isFinite(maxX) &&\n Number.isFinite(maxY) &&\n Number.isFinite(maxZ) &&\n minX <= maxX &&\n minY <= maxY &&\n minZ <= maxZ\n );\n}\n\nfunction finiteMatrix(matrix: ArrayLike<number>): matrix is Mat4Like {\n if (matrix.length < 16) return false;\n for (let index = 0; index < 16; index += 1) {\n if (!Number.isFinite(matrix[index] as number)) return false;\n }\n return true;\n}\n\nfunction includeBox(out: box3.Box3, candidate: box3.Box3Like): void {\n for (const x of [candidate[0] as number, candidate[3] as number]) {\n for (const y of [candidate[1] as number, candidate[4] as number]) {\n for (const z of [candidate[2] as number, candidate[5] as number]) {\n box3.expandByPoint(out, [x, y, z]);\n }\n }\n }\n}\n\n/**\n * Derive the world-space AABB enclosing every instance of a mesh.\n *\n * `undefined` is a conservative signal: the caller must skip CPU culling\n * when an input is missing, malformed, or empty. This prevents an empty\n * `Instances` row from becoming a synthetic identity draw/bounds candidate.\n */\nexport function deriveInstancesUnionBounds(\n input: DerivedInstancesUnionBoundsInput,\n): Float32Array | undefined {\n const { meshAabb, entityWorld, transforms } = input;\n if (!finiteAabb(meshAabb) || !finiteMatrix(entityWorld) || transforms === undefined) {\n return undefined;\n }\n if (transforms.length === 0 || transforms.length % 16 !== 0) return undefined;\n\n const local = box3.create(\n meshAabb[0] as number,\n meshAabb[1] as number,\n meshAabb[2] as number,\n meshAabb[3] as number,\n meshAabb[4] as number,\n meshAabb[5] as number,\n );\n const union = box3.create();\n const composed = mat4.create();\n const transformed = box3.create();\n for (let offset = 0; offset < transforms.length; offset += 16) {\n const instance = new Float32Array(16);\n for (let lane = 0; lane < 16; lane += 1) {\n instance[lane] = transforms[offset + lane] as number;\n }\n if (!finiteMatrix(instance)) return undefined;\n mat4.multiply(composed, entityWorld, instance);\n box3.transformBox3(transformed, local, composed);\n if (!finiteAabb(transformed)) return undefined;\n includeBox(union, transformed);\n }\n return new Float32Array(union);\n}\n\ninterface InstanceBoundsCacheEntry extends InstanceBoundsCacheKey {\n readonly bounds: Float32Array | undefined;\n}\n\n/**\n * Small renderer-owned per-entity cache. A changed generation replaces the\n * entry atomically; packed-id reuse is safe when its owner supplies a new\n * generation (the normal RenderScene slot generation contract).\n */\nexport class InstanceBoundsCache {\n private readonly entries = new Map<string, InstanceBoundsCacheEntry>();\n\n private key(input: Pick<InstanceBoundsCacheKey, 'worldId' | 'entityKey'>): string {\n return `${input.worldId === undefined ? '' : `${input.worldId}:`}${input.entityKey}`;\n }\n\n get(input: InstanceBoundsCacheInput): Float32Array | undefined {\n const previous = this.entries.get(this.key(input));\n if (\n previous !== undefined &&\n previous.meshGeneration === input.meshGeneration &&\n previous.transformGeneration === input.transformGeneration &&\n previous.matrixGeneration === input.matrixGeneration\n ) {\n return previous.bounds;\n }\n const bounds = deriveInstancesUnionBounds(input);\n this.entries.set(this.key(input), {\n ...(input.worldId === undefined ? {} : { worldId: input.worldId }),\n entityKey: input.entityKey,\n meshGeneration: input.meshGeneration,\n transformGeneration: input.transformGeneration,\n matrixGeneration: input.matrixGeneration,\n bounds,\n });\n return bounds;\n }\n\n invalidate(entityKey?: number, worldId?: number): void {\n if (entityKey === undefined) {\n this.entries.clear();\n } else {\n this.entries.delete(this.key({ entityKey, ...(worldId === undefined ? {} : { worldId }) }));\n }\n }\n}\n","import type { PointsLinesStyle } from './snapshot';\n\n/**\n * Expands the local culling envelope by the maximum screen-space raster\n * radius. The shader applies the exact physical-pixel offset; this envelope\n * is deliberately conservative so transformed edge primitives are retained.\n */\nexport function expandPointsLinesBounds(\n bounds: ArrayLike<number>,\n style: PointsLinesStyle | undefined,\n): Float32Array {\n if (bounds.length < 6 || style === undefined) return new Float32Array(bounds);\n const marginPx = style.kind === 'points' ? style.sizePx * 0.5 : style.widthPx * 0.5;\n if (!Number.isFinite(marginPx) || marginPx <= 0) return new Float32Array(bounds);\n return new Float32Array([\n (bounds[0] ?? 0) - marginPx,\n (bounds[1] ?? 0) - marginPx,\n (bounds[2] ?? 0) - marginPx,\n (bounds[3] ?? 0) + marginPx,\n (bounds[4] ?? 0) + marginPx,\n (bounds[5] ?? 0) + marginPx,\n ]);\n}\n","import type { TextureAsset } from '@forgeax/engine-types';\nimport { COOKIE_SLICE_SIZE } from './resources';\n\nexport interface SpotModifierFactors {\n readonly brdf: number;\n readonly range: number;\n readonly cone: number;\n readonly ies?: number | undefined;\n readonly cookie?: number | undefined;\n readonly shadow: number;\n}\n\nexport interface IesCoordinates {\n readonly azimuth: number;\n readonly elevation: number;\n}\n\nexport interface CookieUv {\n readonly u: number;\n readonly v: number;\n}\n\n/**\n * The fixed GPU representation consumed by the extended-lighting Cookie\n * array. The matrix is deliberately keyed by Cookie slice rather than by\n * light: it carries only the source texture aspect correction. The shader\n * still owns the light-local basis, roll, and outer-cone projection, so one\n * Cookie can be shared by Spots with different directions or cone angles.\n */\nexport interface CookieProjection {\n readonly data: Uint8Array;\n readonly matrix: Float32Array;\n readonly aspect: number;\n}\n\nconst DEG_TO_RAD = Math.PI / 180;\n\nconst COOKIE_PROJECTION_CACHE = new WeakMap<TextureAsset, CookieProjection | null>();\n\nfunction srgbToLinear(value: number): number {\n return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;\n}\n\nfunction clamp01(value: number): number {\n return Math.min(1, Math.max(0, value));\n}\n\nfunction sourceChannel(asset: TextureAsset, x: number, y: number, channel: number): number {\n const offset = (y * asset.shape.extent.width + x) * 4 + channel;\n const encoded = (asset.data[offset] ?? 0) / 255;\n return channel < 3 && asset.colorSpace === 'srgb' ? srgbToLinear(encoded) : encoded;\n}\n\nfunction sampleSourceChannel(asset: TextureAsset, x: number, y: number, channel: number): number {\n const sourceX = clamp01((x + 0.5) / COOKIE_SLICE_SIZE) * (asset.shape.extent.width - 1);\n const sourceY = clamp01((y + 0.5) / COOKIE_SLICE_SIZE) * (asset.shape.extent.height - 1);\n const x0 = Math.floor(sourceX);\n const y0 = Math.floor(sourceY);\n const x1 = Math.min(asset.shape.extent.width - 1, x0 + 1);\n const y1 = Math.min(asset.shape.extent.height - 1, y0 + 1);\n const tx = sourceX - x0;\n const ty = sourceY - y0;\n const top =\n sourceChannel(asset, x0, y0, channel) * (1 - tx) + sourceChannel(asset, x1, y0, channel) * tx;\n const bottom =\n sourceChannel(asset, x0, y1, channel) * (1 - tx) + sourceChannel(asset, x1, y1, channel) * tx;\n return top * (1 - ty) + bottom * ty;\n}\n\n/**\n * Project a filterable 2D RGBA Cookie into the renderer's fixed linear\n * 256x256 array slice. This is a producer-boundary operation and is cached by\n * the immutable TextureAsset object, so the frame path never decodes or\n * resamples the source repeatedly.\n */\nexport function prepareCookieProjection(asset: TextureAsset): CookieProjection | undefined {\n if (COOKIE_PROJECTION_CACHE.has(asset)) {\n return COOKIE_PROJECTION_CACHE.get(asset) ?? undefined;\n }\n const supportedFormat = asset.format === 'rgba8unorm' || asset.format === 'rgba8unorm-srgb';\n const validDimensions =\n Number.isSafeInteger(asset.shape.extent.width) &&\n Number.isSafeInteger(asset.shape.extent.height) &&\n asset.shape.extent.width > 0 &&\n asset.shape.extent.height > 0;\n const validFormatPair =\n (asset.format === 'rgba8unorm-srgb' && asset.colorSpace === 'srgb') ||\n (asset.format === 'rgba8unorm' && asset.colorSpace === 'linear');\n const validPayload =\n asset.data.byteLength >= asset.shape.extent.width * asset.shape.extent.height * 4;\n if (!supportedFormat || !validDimensions || !validFormatPair || !validPayload) {\n COOKIE_PROJECTION_CACHE.set(asset, null);\n return undefined;\n }\n\n const data = new Uint8Array(COOKIE_SLICE_SIZE * COOKIE_SLICE_SIZE * 4);\n for (let y = 0; y < COOKIE_SLICE_SIZE; y += 1) {\n for (let x = 0; x < COOKIE_SLICE_SIZE; x += 1) {\n const target = (y * COOKIE_SLICE_SIZE + x) * 4;\n data[target] = Math.round(clamp01(sampleSourceChannel(asset, x, y, 0)) * 255);\n data[target + 1] = Math.round(clamp01(sampleSourceChannel(asset, x, y, 1)) * 255);\n data[target + 2] = Math.round(clamp01(sampleSourceChannel(asset, x, y, 2)) * 255);\n // Alpha stays linear and is intentionally preserved: the shader\n // multiplies sampled RGB by this lane as part of Cookie semantics.\n data[target + 3] = Math.round(clamp01(sampleSourceChannel(asset, x, y, 3)) * 255);\n }\n }\n\n // Column-major mat4. The shader multiplies the unprojected local\n // (x/depth, y/depth) pair by this aspect-only matrix, then applies the\n // Spot's outer-cone tangent and the [0,1] translation. Keeping outerCone\n // out of this slice-keyed matrix allows one Cookie to be shared by lights.\n const matrix = new Float32Array(16);\n matrix[0] = asset.shape.extent.height / asset.shape.extent.width;\n matrix[5] = 1;\n matrix[10] = 1;\n matrix[15] = 1;\n const projection = {\n data,\n matrix,\n aspect: asset.shape.extent.width / asset.shape.extent.height,\n };\n COOKIE_PROJECTION_CACHE.set(asset, projection);\n return projection;\n}\n\n/** Create the deterministic identity payload used for unused Cookie slices. */\nexport function createCookieProjectionMatrixData(count: number): Float32Array {\n const data = new Float32Array(count * 16);\n for (let index = 0; index < count; index += 1) {\n const base = index * 16;\n data[base] = 1;\n data[base + 5] = 1;\n data[base + 10] = 1;\n data[base + 15] = 1;\n }\n return data;\n}\n\nfunction normalized(vector: ArrayLike<number>): [number, number, number] | undefined {\n const x = vector[0] ?? 0;\n const y = vector[1] ?? 0;\n const z = vector[2] ?? 0;\n const length = Math.hypot(x, y, z);\n return length > 0 && Number.isFinite(length) ? [x / length, y / length, z / length] : undefined;\n}\n\nexport function spotModifierProduct(factors: SpotModifierFactors): number {\n return (\n factors.brdf *\n factors.range *\n factors.cone *\n (factors.ies ?? 1) *\n (factors.cookie ?? 1) *\n factors.shadow\n );\n}\n\nexport function projectIesCoordinates(\n toPoint: ArrayLike<number>,\n rollDeg: number,\n): IesCoordinates | undefined {\n const direction = normalized(toPoint);\n if (direction === undefined || direction[2] >= 0) return undefined;\n const roll = rollDeg * DEG_TO_RAD;\n const rolledX = direction[0] * Math.cos(roll) - direction[1] * Math.sin(roll);\n const rolledY = direction[0] * Math.sin(roll) + direction[1] * Math.cos(roll);\n return {\n azimuth: (Math.atan2(rolledY, rolledX) + Math.PI * 2) % (Math.PI * 2),\n elevation: Math.acos(Math.min(1, Math.max(-1, -direction[2]))) / Math.PI,\n };\n}\n\nexport function projectCookieUv(\n toPoint: ArrayLike<number>,\n rollDeg: number,\n aspect: number,\n outerConeDeg = 45,\n): CookieUv | undefined {\n const direction = normalized(toPoint);\n if (direction === undefined || direction[2] >= 0 || !Number.isFinite(aspect) || aspect <= 0)\n return undefined;\n const cone = Math.atan2(Math.hypot(direction[0], direction[1]), -direction[2]);\n const outerCone = outerConeDeg * DEG_TO_RAD;\n if (cone > outerCone) return undefined;\n const roll = rollDeg * DEG_TO_RAD;\n const x = direction[0] * Math.cos(roll) - direction[1] * Math.sin(roll);\n const y = direction[0] * Math.sin(roll) + direction[1] * Math.cos(roll);\n const scale = Math.tan(outerCone);\n return {\n u: 0.5 + (x / -direction[2] / scale / aspect) * 0.5,\n v: 0.5 + (y / -direction[2] / scale) * 0.5,\n };\n}\n","import type { AssetRegistry } from '@forgeax/engine-assets-runtime';\nimport {\n resolveAssetHandle,\n walkMaterialPassesOverSharedRefs,\n} from '@forgeax/engine-assets-runtime';\nimport type { EntityHandle, World } from '@forgeax/engine-ecs';\nimport {\n InstanceTransformsStrideMismatchError,\n routeWorldError,\n SpawnLightInvalidBoundsError,\n SpriteInstancesCountMismatchError,\n SpriteInstancesMutuallyExclusiveWithInstancesError,\n SpriteInstancesRequiresSpriteShaderError,\n} from '@forgeax/engine-ecs/projection';\nimport { deriveVertexLayoutProjection } from '@forgeax/engine-geometry';\nimport { box3, frustum, type Mat4, mat4, type Vec3, vec3 } from '@forgeax/engine-math';\nimport { AssetGuid } from '@forgeax/engine-pack/guid';\nimport type { MaterialCookProgramContext } from '@forgeax/engine-pack/material-cook';\nimport { RhiError } from '@forgeax/engine-rhi';\nimport { GlobalTransform, MorphWeights, Transform } from '@forgeax/engine-scene';\nimport type { MaterialShaderArtifact } from '@forgeax/engine-shader';\nimport {\n JointCountMismatchError,\n JointEntityDanglingError,\n SkeletonResolveFailedError,\n Skin,\n SkinInstancesCoexistForbiddenError,\n} from '@forgeax/engine-skinning';\nimport type {\n Asset,\n Handle,\n IesProfileAsset,\n MeshAsset,\n MeshLodLevel,\n SkeletonAsset,\n TextureAsset,\n} from '@forgeax/engine-types';\nimport {\n ASSET_ERROR_HINTS,\n AssetError,\n derive,\n handleSlot,\n materialValuesToLinearRuntime,\n toShared,\n} from '@forgeax/engine-types';\nimport {\n Atmosphere,\n DirectionalLight,\n Instances,\n Layer,\n LightProbe,\n Lines,\n MeshFilter,\n MeshRenderer,\n PointLight,\n PointLightShadow,\n Points,\n PostProcessParams,\n pointShapeFromU32,\n RectAreaLight,\n SkyboxBackground,\n Skylight,\n SortKey,\n SpotLight,\n SpriteInstances,\n SpriteRegionOverride,\n} from './components';\nimport {\n type DirectionalShadowQuality,\n directionalShadowQualityFromF32,\n} from './components/directional-shadow-filter';\nimport { GlyphText } from './components/glyph-text';\nimport {\n computeInvRangeSquared,\n degToCos,\n type LightValidationError,\n validateDirectionalLightData,\n validateLightProbeData,\n validateRectAreaLightData,\n} from './components/light-helpers';\nimport { selectEnvironment } from './environment/frame';\nimport { MaterialSkinAttrMissingError, SkinMaterialMismatchError } from './errors/render';\nimport type { EnvironmentCandidate, EnvironmentFrame } from './extract/environment';\nimport { buildGpuDrivenDraws, resolvePreparedGpuDrivenDraw } from './extract/gpu-driven';\nimport type { VisibilitySnapshot } from './extract/visibility';\nimport type {\n RenderFeatureHiddenEntityReport,\n RenderFeatureWorldVisibilitySnapshot,\n} from './features/types';\nimport { ensureGlyphMeshMaterialSlots } from './glyph-text-layout-system';\nimport type { GpuDrivenGeometryReceipt } from './gpu-driven/prepared-draw';\nimport type { InstanceProjectionStore } from './instances';\nimport { deriveInstancesUnionBounds, fingerprintNumericArray } from './instances-derived-bounds';\nimport {\n type MeshMaterialBindingDiagnostic,\n type MeshMaterialBindingSource,\n resolveMeshMaterialBindings,\n} from './mesh-material-bindings';\nimport { isStandardPbrSkinMaterialShader } from './pbr-pipeline';\nimport { expandPointsLinesBounds } from './points-lines/bounds';\nimport type { PointsLinesRetainedSnapshot, PointsLinesStyle } from './points-lines/snapshot';\nimport { COOKIE_SLICE_CAPACITY, IES_SLICE_CAPACITY } from './prepare/extended-lighting/resources';\nimport { prepareCookieProjection } from './prepare/extended-lighting/spot-modifiers';\nimport { STANDARD_OUTPUT_TRANSFORM_FEATURE_ID } from './render-contract';\nimport type {\n CsmCameraData,\n DirectionalCsmConfig,\n DirectionalLightSnapshot,\n DispatchEntry,\n ExtractedFrame,\n ExtractedLights,\n ExtractFramesOwner,\n ExtractPipelineSurface,\n InstancesSnapshot,\n LightProbeSnapshot,\n MaterialSnapshot,\n MaterialSnapshotCache,\n MaterialSnapshotCachesByWorld,\n MorphSnapshot,\n PointLightSnapshot,\n PointShadowSnapshot,\n PreparedExtractContext,\n RectAreaDirectLightSnapshot,\n RenderableSnapshot,\n SkyboxSnapshot,\n SkylightSnapshot,\n SpotLightSnapshot,\n SpriteInstancesSnapshot,\n TransformSnapshot,\n} from './render-system-extract';\nimport {\n appendMaterialDispatchEntries,\n assetReferenceText,\n BUILTIN_USER_REGION_TEXTURE_FIELDS,\n buildPointShadowMatrices,\n buildRectAreaWorldFrame,\n collectCubeCameraSnapshots,\n collectMaterialTextureCoordinates,\n collectMaterialTextureSamplers,\n collectMaterialTextureSources,\n collectReflectionProbeFacts,\n computeDirectionalCsm,\n createWorldInternalView,\n DEFAULT_FORWARD_PASS,\n extractVolumeSnapshot,\n fogState,\n internSharedRefFromGuid,\n isEngineInjectedTextureField,\n materialColorParameterSchema,\n materialNormalScale,\n materialParamSchemaForMaterial,\n materialProgramKeysForMaterial,\n materialTextureFields,\n materialTextureRef,\n pipelineRenderState,\n prepareExtractContext,\n pssmSplit,\n readPersistentMaterialSnapshot,\n readStablePersistentMaterialSnapshot,\n resolveMaterialSnapshot,\n resolveVideoFieldHandle,\n runtimeMaterialShaderIdForMaterial,\n Severity,\n selectCameraRoles,\n selectFogFrame,\n sortDispatchByQueue,\n storeMaterialSnapshot,\n tonemapParams,\n} from './render-system-extract';\nimport { SHADOW_ATLAS_DEFAULT_LAYERS } from './shadow-atlas';\nimport type { SkinPaletteSlice } from './systems/skin-palette-types';\nexport function extractFrames(\n worlds: readonly World[],\n owner: number | ExtractFramesOwner,\n assets?: AssetRegistry | null,\n pipelineState?: ExtractPipelineSurface | null,\n materialSnapshotCachesByWorld?: MaterialSnapshotCachesByWorld,\n options: {\n readonly materialContext?: MaterialCookProgramContext;\n readonly cull?: 'normal' | 'none';\n readonly renderables?: 'full' | 'none';\n readonly renderableEntitiesByWorld?: readonly (ReadonlySet<number> | undefined)[];\n readonly retainHidden?: boolean;\n readonly getMaterialShaderArtifact?: (\n materialShaderId: string,\n ) => MaterialShaderArtifact | undefined;\n readonly instanceCollections?: InstanceProjectionStore;\n } = {},\n): ExtractedFrame {\n // w4: normalize the owner argument. A bare number is the legacy single-owner\n // form (cameraOwner === resourceOwner); an object carries the two split\n // indices. When they coincide the code path is byte-identical to the pre-w4\n // single-owner behaviour (w1 contract combination 2).\n const cameraOwner = typeof owner === 'number' ? owner : owner.cameraOwner;\n const resourceOwner = typeof owner === 'number' ? owner : owner.resourceOwner;\n\n // ── D-2: frame-level side effects live here ────────────────────────────\n //\n // resetForFrame is called exactly once per frame, at the extractFrames\n // entry. The skinPaletteAllocator cursor is reset before each per-world\n // extract runs, so sequential per-world allocation yields non-overlapping\n // palette slices (AC-08).\n const skinPaletteAllocator = pipelineState?.skinPaletteAllocator ?? null;\n if (skinPaletteAllocator !== null) {\n skinPaletteAllocator.resetForFrame();\n }\n\n const failedWorlds = new Set<World>();\n // Resource-owner selection is a frame-level concern. Select Fog once before\n // per-world extraction so non-owner worlds do not scan their ECS tables for\n // a value that the merge layer will discard.\n const resourceOwnerWorld = worlds[resourceOwner];\n const resourceOwnerFog =\n resourceOwnerWorld === undefined ? null : (selectFogFrame(resourceOwnerWorld) ?? null);\n // ── D-2: per-world extract with error isolation ────────────────────────\n //\n // Each world runs extractFrame over the final state published by\n // world.update(). Failure in one world is caught, routed to that world's\n // _routeError (systemName carries worldId for source identification),\n // and the world's contribution is skipped (AC-09 graceful degradation).\n\n // The camera-owner frame must be extracted first: non-owner worlds do not\n // carry the surfaced camera, but their renderables still need to be tested\n // against that camera's frustum. Frames are placed back into worlds[] order\n // before merge so queue / directional-light / worldId semantics stay stable.\n const succeededFrames: ExtractedFrame[] = [];\n const succeededIndices: number[] = [];\n\n const extractionOrder = Array.from({ length: worlds.length }, (_, wi) => wi).sort((a, b) => {\n if (a === cameraOwner) return -1;\n if (b === cameraOwner) return 1;\n return a - b;\n });\n const framesByWorld = new Map<number, ExtractedFrame>();\n\n for (const wi of extractionOrder) {\n const world = worlds[wi];\n if (world === undefined || failedWorlds.has(world)) continue;\n try {\n const isCameraOwner = wi === cameraOwner;\n const cameraOwnerFrame = framesByWorld.get(cameraOwner);\n const prepared = prepareExtractContext(world, {\n ...(assets !== undefined ? { assets } : {}),\n ...(pipelineState !== undefined ? { pipelineState } : {}),\n resourceOwnerFog: wi === resourceOwner ? resourceOwnerFog : null,\n ...(materialSnapshotCachesByWorld === undefined\n ? {}\n : {\n materialSnapshotCache:\n materialSnapshotCachesByWorld.get(world) ??\n (() => {\n const cache: MaterialSnapshotCache = new Map();\n materialSnapshotCachesByWorld.set(world, cache);\n return cache;\n })(),\n }),\n ...(options.materialContext === undefined\n ? {}\n : { materialContext: options.materialContext }),\n cull: options.cull === 'none' ? 'none' : isCameraOwner ? 'self' : 'external',\n renderables: options.renderables ?? 'full',\n ...(options.renderableEntitiesByWorld?.[wi] === undefined\n ? {}\n : { renderableEntities: options.renderableEntitiesByWorld[wi] }),\n retainHidden: options.retainHidden ?? false,\n ...(options.getMaterialShaderArtifact === undefined\n ? {}\n : { getMaterialShaderArtifact: options.getMaterialShaderArtifact }),\n ...(options.instanceCollections === undefined\n ? {}\n : { instanceCollections: options.instanceCollections }),\n ...(cameraOwnerFrame === undefined ? {} : { cullCameras: cameraOwnerFrame.cameras }),\n });\n const frame = extractFrame(world, prepared);\n\n framesByWorld.set(wi, frame);\n } catch (err) {\n // Per-world failure: route to world's own error handler, skip contribution.\n try {\n createWorldInternalView(world)._routeError(err, {\n severity: Severity.Error,\n systemName: `RenderSystem.extractFrames(world[${wi}])`,\n });\n } catch {\n // If _routeError itself throws, the world already failed — skip silently.\n }\n }\n }\n\n // Restore the caller's world order after the camera-owner-first extraction.\n for (let wi = 0; wi < worlds.length; wi++) {\n const frame = framesByWorld.get(wi);\n if (frame === undefined) continue;\n succeededFrames.push(frame);\n succeededIndices.push(wi);\n }\n\n // ── D-3: merge semantics ───────────────────────────────────────────────\n\n // AC-04: renderables — concat by worlds[] order, stamp worldId.\n const renderables: RenderableSnapshot[] = [];\n const dispatchEntries: DispatchEntry[] = [];\n const visibilitySnapshots: VisibilitySnapshot[] = [];\n const featureVisibilitySnapshots: RenderFeatureWorldVisibilitySnapshot[] = [];\n const hiddenEntityReports: RenderFeatureHiddenEntityReport[] = [];\n\n for (let fi = 0; fi < succeededFrames.length; fi++) {\n const f = succeededFrames[fi];\n const wId = succeededIndices[fi];\n if (f === undefined || wId === undefined) continue;\n\n const base = renderables.length;\n const visibilitySnapshot = f.visibilitySnapshots[0];\n const world = worlds[wId];\n if (visibilitySnapshot !== undefined) {\n visibilitySnapshots.push(visibilitySnapshot);\n if (world !== undefined)\n featureVisibilitySnapshots.push({ world, snapshot: visibilitySnapshot });\n }\n hiddenEntityReports.push(...f.hiddenEntityReports);\n for (const r of f.renderables) {\n renderables.push({\n ...r,\n worldId: wId,\n ...(r.pointsLines === undefined ? {} : { pointsLines: { ...r.pointsLines, worldId: wId } }),\n });\n }\n\n // D-3: dispatch — per-world renderableIndex rebased by base offset.\n for (const d of f.dispatch) {\n dispatchEntries.push({ ...d, renderableIndex: (d.renderableIndex ?? 0) + base });\n }\n }\n\n // Stable sort dispatch by queue value.\n dispatchEntries.sort((a, b) => (a.queue ?? 0) - (b.queue ?? 0));\n\n // AC-04: lights — point[]/spot[] concat; directional first-hit in\n // succeededFrames order (which preserves worlds[] order for successful\n // frames); directionalCount sum.\n const point: PointLightSnapshot[] = [];\n const spot: SpotLightSnapshot[] = [];\n const rect: RectAreaDirectLightSnapshot[] = [];\n let directional: DirectionalLightSnapshot | undefined;\n let directionalCount = 0;\n let lightViewProj: readonly Float32Array[] | undefined;\n let splitPlanes: Float32Array | undefined;\n let cascadeCount: number | undefined;\n let cascadeBlend: number | undefined;\n let shadowMapSize: number | undefined;\n let depthBias: number | undefined;\n let normalBias: number | undefined;\n let directionalShadowQuality: DirectionalShadowQuality | undefined;\n let directionalShadowError: LightValidationError | undefined;\n const pointShadow: PointShadowSnapshot[] = [];\n // bug-20260710-editor-cross-world-shadow: carry the raw CSM config +\n // direction of the first-hit directional so the merge layer can recompute\n // matrices against the SURFACED (cameraOwner) camera — the light and the\n // camera may live in different worlds (editor super-composite).\n let directionalCsmConfig: DirectionalCsmConfig | undefined;\n let directionalCsmDirection: Vec3 | undefined;\n for (const f of succeededFrames) {\n for (const p of f.lights.point) point.push(p);\n for (const s of f.lights.spot) spot.push(s);\n for (const r of f.lights.rect) rect.push(r);\n for (const ps of f.lights.pointShadow) pointShadow.push(ps);\n if (directional === undefined && f.lights.directional !== undefined) {\n directional = f.lights.directional;\n // Carry CSM shadow fields from the first-hit directional's world.\n lightViewProj = f.lights.lightViewProj;\n splitPlanes = f.lights.splitPlanes;\n cascadeCount = f.lights.cascadeCount;\n cascadeBlend = f.lights.cascadeBlend;\n shadowMapSize = f.lights.shadowMapSize;\n depthBias = f.lights.depthBias;\n normalBias = f.lights.normalBias;\n directionalShadowQuality = f.lights.directionalShadowQuality;\n directionalShadowError = f.lights.directionalShadowError;\n directionalCsmConfig = f.lights.directionalCsmConfig;\n directionalCsmDirection = f.lights.directionalCsmDirection;\n }\n directionalCount += f.lights.directionalCount;\n }\n\n // AC-05/06 + w4 owner split (D-3 / R-6): cameras come from the cameraOwner\n // world; skylight / skybox / postProcessParams come from the resourceOwner\n // world (holistic snapshot selection). Scan succeededIndices once to locate\n // each owner's surviving frame. When cameraOwner === resourceOwner both\n // resolve to the same frame — byte-identical to the pre-w4 single-owner path.\n let cameraOwnerFrame: ExtractedFrame | undefined;\n let resourceOwnerFrame: ExtractedFrame | undefined;\n for (let fi = 0; fi < succeededFrames.length; fi++) {\n if (succeededIndices[fi] === cameraOwner) cameraOwnerFrame = succeededFrames[fi];\n if (succeededIndices[fi] === resourceOwner) resourceOwnerFrame = succeededFrames[fi];\n }\n const cameras = cameraOwnerFrame !== undefined ? [...cameraOwnerFrame.cameras] : [];\n const auxiliaryCameras =\n cameraOwnerFrame !== undefined ? [...cameraOwnerFrame.auxiliaryCameras] : [];\n const cubeCameras = cameraOwnerFrame !== undefined ? [...cameraOwnerFrame.cubeCameras] : [];\n\n // bug-20260710-editor-cross-world-shadow: RECOMPUTE directional CSM matrices\n // against the surfaced camera. In a single-world app the per-world extract\n // already produced correct matrices (light+camera share the world), and this\n // recompute reproduces them byte-identically (same config, same camera). In\n // the editor super-composite the directional light's world has NO camera, so\n // its per-world `lightViewProj` is undefined/degenerate; the surfaced camera\n // lives in the cameraOwner world. Pairing them here is the ONLY place both\n // are visible. Point/spot shadows are camera-independent (light-space only)\n // and need no merge-layer fix-up.\n const mergeCam = cameras[0];\n if (directionalCsmConfig !== undefined && directionalCsmDirection !== undefined) {\n const mergeCameraData: CsmCameraData | undefined =\n mergeCam !== undefined\n ? {\n world: mergeCam.world,\n fov: mergeCam.fov,\n aspect: mergeCam.aspect,\n near: mergeCam.near,\n far: mergeCam.far,\n projection: mergeCam.projection,\n orthoLeft: mergeCam.orthoLeft,\n orthoRight: mergeCam.orthoRight,\n orthoBottom: mergeCam.orthoBottom,\n orthoTop: mergeCam.orthoTop,\n }\n : undefined;\n const csm = computeDirectionalCsm(\n directionalCsmDirection,\n directionalCsmConfig,\n mergeCameraData,\n );\n if (csm !== null) {\n lightViewProj = csm.lightViewProj;\n splitPlanes = csm.splitPlanes;\n cascadeCount = csm.cascadeCount;\n cascadeBlend = csm.cascadeBlend;\n shadowMapSize = csm.shadowMapSize;\n directionalShadowQuality = csm.directionalShadowQuality;\n }\n // csm === null (no surfaced camera at all): keep the per-world carry —\n // there is no better data, and a cameraless frame renders nothing anyway.\n }\n\n const lights: ExtractedLights = {\n directional,\n directionalCount,\n point,\n spot,\n rect,\n lightViewProj,\n splitPlanes,\n cascadeCount,\n cascadeBlend,\n shadowMapSize,\n depthBias,\n normalBias,\n directionalShadowQuality,\n directionalShadowError,\n pointShadow,\n directionalCsmConfig,\n directionalCsmDirection,\n };\n const volumetricFog = resourceOwnerFrame?.volumetricFog;\n const skylight = resourceOwnerFrame?.skylight;\n const skylightCount = resourceOwnerFrame?.skylightCount ?? 0;\n const skybox = resourceOwnerFrame?.skybox;\n const skyboxCount = resourceOwnerFrame?.skyboxCount ?? 0;\n const fog = resourceOwnerFrame?.fog;\n const fogFailure = resourceOwnerFrame?.fogFailure;\n const environment = resourceOwnerFrame?.environment;\n const lightProbes = succeededFrames.flatMap((frame) => frame.lightProbes ?? []);\n // User-authored PostProcessParams entities are singleton scene resources, so\n // they come from the resourceOwner world (holistic snapshot selection).\n const postProcessParams = new Map(resourceOwnerFrame?.postProcessParams);\n // feat-20260709-editor-world-partition ENGINE-fix-round2 (defect 1): the\n // engine built-in Standard tonemap param is NOT a scene resource — the\n // per-world extractFrame bridges it from that world's own `cameras[0]`\n // (Camera.exposure / whitePoint / tonemap is the SSOT). It therefore lives on\n // the CAMERA-owner frame, not the resource-owner frame. In the split-owner\n // editor topology the resourceOwner world has no Camera, so its frame carries\n // no Standard tonemap entry; taking postProcessParams from resourceOwner\n // alone drops it, the tonemap pass's params UBO stays zero-filled\n // (exposure=0 => tonemapped output is uniformly black), and the whole frame\n // reads black even though geometry drew into the HDR target. Overlay the\n // camera-owner frame's tonemap param (its SSOT source) so the surfaced\n // camera's exposure/whitePoint/mode reach the tonemap pass. When\n // cameraOwner === resourceOwner this is a no-op (identical entry). The 'na'\n // Standard tonemap identity mirrors the engine provider key set at the\n // bottom of extractFrame (SSOT: same identity, same 16B layout).\n const OUTPUT_TRANSFORM_PARAM_KEY = STANDARD_OUTPUT_TRANSFORM_FEATURE_ID;\n const cameraTonemapParam = cameraOwnerFrame?.postProcessParams.get(OUTPUT_TRANSFORM_PARAM_KEY);\n if (cameraTonemapParam !== undefined) {\n postProcessParams.set(OUTPUT_TRANSFORM_PARAM_KEY, cameraTonemapParam);\n } else {\n // The camera-owner world produced no tonemap param (no Camera surfaced\n // there this frame); do not leave a stale resource-owner entry that would\n // apply a foreign camera's exposure. Removing it lets the tonemap pass fall\n // back to its param-less zero path only when genuinely no camera exists.\n postProcessParams.delete(OUTPUT_TRANSFORM_PARAM_KEY);\n }\n\n // D-3: frustumStats — culled/total summed across worlds.\n const frustumStats = {\n culled: succeededFrames.reduce((s, f) => s + f.frustumStats.culled, 0),\n total: succeededFrames.reduce((s, f) => s + f.frustumStats.total, 0),\n };\n const visibilityStats = {\n explicitlyHidden: succeededFrames.reduce((s, f) => s + f.visibilityStats.explicitlyHidden, 0),\n };\n const reflectionProbes = succeededFrames.flatMap((f, index) => {\n const worldId = succeededIndices[index] ?? 0;\n return (f.reflectionProbes ?? []).map((probe) => ({ ...probe, worldId }));\n });\n\n if (options.renderables !== 'none' && options.renderableEntitiesByWorld === undefined) {\n options.instanceCollections?.retain(\n new Set(\n renderables.flatMap((row) =>\n row.instances?.collectionId === undefined ? [] : [row.instances.collectionId],\n ),\n ),\n );\n if (\n skinPaletteAllocator !== null &&\n typeof skinPaletteAllocator.retainSliceKeys === 'function'\n ) {\n skinPaletteAllocator.retainSliceKeys(\n new Set(\n renderables.flatMap((row) =>\n row.skin === undefined\n ? []\n : [`${worlds[row.worldId]?.identity ?? row.worldId}:${row.entityKey}`],\n ),\n ),\n );\n }\n }\n\n return {\n cameras,\n auxiliaryCameras,\n cubeCameras,\n reflectionProbes,\n lights,\n ...(volumetricFog === undefined\n ? {}\n : { volumetricFog: { ...volumetricFog, worldId: resourceOwner } }),\n renderables,\n dispatch: dispatchEntries,\n skylight,\n skylightCount,\n lightProbes,\n skybox,\n skyboxCount,\n fog,\n ...(fogFailure === undefined ? {} : { fogFailure }),\n environment,\n environmentReady: resourceOwnerFrame !== undefined && environment !== undefined,\n frustumStats,\n visibilityStats,\n postProcessParams,\n visibilitySnapshots,\n featureVisibilitySnapshots,\n hiddenEntityReports,\n };\n}\n\n/**\n * A MeshAsset participates in frustum culling only when its producer supplied\n * the complete finite local-space bounds promised by the asset contract.\n * Missing, malformed, and inverted-infinity empty bounds remain conservative\n * (always visible) so a bad asset cannot turn into a false-negative render;\n * they are not cull candidates and therefore do not inflate frustumStats.\n */\nfunction hasFiniteOrderedLocalAabb(aabb: Float32Array | undefined): aabb is Float32Array {\n if (aabb === undefined || aabb.length !== 6) return false;\n const minX = aabb[0];\n const minY = aabb[1];\n const minZ = aabb[2];\n const maxX = aabb[3];\n const maxY = aabb[4];\n const maxZ = aabb[5];\n if (\n minX === undefined ||\n minY === undefined ||\n minZ === undefined ||\n maxX === undefined ||\n maxY === undefined ||\n maxZ === undefined\n ) {\n return false;\n }\n if (\n !Number.isFinite(minX) ||\n !Number.isFinite(minY) ||\n !Number.isFinite(minZ) ||\n !Number.isFinite(maxX) ||\n !Number.isFinite(maxY) ||\n !Number.isFinite(maxZ)\n ) {\n return false;\n }\n return minX <= maxX && minY <= maxY && minZ <= maxZ;\n}\n\nfunction morphSnapshotFor(\n mesh: MeshAsset,\n weights: ArrayLike<number> | undefined,\n): MorphSnapshot | undefined {\n const targets = mesh.morphTargets;\n if (targets === undefined || targets.length === 0 || weights === undefined) return undefined;\n if (weights.length !== targets.length) return undefined;\n const firstPositions = targets[0]?.position;\n if (\n firstPositions === undefined ||\n firstPositions.length === 0 ||\n firstPositions.length % 3 !== 0\n ) {\n return undefined;\n }\n const vertexCount = firstPositions.length / 3;\n if (mesh.vertices.length % vertexCount !== 0) return undefined;\n for (let targetIndex = 0; targetIndex < targets.length; targetIndex += 1) {\n const target = targets[targetIndex];\n if (target?.position?.length !== firstPositions.length) return undefined;\n }\n const copied = new Float32Array(weights.length);\n for (let index = 0; index < weights.length; index += 1) {\n const weight = weights[index] ?? Number.NaN;\n if (!Number.isFinite(weight)) return undefined;\n copied[index] = weight;\n }\n return { weights: copied, targetCount: targets.length };\n}\n\nexport function extractFrame(world: World, context: PreparedExtractContext): ExtractedFrame {\n // feat-20260708-composited-multi-world-rendering M2 / D-2: resetForFrame\n // has been lifted to extractFrames (the frame-level entry point).\n // extractFrame is now a pure world->snapshot function with no frame-level\n // side effects. See plan-decisions PD2 for the reviewer ruling.\n const {\n assets,\n pipelineState,\n materialSnapshotCache: persistentMaterialSnapshotCache,\n cull: cullMode,\n resourceOwnerFog,\n getMaterialShaderArtifact,\n instanceCollections,\n renderableEntities,\n retainHidden,\n } = context;\n // Environment reads are owned by the retained resource projection and are\n // established at the frame boundary; record never revisits World state.\n const fog =\n resourceOwnerFog === undefined ? selectFogFrame(world) : (resourceOwnerFog ?? undefined);\n const fogFailure = fogState(world).failure;\n const visibility = context.visibility.hasAnyHiddenIntent ? context.visibility : undefined;\n const skinPaletteAllocator = pipelineState?.skinPaletteAllocator ?? null;\n\n const directionalLightQuery = world.query({ read: [DirectionalLight] }).unwrap();\n\n // feat-20260601 D-3: camera / point / spot light world transforms are read\n // through the single resolved `GlobalTransform.world` mat4 (written by\n // propagateTransforms).\n //\n // Each segment routes through a World-owned Query with explicit read and\n // optional roles. The packed entity handle for `readWorldMat4Copy` /\n // `_getArrayView` reads comes from `row.entity` -- the\n // archetype-graph back-door (`graph.archetypes` / `arch.components.some`) is gone.\n // Plan-decisions K-2 sniffing scheme B (archetype-edge sniff once via\n // `row.get(X) !== undefined`); K-3 invariant preserved (`_getArrayView`\n // calls survive untouched, only the entity source changes).\n const worldInternal = createWorldInternalView(world);\n let volumetricFog = extractVolumeSnapshot(world, assets, worldInternal);\n\n const cameraRoles = selectCameraRoles(world);\n const cameras = [...cameraRoles.display];\n const auxiliaryCameras = cameraRoles.auxiliary;\n const cubeCameras = collectCubeCameraSnapshots(world);\n const reflectionProbes = collectReflectionProbeFacts(world);\n\n // Three-query union (M2 / w16 / AC-03): directional has no Transform\n // dependency (sun-like infinite-source semantics); point + spot pull\n // position from the companion Transform via the joined queries.\n // Host-side pre-multiplication: color *= intensity (charter P4); cone\n // deg -> cos (D-S2); range -> 1/range^2 (D-S5).\n let directional: DirectionalLightSnapshot | undefined;\n let directionalCount = 0;\n // feat-20260621 M2: capture shadow fields from the first-hit DirectionalLight.\n // castShadow defaults to true; the CSM path is gated on firstHitCastShadow !== false.\n let firstHitCastShadow: boolean | undefined;\n let firstHitShadowFields:\n | {\n cascadeCount: number;\n splitLambda: number;\n cascadeBlend: number;\n mapSize: number;\n depthBias: number;\n normalBias: number;\n shadowDistance: number;\n shadowFilter: number;\n shadowAngularRadius: number;\n maxPenumbraTexels: number;\n }\n | undefined;\n for (const row of directionalLightQuery) {\n const l = row.get(DirectionalLight);\n directionalCount += 1;\n const intensity = l.intensity;\n const snapshot: DirectionalLightSnapshot = {\n kind: 'directional',\n entity: row.entity,\n direction: vec3.create(l.direction[0] ?? 0, l.direction[1] ?? -1, l.direction[2] ?? 0),\n color: vec3.create(\n (l.color[0] ?? 1) * intensity,\n (l.color[1] ?? 1) * intensity,\n (l.color[2] ?? 1) * intensity,\n ),\n intensity,\n };\n if (directional === undefined) {\n // First hit wins; record-stage N>1 fail-fast (M3 / w19) flags duplicates.\n directional = snapshot;\n firstHitCastShadow = l.castShadow;\n firstHitShadowFields = {\n cascadeCount: l.cascadeCount,\n splitLambda: l.splitLambda,\n cascadeBlend: l.cascadeBlend,\n mapSize: l.mapSize,\n depthBias: l.depthBias,\n normalBias: l.normalBias,\n shadowDistance: l.shadowDistance,\n shadowFilter: l.shadowFilter,\n shadowAngularRadius: l.shadowAngularRadius,\n maxPenumbraTexels: l.maxPenumbraTexels,\n };\n }\n }\n\n let directionalShadowError: LightValidationError | undefined;\n if (directional !== undefined && firstHitShadowFields !== undefined) {\n const validation = validateDirectionalLightData({\n direction: directional.direction,\n castShadow: firstHitCastShadow,\n ...firstHitShadowFields,\n });\n if (!validation.ok) {\n directionalShadowError = validation.error;\n worldInternal._routeError(directionalShadowError, {\n severity: Severity.Error,\n systemName: 'RenderSystem.extract (directional-shadow)',\n });\n }\n }\n\n const pointSnapshots: PointLightSnapshot[] = [];\n // feat-20260612-point-light-shadows-urp-hdrp M4 / T-M4-4: track entity per\n // pointSnapshots index so the post-extract pointShadow join can stamp\n // `shadowAtlasLayer + shadowNear + shadowFar` onto the matching PointLight.\n const pointSnapshotEntities: number[] = [];\n const pointLightQuery = world\n .query({\n read: [PointLight],\n optional: [Transform, GlobalTransform],\n })\n .unwrap();\n for (const row of pointLightQuery) {\n const p = row.get(PointLight);\n // K-2 scheme B: archetype-edge sniff -- `bundle.Transform` key is absent\n // when the archetype does not carry the Transform column.\n const hasTransform = row.get(GlobalTransform) !== undefined;\n const intensity = p.intensity;\n const range = p.range;\n const entityId = row.entity;\n // Position = world-space translation extracted from GlobalTransform.world.\n // A point light archetype without a Transform column sits at the origin.\n let worldMat: Float32Array | undefined;\n if (hasTransform) {\n const view = worldInternal._getArrayView(entityId, GlobalTransform, 'world');\n if (view !== undefined) worldMat = new Float32Array(view);\n }\n const position =\n worldMat !== undefined ? mat4.getTranslation(vec3.create(), worldMat) : vec3.create(0, 0, 0);\n pointSnapshots.push({\n kind: 'point',\n entity: entityId,\n position,\n color: vec3.create(\n (p.color[0] ?? 1) * intensity,\n (p.color[1] ?? 1) * intensity,\n (p.color[2] ?? 1) * intensity,\n ),\n intensity,\n invRangeSquared: computeInvRangeSquared(range),\n });\n pointSnapshotEntities.push(entityId);\n }\n\n const spotSnapshots: SpotLightSnapshot[] = [];\n const spotLightQuery = world\n .query({\n read: [SpotLight],\n optional: [Transform, GlobalTransform],\n })\n .unwrap();\n // feat-20260625-spot-light-shadow-mapping M1 w5: tile allocation for castShadow spots.\n // Cap = 4 (OOS-5), sentinel -1 = unassigned (plan-strategy D-4).\n // Direction degeneration (near-zero) also skips shadow (requirements $112).\n let spotTileNext = 0;\n const iesSlices = new Map<number, number>();\n const cookieSlices = new Map<number, number>();\n const projectorSlices = new Map<number, number>();\n for (const row of spotLightQuery) {\n const s = row.get(SpotLight);\n const hasTransform = row.get(GlobalTransform) !== undefined;\n const intensity = s.intensity;\n const range = s.range;\n const innerConeDeg = s.innerConeDeg;\n const outerConeDeg = s.outerConeDeg;\n let worldMat: Float32Array | undefined;\n if (hasTransform) {\n const entity = row.entity;\n const view = worldInternal._getArrayView(entity, GlobalTransform, 'world');\n if (view !== undefined) worldMat = new Float32Array(view);\n }\n const position =\n worldMat !== undefined ? mat4.getTranslation(vec3.create(), worldMat) : vec3.create(0, 0, 0);\n const dir = vec3.create(s.direction[0] ?? 0, s.direction[1] ?? -1, s.direction[2] ?? 0);\n\n // Extract is the single direction-normalization owner for direct-light\n // snapshots. URP and HDRP preserve this value downstream.\n const dirLen = Math.sqrt(\n (dir[0] ?? 0) * (dir[0] ?? 0) + (dir[1] ?? 0) * (dir[1] ?? 0) + (dir[2] ?? 0) * (dir[2] ?? 0),\n );\n const EPSILON = 1e-6;\n const hasValidDirection = dirLen > EPSILON;\n if (!hasValidDirection) {\n worldInternal._routeError(\n new SpawnLightInvalidBoundsError('SpotLight', 'direction', [\n dir[0] ?? 0,\n dir[1] ?? 0,\n dir[2] ?? 0,\n ]),\n {\n severity: Severity.Error,\n systemName: 'RenderSystem.extract (spot-direction)',\n },\n );\n }\n const dirN = vec3.create(\n hasValidDirection ? (dir[0] ?? 0) / dirLen : (dir[0] ?? 0),\n hasValidDirection ? (dir[1] ?? 0) / dirLen : (dir[1] ?? 0),\n hasValidDirection ? (dir[2] ?? 0) / dirLen : (dir[2] ?? 0),\n );\n\n // ── shadow fields (feat-20260625-spot-light-shadow-mapping M1) ──\n const castShadow = s.castShadow;\n const sMapSize = s.mapSize;\n const sNearPlane = s.nearPlane;\n const sFarPlane = s.farPlane;\n const iesProfileAsset =\n s.iesProfile === undefined\n ? undefined\n : resolveAssetHandle<IesProfileAsset>(world, s.iesProfile);\n const cookieAsset =\n s.cookie === undefined ? undefined : resolveAssetHandle<TextureAsset>(world, s.cookie);\n // Resolve the legacy projector before assigning array slices so the\n // extended-lighting path can reuse its texture transport without losing\n // the old lightViewProj projection semantics.\n const hasProjector = Number(s.projector) > 0;\n let projectorHandle: Handle<'TextureAsset', 'shared'> | undefined;\n let projectorAsset: TextureAsset | undefined;\n let projectorGuid: string | undefined;\n if (hasProjector) {\n const candidate = toShared<'TextureAsset'>(Math.round(Number(s.projector)));\n const resolvedProjector = resolveAssetHandle<TextureAsset>(world, candidate);\n if (!resolvedProjector.ok || resolvedProjector.value.kind !== 'texture') {\n worldInternal._routeError(\n resolvedProjector.ok\n ? new RhiError({\n code: 'asset-not-registered',\n expected: 'SpotLight.projector resolves to a TextureAsset',\n hint: 'load the authored projector TextureAsset before assigning SpotLight.projector',\n detail: { assetHandle: Number(candidate) },\n })\n : resolvedProjector.error,\n { severity: Severity.Error, systemName: 'RenderSystem.extract (spot-projector)' },\n );\n } else {\n projectorHandle = candidate;\n projectorAsset = resolvedProjector.value;\n projectorGuid = assets?.guidOf(projectorAsset) ?? `handle:${Number(candidate)}`;\n }\n }\n const iesProfileData =\n iesProfileAsset?.ok && iesProfileAsset.value.kind === 'ies-profile'\n ? new Uint8Array(iesProfileAsset.value.data)\n : undefined;\n const cookieProjection =\n cookieAsset?.ok && cookieAsset.value.kind === 'texture'\n ? prepareCookieProjection(cookieAsset.value)\n : undefined;\n const cookieData = cookieProjection?.data;\n const projectorProjection =\n projectorAsset === undefined ? undefined : prepareCookieProjection(projectorAsset);\n const projectorData = projectorProjection?.data;\n const iesProfileHandle = s.iesProfile === undefined ? undefined : handleSlot(s.iesProfile);\n const cookieHandle = s.cookie === undefined ? undefined : handleSlot(s.cookie);\n let iesProfileSlice =\n iesProfileHandle === undefined ? undefined : iesSlices.get(iesProfileHandle);\n if (\n iesProfileSlice === undefined &&\n iesProfileHandle !== undefined &&\n iesProfileData !== undefined &&\n iesSlices.size < IES_SLICE_CAPACITY\n ) {\n iesProfileSlice = iesSlices.size;\n iesSlices.set(iesProfileHandle, iesProfileSlice);\n }\n let cookieSlice = cookieHandle === undefined ? undefined : cookieSlices.get(cookieHandle);\n if (\n cookieSlice === undefined &&\n cookieHandle !== undefined &&\n cookieData !== undefined &&\n cookieSlices.size < COOKIE_SLICE_CAPACITY\n ) {\n cookieSlice = cookieSlices.size;\n cookieSlices.set(cookieHandle, cookieSlice);\n }\n let projectorSlice =\n projectorHandle === undefined\n ? undefined\n : (projectorSlices.get(projectorHandle) ?? cookieSlices.get(projectorHandle));\n if (\n projectorSlice === undefined &&\n projectorHandle !== undefined &&\n projectorData !== undefined &&\n cookieSlices.size + projectorSlices.size < COOKIE_SLICE_CAPACITY\n ) {\n projectorSlice = cookieSlices.size + projectorSlices.size;\n projectorSlices.set(projectorHandle, projectorSlice);\n }\n const shadowIntensity = s.shadowIntensity;\n // `shared<T>` columns are u32-backed and zero-filled when the optional\n // field is absent. Treat only a positive handle as an authored projector;\n // checking nullish values alone would turn the zero sentinel into a\n // phantom projector matrix and an avoidable asset-not-found diagnostic.\n let lightViewProj: Float32Array | undefined;\n let shadowAtlasTile = -1;\n\n // A projector needs the same perspective transform even when its SpotLight\n // has no shadow atlas tile. The matrix remains a derived light fact; the\n // shadow tile stays -1 so shadow visibility is still independently gated.\n if ((castShadow || hasProjector) && hasValidDirection) {\n const target = vec3.create(\n (position[0] ?? 0) + (dirN[0] ?? 0),\n (position[1] ?? 0) + (dirN[1] ?? 0),\n (position[2] ?? 0) + (dirN[2] ?? 0),\n );\n // D-1: perspective(outerConeDeg*2, aspect=1, near, far) x lookAt(pos, pos+dir).\n // FOV = outerConeDeg * 2 in degrees; mat4.perspective takes fov in radians.\n const fov = outerConeDeg * 2 * (Math.PI / 180);\n const proj = mat4.create();\n mat4.perspective(proj, fov, 1, sNearPlane, sFarPlane);\n const view = mat4.create();\n mat4.lookAt(view, position, target, vec3.create(0, 1, 0));\n lightViewProj = new Float32Array(16);\n // Reinterpret the Float32Array surface field as a Mat4 out-param; a\n // factory would force a needless alloc+copy. brand-cast-ok\n mat4.multiply(lightViewProj as Mat4, proj, view);\n\n // D-4: allocate tile 0..3; 5th+ = -1 sentinel.\n if (castShadow && spotTileNext < 4) {\n shadowAtlasTile = spotTileNext;\n spotTileNext += 1;\n }\n }\n\n spotSnapshots.push({\n kind: 'spot',\n entity: row.entity,\n // D-6: position reflects world transform; direction stays sourced\n // from SpotLight.direction (NOT rotated by the parent).\n position,\n direction: dirN,\n color: vec3.create(\n (s.color[0] ?? 1) * intensity,\n (s.color[1] ?? 1) * intensity,\n (s.color[2] ?? 1) * intensity,\n ),\n intensity,\n invRangeSquared: computeInvRangeSquared(range),\n cosInner: degToCos(innerConeDeg),\n cosOuter: degToCos(outerConeDeg),\n ...(s.iesProfile === undefined\n ? {}\n : {\n iesProfileHandle: handleSlot(s.iesProfile),\n ...(iesProfileSlice === undefined ? {} : { iesProfileSlice }),\n }),\n ...(s.cookie === undefined\n ? {}\n : {\n cookieHandle: handleSlot(s.cookie),\n ...(cookieSlice === undefined ? {} : { cookieSlice }),\n }),\n ...(iesProfileData === undefined ? {} : { iesProfileData }),\n ...(cookieData === undefined ? {} : { cookieData }),\n ...(cookieProjection === undefined ? {} : { cookieMatrix: cookieProjection.matrix }),\n ...(projectorSlice === undefined ? {} : { projectorSlice }),\n ...(projectorData === undefined ? {} : { projectorData }),\n ...(projectorProjection === undefined ? {} : { projectorMatrix: projectorProjection.matrix }),\n rollDeg: s.rollDeg,\n // ── shadow fields ──\n castShadow,\n lightViewProj,\n mapSize: sMapSize,\n nearPlane: sNearPlane,\n farPlane: sFarPlane,\n shadowAtlasTile,\n shadowIntensity,\n depthBias: s.depthBias,\n normalBias: s.normalBias,\n pcfKernelSize: s.pcfKernelSize,\n ...(projectorHandle === undefined ||\n projectorAsset === undefined ||\n projectorGuid === undefined\n ? {}\n : {\n projectorHandle,\n projectorAsset,\n projectorGuid,\n projectorGeneration: 1,\n projectorRevision: 1,\n }),\n });\n }\n\n const rectSnapshots: RectAreaDirectLightSnapshot[] = [];\n const rectLightQuery = world\n .query({\n read: [RectAreaLight],\n optional: [Transform, GlobalTransform],\n })\n .unwrap();\n for (const row of rectLightQuery) {\n const light = row.get(RectAreaLight);\n const validation = validateRectAreaLightData({\n intensity: light.intensity,\n color: light.color,\n width: light.width,\n height: light.height,\n range: light.range,\n });\n if (!validation.ok) {\n worldInternal._routeError(validation.error, {\n severity: Severity.Error,\n systemName: 'RenderSystem.extract (rect-area-light)',\n });\n continue;\n }\n const worldView = row.get(GlobalTransform);\n const worldMat =\n worldView === undefined\n ? undefined\n : new Float32Array(worldInternal._getArrayView(row.entity, GlobalTransform, 'world') ?? []);\n const position =\n worldMat !== undefined ? mat4.getTranslation(vec3.create(), worldMat) : vec3.create(0, 0, 0);\n const frame = buildRectAreaWorldFrame({\n center: position,\n axisX: [worldMat?.[0] ?? 1, worldMat?.[1] ?? 0, worldMat?.[2] ?? 0],\n axisY: [worldMat?.[4] ?? 0, worldMat?.[5] ?? 1, worldMat?.[6] ?? 0],\n width: light.width,\n height: light.height,\n });\n rectSnapshots.push({\n kind: 'rect-area',\n position,\n color: vec3.create(\n (light.color[0] ?? 1) * light.intensity,\n (light.color[1] ?? 1) * light.intensity,\n (light.color[2] ?? 1) * light.intensity,\n ),\n intensity: light.intensity,\n invRangeSquared: computeInvRangeSquared(light.range),\n halfWidth: frame.halfWidth,\n halfHeight: frame.halfHeight,\n axisX: frame.axisX,\n axisY: frame.axisY,\n });\n }\n // The SpotLight is the sole projector owner. Once all light snapshots have\n // been extracted, publish its accepted TextureAsset tuple on the volume\n // snapshot so surface and volume consume the same identity and revision.\n let volumeSpot: SpotLightSnapshot | undefined;\n const extractedFog = volumetricFog;\n if (extractedFog !== undefined) {\n if (extractedFog.spotLightEntity !== undefined) {\n volumeSpot = spotSnapshots.find((light) => light.entity === extractedFog.spotLightEntity);\n } else if (extractedFog.lightKind === 'spot') {\n volumeSpot = spotSnapshots.find((light) => light.entity === extractedFog.lightEntity);\n }\n }\n if (\n volumetricFog !== undefined &&\n volumetricFog.status === 'available' &&\n volumeSpot?.projectorAsset !== undefined &&\n volumeSpot.projectorHandle !== undefined\n ) {\n const projectorHandle = volumeSpot.projectorHandle;\n const projectorAsset = volumeSpot.projectorAsset;\n volumetricFog = {\n ...volumetricFog,\n projector: {\n guid: volumeSpot.projectorGuid ?? `handle:${Number(volumeSpot.projectorHandle)}`,\n generation: volumeSpot.projectorGeneration ?? 1,\n view: '2d',\n sampler: 'linear-clamp-to-edge',\n projection: 'spot-projection',\n revision: volumeSpot.projectorRevision ?? 1,\n },\n projectorHandle,\n projectorAsset,\n };\n }\n\n // bug-20260710-editor-cross-world-shadow: CSM matrices are computed by the\n // shared pure {@link computeDirectionalCsm}, called here per-world with THIS\n // world's own `cameras[0]`. In a single-world app the light and camera share\n // the world, so this per-world result is final (byte-identical to the prior\n // inline block). In the editor super-composite the light's world may have no\n // camera → this yields no matrices; {@link extractFrames} then RECOMPUTES at\n // the merge layer using the surfaced (cameraOwner) camera + the raw config\n // carried on ExtractedLights. The raw config + direction are surfaced\n // unconditionally so the merge layer can re-run the builder.\n let lightViewProj: Float32Array[] | undefined;\n let splitPlanes: Float32Array | undefined;\n let cascadeCount: number | undefined;\n let cascadeBlend: number | undefined;\n let shadowMapSize: number | undefined;\n let directionalShadowQuality: DirectionalShadowQuality | undefined;\n let directionalCsmConfig: DirectionalCsmConfig | undefined;\n let directionalCsmDirection: Vec3 | undefined;\n\n // Camera data needed for frustum corner computation (first camera only;\n // multi-camera CSM is OOS-1). Undefined in a cameraless world.\n const cam0 = cameras[0];\n const cameraData: CsmCameraData | undefined =\n cam0 !== undefined\n ? {\n world: cam0.world,\n fov: cam0.fov,\n aspect: cam0.aspect,\n near: cam0.near,\n far: cam0.far,\n projection: cam0.projection,\n orthoLeft: cam0.orthoLeft,\n orthoRight: cam0.orthoRight,\n orthoBottom: cam0.orthoBottom,\n orthoTop: cam0.orthoTop,\n }\n : undefined;\n\n // feat-20260621 M2: CSM computation gated on castShadow from the\n // merged DirectionalLight. castShadow defaults to true (first-hit-wins\n // semantics, D-6 no cardinality cap).\n if (\n directional !== undefined &&\n firstHitCastShadow !== false &&\n directionalShadowError === undefined\n ) {\n const dirSnapshot = directional;\n const sf = firstHitShadowFields;\n if (sf !== undefined) {\n directionalCsmConfig = {\n cascadeCount: sf.cascadeCount,\n splitLambda: sf.splitLambda,\n cascadeBlend: sf.cascadeBlend,\n mapSize: sf.mapSize,\n shadowDistance: sf.shadowDistance,\n shadowFilter: sf.shadowFilter,\n shadowAngularRadius: sf.shadowAngularRadius,\n maxPenumbraTexels: sf.maxPenumbraTexels,\n };\n directionalCsmDirection = dirSnapshot.direction;\n const csm = computeDirectionalCsm(dirSnapshot.direction, directionalCsmConfig, cameraData);\n // Cascade metadata (splitPlanes / count / blend / mapSize) is available\n // even without a camera (splitPlanes needs only near/far); the matrices\n // need the camera. When csm is null (no camera) leave lightViewProj\n // undefined — the merge layer recomputes. Still surface the split/count\n // metadata so a single-world path keeps its prior fields.\n cascadeCount = Math.round(sf.cascadeCount);\n cascadeBlend = sf.cascadeBlend;\n shadowMapSize = sf.mapSize;\n if (csm !== null) {\n lightViewProj = csm.lightViewProj;\n splitPlanes = csm.splitPlanes;\n directionalShadowQuality = csm.directionalShadowQuality;\n } else {\n const sNear = cameraData?.near ?? 0.1;\n const splits = pssmSplit(sNear, sf.shadowDistance, cascadeCount, sf.splitLambda);\n const padded = new Float32Array(16);\n for (let i = 0; i < splits.length; i++) padded[i * 4] = splits[i] ?? 0;\n splitPlanes = padded;\n }\n directionalShadowQuality = directionalShadowQualityFromF32(\n sf.shadowFilter,\n sf.shadowAngularRadius,\n sf.maxPenumbraTexels,\n );\n }\n }\n\n // feat-20260613-csm M3 / w14 (plan-strategy §D-7): pad the up-to-4\n // splitPlanes into a fixed length-4 Float32Array (unused slots = 0) so\n // the View UBO tail keeps a stable layout regardless of the runtime\n // cascadeCount. Host-side correctness invariant: only the first\n // cascadeCount slots are ever read by the WGSL kernel.\n const paddedSplitPlanes = new Float32Array(16);\n if (splitPlanes !== undefined) {\n for (let i = 0; i < splitPlanes.length; i++) {\n paddedSplitPlanes[i] = splitPlanes[i] ?? 0;\n }\n }\n\n // feat-20260612-point-light-shadows-urp-hdrp M1 / T-M1-7 (plan-strategy §D-3,\n // requirements §5.3): query (PointLight + PointLightShadow + Transform)\n // archetype join. For each shadow caster, build 6 face VP matrices and pack\n // into Float32Array(96). Atlas layer is assigned in spawn order while the\n // renderer-owned atlas has capacity; the sentinel -1 is shader-side and\n // applies to non-admitted PointLightShadow requests as well.\n const pointShadowSnapshots: PointShadowSnapshot[] = [];\n {\n const pointShadowQuery = world\n .query({ read: [Transform, GlobalTransform, PointLightShadow], with: [PointLight] })\n .unwrap();\n for (const row of pointShadowQuery) {\n const ps = row.get(PointLightShadow);\n // Read world-space position from GlobalTransform.world (mat4 column-major;\n // translation lives at indices 12..14, mirroring CameraSnapshot.world\n // semantics in this file).\n // feat-20260614 M4 / w13: TypedArrayFor for `array<f32, 16>` now\n // resolves to a concrete `Float32Array` (was `never` pre-w11), which\n // surfaces the row-window slicing -- `t.world` is the stride-16 flat\n // column view; row i lives at `[i*16, (i+1)*16)`. The prior\n // `t.world?.[i]` form silently returned a single element under the\n // `never`-typed bundle path and `wRow[12]` widened to `undefined ?? 0`\n // so light positions clamped to the origin.\n const wRow = row.get(GlobalTransform).world;\n if (wRow === undefined) continue;\n const px = wRow[12] ?? 0;\n const py = wRow[13] ?? 0;\n const pz = wRow[14] ?? 0;\n const lightPos = vec3.create(px, py, pz);\n const mapSize = ps.mapSize;\n const nearPlane = ps.nearPlane;\n const farPlane = ps.farPlane;\n // The renderer, not ECS, owns the atlas budget. Preserve every request\n // for inspection, but emit the shader sentinel for entries that cannot\n // acquire a layer so record never calls faceView outside the atlas.\n const layer =\n pointShadowSnapshots.length < SHADOW_ATLAS_DEFAULT_LAYERS\n ? pointShadowSnapshots.length\n : -1;\n\n const matrices = buildPointShadowMatrices(lightPos, nearPlane, farPlane);\n const packed = new Float32Array(96);\n for (let f = 0; f < 6; f++) {\n const m = matrices[f];\n if (m === undefined) continue;\n for (let k = 0; k < 16; k++) {\n packed[f * 16 + k] = m[k] ?? 0;\n }\n }\n pointShadowSnapshots.push({\n entity: row.entity,\n position: lightPos,\n mapSize,\n nearPlane,\n farPlane,\n shadowAtlasLayer: layer,\n shadowMatrices: packed,\n });\n }\n }\n\n // feat-20260612-point-light-shadows-urp-hdrp M4 / T-M4-4 (plan-strategy §D-8):\n // join pointShadow snapshots into the matching PointLightSnapshot so the\n // record stage threads `shadowAtlasLayer + shadowNear + shadowFar` through\n // the unified direct-light metadata payload.\n // Mutates the freshly-built PointLightSnapshot in place; the snapshot is\n // not exposed elsewhere this frame yet (consumed only by lights.point[]).\n if (pointShadowSnapshots.length > 0) {\n const shadowByEntity = new Map<number, PointShadowSnapshot>();\n for (const ps of pointShadowSnapshots) shadowByEntity.set(ps.entity, ps);\n for (let i = 0; i < pointSnapshots.length; i++) {\n const entityId = pointSnapshotEntities[i] ?? 0;\n const ps = shadowByEntity.get(entityId);\n if (ps !== undefined) {\n pointSnapshots[i] = {\n ...(pointSnapshots[i] as PointLightSnapshot),\n shadowAtlasLayer: ps.shadowAtlasLayer,\n shadowNear: ps.nearPlane,\n shadowFar: ps.farPlane,\n };\n }\n }\n }\n\n const lights: ExtractedLights = {\n directional,\n directionalCount,\n point: pointSnapshots,\n spot: spotSnapshots,\n rect: rectSnapshots,\n lightViewProj,\n splitPlanes: splitPlanes !== undefined ? paddedSplitPlanes : undefined,\n cascadeCount,\n cascadeBlend,\n shadowMapSize,\n depthBias: firstHitCastShadow !== false ? firstHitShadowFields?.depthBias : undefined,\n normalBias: firstHitCastShadow !== false ? firstHitShadowFields?.normalBias : undefined,\n directionalShadowQuality,\n directionalShadowError,\n pointShadow: pointShadowSnapshots,\n // bug-20260710-editor-cross-world-shadow: raw CSM config + light direction\n // so the merge layer can recompute matrices against the surfaced camera.\n directionalCsmConfig,\n directionalCsmDirection,\n };\n\n // feat-20260520-skylight-ibl-cubemap M4 / t26+t27: query Skylight entities.\n // First archetype hit wins (mirrors DirectionalLight pattern); multi-Skylight\n // warn in record stage (t27) uses skylightCount.\n const skylightQuery = world.query({ read: [Skylight] }).unwrap();\n let skylight: SkylightSnapshot | undefined;\n let skylightCount = 0;\n for (const row of skylightQuery) {\n const s = row.get(Skylight);\n // equirect is OPTIONAL: an omitted field zero-inits to handle 0, which\n // record treats as \"no equirect\" -> solid-color ambient via the white\n // fallback cube. A Skylight WITHOUT an equirect is still a valid snapshot\n // (the prior `equirectRaw !== undefined` gate dropped color-only\n // skylights, leaving the scene black -- the downstream gap #4).\n const equirectRaw = s.equirect;\n const intensity = s.intensity;\n const colorR = s.color[0] ?? 1.0;\n const colorG = s.color[1] ?? 1.0;\n const colorB = s.color[2] ?? 1.0;\n const rotation: [number, number, number, number] = [\n s.rotation[0] ?? 0,\n s.rotation[1] ?? 0,\n s.rotation[2] ?? 0,\n s.rotation[3] ?? 1,\n ];\n skylightCount += 1;\n if (skylight === undefined) {\n skylight = {\n equirectHandle: equirectRaw !== undefined ? Math.round(equirectRaw) : 0,\n color: [colorR, colorG, colorB],\n intensity,\n rotation,\n // w19: winning entity handle for the multi-Skylight once-warn (F-8).\n entityHandle: row.entity,\n };\n }\n }\n\n const lightProbeQuery = world.query({ read: [LightProbe, GlobalTransform] }).unwrap();\n const lightProbes: LightProbeSnapshot[] = [];\n for (const row of lightProbeQuery) {\n const probe = row.get(LightProbe);\n const validation = validateLightProbeData({\n irradiance: probe.irradiance,\n radius: probe.radius,\n });\n if (!validation.ok) {\n worldInternal._routeError(validation.error, {\n severity: Severity.Error,\n systemName: 'RenderSystem.extract (light-probe)',\n });\n continue;\n }\n const transform = row.get(GlobalTransform);\n lightProbes.push({\n identity: String(row.entity),\n position: [transform.world[12] ?? 0, transform.world[13] ?? 0, transform.world[14] ?? 0],\n radius: probe.radius,\n irradiance: new Float32Array(probe.irradiance),\n admitted: true,\n });\n }\n\n // feat-20260531-skybox-env-background M2 / w5: query SkyboxBackground entities.\n // First archetype hit wins (mirrors Skylight pattern); multi-entity\n // once-warn in record stage uses skyboxCount.\n const skyboxQuery = world.query({ read: [SkyboxBackground] }).unwrap();\n let skybox: SkyboxSnapshot | undefined;\n let skyboxCount = 0;\n for (const row of skyboxQuery) {\n const s = row.get(SkyboxBackground);\n const equirectRaw = s.equirect;\n const modeRaw = s.mode;\n const rotation: [number, number, number, number] = [\n s.rotation[0] ?? 0,\n s.rotation[1] ?? 0,\n s.rotation[2] ?? 0,\n s.rotation[3] ?? 1,\n ];\n skyboxCount += 1;\n if (skybox === undefined && equirectRaw !== undefined) {\n skybox = {\n equirectHandle: Math.round(equirectRaw),\n mode: modeRaw,\n rotation,\n // w19: winning entity handle for the multi-SkyboxBackground warn (F-8).\n entityHandle: row.entity,\n };\n }\n }\n\n const environmentCandidates: EnvironmentCandidate[] = [];\n const imageEnvironment =\n skylight?.equirectHandle !== undefined && skylight.equirectHandle > 0\n ? skylight\n : skybox?.equirectHandle !== undefined && skybox.equirectHandle > 0\n ? skybox\n : undefined;\n if (imageEnvironment !== undefined) {\n environmentCandidates.push({\n kind: 'image',\n entityKey: imageEnvironment.entityHandle,\n sourceKey: `equirect:${imageEnvironment.equirectHandle}`,\n });\n }\n const atmosphereQuery = world.query({ read: [Atmosphere] }).unwrap();\n for (const row of atmosphereQuery) {\n const value = row.get(Atmosphere);\n const atmosphere = {\n turbidity: value.turbidity,\n rayleigh: value.rayleigh,\n mieCoefficient: value.mieCoefficient,\n mieDirectionalG: value.mieDirectionalG,\n sunAngularRadius: value.sunAngularRadius,\n } as const;\n environmentCandidates.push({\n kind: 'atmosphere',\n entityKey: row.entity,\n sourceKey: `atmosphere:${row.entity}`,\n atmosphere,\n });\n }\n const directionalDirection = directional?.direction;\n const directionalLength =\n directionalDirection === undefined\n ? 0\n : Math.hypot(\n directionalDirection[0] ?? 0,\n directionalDirection[1] ?? 0,\n directionalDirection[2] ?? 0,\n );\n const sun =\n directional === undefined || directionalLength <= 1e-6\n ? []\n : [\n {\n entityKey: 0,\n direction: [\n -(directionalDirection?.[0] ?? 0) / directionalLength,\n -(directionalDirection?.[1] ?? 0) / directionalLength,\n -(directionalDirection?.[2] ?? 0) / directionalLength,\n ] as [number, number, number],\n color: [\n directional.color[0] ?? 0,\n directional.color[1] ?? 0,\n directional.color[2] ?? 0,\n ] as [number, number, number],\n intensity: directional.intensity,\n },\n ];\n const environmentSelection = selectEnvironment({\n environments: environmentCandidates,\n fogs: fog === undefined ? [] : [fog],\n suns: sun,\n lane: 'direct',\n });\n if (!environmentSelection.ok) {\n routeWorldError(world, environmentSelection.error, {\n systemName: 'RenderSystem.extract (environment-selection)',\n });\n throw environmentSelection.error;\n }\n const environment: EnvironmentFrame = environmentSelection.value;\n\n // feat-20260528-frustum-culling M3 / w10: precompute per-camera frustum\n // planes so entities can be tested against all cameras in the inner loop.\n // Cameras with degenerate projection parameters (e.g. zero fov, zero aspect)\n // are skipped — entities are always-visible for those. Frustum plane cache\n // stored as Float32Array[] parallel to the cameras[] array.\n //\n // feat-20260708-composited-multi-world-rendering M2 / D-4: a composite\n // non-owner world uses the camera-owner snapshots, not its own cameras.\n // This keeps culling correct when the surfaced camera and renderables live\n // in different worlds. The explicit 'none' mode remains the always-visible\n // escape hatch for callers that genuinely need it.\n const frustumPlanes: Float32Array[] = [];\n const cullingCameras = cullMode === 'external' ? (context.cullCameras ?? []) : cameras;\n if (cullMode !== 'none') {\n for (const cam of cullingCameras) {\n // feat-20260613 M6 / w20: orthographic cameras have fov=0 by design;\n // the previous degeneracy guard (`fov <= 0`) was rejecting valid ortho\n // cameras and returning the always-visible escape hatch. Only the\n // perspective path needs the fov check.\n if (cam.projection === 'perspective' && (cam.fov <= 0 || cam.aspect <= 0)) {\n frustumPlanes.push(new Float32Array(0)); // degenerate → always-visible\n continue;\n }\n if (cam.near >= cam.far) {\n frustumPlanes.push(new Float32Array(0));\n continue;\n }\n const proj = mat4.create();\n if (cam.projection === 'orthographic') {\n mat4.orthographic(\n proj,\n cam.orthoLeft,\n cam.orthoRight,\n cam.orthoTop,\n cam.orthoBottom,\n cam.near,\n cam.far,\n );\n } else {\n mat4.perspective(proj, cam.fov, cam.aspect, cam.near, cam.far);\n }\n // feat-20260601 D-3: view = invert(camera world mat4). The camera scale is\n // carried in the world basis columns; the cull frustum uses the same view\n // the record stage derives, so cull stays same-source with render (AC-05).\n const view = mat4.create();\n mat4.invert(view, cam.world);\n const vp = mat4.create();\n mat4.multiply(vp, proj, view);\n const f = frustum.create();\n frustum.fromViewProjection(f, vp);\n frustumPlanes.push(f);\n }\n }\n\n const renderables: RenderableSnapshot[] = [];\n // feat-20260528-frustum-culling M3 / w11: frustum culling counters.\n let frustumCulled = 0;\n let frustumTotal = 0;\n const explicitlyHidden = new Set<EntityHandle>();\n // feat-20260520-2d-sprite-layer-mvp M-3 / w22 (@new-surface): three-\n // bucket dispatch arrays. The legacy `materialDispatch` field stays as\n // a back-compat union (opaque + transparent + overlay back-compat\n // entries) so the pre-w25 RenderSystem.draw consumer loop keeps\n // working until M-3 / w25 lands the bucket-aware record. Plan-strategy\n // §6.1 (back-compat field stays until M-4 acceptance round green).\n // M3 / w26: single dispatch list replaces old three-bucket model\n // (plan-strategy D-3). Entries built per-entity per-pass inside the\n // archetype walk, then sorted by queue at the end.\n let dispatch: DispatchEntry[] = [];\n // Keep the derived material snapshot and its resolved passes local to this\n // extraction. Shared handles are immutable inputs for the frame, while\n // dispatch entries still need to be rebuilt for each entity.\n const materialSnapshotCache: MaterialSnapshotCache = new Map();\n const skinnedMaterialSnapshotCache: MaterialSnapshotCache = new Map();\n // tweak-20260611 M1: MeshRenderer renderable archetype walk routes\n // through one World-owned Query. K-2 sniffing scheme B\n // (`row.get(X) !== undefined` edge sniff) replaces the prior\n // `arch.components.some` row-internal back-door. K-3 invariant: the\n // variable-length array reads (`MeshRenderer.materials`, SpriteInstances\n // arrays) still flow through `_getArrayView`; explicit Instances bytes also come\n // from World, before projection into renderer-owned snapshots.\n //\n // archVersion remains the content fingerprint for SpriteInstances' managed\n // arrays; explicit Instances use the collection revision below and never\n // need an archetype graph access for their matrix bytes.\n // feat-20260521-sprite-atlas-animation M3 / T-16: SpriteRegionOverride\n // column id for the sprite-bucket per-entity region override read\n void SpriteRegionOverride;\n\n const meshRendererQuery =\n context.renderables === 'none'\n ? []\n : world\n .query({\n read: [MeshRenderer],\n optional: [\n Transform,\n GlobalTransform,\n MeshFilter,\n Instances,\n Skin,\n Layer,\n MorphWeights,\n SpriteRegionOverride,\n SpriteInstances,\n Points,\n Lines,\n SortKey,\n ],\n })\n .unwrap();\n // QueryRow deliberately exposes component data, not an archetype version.\n // SpriteInstances still uses a content fingerprint for its managed arrays;\n // explicit Instances use the renderer-owned collection revision below.\n const resolveArchVersion = (entity: EntityHandle): number => {\n const values = [\n worldInternal._getArrayView(entity, SpriteInstances, 'transforms'),\n worldInternal._getArrayView(entity, SpriteInstances, 'regions'),\n ];\n let hash = 2166136261;\n for (const value of values) {\n hash = Math.imul(hash ^ (value?.length ?? 0), 16777619) >>> 0;\n if (value === undefined) continue;\n for (let index = 0; index < value.length; index += 1) {\n hash = Math.imul(hash ^ Math.fround(value[index] ?? 0), 16777619) >>> 0;\n }\n }\n return hash;\n };\n // Pending entries are created with the current renderables.length, which is\n // exactly the slot this entity receives if it survives culling. No other\n // renderable can be pushed between staging and this entity's push, so publish\n // the original fresh entries instead of cloning every submesh descriptor.\n // A culled entity still discards its private pending array unchanged.\n const flushPendingDispatch = (pending: readonly DispatchEntry[]): void => {\n for (const entry of pending) dispatch.push(entry);\n };\n for (const row of meshRendererQuery) {\n if (\n context.renderables === 'full' &&\n renderableEntities !== undefined &&\n !renderableEntities.has(row.entity)\n ) {\n continue;\n }\n // K-2 archetype-edge sniff (scheme B): a missing optional component\n // surfaces as an absent bundle key, not a row-internal optional chain.\n // Presence-only checks use QueryRow.has so large array-bearing components\n // are not materialised merely to answer a boolean question.\n const hasTransform = row.has(Transform);\n const meshFilter = row.get(MeshFilter);\n const hasInstances = row.has(Instances);\n const skin = row.get(Skin);\n const morphWeightsView = worldInternal._getArrayView(row.entity, MorphWeights, 'weights');\n const hasMeshFilter = meshFilter !== undefined;\n const hasSkin = skin !== undefined;\n // feat-20260625-sprite-instances-and-tilemap-terrain-static-batch M3 / w10:\n // SpriteInstances optional component archetype-edge sniff. Three structured\n // EcsError codes fire at the row-loop entry (D-6 fail-fast at extract):\n // - 'sprite-instances-mutually-exclusive-with-instances'\n // (hasInstances && hasSpriteInstances) — Instances + SpriteInstances peers.\n // - 'sprite-instances-requires-sprite-shading-model'\n // (materialSnap.materialShaderId !== 'forgeax::sprite') — non-sprite material.\n // - 'sprite-instances-count-mismatch'\n // (transforms.length / 16 !== regions.length / 4) — stride pair desync.\n const hasSpriteInstances = row.has(SpriteInstances);\n const points = row.get(Points);\n const lines = row.get(Lines);\n const sortKey = row.get(SortKey)?.value;\n const pointsLinesComponent =\n points !== undefined ? 'Points' : lines !== undefined ? 'Lines' : undefined;\n const isRenderable = hasTransform && hasMeshFilter;\n\n // The resolved world transform is read per-entity from the single\n // `GlobalTransform.world` mat4 (propagateTransforms output) inside the row\n // loop below. Normal structural paths materialize this carrier through\n // Transform's generic ECS requirement; keep the defensive row check because\n // an owner can explicitly remove a required component during recovery.\n const fAssetHandle = meshFilter?.assetHandle;\n // feat-20260520-2d-sprite-layer-mvp M-3 / w22: Layer column read here;\n // value folded into each DispatchEntry so the render-system sort can use\n // it as the primary transparent-sort key without a second ECS round-trip.\n const fLayerValue = row.get(Layer)?.value;\n // feat-20260608-tilemap-object-layer-rendering M3 / m3-t5: tilemap-spawned\n // per-cell render entities (the ones `tilemap-chunk-extract-system`\n // pushes via `spawnDerivedRenderEntities`) reach this loop via the same\n // archetype edge that carries a sprite entity -- they all wear\n // `MeshFilter.assetHandle === HANDLE_QUAD` + a `forgeax::sprite`-shaded\n // material asset + the sprite-bucket `values.region` rectangle.\n // For the per-entity Y-sort path (requirements §AC-12 / §AC-13):\n //\n // sortKey = -(Transform.posY - effectivePivotY * |Transform.scaleY|)\n //\n // with `effectivePivotY = effectivePivotYForTilemapFlip(pivotY, pivotX,\n // flipV, flipDiagonal)` from `tilemap-chunk-extract-system` (the SAME\n // helper drives `spawnDerivedRenderEntities`, so the value the sort\n // uses matches the value baked into `Transform.posY` -- charter P4\n // single SSOT for the post-flip pivot). Sprite entities reuse the same\n // formula but skip the flip composition (their pivot stays raw); both\n // bucket types therefore feed one `transparentSortEntries` argsort\n // step + share the `argsortInPlace` radix LSD primitive (plan-strategy\n // §D-1 / §D-3). The detection lives on the material side -- detect a\n // tilemap-spawned entity by `MeshFilter.assetHandle === HANDLE_QUAD`\n // plus the `forgeax::sprite` shader id on `MeshRenderer.material`'s\n // first pass + non-empty `values.region`; no new public ECS\n // marker component lands (charter F1 minimum surface).\n //\n // Layer.value is now folded into each DispatchEntry.layer (fLayerValue\n // column, read once per archetype pass above). render-system.ts\n // `sortTransparentDispatch` applies (layer ASC, sortValue ASC) for all\n // transparent-sort modes (0/1/2) using posY/pivotY/sizeY from the\n // parallel renderables[] snapshot -- no second ECS round-trip needed.\n // feat-20260527-sprite-nineslice M4 / w17 (AC-14): SpriteRegionOverride\n // per-entity UV sub-rectangle. When the entity carries this component the\n // 4-float `[uMin, vMin, uW, vH]` override displaces the asset-side\n // `values.region` for this entity only — downstream 9-slice logic\n // measures slices against this effective region.zw, so a half-width sub-\n // sprite reduces the anchor budget to 0.5 rather than the asset's 1.0.\n //\n // SpriteRegionOverride.region is a fixed stride-4 value. Per-row reads\n // route through `_getArrayView` for the zero-copy row window\n // row-window slice (consistent with the variable-length array column\n // reads -- K-3 carve-out keeps `_getArrayView` as the row-accessor of\n // record for each non-scalar column).\n const hasSpriteRegionOverride = row.has(SpriteRegionOverride);\n // feat-20260523-skin-skeleton-animation M2 / T-21: Skin component\n // column views for coexistence check + joint despawn fail-fast.\n // `skeleton` holds the packed Handle<SkeletonAsset>; `joints` holds\n // the packed Entity u32 array (N x one u32 each).\n const skinSkeletonView = skin?.skeleton;\n\n let archVersion = 0;\n if (hasInstances || hasSpriteInstances) {\n // All rows in this callback share one archetype. Only these two\n // instance-bearing paths consume the version in their cache key.\n archVersion = resolveArchVersion(row.entity);\n }\n\n {\n // feat-20260608 M2 / w11: read materials array via _getArrayView\n const entity = row.entity;\n const authorVisible = !(isRenderable && visibility?.effective(entity) === 'hidden');\n if (!authorVisible) explicitlyHidden.add(entity);\n if (!authorVisible && !retainHidden) {\n continue;\n }\n const layerVal = fLayerValue ?? 0;\n // bug-20260709-builtin-quad-withoutaabb-disables-sprite-frustum-cu M2.5\n // (carries PR #598 feat-20260703 D-7): dispatch entries for this entity\n // are staged locally and flushed into the shared `dispatch[]` array\n // ONLY when the entity survives the frustum-cull `continue` below —\n // same cull-passed branch as the paired `renderables.push`. Prior to\n // this fix the three `dispatch.push` sites ran before the cull check,\n // so a culled entity left dangling entries whose `renderableIndex`\n // aliased the slot a LATER visible entity occupied — surfacing as the\n // pbr-mesh-array-bgl vs hdrp-unified-bgl-group2 BGL/PL mismatch on\n // the deferred-shading smoke (PR #598 CI). Pure ordering fix; cull\n // logic and MeshRenderer contract unchanged.\n const pendingDispatch: DispatchEntry[] = [];\n const materialsView = worldInternal._getArrayView(entity, MeshRenderer, 'materials') as\n | Uint32Array\n | undefined;\n const materialCount = materialsView?.length ?? 0;\n let materialHandles = Array.from(materialsView ?? []);\n let materialBindingSources: MeshMaterialBindingSource[] = materialHandles.map(\n () => 'renderer-override',\n );\n let materialBindingDiagnostics: MeshMaterialBindingDiagnostic[] = [];\n let gpuDrivenSubmeshes: readonly MeshAsset['submeshes'][number][] = [];\n let gpuDrivenIndexed = false;\n let gpuDrivenGeometry: GpuDrivenGeometryReceipt | undefined;\n\n // Resolve instance overrides against mesh-owned slot defaults once.\n const fAssetHandleVal = fAssetHandle;\n if (\n fAssetHandleVal !== undefined &&\n fAssetHandleVal !== 0 &&\n assets !== undefined &&\n assets !== null\n ) {\n const meshHandle = toShared<'MeshAsset'>(fAssetHandleVal);\n const meshRes = resolveAssetHandle<Asset>(world, meshHandle);\n if (meshRes.ok && meshRes.value.kind === 'mesh') {\n const meshAsset = meshRes.value as MeshAsset;\n const guid = (meshRes.value as { guid?: string }).guid ?? '<no-guid>';\n gpuDrivenSubmeshes = meshAsset.submeshes;\n gpuDrivenIndexed = meshAsset.indices !== undefined;\n const layoutProjection = deriveVertexLayoutProjection(meshAsset.attributes);\n gpuDrivenGeometry = {\n identity: `${guid}:${layoutProjection.digest}`,\n vertexInputs: layoutProjection.attributes.map((attribute) => ({\n semantic: attribute.key,\n location: attribute.shaderLocation,\n format: attribute.format,\n })),\n topology: meshAsset.submeshes[0]?.topology ?? 'triangle-list',\n indexed: gpuDrivenIndexed,\n };\n // extractFrames is also a public read path and can run before the\n // Renderer.draw pre-render stage. GlyphText proves the derived mesh\n // owns exactly one Default slot; arbitrary meshes still fail closed\n // and never infer slot topology from their submeshes.\n if (!Array.isArray(meshAsset.materialSlots) && world.get(entity, GlyphText).ok) {\n ensureGlyphMeshMaterialSlots(world, meshHandle);\n }\n const resolvedBindings = resolveMeshMaterialBindings(meshAsset, materialsView ?? [], {\n isValidOverride(handle) {\n const resolved = resolveAssetHandle(world, toShared<'MaterialAsset'>(handle));\n return resolved.ok && resolved.value.kind === 'material';\n },\n resolveMeshDefault(defaultGuid) {\n const guidText = AssetGuid.format(defaultGuid);\n if (assets.lookup<Asset>(guidText)?.kind !== 'material') return undefined;\n return internSharedRefFromGuid(world, assets, guidText, 'MaterialAsset') as\n | number\n | undefined;\n },\n });\n if (!resolvedBindings.ok) {\n if (resolvedBindings.code === 'mesh-material-slots-missing') {\n worldInternal._routeError(\n new AssetError({\n code: 'load-failed',\n expected: 'every MeshAsset producer supplies materialSlots[]',\n hint: `fix the MeshAsset producer; renderer inheritance never guesses slot topology (mesh=${guid}, entity=${entity}, vertices=${meshAsset.vertices.length}, indices=${meshAsset.indices?.length ?? 0})`,\n detail: {\n referencedByGuid: guid,\n referencedByKind: 'mesh',\n subAssetGuid: '<material-slots-missing>',\n sourceField: { fieldName: 'materialSlots' },\n },\n }),\n {\n severity: Severity.Error,\n systemName: 'RenderSystem.extract (mesh-material-slots-missing)',\n },\n );\n continue;\n }\n const materialGuid = AssetGuid.format(resolvedBindings.defaultMaterial);\n worldInternal._routeError(\n new AssetError({\n code: 'load-failed',\n expected: `MeshAsset materialSlots[${resolvedBindings.slotIndex}] default ${materialGuid} is ready and a MaterialAsset`,\n hint: `loadByGuid(meshGuid) must recursively load the declared default material; mesh=${guid}, slot=${resolvedBindings.slotIndex}, material=${materialGuid}`,\n detail: {\n referencedByGuid: guid,\n referencedByKind: 'mesh',\n subAssetGuid: materialGuid,\n sourceField: {\n fieldName: 'materialSlots',\n arrayIndex: resolvedBindings.slotIndex,\n },\n },\n }),\n {\n severity: Severity.Error,\n systemName: 'RenderSystem.extract (mesh-default-not-ready)',\n },\n );\n continue;\n }\n materialHandles = resolvedBindings.bindings.map((binding) => binding.handle);\n materialBindingSources = resolvedBindings.bindings.map((binding) => binding.source);\n materialBindingDiagnostics = resolvedBindings.diagnostics.map((diagnostic) => ({\n ...diagnostic,\n detail:\n diagnostic.code === 'mesh-renderer-material-override-overflow'\n ? {\n expectedCount: meshAsset.materialSlots.length,\n actualCount: materialCount,\n meshAssetGuid: guid,\n }\n : {\n meshAssetGuid: guid,\n slotIndex: diagnostic.slotIndex,\n handle: diagnostic.handle ?? 0,\n },\n }));\n for (const diagnostic of resolvedBindings.diagnostics) {\n worldInternal._routeError(\n new AssetError({\n code: diagnostic.code,\n expected:\n diagnostic.code === 'mesh-renderer-material-override-overflow'\n ? `materials.length <= materialSlots.length (${meshAsset.materialSlots.length})`\n : `materials[${diagnostic.slotIndex}] resolves to a live MaterialAsset`,\n hint: ASSET_ERROR_HINTS[diagnostic.code],\n detail:\n diagnostic.code === 'mesh-renderer-material-override-overflow'\n ? {\n expectedCount: meshAsset.materialSlots.length,\n actualCount: materialCount,\n meshAssetGuid: guid,\n }\n : {\n meshAssetGuid: guid,\n slotIndex: diagnostic.slotIndex,\n handle: diagnostic.handle ?? 0,\n },\n }),\n {\n severity: Severity.Warning,\n systemName: `RenderSystem.extract (${diagnostic.code})`,\n },\n );\n }\n }\n }\n\n if (materialHandles.length === 0) {\n materialHandles = [0];\n materialBindingSources = ['engine-default'];\n }\n\n // Use the first material handle for the entity-level snapshot\n // (shading-model dispatch routing + multi-pass DispatchEntry. Per-\n // submesh materials[i>=1] are resolved by `resolveMaterialSnapshot`\n // below into the `materials[]` array, used by the record stage to\n // upload N material UBO slots and bind the i-th slot before the\n // i-th submesh draw.) -- feat-20260608 M5 amend / w11-a.\n const handleRaw = materialHandles[0] ?? 0;\n\n const cachedMaterial =\n handleRaw !== 0 && !hasSpriteRegionOverride && !hasSkin\n ? materialSnapshotCache.get(handleRaw)\n : undefined;\n\n let materialSnap: MaterialSnapshot;\n\n if (cachedMaterial !== undefined) {\n materialSnap = cachedMaterial.snapshot;\n if (isRenderable) {\n appendMaterialDispatchEntries(\n pendingDispatch,\n cachedMaterial.passes,\n entity,\n handleRaw,\n renderables.length,\n layerVal,\n materialSnap.paramSnapshot,\n 0,\n materialSnap.materialProgramKeys,\n );\n }\n } else if (handleRaw === 0 || assets === undefined || assets === null) {\n // case B: missing-spec sentinel -> mid-grey defaultMaterialSnapshot.\n materialSnap = defaultMaterialSnapshot(handleRaw);\n } else {\n const tagged = toShared<'MaterialAsset'>(handleRaw);\n const stablePersistentCached =\n !hasSpriteRegionOverride && !hasSkin\n ? readStablePersistentMaterialSnapshot(\n persistentMaterialSnapshotCache,\n handleRaw,\n assets,\n )\n : undefined;\n if (stablePersistentCached !== undefined) {\n materialSnapshotCache.set(handleRaw, stablePersistentCached);\n materialSnap = stablePersistentCached.snapshot;\n if (isRenderable) {\n appendMaterialDispatchEntries(\n pendingDispatch,\n stablePersistentCached.passes,\n entity,\n handleRaw,\n renderables.length,\n layerVal,\n materialSnap.paramSnapshot,\n 0,\n materialSnap.materialProgramKeys,\n );\n }\n } else {\n const res = resolveAssetHandle(world, tagged);\n if (!res.ok) {\n if (isRenderable) {\n const rhiErr = new RhiError({\n code: 'asset-not-registered',\n expected: 'MeshRenderer.material in AssetRegistry',\n hint: 'catalog the material via assetRegistry.catalog(guid, asset) + world.allocSharedRef before spawn, or remove the material field to fall back to default',\n detail: { assetHandle: handleRaw },\n });\n worldInternal._routeError(rhiErr, {\n severity: Severity.Error,\n systemName: 'RenderSystem.extract (material asset-not-registered)',\n });\n }\n continue;\n }\n const asset = res.value;\n if (asset.kind !== 'material') {\n materialSnap = defaultMaterialSnapshot(handleRaw);\n } else {\n // feat-20260529 M3 / w11: material parent chain inheritance via\n // read-through _materialWalk accessor (plan-strategy D-6).\n // The old direct asset.passes / asset.values read never\n // walked the parent chain, causing broken-inheritance (root cause).\n const resolvedResult = walkMaterialPassesOverSharedRefs(world, tagged, assets);\n if (!resolvedResult.ok) {\n // AC-09 / S-7 / q8=A: passes-empty or cycle must fire structured\n // error through _routeError (same routing as asset-not-registered\n // branch above). Silent continue is forbidden because it produces\n // a black screen indistinguishable from a content bug.\n const err = resolvedResult.error;\n switch (err.code) {\n case 'material-parent-not-found':\n case 'material-no-effective-pass':\n case 'material-value-unknown':\n case 'material-value-type-mismatch':\n case 'material-contract-program-mismatch':\n worldInternal._routeError(err, {\n severity: Severity.Error,\n systemName: `RenderSystem.extract (${err.code})`,\n });\n break;\n case 'material-circular-inheritance':\n worldInternal._routeError(err, {\n severity: Severity.Error,\n systemName: 'RenderSystem.extract (material-circular-inheritance)',\n });\n break;\n default:\n // Exhaustive guard: unhandled error codes from _materialWalk\n // surface an internal assertion to avoid silent continuation.\n worldInternal._routeError(err, {\n severity: Severity.Error,\n systemName: `RenderSystem.extract (_materialWalk: ${err.code})`,\n });\n }\n continue;\n }\n const resolved = resolvedResult.value;\n const allPasses = resolved.passes;\n const materialContext =\n context.materialContext === undefined\n ? undefined\n : {\n ...context.materialContext,\n geometry: hasSkin ? ('skinned' as const) : context.materialContext.geometry,\n };\n const materialProgramKeys = materialProgramKeysForMaterial(\n asset,\n assets,\n materialContext,\n );\n const authoredFirstPassShader = runtimeMaterialShaderIdForMaterial(\n allPasses,\n undefined,\n );\n const firstPassShader = runtimeMaterialShaderIdForMaterial(\n allPasses,\n materialProgramKeys,\n );\n const pv = materialValuesToLinearRuntime(\n resolved.values,\n materialColorParameterSchema(resolved.parameters ?? [], firstPassShader, assets),\n resolved.colorSpace,\n ) as Readonly<Record<string, unknown>>;\n\n const baseColorPv = pv.baseColor as readonly number[] | undefined;\n const baseColor = vec3.create(\n baseColorPv?.[0] ?? 1,\n baseColorPv?.[1] ?? 1,\n baseColorPv?.[2] ?? 1,\n );\n const metallicPv = typeof pv.metallic === 'number' ? pv.metallic : 0;\n const roughnessPv = typeof pv.roughness === 'number' ? pv.roughness : 0.5;\n const specularColorPv = pv.specularColor as readonly number[] | undefined;\n const normalScalePv = materialNormalScale(pv);\n\n const paramSnap: Record<string, number | number[] | string> = {};\n for (const [k, v] of Object.entries(pv)) {\n if (typeof v === 'number') paramSnap[k] = v;\n else if (typeof v === 'string') paramSnap[k] = v;\n else if (Array.isArray(v) && v.every((x) => typeof x === 'number')) {\n paramSnap[k] = v as number[];\n }\n }\n\n const materialParamSchema = materialParamSchemaForMaterial(\n resolved.parameters ?? [],\n authoredFirstPassShader,\n allPasses,\n );\n // feat-20260611-fox-skinning-vertex-attribute-chain M4 / w17 (D-5):\n // bidirectional Skin <-> pbr-skin material fail-fast at extract.\n // Skin component without a forgeax::pbr-skin first-pass material\n // would draw with a non-skin shader against the 18-float vertex\n // buffer (joints/weights bytes interpreted as garbage). Conversely\n // a forgeax::pbr-skin material against a 12-float (unskinned) mesh\n // would have @location(4)/@location(5) read uninitialized memory.\n // Both cases route through `_routeError` + `continue` so a single\n // misconfigured entity does NOT abort the whole frame's draw list\n // (charter P3 explicit failure + plan-decisions D-5 over `return err`).\n {\n const hasSkinSkel =\n hasSkin &&\n skinSkeletonView !== undefined &&\n skinSkeletonView !== undefined &&\n skinSkeletonView !== 0;\n const isPbrSkinMaterial = isStandardPbrSkinMaterialShader(firstPassShader);\n if (hasSkinSkel && !isPbrSkinMaterial) {\n worldInternal._routeError(new SkinMaterialMismatchError(entity, firstPassShader), {\n severity: Severity.Error,\n systemName: 'RenderSystem.extract (skin-material-mismatch)',\n });\n continue;\n }\n if (isPbrSkinMaterial && fAssetHandleVal !== undefined && fAssetHandleVal !== 0) {\n const meshHandleForSkinCheck = toShared<'MeshAsset'>(fAssetHandleVal);\n const meshResForSkinCheck = resolveAssetHandle<MeshAsset>(\n world,\n meshHandleForSkinCheck,\n );\n if (meshResForSkinCheck.ok) {\n const meshAttrs = meshResForSkinCheck.value.attributes;\n const hasSkinIdx = meshAttrs.skinIndex !== undefined;\n const hasSkinWt = meshAttrs.skinWeight !== undefined;\n if (!hasSkinIdx || !hasSkinWt) {\n const missing: 'skinIndex' | 'skinWeight' | 'both' =\n !hasSkinIdx && !hasSkinWt ? 'both' : !hasSkinIdx ? 'skinIndex' : 'skinWeight';\n worldInternal._routeError(new MaterialSkinAttrMissingError(entity, missing), {\n severity: Severity.Error,\n systemName: 'RenderSystem.extract (material-skin-attr-missing)',\n });\n continue;\n }\n }\n }\n }\n // feat-20260625-refactor-sprite-as-transparent-mesh M3 / w12 (D-3):\n // sprite materials now flow through the same generic paramSchema-\n // driven extract path PBR / unlit use. The narrow `forgeax::sprite`\n // exception block below covers exactly 2 plan-authorised cases:\n // 1. SpriteRegionOverride per-entity region displacement (Q4=a)\n // 2. flipX / flipY -> region fold (plan-strategy D-8)\n // No legacy values field-name shim; demos and SpriteParamValues\n // are UBO-aligned (no `texture` / `baseColor` / `pivot` / `slices`\n // / `sliceMode` keys reaching this code path). AGENTS.md §Change\n // stance: \"no shim layer, no v1/v2 dual-path\".\n //\n // feat-20260624 M1' / t6: `'forgeax::sprite-lit'` walks the same\n // sprite-family vertex path (VsOut byte-identical, paramSchema\n // mirror) so the SAME 2 folds apply — extending `isSprite` to\n // cover both shader ids keeps the narrowing-point count at 1\n // (plan-strategy §1.6 + D-1: mirror sprite, no new branch).\n const isSprite =\n firstPassShader === 'forgeax::sprite' || firstPassShader === 'forgeax::sprite-lit';\n\n // feat-20260613-material-paramschema-driven-binding M4 / w23\n // (D-5 graceful): paramSchema-driven texture-field validation.\n // For each handle-shaped paramValue (typeof === 'number'),\n // verify it actually points at a registered texture asset\n // when the field is declared as a texture in the shader's\n // paramSchema; mis-typed handles (e.g. a scalar f32 stored as\n // int 0 the M4 / w22 graceful fallback resolved to a wrong\n // sub-asset) are dropped here so the record stage falls back\n // to MISSING_TEXTURE_HANDLE (default white) without raising.\n const validateTextureHandle = (\n fieldName: string,\n raw: unknown,\n ): Handle<'TextureAsset', 'shared'> | undefined => {\n // feat-20260614 M8 (D-19): a string value is an embedded texture\n // GUID; resolve it to a column handle via catalog + allocSharedRef\n // before validation. A number is an already-minted column handle.\n let handle: Handle<'TextureAsset', 'shared'>;\n const textureRef = materialTextureRef(raw);\n const textureGuid = assetReferenceText(textureRef);\n if (textureGuid !== undefined) {\n if (assets === null || assets === undefined) return undefined;\n // M4: intern so the GUID mints one stable handle per World\n // instead of a fresh slot every frame (GPU residency relies on\n // a stable handleSlot). onLastRelease -> gpuStore.evictTexture.\n const interned = internSharedRefFromGuid(\n world,\n assets,\n textureGuid,\n 'TextureAsset',\n );\n if (interned === undefined) return undefined;\n handle = interned;\n } else if (typeof textureRef === 'number') {\n handle = toShared<'TextureAsset'>(textureRef);\n } else {\n return undefined;\n }\n if (assets === null || assets === undefined) return handle;\n const declaredFields = materialTextureFields(\n firstPassShader,\n materialParamSchema.length > 0\n ? derive(materialParamSchema).textureFieldNames\n : firstPassShader !== undefined\n ? assets.materialShaderTextureFieldNames(firstPassShader)\n : undefined,\n );\n // Shader not registered (R-4 cross-worktree path) -> trust the\n // raw handle and let the record stage / GPU layer surface each\n // mismatch via MISSING_TEXTURE_HANDLE.\n if (declaredFields === undefined) return handle;\n // Field is not declared as a texture by the shader -> the\n // loader's \"try every int\" fallback misclassified a scalar;\n // drop the slot so the record stage uses the default white.\n if (\n !declaredFields.has(fieldName) &&\n !isEngineInjectedTextureField(firstPassShader, fieldName)\n ) {\n return undefined;\n }\n // Field declared as texture: verify the handle's asset kind.\n const assetRes = resolveAssetHandle(world, handle);\n if (!assetRes.ok) return undefined;\n const kind = (assetRes.value as { kind?: string }).kind;\n if (kind !== 'texture') return undefined;\n return handle;\n };\n // feat-20260614 M8 (D-19): resolve a sampler / texture paramValue\n // that may be an embedded GUID string (catalog + allocSharedRef) or\n // an already-minted column handle (number passthrough).\n const resolveParamHandle = <B extends string>(\n raw: unknown,\n brand: B,\n ): Handle<B, 'shared'> | undefined => {\n const value = materialTextureRef(raw);\n if (typeof value === 'number') return toShared<B>(value);\n const guid = assetReferenceText(value);\n if (guid !== undefined) {\n if (assets === null || assets === undefined) return undefined;\n // M4: intern the GUID -> column-handle resolution (one stable\n // handle per (world, guid, brand), reused across frames).\n return internSharedRefFromGuid(world, assets, guid, brand);\n }\n return undefined;\n };\n // feat-20260621-learn-render-5-5-parallax M2 / w7 (D-3): iterate the\n // shader's derive(paramSchema).textureFieldNames SSOT so the Nth\n // user-region texture (e.g. parallax heightTexture) is validated +\n // carried, replacing the hardcoded 3-field list. validateTextureHandle\n // already drops fields a shader doesn't declare as a texture.\n const userRegionFields =\n materialTextureFields(\n firstPassShader,\n materialParamSchema.length > 0\n ? derive(materialParamSchema).textureFieldNames\n : firstPassShader !== undefined && assets !== null && assets !== undefined\n ? assets.materialShaderTextureFieldNames(firstPassShader)\n : undefined,\n ) ?? BUILTIN_USER_REGION_TEXTURE_FIELDS;\n const textureHandles = new Map<string, Handle<'TextureAsset', 'shared'>>();\n const videoTextureFields = new Map<string, Handle<'VideoAsset', 'shared'>>();\n for (const field of userRegionFields) {\n // D-5: a video-kind paramValue routes to the transient path\n // (videoTextureFields), NOT validateTextureHandle (which drops\n // kind!=='texture', the R-7 silent-fail path). Static fields fall\n // through to validateTextureHandle unchanged.\n const videoHandle =\n assets !== null && assets !== undefined\n ? resolveVideoFieldHandle(pv[field], world, assets)\n : undefined;\n if (videoHandle !== undefined) {\n videoTextureFields.set(field, videoHandle);\n continue;\n }\n const handle = validateTextureHandle(field, pv[field]);\n if (handle !== undefined) textureHandles.set(field, handle);\n }\n const baseColorTextureHandle = textureHandles.get('baseColorTexture');\n const metallicRoughnessTextureHandle = textureHandles.get('metallicRoughnessTexture');\n const normalTextureHandle = textureHandles.get('normalTexture');\n const samplerHandles = collectMaterialTextureSamplers(pv, (value) =>\n resolveParamHandle(materialTextureRef(value), 'SamplerAsset'),\n );\n const emissiveTextureHandle = validateTextureHandle(\n 'emissiveTexture',\n pv.emissiveTexture,\n );\n const occlusionTextureHandle = validateTextureHandle(\n 'occlusionTexture',\n pv.occlusionTexture,\n );\n const textureCoordinates = collectMaterialTextureCoordinates(pv);\n const textureSources = collectMaterialTextureSources(pv, world);\n const emissivePv = pv.emissive as readonly number[] | undefined;\n // feat-20260625 M2 / w6: first-pass transparency flag folds into\n // MaterialSnapshot.transparent so the record stage can drive the\n // LDR split + premultiplied-alpha blend decision without\n // re-reading passes[]. feat-20260626-collapse M2: derive from\n // `passes[0].renderState.blend !== undefined` (blend presence is\n // the SSOT after MaterialPass.transparent was dropped).\n // Result is plain boolean (always defined here) — written as-is\n // into the snapshot (`boolean | undefined` field, see L759).\n const firstPassTransparent: boolean = allPasses[0]?.renderState?.blend !== undefined;\n\n // feat-20260625-refactor-sprite-as-transparent-mesh M3 / w12 (D-8):\n // narrow `forgeax::sprite` extract block --- folds the legacy user\n // values format (flipX / flipY / slices / sliceMode + free\n // region / pivot) into the UBO-aligned paramSnapshot vec4 fields\n // (region / pivotAndSize / slicesAndMode + colorTint). Also folds\n // per-entity SpriteRegionOverride (Q4=a). After this block the\n // generic else branch picks up the snapshot via the same writer\n // path PBR / unlit use; no more shadingModel='sprite' arm, no\n // spriteFields POD (AC-02 / AC-07: extract has exactly 2 hard\n // `forgeax::sprite` checks --- this fold + the slices mesh swap on\n // the record side).\n if (isSprite) {\n // SpriteRegionOverride: per-entity per-frame region displacement.\n let overrideRegion: readonly [number, number, number, number] | undefined;\n if (hasSpriteRegionOverride) {\n const overrideView = worldInternal._getArrayView(\n entity,\n SpriteRegionOverride,\n 'region',\n ) as Float32Array | undefined;\n if (overrideView !== undefined && overrideView.length >= 4) {\n overrideRegion = [\n overrideView[0] ?? 0,\n overrideView[1] ?? 0,\n overrideView[2] ?? 1,\n overrideView[3] ?? 1,\n ];\n }\n }\n // Region resolution priority: SpriteRegionOverride > paramSnapshot.\n // region (UBO-aligned user input) > [0,0,1,1] identity.\n const regionPv = paramSnap.region as readonly number[] | undefined;\n let regionX = overrideRegion?.[0] ?? regionPv?.[0] ?? 0;\n let regionY = overrideRegion?.[1] ?? regionPv?.[1] ?? 0;\n let regionZ = overrideRegion?.[2] ?? regionPv?.[2] ?? 1;\n let regionW = overrideRegion?.[3] ?? regionPv?.[3] ?? 1;\n // flipX / flipY fold into region (D-8): the shader does\n // `uv * region.zw + region.xy`, so flipping along U is a sign\n // negation of region.z plus an origin offset.\n const flipXPv = typeof pv.flipX === 'number' ? pv.flipX : 0;\n const flipYPv = typeof pv.flipY === 'number' ? pv.flipY : 0;\n if (flipXPv !== 0) {\n regionX += regionZ;\n regionZ = -regionZ;\n }\n if (flipYPv !== 0) {\n regionY += regionW;\n regionW = -regionW;\n }\n paramSnap.region = [regionX, regionY, regionZ, regionW];\n // Guard: slicesAndMode must be present and zero for non-9-slice\n // sprites so the record-stage UBO writer (applyParamSnapshotToUbo)\n // writes [0,0,0,0] at offset 48 instead of leaving the\n // buildPbrMaterialUboPayload PBR baseline (e.g. occlusionStrength=1\n // at that slot). A non-zero slicesAndMode trips `useSlices=true`\n // in sprite.wgsl, which degenerates HANDLE_QUAD geometry → invisible.\n if (!('slicesAndMode' in paramSnap)) {\n (paramSnap as Record<string, unknown>).slicesAndMode = [0, 0, 0, 0];\n }\n }\n\n // Generic materialShaderId snapshot --- sprite included now flows\n // through this single branch (plan-strategy D-3 / AC-01 / AC-02 /\n // AC-07). The sprite block above only writes paramSnap.region (D-8\n // SpriteRegionOverride + flip fold); the rest of the UBO is filled\n // by the same paramSchema-driven path PBR / unlit use.\n materialSnap = {\n baseColor,\n metallic: metallicPv,\n roughness: roughnessPv,\n ...(specularColorPv !== undefined && {\n specularColor: [\n specularColorPv[0] ?? 1,\n specularColorPv[1] ?? 1,\n specularColorPv[2] ?? 1,\n ] as readonly [number, number, number],\n }),\n normalScale: normalScalePv,\n materialShaderId: firstPassShader,\n materialProgramKeys,\n materialHandle: handleRaw,\n renderState: pipelineRenderState(allPasses[0]?.renderState),\n paramSnapshot: paramSnap,\n ...(materialParamSchema.length > 0 && { materialParamSchema }),\n ...(textureCoordinates.size > 0 && { textureCoordinates }),\n ...(samplerHandles.size > 0 && { samplerHandles }),\n ...(textureHandles.size > 0 && { textureHandles }),\n ...(textureSources.size > 0 && { textureSources }),\n ...(videoTextureFields.size > 0 && { videoTextureFields }),\n ...(baseColorTextureHandle !== undefined && {\n baseColorTexture: baseColorTextureHandle,\n }),\n ...(metallicRoughnessTextureHandle !== undefined && {\n metallicRoughnessTexture: metallicRoughnessTextureHandle,\n }),\n ...(normalTextureHandle !== undefined && { normalTexture: normalTextureHandle }),\n ...(emissivePv !== undefined && {\n emissive: [emissivePv[0] ?? 0, emissivePv[1] ?? 0, emissivePv[2] ?? 0] as readonly [\n number,\n number,\n number,\n ],\n }),\n ...(typeof pv.emissiveIntensity === 'number' && {\n emissiveIntensity: pv.emissiveIntensity,\n }),\n ...(emissiveTextureHandle !== undefined && {\n emissiveTexture: emissiveTextureHandle,\n }),\n ...(occlusionTextureHandle !== undefined && {\n occlusionTexture: occlusionTextureHandle,\n }),\n ...(typeof pv.occlusionStrength === 'number' && {\n occlusionStrength: pv.occlusionStrength,\n }),\n transparent: firstPassTransparent,\n };\n\n if (!hasSpriteRegionOverride && !hasSkin) {\n const stored = storeMaterialSnapshot(\n materialSnapshotCache,\n handleRaw,\n materialSnap,\n allPasses,\n asset,\n assets,\n );\n if (stored.crossFrameSafe) persistentMaterialSnapshotCache?.set(handleRaw, stored);\n }\n\n // Build dispatch entries from resolved passes.\n if (isRenderable) {\n appendMaterialDispatchEntries(\n pendingDispatch,\n allPasses,\n entity,\n handleRaw,\n renderables.length,\n layerVal,\n paramSnap,\n 0,\n materialProgramKeys,\n );\n }\n }\n }\n }\n\n // feat-20260609 M2/M5 corrective fixup: default-material entities\n // (handleRaw===0 / case-B MeshRenderer{data:{}}) must produce\n // ShadowCaster dispatch entries so the shadow pass includes them.\n // The pre-existing logic only builds dispatch entries from\n // resolved material assets; defaultMaterialSnapshot() (mid-grey unlit)\n // left dispatch empty, causing shadow-m2/m3 test failures.\n // Requirements §10.5: shadow-casting is default behaviour, opt-out\n // via castShadow:false. The default material has no opt-out, so\n // it casts shadows.\n //\n // CHARTER NOTE (feat-20260609 T-005-a): the URP literals\n // `LightMode: 'ShadowCaster'` / `LightMode: 'Forward'` below are a\n // local URP-bridge — they mirror what `Materials.unlit({ castShadow:\n // true })` produces at the asset layer. The default-material\n // handle=0 path bypasses asset registration, so we synthesize the\n // same dispatch shape inline. Follow-up cleanup (F-1 from\n // implement-review R1): thread default materials through the\n // Materials factory so this block can call into the shared\n // passes[] producer.\n // tweak-20260701 M1: `materialSnap.shadingModel === 'unlit'` removed —\n // for handleRaw===0, defaultMaterialSnapshot() was always unlit\n // (the shadingModel check was a tautology); the isRenderable &&\n // handleRaw===0 guard alone preserves the exact same dispatch shape.\n if (isRenderable && handleRaw === 0) {\n const shadowCasterTags: Record<string, string> = { LightMode: 'ShadowCaster' };\n const nextRenderableIndex = renderables.length;\n // M2.5: stage into pendingDispatch; flushed at the renderable push\n // site below only when the entity survives cull.\n pendingDispatch.push({\n entityIndex: entity,\n materialHandle: 0,\n renderableIndex: nextRenderableIndex,\n passIndex: 0,\n queue: 2000,\n layer: layerVal,\n tags: shadowCasterTags,\n renderState: undefined,\n defines: undefined,\n vertexEntry: 'vs_main',\n fragmentEntry: undefined,\n materialShaderId: 'forgeax::default-shadow-caster',\n paramSnapshot: {},\n });\n // Also add a Forward pass entry so the entity renders in the\n // main scene pass (mirrors Materials.unlit default).\n appendMaterialDispatchEntries(\n pendingDispatch,\n [DEFAULT_FORWARD_PASS],\n entity,\n 0,\n nextRenderableIndex,\n layerVal,\n {},\n 1,\n );\n }\n\n if (isRenderable) {\n // feat-20260612 M2 / m2-6: Skin + Instances coexistence + per-joint\n // dangling fail-fast + real palette slice allocation. Replaces the\n // T-21 placeholder ({0,0} discriminator-only sentinel) with full\n // resolve / validate / write chain (D-9 reset already fired at\n // extractFrame entry; per-entity allocate + writeJointPalette here).\n let skinSlice: SkinPaletteSlice | undefined;\n if (hasSkin) {\n const skeletonHandleRaw = skinSkeletonView;\n if (\n skeletonHandleRaw !== undefined &&\n skeletonHandleRaw !== 0 &&\n assets !== undefined &&\n assets !== null\n ) {\n // Skin + Instances coexistence is forbidden (D-10).\n if (hasInstances) {\n worldInternal._routeError(new SkinInstancesCoexistForbiddenError(entity), {\n severity: Severity.Error,\n systemName: 'RenderSystem.extract (skin-instances-coexist)',\n });\n\n continue;\n }\n // (a) Resolve skeleton asset; on failure -> skeleton-resolve-failed.\n const skeletonHandle = toShared<'SkeletonAsset'>(skeletonHandleRaw);\n const skeletonRes = resolveAssetHandle<SkeletonAsset>(world, skeletonHandle);\n if (!skeletonRes.ok || skeletonRes.value.kind !== 'skeleton') {\n worldInternal._routeError(new SkeletonResolveFailedError(entity, skeletonHandleRaw), {\n severity: Severity.Error,\n systemName: 'RenderSystem.extract (skeleton-resolve-failed)',\n });\n continue;\n }\n const skeleton = skeletonRes.value;\n // (b) Reuse the Skin row already read for its skeleton handle;\n // the old path repeated a second whole-row world.get here.\n const skinJoints = skin?.joints;\n if (skinJoints === undefined) continue;\n const jointsLength = skinJoints.length;\n if (jointsLength !== skeleton.jointCount) {\n worldInternal._routeError(\n new JointCountMismatchError(entity, skeleton.jointCount, jointsLength),\n {\n severity: Severity.Error,\n systemName: 'RenderSystem.extract (joint-count-mismatch)',\n },\n );\n continue;\n }\n // (c) Resolve only each joint's GlobalTransform.world column. The\n // transient view is consumed before a structural mutation and\n // therefore preserves the same dangling-joint behavior without\n // constructing every other Transform field.\n // Build mat4 list eagerly so write happens once per entity (no\n // half-written slice on dangling).\n const jointWorlds = new Array<Mat4>(skeleton.jointCount);\n let jointDangling = -1;\n for (let jIdx = 0; jIdx < skeleton.jointCount; jIdx++) {\n const jointEntityRaw = skinJoints[jIdx] ?? 0;\n const jointEntity = jointEntityRaw as EntityHandle;\n const jointWorld = worldInternal._getArrayView(jointEntity, GlobalTransform, 'world');\n if (jointWorld === undefined) {\n jointDangling = jIdx;\n break;\n }\n // The allocator consumes the canonical Mat4 brand. Copy the\n // column view into that owner-created value so the ECS storage\n // view never crosses the math brand boundary by assertion.\n const jointWorldMat = mat4.create();\n jointWorldMat.set(jointWorld);\n jointWorlds[jIdx] = jointWorldMat;\n }\n if (jointDangling >= 0) {\n worldInternal._routeError(new JointEntityDanglingError(entity, jointDangling), {\n severity: Severity.Error,\n systemName: 'RenderSystem.extract (joint-entity-dangling)',\n });\n continue;\n }\n // (d) Slice the IBM flat Float32Array into per-joint Float32Arrays.\n // skeleton.inverseBindMatrices length === jointCount * 16.\n const ibmFlat = skeleton.inverseBindMatrices;\n const ibms: Float32Array[] = new Array<Float32Array>(skeleton.jointCount);\n for (let jIdx = 0; jIdx < skeleton.jointCount; jIdx++) {\n ibms[jIdx] = ibmFlat.subarray(jIdx * 16, jIdx * 16 + 16);\n }\n // (e) Allocate slice + write palette via the allocator (D-9 reset\n // already fired at extractFrame entry). When the pipelineState\n // surface is absent (test fixtures that pass undefined) the\n // hasSkin segment is skipped silently — bind-pose equivalent.\n if (skinPaletteAllocator !== null) {\n // Keep the narrow extraction seam compatible with older test or\n // host-owned allocator doubles while the real renderer uses the\n // stable-key path. The fallback is frame-local and therefore\n // cannot affect production allocators that implement the new\n // method.\n const slice =\n typeof skinPaletteAllocator.allocateSliceFor === 'function'\n ? skinPaletteAllocator.allocateSliceFor(\n `${world.identity}:${entity}`,\n skeleton.jointCount,\n )\n : skinPaletteAllocator.allocateSlice(skeleton.jointCount);\n skinPaletteAllocator.writeJointPalette(slice, ibms, jointWorlds);\n skinSlice = {\n jointCount: slice.jointCount,\n byteOffset: slice.byteOffset,\n buffer: slice.buffer,\n };\n }\n }\n }\n\n // A pbr-skin PSO requires the complete three-binding group(2) skin\n // projection. Do not publish a renderable or its staged dispatch when\n // palette extraction was unavailable; the record stage must never\n // reinterpret a skinned vertex stream through an ordinary mesh group.\n if (materialSnap.materialShaderId === 'forgeax::pbr-skin' && skinSlice === undefined) {\n pendingDispatch.length = 0;\n continue;\n }\n\n // feat-20260601 D-3: read the resolved world mat4 (propagateTransforms\n // output) straight from the GlobalTransform.world column array view. The\n // record stage copies these 16 floats into the mesh SSBO with zero\n // per-snapshot `mat4.compose` (AC-07). A stale slot (generation gone)\n // skips the renderable, mirroring the Instances dangling-row sweep.\n // tweak-20260611 M1 / K-3: `_getArrayView` call survives untouched;\n // only the `entity` source switched to `bundle.Entity.self[i]`.\n const worldView = worldInternal._getArrayView(entity, GlobalTransform, 'world');\n if (worldView === undefined) continue;\n const worldMat = new Float32Array(worldView);\n const transformSnap: TransformSnapshot = { world: worldMat };\n // feat-20260608 M5 amend / w11-a: per-submesh `materials[]` array\n // aligned 1-1 with `MeshAsset.submeshes[]`. materials[0] === the\n // representative entity-level snapshot already built; materials[i>=1]\n // are resolved via `resolveMaterialSnapshot` (a non-sprite, single-\n // pass-equivalent resolver — sprite per-submesh is OOS-1). When the\n // entity has no materialsView (case-B sentinel) the array is a single\n // mid-grey default mirroring the legacy single-material path so the\n // record stage's per-submesh UBO upload loop trivially writes one\n // slot, no special branch.\n const materialsArr: MaterialSnapshot[] = [materialSnap];\n if (assets !== undefined && assets !== null) {\n for (let mi = 1; mi < materialHandles.length; mi++) {\n const subHandle = materialHandles[mi] ?? 0;\n const subCache = hasSkin ? skinnedMaterialSnapshotCache : materialSnapshotCache;\n const cachedSubmaterial = subCache.get(subHandle);\n materialsArr.push(\n cachedSubmaterial?.snapshot ??\n resolveMaterialSnapshot(\n subHandle,\n world,\n assets,\n subCache,\n hasSkin ? undefined : persistentMaterialSnapshotCache,\n context.materialContext === undefined\n ? undefined\n : {\n ...context.materialContext,\n geometry: hasSkin ? 'skinned' : context.materialContext.geometry,\n },\n ),\n );\n }\n }\n if (isRenderable && assets !== undefined && assets !== null) {\n for (let mi = 1; mi < materialHandles.length; mi++) {\n const subHandle = materialHandles[mi] ?? 0;\n if (subHandle === handleRaw) continue;\n const subEntry =\n (hasSkin ? skinnedMaterialSnapshotCache : materialSnapshotCache).get(subHandle) ??\n (hasSkin\n ? undefined\n : readPersistentMaterialSnapshot(\n persistentMaterialSnapshotCache,\n subHandle,\n assets,\n ));\n appendMaterialDispatchEntries(\n pendingDispatch,\n subEntry?.passes ?? (subHandle === 0 ? [DEFAULT_FORWARD_PASS] : []),\n entity,\n subHandle,\n renderables.length,\n layerVal,\n materialsArr[mi]?.paramSnapshot,\n 0,\n materialsArr[mi]?.materialProgramKeys,\n );\n }\n }\n\n // feat-20260625-sprite-instances-and-tilemap-terrain-static-batch M3 /\n // w10: SpriteInstances validation + snapshot materialisation.\n // Three structured EcsError fires at this single point (plan-strategy\n // D-6 \"fail-fast at the render domain entry, not at ECS spawn-time\"):\n let spriteInstancesSnap: SpriteInstancesSnapshot | undefined;\n if (hasSpriteInstances) {\n // (1) mutually exclusive with Instances (peers — pick one).\n if (hasInstances) {\n worldInternal._routeError(\n new SpriteInstancesMutuallyExclusiveWithInstancesError(entity),\n {\n severity: Severity.Error,\n systemName: 'RenderSystem.extract (sprite-instances-mutually-exclusive)',\n },\n );\n continue;\n }\n // (2) requires sprite shader — the per-instance UV region is\n // consumed by the sprite vertex shader path only (plan-strategy D-4\n // axis on sprite.wgsl). Post-collapse (PR #520): sprite is no longer\n // a `shadingModel` enum member; identification is via the first-pass\n // `materialShaderId === 'forgeax::sprite'` (OOS-1 path retained).\n //\n // feat-20260624 M1' / t6: `'forgeax::sprite-lit'` also walks the same\n // per-instance UV region vertex path (VsOut byte-identical, paramSchema\n // mirror); accept either shader id.\n if (\n materialSnap.materialShaderId !== 'forgeax::sprite' &&\n materialSnap.materialShaderId !== 'forgeax::sprite-lit'\n ) {\n worldInternal._routeError(\n new SpriteInstancesRequiresSpriteShaderError(\n entity,\n materialSnap.materialShaderId ?? 'undefined',\n ),\n {\n severity: Severity.Error,\n systemName: 'RenderSystem.extract (sprite-instances-requires-sprite-shader)',\n },\n );\n continue;\n }\n // (3) count mismatch — transforms.length / 16 === regions.length / 4\n // (transforms.length=0 + regions.length=0 is the zero-instance lawful\n // boundary; both derivations are 0 and equality holds, so no fire).\n const transforms = worldInternal._getArrayView(entity, SpriteInstances, 'transforms');\n const regions = worldInternal._getArrayView(entity, SpriteInstances, 'regions');\n if (transforms !== undefined && regions !== undefined) {\n const transformsLength = transforms.length;\n const regionsLength = regions.length;\n // Stride sanity: transforms must be mod 16, regions must be mod 4.\n // A stride violation expresses as a count mismatch under the\n // canonical derivation transforms/16 vs regions/4 — fire the\n // count-mismatch code (the same code carries detail.expectedStride).\n const tCount = transformsLength / 16;\n const rCount = regionsLength / 4;\n if (transformsLength % 16 !== 0 || regionsLength % 4 !== 0 || tCount !== rCount) {\n worldInternal._routeError(\n new SpriteInstancesCountMismatchError(transformsLength, regionsLength),\n {\n severity: Severity.Error,\n systemName: 'RenderSystem.extract (sprite-instances-count-mismatch)',\n },\n );\n continue;\n }\n // Validation passes — build the snapshot. transforms.length === 0\n // is lawful (zero-instance) and produces instanceCount=0; the\n // record stage skips drawIndexed when instanceCount===0.\n const transformsCopy = new Float32Array(transforms);\n const regionsCopy = new Float32Array(regions);\n spriteInstancesSnap = {\n transforms: transformsCopy,\n regions: regionsCopy,\n instanceCount: tCount,\n cacheKey: entity,\n archVersion,\n };\n }\n }\n\n let localAabb: Float32Array | undefined;\n let lods: readonly MeshLodLevel[] | undefined;\n let lodHysteresis: number | undefined;\n let morph: MorphSnapshot | undefined;\n const assetHandleRaw = Math.round(fAssetHandle ?? 0);\n if (assetHandleRaw !== 0) {\n const meshRes = resolveAssetHandle(world, toShared<'MeshAsset'>(assetHandleRaw));\n if (meshRes.ok && meshRes.value.kind === 'mesh') {\n const meshAsset = meshRes.value as MeshAsset;\n lods = meshAsset.lods;\n lodHysteresis = meshAsset.lodHysteresis;\n morph = morphSnapshotFor(meshAsset, morphWeightsView);\n const meshAabb = meshAsset.aabb;\n // Morph targets can expand the authored bounds. Keep the\n // specialized lane conservative until a target-aware bounds\n // projection is available; a false-positive draw is preferable\n // to culling a valid deformed vertex.\n if (morph === undefined && hasFiniteOrderedLocalAabb(meshAabb)) {\n localAabb = new Float32Array(meshAabb);\n }\n }\n }\n\n const pointsLinesStyle: PointsLinesStyle | undefined =\n points !== undefined\n ? (() => {\n const shape = pointShapeFromU32(points.shape);\n return shape === undefined\n ? undefined\n : { kind: 'points' as const, sizePx: points.sizePx, shape };\n })()\n : lines === undefined\n ? undefined\n : { kind: 'lines' as const, widthPx: lines.widthPx };\n const cullingLocalAabb = expandPointsLinesBounds(localAabb ?? [], pointsLinesStyle);\n const pointsLines =\n pointsLinesComponent === undefined\n ? undefined\n : ({\n worldId: 0,\n entityKey: entity,\n component: pointsLinesComponent,\n meshHandle: assetHandleRaw,\n meshGeneration: assets?.catalogEpoch ?? 0,\n materialHandle: handleRaw,\n materialGeneration: assets?.catalogEpoch ?? 0,\n style: pointsLinesStyle,\n layer: layerVal,\n sortKey,\n visible: true,\n sourceBounds: cullingLocalAabb,\n viewport: { width: 0, height: 0, dpr: 1 },\n projection: identityProjection(),\n } satisfies PointsLinesRetainedSnapshot);\n\n // Instances are snapshotted before the CPU visibility decision so the\n // culling owner can derive the union of every instance's transformed\n // mesh bounds. The same detached snapshot is then carried to record;\n // do not re-read the collection after culling (a mutation must not\n // make the cull and draw disagree within one frame).\n let instancesSnap: InstancesSnapshot | undefined;\n if (hasInstances) {\n const transforms =\n worldInternal._getArrayView(entity, Instances, 'transforms') ?? new Float32Array();\n if (transforms.length % 16 !== 0) {\n worldInternal._routeError(\n new InstanceTransformsStrideMismatchError(transforms.length),\n {\n severity: Severity.Error,\n systemName: 'RenderSystem.extract (Instances stride)',\n },\n );\n continue;\n }\n const projected = instanceCollections?.project(world, entity, transforms);\n instancesSnap = {\n transforms: projected?.transforms ?? new Float32Array(transforms),\n instanceCount: transforms.length / 16,\n cacheKey: entity,\n archVersion: projected === undefined ? fingerprintNumericArray(transforms) : 0,\n ...(projected === undefined\n ? {}\n : {\n collectionId: projected.collectionId,\n revision: projected.revision,\n }),\n };\n }\n\n const baseRenderable: RenderableSnapshot = {\n assetHandle: Math.round(fAssetHandle ?? 0),\n transform: transformSnap,\n ...(lods === undefined ? {} : { lods }),\n ...(lodHysteresis === undefined ? {} : { lodHysteresis }),\n ...(localAabb !== undefined ? { localAabb: cullingLocalAabb } : {}),\n material: materialSnap,\n materials: materialsArr,\n materialBindingSources,\n materialBindingDiagnostics,\n worldId: 0,\n entityKey: entity,\n ...(authorVisible ? {} : { authorVisible: false }),\n ...(skinSlice !== undefined ? { skin: skinSlice } : {}),\n ...(skin?.joints === undefined\n ? {}\n : { skinJointEntities: Array.from(skin.joints, (joint) => Number(joint)) }),\n ...(morph !== undefined ? { morph } : {}),\n ...(instancesSnap !== undefined ? { instances: instancesSnap } : {}),\n ...(spriteInstancesSnap !== undefined ? { spriteInstances: spriteInstancesSnap } : {}),\n ...(pointsLines !== undefined ? { pointsLines } : {}),\n };\n const gpuDrivenDraws = buildGpuDrivenDraws({\n submeshes: gpuDrivenSubmeshes,\n indexed: gpuDrivenIndexed,\n materials: materialsArr,\n fallbackMaterial: materialSnap,\n ...(gpuDrivenGeometry === undefined || getMaterialShaderArtifact === undefined\n ? {}\n : {\n prepare(draw, drawMaterial) {\n const materialShaderId = drawMaterial.materialShaderId;\n if (materialShaderId === undefined) return undefined;\n const artifact = getMaterialShaderArtifact(materialShaderId);\n if (artifact?.receipt === undefined) return undefined;\n const geometry: GpuDrivenGeometryReceipt = {\n ...gpuDrivenGeometry,\n topology: draw.topology,\n indexed: draw.kind === 'indexed',\n };\n const result = resolvePreparedGpuDrivenDraw({\n snapshot: { ...baseRenderable, material: drawMaterial },\n artifact,\n geometry,\n generation: artifact.receipt.generation,\n draw,\n });\n return result.ok ? result.value : undefined;\n },\n }),\n });\n const renderable =\n morph === undefined && gpuDrivenDraws.length > 0\n ? { ...baseRenderable, gpuDrivenDraws }\n : baseRenderable;\n\n // feat-20260528-frustum-culling M3 / w10: frustum culling check.\n // Skip the entity if a valid AABB exists AND ALL cameras' frusta\n // reject the world-space AABB. Missing or malformed AABBs are\n // conservative always-visible fallbacks; valid culling bounds are\n // producer-owned finite local-space AABBs. Culling is unconditional\n // engine behavior; there is no per-entity opt-out.\n if (localAabb !== undefined) {\n // An empty or malformed Instances payload has no meaningful bounds.\n // Keep it conservative (the draw path later emits zero instances)\n // instead of manufacturing the entity's identity bounds. For a\n // valid payload, derive one world-space union for CPU culling while\n // leaving the mesh-local AABB untouched for GPU per-instance cull.\n const derivedInstancesBounds =\n instancesSnap === undefined || instancesSnap.instanceCount === 0\n ? undefined\n : deriveInstancesUnionBounds({\n meshAabb: cullingLocalAabb,\n entityWorld: transformSnap.world,\n transforms: instancesSnap.transforms,\n });\n if (instancesSnap?.instanceCount === 0) {\n // No instance can contribute a visible bound. The retained\n // snapshot still records instanceCount=0 for the record stage.\n } else if (\n hasInstances &&\n (instancesSnap === undefined || derivedInstancesBounds === undefined)\n ) {\n // Missing/malformed derived facts are a conservative no-cull\n // result. The stride validator above already rejects malformed\n // lengths; this branch covers non-finite producer matrices/AABB.\n } else {\n // feat-20260601 D-3: cull AABB uses the resolved world mat4\n // directly (no compose) -- same source the record stage feeds\n // the mesh SSBO, so cull stays same-source with render (AC-05).\n const worldAabb = box3.create();\n if (derivedInstancesBounds !== undefined) {\n worldAabb[0] = derivedInstancesBounds[0] ?? 0;\n worldAabb[1] = derivedInstancesBounds[1] ?? 0;\n worldAabb[2] = derivedInstancesBounds[2] ?? 0;\n worldAabb[3] = derivedInstancesBounds[3] ?? 0;\n worldAabb[4] = derivedInstancesBounds[4] ?? 0;\n worldAabb[5] = derivedInstancesBounds[5] ?? 0;\n } else {\n box3.transformBox3(worldAabb, cullingLocalAabb, transformSnap.world);\n }\n\n // Test against all cameras. Entity is visible if one camera\n // frustum intersects the world-space AABB (or planes are empty\n // from degenerate projection).\n frustumTotal += 1;\n let visible = frustumPlanes.length === 0;\n for (let ci = 0; ci < frustumPlanes.length; ci++) {\n const planes = frustumPlanes[ci] as Float32Array;\n if (planes.length === 0) {\n visible = true;\n break;\n }\n if (frustum.intersectsBox(planes as frustum.Frustum, worldAabb as box3.Box3Like)) {\n visible = true;\n break;\n }\n }\n if (!visible) {\n frustumCulled += 1;\n continue;\n }\n }\n }\n\n flushPendingDispatch(pendingDispatch);\n renderables.push(renderable);\n }\n\n // feat-20260520-2d-sprite-layer-mvp M-3 / w22 + w25: finalise the\n // pending TransparentEntry with the renderableIndex pointing at the\n // RenderableSnapshot we just pushed (when isRenderable === true).\n // The check below also covers a sprite entity that survives the\n // dangling-Instances branch (silent skip with `dispatchEntry !==\n // null` early-continue) — in that case renderableIndex is still set\n // to the just-pushed slot which is correct because materialDispatch\n // already captures the dispatch position.\n }\n }\n\n // M3 / w26: sort dispatch entries by queue (ascending, stable sort)\n // per plan-strategy D-3.\n dispatch = sortDispatchByQueue(dispatch);\n\n // D-1: collect PostProcessParams entities into Map<shaderId, Uint8Array>.\n // Last-one-wins when multiple entities bear the same shader id (mirrors\n // Camera.exposure -> CameraSnapshot pattern; extract stage only reads).\n const postProcessParams: Map<string, Uint8Array> = new Map();\n const postProcessParamsQuery = world.query({ with: [PostProcessParams] }).unwrap();\n for (const row of postProcessParamsQuery) {\n const entity = row.entity;\n const read = world.get(entity, PostProcessParams);\n if (!read.ok) continue;\n postProcessParams.set(read.value.shader, read.value.data);\n }\n\n // feat-20260621 M-A3 / w13 (D-5): engine built-in tonemap data-driven\n // provider. The engine bridges the active camera's `Camera.exposure /\n // whitePoint / tonemap` onto the SAME unified params channel custom\n // post-processes use — `Camera.exposure` stays the AI-user-facing SSOT (D-5),\n // the engine itself acts as the provider for the Standard tonemap shader\n // id. The 16B layout keeps the prior recordTonemapPass packing\n // (render-system-record.ts pre-w14): Float32 [exposure, whitePoint, _,\n // ditherEnabled], with the mode u32 occupying the third 4-byte slot via\n // tonemapToU32 (SSOT in camera.ts). The final Output Transform makes a\n // per-pass copy and writes ditherEnabled at byte offset 12; the extracted\n // camera snapshot remains the SSOT. Run AFTER the user-entity collection above so the engine's\n // built-in provider is authoritative for its own reserved key (a user entity\n // can never shadow the Standard tonemap identity. The single active camera mirrors\n // recordFrame's `activeCameras[0]` selection.\n const tonemapCamera = cameras[0];\n if (tonemapCamera !== undefined) {\n postProcessParams.set(STANDARD_OUTPUT_TRANSFORM_FEATURE_ID, tonemapParams(tonemapCamera));\n }\n\n return {\n cameras,\n auxiliaryCameras,\n cubeCameras,\n reflectionProbes,\n lights,\n environment,\n environmentReady: true,\n ...(volumetricFog === undefined ? {} : { volumetricFog }),\n renderables,\n dispatch,\n skylight,\n skylightCount,\n lightProbes,\n skybox,\n skyboxCount,\n fog,\n ...(fogFailure === undefined ? {} : { fogFailure }),\n frustumStats: { culled: frustumCulled, total: frustumTotal },\n visibilityStats: { explicitlyHidden: explicitlyHidden.size },\n postProcessParams,\n visibilitySnapshots: [context.visibility],\n featureVisibilitySnapshots: [{ world, snapshot: context.visibility }],\n hiddenEntityReports: [...explicitlyHidden].map((entity) => ({ world, entity })),\n };\n}\n\nexport function defaultMaterialSnapshot(materialHandle = 0): MaterialSnapshot {\n // Mid-grey unlit fallback (D-Q7 case B + extract-stage missing-spec),\n // matching the pre-w6 visual outcome where the record stage's force-cast\n // read of `firstMaterial.baseColorTexture` returned undefined and the\n // unlit fallback shader was selected.\n return {\n baseColor: vec3.create(0.5, 0.5, 0.5),\n metallic: 0,\n roughness: 1,\n materialHandle,\n };\n}\n\nfunction identityProjection(): Float32Array {\n const projection = new Float32Array(16);\n projection[0] = 1;\n projection[5] = 1;\n projection[10] = 1;\n projection[15] = 1;\n return projection;\n}\n","import type { MaterialCookProgramContext } from '@forgeax/engine-pack/material-cook';\n// @forgeax/engine-runtime - RenderSystem Extract stage (D-S2 + plan-strategy R-15\n// fallback split). Pure ECS query phase: walks Camera / DirectionalLight /\n// the merged-MeshRenderer renderable archetype and produces SoA-free snapshot\n// arrays consumed by the Record stage.\n//\n// Carve-out from render-system.ts (review round 1 finding #3 - 505 line cap\n// fallback split into 3 files; main + extract + record). The public API remains\n// limited to the renderer contract; this module is an owner-local\n// implementation seam consumed through relative imports.\n//\n// w15 (feat-20260511-asset-system-v1 M5 / plan-strategy D-P4) +\n// feat-20260513-component-naming-bevy-align M3 / D-2 (merged) +\n// feat-20260517-merge-mesh-renderer-material-renderer M2 / w5 (rename) +\n// M3 / w9 (single-query convergence; this commit):\n// The previous 4-query alpha split (one full-archetype query gating on\n// Transform + MeshFilter + MeshRenderer without Instances; one direct\n// archetype-graph walk for the instanced variant; two fallback queries\n// on Transform+MeshFilter without MeshRenderer / MeshFilter without\n// Transform; one trailing dispatch query gating on MeshRenderer alone)\n// collapses into ONE archetype-graph walk gated on `MeshRenderer`\n// component presence (plan-strategy section 2.2 case A archetype-\n// natural-absence + section 3.2 sequence diagram \"with: [MeshRenderer]\n// (sole)\"). Inside the loop\n// the four D-Q7 dispositions land:\n// - case A (no MeshRenderer) : not in domain; archetype absent. No\n// fire; no renderable; no dispatch.\n// - case B (material === 0) : missing-spec sentinel; defaultMaterial\n// Snapshot fills the slot. No fire.\n// - case C (handle unresolved): assets.get(handle).err with the entity\n// carrying the full T+MF+MR renderable\n// archetype -> structured RhiError(\n// `asset-not-registered`) routed through\n// the World Layer-3 ErrorHandler + entity\n// skipped from RenderableSnapshot[] +\n// from MaterialDispatchSnapshot[]; with a\n// non-renderable archetype (MeshRenderer\n// only / lacking T or MF) the dangling\n// handle stays a silent skip (charter F1\n// surface minimization: AI users without\n// render intent should not see render\n// errors).\n// - resolved : populated MaterialSnapshot (5 fields)\n// + MaterialDispatchSnapshot dispatch\n// entry (regardless of T+MF presence,\n// preserving the dispatch-only counter\n// semantics).\n//\n// D-Q7 three-tier subtable (SSOT mirrored in `packages/runtime/README.md`\n// §ECS render bridge D-Q7 `MeshRenderer` three-tier subtable +\n// `components/mesh-renderer.ts` head JSDoc; AGENTS.md §Component naming\n// + §Breaking changes 2026-05-17 row references this surface):\n// - case A archetype absent : silent skip; no onError; not in\n// RenderableSnapshot[]; hint literal N/A\n// (charter \"ergonomic omission, not a\n// misuse\"; AC-09).\n// - case B missing-spec : `material === undefined` ->\n// `defaultMaterialSnapshot()` mid-grey\n// unlit; no onError; entity present in\n// RenderableSnapshot[] with default\n// material; hint literal: `'pass\n// undefined or omit field to request\n// default material'` (AC-10).\n// - case C dangling-ref : `assets.get(handle).err` (strict path,\n// isRenderable === true) ->\n// `RhiError({ code: 'asset-not-\n// registered', detail: { assetHandle },\n// hint: 'register material via\n// assetRegistry.register(asset) before\n// spawn, or remove the material field\n// to fall back to default' })` routed\n// through World Layer-3 ErrorHandler;\n// entity skipped from\n// RenderableSnapshot[] +\n// MaterialDispatchSnapshot[]; mirrors\n// `MeshFilter.assetHandle` dangling path\n// (charter proposition 5; AC-11).\n//\n// World owns explicit Instances transforms. Extraction makes a detached\n// per-renderer projection; GPU residents acknowledge complete snapshots only\n// after successful uploads. Reading a snapshot never changes author state.\n\nimport type { AssetRegistry } from '@forgeax/engine-assets-runtime';\nimport {\n materialParametersToParamSchema as projectMaterialParametersToParamSchema,\n resolveAssetHandle,\n selectMaterialPassProgram,\n walkMaterialPassesOverSharedRefs,\n} from '@forgeax/engine-assets-runtime';\nimport type { Component, ComponentSchema, EntityHandle, Query, World } from '@forgeax/engine-ecs';\nimport { readRenderArrayView, routeWorldError } from '@forgeax/engine-ecs/projection';\nimport { type Mat4, mat4, type Vec3, vec3 } from '@forgeax/engine-math';\nimport { AssetGuid, type AssetGuid as AssetGuidBytes } from '@forgeax/engine-pack/guid';\nimport { RhiError } from '@forgeax/engine-rhi';\nimport { GlobalTransform, Transform } from '@forgeax/engine-scene';\nimport {\n DEFAULT_STANDARD_SURFACE_MODULE,\n type MaterialShaderArtifact,\n STANDARD_PIPELINE_PARAM_SCHEMA,\n} from '@forgeax/engine-shader';\nimport type {\n Asset,\n Handle,\n MaterialAsset,\n MaterialColorParameterSchema,\n MaterialParameter,\n MaterialPass,\n MaterialRenderState,\n MaterialTextureCoordinates,\n MaterialTextureValue,\n MeshLodLevel,\n ParamSchemaEntry,\n PrimitiveTopology,\n TextureAsset,\n} from '@forgeax/engine-types';\nimport {\n derive,\n materialGuidText,\n materialValuesToLinearRuntime,\n toShared,\n} from '@forgeax/engine-types';\nimport {\n antialiasFromF32,\n bloomEnabledFromF32,\n Camera,\n CubeCamera,\n cameraProjectionFromF32,\n cubeCameraUpdateIntentFromF32,\n Fog,\n MotionBlur,\n ReflectionProbe,\n reflectionProbeUpdateIntentFromF32,\n tonemapFromF32,\n tonemapToU32,\n} from './components';\nimport type { DirectionalShadowQuality } from './components/directional-shadow-filter';\nimport type { LightValidationError } from './components/light-helpers';\nimport { selectEnvironment } from './environment/frame';\nimport { ShadowInvalidConfigError } from './errors/render';\nimport {\n type DirectionalShadowCascadeFit,\n projectDirectionalShadow,\n} from './extract/directional-shadow-projection';\nimport type {\n EnvironmentFrame,\n FogCandidate,\n FogFrame,\n FogSelectionFailure,\n} from './extract/environment';\nimport { resolveVisibility, type VisibilitySnapshot } from './extract/visibility';\nimport type {\n RenderFeatureHiddenEntityReport,\n RenderFeatureWorldVisibilitySnapshot,\n} from './features/types';\nimport type { InstanceCollectionId, InstanceProjectionStore } from './instances';\nimport type {\n MeshMaterialBindingDiagnostic,\n MeshMaterialBindingSource,\n} from './mesh-material-bindings';\nimport { isCanonicalStandardPbrMaterialShader, isStandardPbrMaterialShader } from './pbr-pipeline';\nimport type { PointsLinesRetainedSnapshot } from './points-lines/snapshot';\nimport type { ReflectionProbeFact } from './reflection/projection';\nimport type { CameraSnapshot, CubeCameraSnapshot } from './render-contract';\nimport { defaultMaterialSnapshot } from './render-system-extract-tail';\nimport { getActiveCamera, selectActiveCameraIndex } from './systems/active-camera';\nimport { selectPasses } from './systems/pass-selector';\nimport type { SkinPaletteAllocator } from './systems/skin-palette-allocator';\nimport type { SkinPaletteSlice } from './systems/skin-palette-types';\nimport type { RenderTarget, RenderTargetTextureSource } from './targets/contracts';\nimport { resolveRenderTargetMaterialSource } from './targets/material-source';\nimport { resolveSelectedVolumetricLight } from './volume/capability';\nimport {\n type ValidatedVolumetricFog,\n type VolumeDensityBinding,\n VolumetricFog,\n type VolumetricFogAuthoring,\n} from './volume/component';\nimport { extractVolumetricFog } from './volume/extract';\nimport type { VolumeProjectorTuple } from './volume/temporal';\n\n/**\n * DirectionalLightSnapshot — sun-like infinite light variant of the\n * `LightSnapshot` discriminated union (M2 / w16 / AC-03). Host pre-multiplies\n * `color * intensity` so the shader sees the radiance term directly (charter\n * P4 host-side parity); `direction` stays in raw outgoing-vector form so the\n * shader can negate it once for BRDF (`let l = normalize(-light.direction)`).\n *\n * Plan-strategy D-S1 (3) (LightSnapshot to GPU buffer bucket 1:1 mapping).\n */\nexport interface DirectionalLightSnapshot {\n readonly kind: 'directional';\n readonly entity?: EntityHandle;\n readonly direction: Vec3;\n readonly color: Vec3;\n readonly intensity: number;\n}\n\n/**\n * PointLightSnapshot — omnidirectional point variant. `position` from the\n * companion Transform; `invRangeSquared = 1 / range^2` host-folded via\n * `computeInvRangeSquared` (range = +Infinity -> 0; range = 0 -> 1e8 NaN\n * protection per D-S5).\n */\nexport interface PointLightSnapshot {\n readonly kind: 'point';\n readonly entity?: EntityHandle | number;\n readonly position: Vec3;\n readonly color: Vec3;\n readonly intensity: number;\n readonly invRangeSquared: number;\n /**\n * feat-20260612-point-light-shadows-urp-hdrp M1 / T-M1-8 + M4 / T-M4-4:\n * cube_array atlas layer index for this light's shadow map (0..capacity-1\n * for admitted shadow casters; sentinel `-1` for non-admitted lights).\n * Default `-1` per\n * plan-strategy §D-2 — record stage / shader skips shadow sampling when the\n * lane equals the sentinel. Joined with `pointShadow[]` by entity at the\n * end of extract; HDRP record stage threads `shadowAtlasLayer + shadowNear +\n * shadowFar` through the unified direct-light metadata payload.\n */\n readonly shadowAtlasLayer?: number;\n /**\n * Per-face perspective near plane (matches `PointLightShadow.nearPlane`).\n * Used by HDRP `evalPointShadowed` for depth-ref reconstruction; URP keeps\n * the projection constants in its dedicated shadow-parameter buffer.\n */\n readonly shadowNear?: number;\n /**\n * Per-face perspective far plane (matches `PointLightShadow.farPlane`).\n * It is consumed with the shadow atlas layer through the shared\n * shadow-parameter buffer; DirectLightSlot carries only the layer identity.\n */\n readonly shadowFar?: number;\n}\n\n/**\n * PointShadowSnapshot — extract-stage view of one shadow-casting point light\n * (feat-20260612-point-light-shadows-urp-hdrp M1 / T-M1-7).\n *\n * `entity` is the spawning entity (joins PointLight + PointLightShadow on the\n * same archetype); `position` is the light world-space position resolved from\n * the companion Transform (mirrors PointLightSnapshot.position).\n * `shadowMatrices` is the 96-float packed mat4[6] table (column-major,\n * 6 mat4 * 16 floats = 384 bytes) ready for UBO upload.\n *\n * Plan-strategy §D-3: the record stage allocates a dynamic-offset uniform\n * buffer (384 B per-light, aligned to minUniformBufferOffsetAlignment, WebGPU\n * min 256 -> 512 B stride). Extract owns the host-side `Float32Array(96)`;\n * record owns the GPU `RhiBuffer` lifetime.\n *\n * `mapSize` / `nearPlane` / `farPlane` ride here so record stage can size the\n * cube atlas faces and feed shader the proj constants without re-querying ECS.\n * `shadowAtlasLayer` is assigned by extract in spawn order up to the renderer\n * atlas capacity; over-budget requests retain the sentinel `-1` so the\n * downstream DirectLightSlot packing carries no invalid layer identity.\n */\nexport interface PointShadowSnapshot {\n /** Spawning entity index (joins PointLight + PointLightShadow + Transform). */\n readonly entity: number;\n /** World-space light position (sourced from companion Transform). */\n readonly position: Vec3;\n /** PointLightShadow.mapSize (per-face cube square dimension; 512 default). */\n readonly mapSize: number;\n readonly nearPlane: number;\n readonly farPlane: number;\n /**\n * Atlas layer assigned by extract in spawn order while capacity remains.\n * Sentinel -1 is used for a request that cannot be admitted and is\n * reserved by the shader-side DirectLightSlot metadata for no-shadow lights.\n */\n readonly shadowAtlasLayer: number;\n /**\n * 6 view-proj mat4 in face order [+X, -X, +Y, -Y, +Z, -Z] packed into one\n * Float32Array(96). 16 floats per face = 64 B; 6 * 64 = 384 B raw. The\n * record stage pads each slot to 512 B (256 alignment) when packing into\n * the per-light dynamic-offset UBO (plan-strategy §D-3).\n */\n readonly shadowMatrices: Float32Array;\n}\n\n/**\n * SpotLightSnapshot — cone-restricted variant. `position` from companion\n * Transform; `direction` raw outgoing-vector; `cosInner` / `cosOuter` host\n * pre-converted via `degToCos` so the shader sees only cosines (D-S2).\n *\n * feat-20260625-spot-light-shadow-mapping M1 w5: added shadow fields.\n * castShadow (bool) gates shadow projection; lightViewProj is the perspective\n * light-view-projection matrix computed in extract (undefined when castShadow\n * is false, dir degenerates, or the light is clipped). shadowAtlasTile\n * (i32 sentinel -1) is the allocated tile index 0..3 or -1 for unassigned\n * (plan-strategy D-4). mapSize / nearPlane / farPlane are the source\n * component shadow parameters carried through to the record stage. The\n * author-facing `shadowIntensity` remains in [0,1] and is copied unchanged;\n * shader consumers apply it only to shadow visibility, never to candela\n * radiance.\n */\nexport interface SpotLightSnapshot {\n readonly kind: 'spot';\n /** Entity identity is branded in extracted frames; numeric fixtures remain compatible. */\n readonly entity?: EntityHandle | number;\n readonly position: Vec3;\n readonly direction: Vec3;\n readonly color: Vec3;\n readonly intensity: number;\n readonly invRangeSquared: number;\n readonly cosInner: number;\n readonly cosOuter: number;\n /** Shared asset identities projected from the authored modifier fields. */\n readonly iesProfileHandle?: number;\n readonly cookieHandle?: number;\n /** Resource-array slice identities; absent means the modifier falls back. */\n readonly iesProfileSlice?: number;\n readonly cookieSlice?: number;\n /** Resolved authored payloads; absent means the renderer keeps identity LKG. */\n readonly iesProfileData?: Uint8Array;\n readonly cookieData?: Uint8Array;\n /** Aspect-only UV matrix paired with `cookieSlice`; upload is dirty-ranged. */\n readonly cookieMatrix?: Float32Array;\n /**\n * Legacy projector payload projected into the shared Cookie array lane when\n * the adapter exposes the extended-lighting topology. The projector keeps\n * its lightViewProj sampling semantics; only the texture transport is\n * shared with authored Cookie resources.\n */\n readonly projectorSlice?: number;\n readonly projectorData?: Uint8Array;\n readonly projectorMatrix?: Float32Array;\n readonly rollDeg?: number;\n // ── shadow fields (feat-20260625-spot-light-shadow-mapping M1) ──\n readonly castShadow: boolean;\n readonly lightViewProj: Float32Array | undefined;\n readonly mapSize: number;\n readonly nearPlane: number;\n readonly farPlane: number;\n readonly shadowAtlasTile: number;\n /** Fraction of sampled shadow visibility to retain; 1 = fully opaque shadow. */\n readonly shadowIntensity?: number;\n readonly depthBias?: number;\n readonly normalBias?: number;\n readonly pcfKernelSize?: number;\n /** Authoritative TextureAsset projector resolved from the SpotLight handle. */\n readonly projectorHandle?: Handle<'TextureAsset', 'shared'>;\n readonly projectorAsset?: TextureAsset;\n readonly projectorGuid?: string;\n readonly projectorGeneration?: number;\n readonly projectorRevision?: number;\n}\n\n/** RectArea direct-light snapshot carried by the unified slot contract. */\nexport interface RectAreaDirectLightSnapshot {\n readonly kind: 'rect-area';\n readonly position: Vec3;\n readonly color: Vec3;\n readonly intensity: number;\n readonly invRangeSquared: number;\n readonly halfWidth: number;\n readonly halfHeight: number;\n readonly axisX: Vec3;\n readonly axisY: Vec3;\n readonly shadowAtlasTile?: number;\n}\n\n/** Normalized world-space frame used by Rect extraction, culling, and BRDF. */\nexport interface RectAreaWorldFrame {\n readonly center: Vec3;\n readonly axisX: Vec3;\n readonly axisY: Vec3;\n readonly normal: Vec3;\n readonly halfWidth: number;\n readonly halfHeight: number;\n}\n\n/** Build the single normalized Rect frame shared by direct and cluster paths. */\nexport function buildRectAreaWorldFrame(input: {\n readonly center: ArrayLike<number>;\n readonly axisX: ArrayLike<number>;\n readonly axisY: ArrayLike<number>;\n readonly width: number;\n readonly height: number;\n}): RectAreaWorldFrame {\n const center = vec3.create(input.center[0] ?? 0, input.center[1] ?? 0, input.center[2] ?? 0);\n const axisX = vec3.normalize(\n vec3.create(),\n vec3.create(input.axisX[0] ?? 0, input.axisX[1] ?? 0, input.axisX[2] ?? 0),\n );\n const axisY = vec3.normalize(\n vec3.create(),\n vec3.create(input.axisY[0] ?? 0, input.axisY[1] ?? 0, input.axisY[2] ?? 0),\n );\n const normal = vec3.normalize(vec3.create(), vec3.cross(vec3.create(), axisX, axisY));\n normal[0] = normal[0] === 0 ? 0 : (normal[0] ?? 0);\n normal[1] = normal[1] === 0 ? 0 : (normal[1] ?? 0);\n normal[2] = normal[2] === 0 ? 0 : (normal[2] ?? 0);\n return {\n center,\n axisX,\n axisY,\n normal,\n halfWidth: Math.max(0, input.width * 0.5),\n halfHeight: Math.max(0, input.height * 0.5),\n };\n}\n\n/** Return true only on the authored front side of a one-sided Rect. */\nexport function rectAreaFacesPoint(frame: RectAreaWorldFrame, point: ArrayLike<number>): boolean {\n const toPoint = vec3.create(\n (point[0] ?? 0) - (frame.center[0] ?? 0),\n (point[1] ?? 0) - (frame.center[1] ?? 0),\n (point[2] ?? 0) - (frame.center[2] ?? 0),\n );\n return vec3.dot(frame.normal, toPoint) > 0;\n}\n\n/** Project a world point onto the finite authored Rect boundary. */\nexport function closestPointOnRectArea(frame: RectAreaWorldFrame, point: ArrayLike<number>): Vec3 {\n const toPoint = vec3.create(\n (point[0] ?? 0) - (frame.center[0] ?? 0),\n (point[1] ?? 0) - (frame.center[1] ?? 0),\n (point[2] ?? 0) - (frame.center[2] ?? 0),\n );\n const localX = Math.min(\n frame.halfWidth,\n Math.max(-frame.halfWidth, vec3.dot(toPoint, frame.axisX)),\n );\n const localY = Math.min(\n frame.halfHeight,\n Math.max(-frame.halfHeight, vec3.dot(toPoint, frame.axisY)),\n );\n return vec3.create(\n (frame.center[0] ?? 0) + (frame.axisX[0] ?? 0) * localX + (frame.axisY[0] ?? 0) * localY,\n (frame.center[1] ?? 0) + (frame.axisX[1] ?? 0) * localX + (frame.axisY[1] ?? 0) * localY,\n (frame.center[2] ?? 0) + (frame.axisX[2] ?? 0) * localX + (frame.axisY[2] ?? 0) * localY,\n );\n}\n\n/**\n * LightSnapshot — discriminated union of the directional and punctual\n * variants. AI users + the record stage perform an exhaustive switch on\n * `kind`; missing arms are caught at compile time (no `default`,\n * `assertNever`-style guards). Plan-strategy R-10.\n */\nexport type LightSnapshot =\n | DirectionalLightSnapshot\n | PointLightSnapshot\n | SpotLightSnapshot\n | RectAreaDirectLightSnapshot;\n\n/**\n * ExtractedLights — three-bucket output of the extractFrame three-query\n * union (M2 / w16 / AC-03). Plan-strategy section 3.1 EXT node:\n * - `directional` — at most one (record-stage N>1 fail-fast lands in M3)\n * - `point[]` — first-slice cap of 4 enforced at record stage (M3)\n * - `spot[]` — first-slice cap of 4 enforced at record stage (M3)\n * `directionalCount` exposes the raw count of DirectionalLight entities the\n * extract observed (so the record stage can fire `render-system-multi-light`\n * when N>1 without re-running the query). M3 / w19 will widen this with\n * pointCount / spotCount fields once the matching record-time fail-fast\n * lands; for M2 the field stays directional-only to keep AC-06 (a) intact.\n */\nexport interface ExtractedLights {\n readonly directional: DirectionalLightSnapshot | undefined;\n readonly directionalCount: number;\n readonly point: readonly PointLightSnapshot[];\n readonly spot: readonly SpotLightSnapshot[];\n readonly rect: readonly RectAreaDirectLightSnapshot[];\n /**\n * feat-20260613-csm-cascaded-shadow-maps M2 / w9: per-cascade light-view-\n * projection matrices (one per cascade, length 4 pre-allocated). Each matrix\n * is a column-major 16-float mat4 with atlas tile UV inset baked in\n * (plan-strategy D-3). cascadeCount < 4: unused slots are zero matrices.\n * Undefined when castShadow=false or no directional light.\n */\n readonly lightViewProj: readonly Float32Array[] | undefined;\n /**\n * feat-20260613-csm-cascaded-shadow-maps M2 / w9: view-space z depths\n * of the PSSM split planes (length 4, Float32Array). cascadeCount < 4:\n * unused slots are 0.0f. Undefined when castShadow=false or no directional\n * light.\n */\n /** Four vec4 lanes: split, worldUnitsPerTexel, lightDepthWorldSpan, reserved. */\n readonly splitPlanes: Float32Array | undefined;\n /**\n * feat-20260613-csm-cascaded-shadow-maps M2 / w9: effective cascade count\n * from the DirectionalLight component (1..4). Undefined when castShadow=false\n * or no directional light.\n */\n readonly cascadeCount: number | undefined;\n /**\n * feat-20260613-csm-cascaded-shadow-maps M2 / w9: cascade blend width\n * from the DirectionalLight component (0..0.5). Undefined when castShadow=false\n * or no directional light.\n */\n readonly cascadeBlend: number | undefined;\n /**\n * feat-20260520-directional-light-shadow-mapping M1c / w8:\n * shadowMapSize from DirectionalLight.mapSize. Drives shadow RT\n * lazy-allocate (idempotency: same size -> no rebuild). Undefined when\n * castShadow=false or no directional light.\n */\n readonly shadowMapSize: number | undefined;\n /**\n * feat-20260621-merge-directionallightshadow-into-directionallight M2:\n * depthBias from the merged DirectionalLight (constant shadow-bias floor).\n * Populated when castShadow=true on the first-hit directional light;\n * undefined otherwise.\n */\n readonly depthBias: number | undefined;\n /**\n * feat-20260621-merge-directionallightshadow-into-directionallight M2:\n * normalBias from the merged DirectionalLight (slope-based shadow-bias\n * coefficient).\n * Populated when castShadow=true on the first-hit directional light;\n * undefined otherwise.\n */\n readonly normalBias: number | undefined;\n /** Accepted closed Directional filter projected from the first query result. */\n readonly directionalShadowQuality: DirectionalShadowQuality | undefined;\n /** Structured author-config failure; the candidate is withheld from record. */\n readonly directionalShadowError: LightValidationError | undefined;\n /**\n * feat-20260612-point-light-shadows-urp-hdrp M1 / T-M1-7:\n * shadow-casting point lights (PointLight + PointLightShadow + Transform\n * archetype join). Each entry carries the per-light 6-face VP matrices and\n * the assigned cube_array atlas layer (0..3 in spawn order; sentinel -1 is\n * reserved by the shader-side DirectLightSlot metadata for no-shadow point\n * lights).\n *\n * Empty array when no PointLightShadow components exist (zero-cost gate per\n * AC-09; record stage skips atlas allocation + shadow pass dispatch).\n */\n readonly pointShadow: readonly PointShadowSnapshot[];\n /**\n * bug-20260710-editor-cross-world-shadow: the RAW directional-shadow config\n * (cascadeCount / splitLambda / cascadeBlend / mapSize / shadowDistance) of\n * the first-hit castShadow DirectionalLight, carried unconditionally of\n * whether this world had a camera. The {@link extractFrames} merge layer\n * re-runs {@link computeDirectionalCsm} with this config + the surfaced\n * camera so directional shadows work when the light and camera live in\n * DIFFERENT worlds (editor editorWorld/sceneWorld super-composite). Undefined\n * when castShadow=false or no directional light. The `lightViewProj` /\n * `splitPlanes` fields above remain the *computed* per-world outputs (correct\n * for single-world; recomputed at merge for cross-world).\n */\n readonly directionalCsmConfig: DirectionalCsmConfig | undefined;\n /**\n * bug-20260710-editor-cross-world-shadow: the light-direction of the\n * first-hit castShadow DirectionalLight, carried so the merge layer can\n * rebuild the light-view matrix. Redundant with `directional.direction` but\n * kept explicit so the CSM recompute reads a single config bundle. Undefined\n * when castShadow=false or no directional light.\n */\n readonly directionalCsmDirection: Vec3 | undefined;\n}\n\n/**\n * SkylightSnapshot -- extract-stage view of one Skylight entity\n * (feat-20260520-skylight-ibl-cubemap M4 / t26).\n *\n * `equirectHandle` carries the packed u32 handle for\n * `Handle<EquirectAsset, 'shared'>`; the record stage drives the internal\n * lazy cubemap projection from it and resolves the projected GPU cubemap via\n * `GpuResidencyCache.getCubemapGpuView(...)` and related helpers\n * (feat-20260630 M3 / w16-w18). The snapshot carries NO projection status\n * field: the status truth lives in the store's CubemapGpuEntry (D-3 SSOT);\n * record queries it once per frame.\n *\n * `intensity` defaults to 1.0 via the Skylight component token defaults\n * (plan-strategy D-6: Skylight data flows through existing extract->record\n * pipeline; no independent ECS system).\n */\nexport interface SkylightSnapshot {\n // 0 = no equirect supplied -> solid-color ambient via the white fallback\n // cube (record falls to fallback resources when no IBL views are cached).\n readonly equirectHandle: number;\n readonly color: readonly [number, number, number];\n readonly intensity: number;\n /** Environment-space quaternion [x, y, z, w], identity by default. */\n readonly rotation: readonly [number, number, number, number];\n // feat-20260630 M3 / w19: the WINNING Skylight entity's packed handle (first\n // archetype hit). Carried so the multi-Skylight once-warn can name which\n // entity is used and which is ignored (F-8: warn carries conflicting entity\n // info). 0 only if the bundle had no live entity (never happens for a hit).\n readonly entityHandle: number;\n}\n\n/** Local diffuse probe facts; specular remains owned by Skylight/ReflectionProbe. */\nexport interface LightProbeSnapshot {\n readonly identity: string;\n readonly position: readonly [number, number, number];\n readonly radius: number;\n readonly irradiance: Float32Array;\n readonly admitted: boolean;\n}\n\n/**\n * SkyboxSnapshot -- extract-stage view of one SkyboxBackground entity\n * (feat-20260531-skybox-env-background M2 / w5).\n *\n * `equirectHandle` carries the packed u32 handle for\n * `Handle<EquirectAsset, 'shared'>`; the record stage resolves the projected\n * GPU cubemap via `GpuResidencyCache.getCubemapGpuView(...)`.\n *\n * `mode` carries the raw `f32` column value (`SKYBOX_MODE_CUBEMAP = 0`).\n * First hit wins per plan-strategy D-6; multi-entity once-warn in record stage.\n */\nexport interface SkyboxSnapshot {\n readonly equirectHandle: number;\n readonly mode: number;\n /** Environment-space quaternion [x, y, z, w], identity by default. */\n readonly rotation: readonly [number, number, number, number];\n // feat-20260630 M3 / w19: the WINNING SkyboxBackground entity's packed handle\n // (first archetype hit), so the multi-SkyboxBackground once-warn can name the\n // used entity (F-8 parity with the Skylight warn).\n readonly entityHandle: number;\n}\n\n/**\n * Resource-owner projection for the single ECS VolumetricFog singleton.\n *\n * The renderer carries the validated authoring facts and the source POD all\n * the way to the record stage. No profile flag or source/catalog byte is\n * allowed to enable the graph: `status: 'available'` is produced only after\n * the ECS component, its shared TextureAsset, and the volume validator all\n * agree on one linear 3D density owner.\n */\nexport interface ExtractedVolumetricFog {\n readonly status: 'off' | 'available' | 'degraded';\n readonly fog?: ValidatedVolumetricFog;\n readonly densityHandle?: Handle<'TextureAsset', 'shared'>;\n readonly densityAsset?: TextureAsset;\n readonly guid?: string;\n readonly generation?: number;\n readonly digest?: string;\n readonly worldId?: number;\n /** Required same-World light selected by the authoring component. */\n readonly lightEntity?: EntityHandle;\n readonly lightKind?: 'directional' | 'point' | 'spot';\n /** Optional Point+Spot pair identities consumed by the volume integrator. */\n readonly pointLightEntity?: EntityHandle;\n readonly spotLightEntity?: EntityHandle;\n /** Accepted projector tuple shared by surface and volume when authored. */\n readonly projector?: VolumeProjectorTuple;\n /** The resolved projector payload shared with the surface light snapshot. */\n readonly projectorHandle?: Handle<'TextureAsset', 'shared'>;\n readonly projectorAsset?: TextureAsset;\n}\n\nexport interface RenderableSnapshot {\n readonly assetHandle: number;\n readonly transform: TransformSnapshot;\n /** Producer-authored lower-detail references projected from MeshAsset. */\n readonly lods?: readonly MeshLodLevel[];\n readonly lodHysteresis?: number;\n /** Finite producer-owned local bounds retained for persistent CPU view work. */\n readonly localAabb?: Float32Array;\n /** Indexed single-submesh facts consumed by the first GPU-driven rigid lane. */\n readonly gpuDrivenDraws?: readonly GpuDrivenDrawSnapshot[];\n /**\n * feat-20260608 M5 amend / w11-a: the entity's representative (first)\n * material snapshot, kept as a same-name shorthand for `materials[0]`.\n * Per-entity dispatch (shading model routing, sprite-vs-mesh split, the\n * D-1/D-3 pipeline-tag pick) is uniform across the entity's submeshes\n * today, so the existing 20+ `entry.source.material.X` consumers in the\n * record stage stay unchanged. Per-submesh material data (baseColor /\n * UBO payload / paramSnapshot) lives in `materials[i]`.\n */\n readonly material: MaterialSnapshot;\n /**\n * feat-20260608 M5 amend / w11-a: per-submesh MaterialSnapshot[]\n * positionally aligned with `MeshAsset.submeshes[]` (plan §3.2 sequence\n * step 6 + AC-08). Length always equals the entity's submesh count once\n * the extract stage's count-mismatch validator (M2 / w12) has filtered\n * misaligned spawns. The record stage reads `materials[i]` to upload the\n * i-th material UBO slot before drawing the i-th submesh.\n *\n * Backward-compat: `materials[0] === material` (the legacy mid-grey\n * default-material case-B path also routes through `materials = [default]`,\n * keeping the legacy single-mesh-no-material spawn shape working without\n * a special branch in record).\n */\n readonly materials: readonly MaterialSnapshot[];\n /** Per-slot provenance trace from the shared mesh-material resolver. */\n readonly materialBindingSources: readonly MeshMaterialBindingSource[];\n /** Active structured override diagnostics for this renderable. */\n readonly materialBindingDiagnostics?: readonly MeshMaterialBindingDiagnostic[];\n /** Effective authored visibility retained by the persistent scene owner. */\n readonly authorVisible?: boolean;\n /**\n * feat-20260708-composited-multi-world-rendering M1 / D-1: the worldId\n * of the world this renderable was extracted from. Defaults to 0 in\n * single-world path (extractFrame always assigns 0). The merge layer\n * (extractFrames in M2) stamps the correct worldId per world before\n * the record stage consumes it. Combined with `entityKey` via\n * `worldEntityKey(worldId, entityKey)` to form per-entity cache keys.\n *\n * Never rewrite `entityKey` itself — consumers that need the real\n * entity handle (video provider, etc.) read the bare `entityKey`.\n */\n readonly worldId: number;\n /**\n * feat-20260531-per-frame-bind-group-cache M1 / w3: packed Entity u32\n * (encodeEntity(indexSlot, generation)) surface'd from the extract\n * stage. Stable per-entity identity for the record stage cache keys\n * (material / instances / per-frame clean-up) without re-querying the\n * World (charter P5 Pipeline Isolation: record stage only consumes\n * snapshot POD). Reuses the encodeEntity calculation already performed\n * at :1293 for the Instances path, and now also computed for plain\n * (non-Instances) renderables.\n *\n * Never rewrite this field — cache keys use `worldEntityKey(worldId, entityKey)`,\n * not the bare entityKey alone (D-1).\n */\n readonly entityKey: number;\n /**\n * feat-20260514 M3 (w15): when the entity carries an `Instances` component\n * the extract stage materialises a fresh `Float32Array` snapshot of the\n * packed mat4 transforms (16 f32 per instance, stride 16) plus a stable\n * `cacheKey` (the entity's packed u32) and the `archVersion` (used by the\n * record stage to invalidate its per-entity GPU buffer cache when the\n * archetype storage grew). Absent (`undefined`) means the record stage\n * falls back to the shared 1-element identity-mat4 storage buffer +\n * `drawIndexed(.., 1, ..)`.\n */\n readonly instances?: InstancesSnapshot;\n /**\n * feat-20260625-sprite-instances-and-tilemap-terrain-static-batch M3 / w10\n * (plan-strategy D-1 + D-9): when the entity carries a `SpriteInstances`\n * component the extract stage materialises a paired snapshot — packed mat4\n * `transforms` (16 f32, stride 16) + per-instance UV `regions` (4 f32,\n * stride 4) — plus the same cache fingerprint pair (`cacheKey` = entity\n * packed u32, `archVersion` = archetype version stamp at snapshot time).\n * The record stage interleaves the two arrays into an 80B-per-instance\n * single GPU buffer routed through `@group(3) @binding(0)` (BGL unchanged,\n * D-1). Absent (`undefined`) means the entity is not a `SpriteInstances`\n * carrier; the record stage falls back to its existing sprite path\n * (material UBO region + identity-instance buffer).\n *\n * Three structured `EcsError` codes fire at extract entry and skip the\n * renderable on violation (charter P3 explicit failure):\n * - `'sprite-instances-mutually-exclusive-with-instances'`\n * - `'sprite-instances-requires-sprite-shading-model'`\n * - `'sprite-instances-count-mismatch'`\n */\n readonly spriteInstances?: SpriteInstancesSnapshot;\n /**\n * feat-20260523-skin-skeleton-animation M2 / T-21: when the entity carries\n * a `Skin` component the extract stage populates this field with the\n * skin palette slice metadata. The record stage uses this to route the\n * draw to `forgeax::pbr-skin` pipeline + set the palette dynamic offset.\n * Absent (`undefined`) means the entity is not skinned.\n */\n readonly skin?: SkinPaletteSlice;\n /** Joint entity identities used by the persistent skin dependency index. */\n readonly skinJointEntities?: readonly number[];\n /**\n * ECS-owned morph weights. Presence selects the Standard Pipeline CPU\n * specialized deformation lane; the asset remains the source of target\n * deltas and the record stage only receives this frozen POD snapshot.\n */\n readonly morph?: MorphSnapshot;\n /** Renderer-owned previous-frame facts attached during temporal projection. */\n readonly temporal?: RenderableTemporalSnapshot;\n /** Detached M2 authoring facts for the optional Points/Lines projection. */\n readonly pointsLines?: PointsLinesRetainedSnapshot;\n /** Renderer-owned per-object probe record uploaded at group(3) binding(1). */\n readonly probeBlendRecord?: import('./scene/probe-blend-record').ProbeBlendRecord;\n}\n\nexport type RenderablePreviousSource = 'last-submitted' | 'current-seed';\nexport type RenderableReactiveReason =\n | 'new-slot'\n | 'generation-reuse'\n | 'reentered'\n | 'geometry-revision'\n | 'material-revision'\n | 'skinning-deformation'\n | 'morph-deformation';\nexport interface RenderableTemporalSnapshot {\n readonly previousEpoch: number | undefined;\n readonly previousSource: RenderablePreviousSource;\n readonly reactive: boolean;\n readonly reactiveReasons: readonly RenderableReactiveReason[];\n readonly previousTransform: TransformSnapshot;\n readonly previousInstances: InstancesSnapshot | undefined;\n readonly previousSkin: SkinPaletteSlice | undefined;\n readonly previousMorphWeights: Float32Array | undefined;\n}\n\nexport interface MorphSnapshot {\n readonly weights: Float32Array;\n readonly targetCount: number;\n}\n\nexport interface GpuDrivenDrawSnapshot {\n readonly kind: 'indexed' | 'non-indexed';\n readonly first: number;\n readonly count: number;\n readonly baseVertex: number;\n readonly materialSlot: number;\n readonly topology: PrimitiveTopology;\n readonly pipelineClass: string;\n readonly materialResourceClass: string;\n /** Producer-owned prepared ABI facts used by the Standard PBR GPU lane. */\n readonly prepared?: import('./gpu-driven/prepared-draw').PreparedGpuDrivenDraw;\n /** Optional projected height supplied by direct GPU-view evidence/tests. */\n readonly projectedHeight?: number;\n /** Root plus lower-detail index/vertex ranges, in LOD order. */\n readonly lodRanges?: readonly {\n readonly first: number;\n readonly count: number;\n readonly baseVertex: number;\n }[];\n}\n\nexport interface InstancesSnapshot {\n /** Renderer-owned collection identity. */\n readonly collectionId?: InstanceCollectionId;\n /** Packed column-major mat4 transforms (16 f32 per instance). */\n readonly transforms: Float32Array;\n /** Number of instances (transforms.length / 16). */\n readonly instanceCount: number;\n /** Collection revision captured by this detached frame snapshot. */\n readonly revision?: number;\n /** Stable per-entity GPU buffer cache key (the packed Entity u32). */\n readonly cacheKey: number;\n /**\n * Archetype version stamp at snapshot time. The record stage compares this\n * against its cached version per cacheKey; a bump means the underlying\n * BufferPool slot may have grown / been reallocated, forcing a fresh\n * `device.createBuffer + queue.writeBuffer` round.\n */\n readonly archVersion: number;\n}\n\n/**\n * feat-20260625-sprite-instances-and-tilemap-terrain-static-batch M3 / w10:\n * extract-stage view of a `SpriteInstances` carrier (2D peer of\n * `InstancesSnapshot`).\n *\n * Field shapes mirror `InstancesSnapshot` so the record-stage cache protocol\n * (`(cacheKey, archVersion, byteLength)` fingerprint triple) is reused\n * verbatim. The byte length consumed at upload time is the sum\n * `transforms.byteLength + regions.byteLength` (= 80*N for N instances,\n * plan-strategy D-1 interleaved single-buffer); the record stage builds the\n * 80B/instance interleaved buffer once per (entity, archVersion, byteLength)\n * fingerprint change.\n */\nexport interface SpriteInstancesSnapshot {\n /** Packed column-major mat4 transforms (16 f32 per instance, stride 16). */\n readonly transforms: Float32Array;\n /** Per-instance UV vec4 regions (4 f32 per instance, stride 4). */\n readonly regions: Float32Array;\n /**\n * Number of instances. Derived from `transforms.length / 16` (equivalently\n * `regions.length / 4`); the extract-entry validator guarantees the two\n * derivations agree, otherwise it fires\n * `'sprite-instances-count-mismatch'` and skips the renderable.\n */\n readonly instanceCount: number;\n /** Stable per-entity GPU buffer cache key (the packed Entity u32, D-9). */\n readonly cacheKey: number;\n /** Archetype version stamp at snapshot time (cache invalidation fingerprint). */\n readonly archVersion: number;\n}\n\n/**\n * TransformSnapshot: extract-stage view of one entity's resolved world\n * transform (feat-20260601 D-3). Holds the single `world` mat4 (column-major\n * 16 floats, copied from the entity's `GlobalTransform.world` view written by\n * propagateTransforms). The record stage copies these 16 floats straight into\n * the mesh SSBO slot (zero `mat4.compose`); position / scale consumers derive\n * from the mat4 via `mat4.getTranslation` / basis-column lengths.\n */\nexport interface TransformSnapshot {\n readonly world: Float32Array;\n}\n\n/**\n * MaterialSnapshot: extract-stage view of one entity's material asset (M2 / w6\n * of feat-20260517-merge-mesh-renderer-material-renderer; plan-strategy section 2.3).\n *\n * Adds optional `baseColorTexture` + `sampler` slots (consumed by the record\n * stage's textured-material code path; M3 / w10 dropped the cast-over-firstMaterial\n * pattern in favour of direct snapshot field reads).\n *\n * feat-20260522-learn-render-3-1-sponza-model-loading-with-multi-l M4 extends\n * the snapshot with `metallicRoughnessTexture` and `normalTexture`\n * so the record stage can wire PBR texture bindings 4 and 6\n * from real GPU views instead of placeholder 1x1 white / flat-normal views.\n *\n * Bounded scope: the snapshot tracks only what the record stage actually\n * consumes today (charter proposition 5 consistent abstraction; YAGNI for\n * future-proof field bloat). Future MaterialAsset extensions (emissive / etc)\n * drive snapshot extensions when the record stage starts consuming them, not\n * vice-versa.\n *\n * tweak-20260701 M1: `shadingModel` field removed — shader identity via\n * {@link materialShaderId} is the single source of truth for material dispatch.\n */\nexport interface MaterialSnapshot {\n readonly baseColor: Vec3;\n readonly metallic: number;\n readonly roughness: number;\n /** Authored Standard PBR specular color in linear runtime color space. */\n readonly specularColor?: readonly [number, number, number] | undefined;\n /**\n * Schema-driven material shader identifier (feat-20260523 M4-T05).\n * Populated when the material asset uses the schema-driven path\n * (payload.materialShader set). Undefined for unlit/sprite legacy\n * materials and for case-B defaultMaterialSnapshot.\n *\n * The record stage uses this as the pipeline cache key first-level\n * discriminator (M4-T06).\n */\n readonly materialShaderId?: string | undefined;\n readonly materialProgramKeys?: Readonly<Record<string, string>> | undefined;\n /**\n * Stable source handle for the material asset. Record uses this only for\n * same-frame assembly reuse; GPU bind-group validity still comes from the\n * resource-identity cache.\n */\n readonly materialHandle?: number | undefined;\n /**\n * The selected forward-pass state for this exact material. A mesh can bind\n * different materials to its submeshes, so pipeline selection must read the\n * state from the submesh snapshot rather than the entity's first material.\n */\n readonly renderState?: MaterialRenderState | undefined;\n /**\n * Schema-driven parameter snapshot (feat-20260523 M4-T05).\n * Populated alongside materialShaderId. Maps param name to its\n * runtime-resolved value: number for scalar params, number[] for\n * vec/color params, string (GUID) for texture2d/sampler params.\n */\n readonly paramSnapshot?: Readonly<Record<string, number | number[] | string>> | undefined;\n /** Effective MaterialAsset parameter contract used to lay out this snapshot. */\n readonly materialParamSchema?: readonly ParamSchemaEntry[] | undefined;\n /** Authored per-slot UV set and KHR texture transform metadata. */\n readonly textureCoordinates?: ReadonlyMap<string, MaterialTextureCoordinates> | undefined;\n /**\n * User-region texture handles keyed by paramSchema field name\n * (feat-20260621-learn-render-5-5-parallax M2 / w7). The SSOT carrier for\n * EVERY texture the shader's `derive(paramSchema).textureFieldNames`\n * declares — `baseColorTexture` / `metallicRoughnessTexture` /\n * `normalTexture` for built-in standard-PBR, plus each custom field such as\n * `heightTexture` (LO 5.5 parallax). The record stage iterates this map to\n * assemble the user-region bind group per the per-shader BGL (w8), so a 4th\n * (or Nth) texture flows end-to-end without a hardcoded field list.\n *\n * Populated by iterating `textureFieldNames`; absent keys mean the\n * paramValue was missing / mis-typed (record falls back to default white).\n * `emissiveTexture` / `occlusionTexture` are included here as ordinary\n * Standard user-region fields; the production layout does not duplicate\n * them in a lightmap injection region.\n */\n readonly textureHandles?: ReadonlyMap<string, Handle<'TextureAsset', 'shared'>> | undefined;\n /** Renderer-local target sources; never projected as TextureAsset handles. */\n readonly textureSources?: ReadonlyMap<string, RenderTargetTextureSource> | undefined;\n /**\n * User-region texture field names whose paramValue resolved to a VideoAsset\n * (kind `'video'`) rather than a static TextureAsset\n * (feat-20260623-world-space-video-asset M4 / w14, D-5). The video GUID\n * occupies the same texture2d values slot a static texture would (P4:\n * one binding shape), but extract routes it here instead of `textureHandles`\n * so the record stage pulls the current-frame view from the transient\n * DynamicTextureStore (D-3) instead of `GpuResidencyCache.ensureResident`\n * (which has no `video` arm; AC-08). Each entry also carries the resolved\n * clip handle so the record stage can key the per-frame upload.\n *\n * Producer/consumer split (charter P5 / AC-07 gate): extract owns the\n * asset->snapshot translation; record consumes this POD field only — it never\n * reaches back into the MaterialAsset to learn a field is video-sourced.\n */\n readonly videoTextureFields?: ReadonlyMap<string, Handle<'VideoAsset', 'shared'>> | undefined;\n /** Authored sampler handles keyed by their matching texture parameter. */\n readonly samplerHandles?: ReadonlyMap<string, Handle<'SamplerAsset', 'shared'>> | undefined;\n readonly baseColorTexture?: Handle<'TextureAsset', 'shared'> | undefined;\n /**\n * PBR metallic-roughness texture handle (present for PBR/sprite/skin\n * shaders). Undefined for the default-unlit shader\n * (materialShaderId === 'forgeax::default-unlit'). The record stage reads\n * this to write GPU view at material bind-group binding 4, falling\n * back to a 1x1 white placeholder when undefined.\n *\n * feat-20260522-learn-render-3-1-sponza-model-loading-with-multi-l M4:\n * field added so the record stage can wire real metallic-roughness\n * textures from Sponza glTF materials (M3 writes the handle into\n * SchemaDrivenMaterialAsset values; M4 extract carries it through to the snapshot).\n */\n readonly metallicRoughnessTexture?: Handle<'TextureAsset', 'shared'> | undefined;\n /**\n * PBR tangent-space normal texture handle (present for PBR/sprite/skin\n * shaders). Undefined for the default-unlit shader\n * (materialShaderId === 'forgeax::default-unlit'). The record stage reads\n * this to write GPU view at material bind-group binding 6, falling\n * back to a (0.5,0.5,1.0) flat-normal placeholder when undefined.\n *\n * feat-20260522-learn-render-3-1-sponza-model-loading-with-multi-l M4:\n * field added symmetrically with metallicRoughnessTexture so the record\n * stage can wire real normal textures from Sponza glTF materials.\n */\n readonly normalTexture?: Handle<'TextureAsset', 'shared'> | undefined;\n /** Scalar applied to tangent-space normal XY after the normal texture sample. */\n readonly normalScale?: number | undefined;\n readonly emissive?: readonly [number, number, number] | undefined;\n readonly emissiveIntensity?: number | undefined;\n readonly emissiveTexture?: Handle<'TextureAsset', 'shared'> | undefined;\n readonly occlusionTexture?: Handle<'TextureAsset', 'shared'> | undefined;\n readonly occlusionStrength?: number | undefined;\n /**\n * Transparent composition flag derived from the first pass's\n * `renderState.blend` presence on the underlying\n * {@link MaterialPass} (feat-20260626-collapse M2: blend\n * presence is the SSOT after `MaterialPass.transparent` was\n * dropped in M1).\n *\n * The record stage reads this to drive both the LDR split-pass\n * decision and the premultiplied-alpha blend resolution on the\n * generic materialShaderId pipeline path — shader-agnostic, decoupled\n * from the legacy `shadingModel` discriminant (feat-20260625 M2 D-3,\n * finalised in w15; `shadingModel` field removed in tweak-20260701 M1).\n *\n * This describes the primary-pass snapshot for consumers that need a\n * material summary. Actual draw routing and the LDR split read the selected\n * DispatchEntry.renderState, so mixed opaque/transparent Passes remain valid.\n *\n * Type is `boolean | undefined` (derived): `undefined` means \"no\n * passes / unknown\"; consumers must read `=== true` / `!== true` to\n * stay correct under both populated and absent cases.\n */\n readonly transparent?: boolean | undefined;\n}\n\nexport interface MaterialCacheChainIdentity {\n readonly asset: MaterialAsset;\n readonly parentGuid: string | undefined;\n}\n\nexport interface MaterialSnapshotCacheEntry {\n readonly snapshot: MaterialSnapshot;\n readonly passes: readonly MaterialPass[];\n /** Root/chain identities are present only on cross-frame-safe entries. */\n readonly chain?: readonly MaterialCacheChainIdentity[];\n /** AssetRegistry epoch at which the root/parent chain was last validated. */\n readonly catalogEpoch?: number;\n /** True only when every object reachable from the authored chain is frozen. */\n readonly crossFrameSafe: boolean;\n}\n\nexport type MaterialSnapshotCache = Map<number, MaterialSnapshotCacheEntry>;\nexport type MaterialSnapshotCachesByWorld = WeakMap<World, MaterialSnapshotCache>;\n\nexport function gpuDrivenMaterialResourceClass(material: MaterialSnapshot): string {\n const textures = [...(material.textureHandles?.entries() ?? [])]\n .map(([name, handle]) => [name, Number(handle)] as const)\n .sort(([left], [right]) => left.localeCompare(right));\n const samplers = [...(material.samplerHandles?.entries() ?? [])]\n .map(([name, handle]) => [name, Number(handle)] as const)\n .sort(([left], [right]) => left.localeCompare(right));\n return JSON.stringify({\n textures,\n samplers,\n video: [...(material.videoTextureFields?.keys() ?? [])].sort(),\n });\n}\n\n// === DispatchEntry — M3 / w26 single dispatch list (feat-20260526-material-asset-multipass-renderstate) ===\n//\n// Plan-strategy D-3: single dispatch list sorted by queue value,\n// replacing the old three-bucket opaque/transparent/overlay dispatch.\n// Each entry carries the per-pass render-state and entry-point\n// data from the resolved MaterialPass so the record stage\n// reads them without re-resolving the material.\n\nexport interface DispatchEntry {\n readonly entityIndex: number;\n readonly materialHandle: number;\n readonly renderableIndex: number;\n readonly passIndex: number;\n readonly queue: number;\n /**\n * Signed i32 from the entity's {@link Layer} component value (default 0 for\n * entities without a Layer). Primary sort key for the transparent-dispatch\n * sort in {@link render-system.ts}: lower value = drawn first (behind).\n */\n readonly layer: number;\n readonly tags: Record<string, string>;\n readonly renderState: MaterialRenderState | undefined;\n readonly defines: Record<string, string> | undefined;\n readonly vertexEntry: string | undefined;\n readonly fragmentEntry: string | undefined;\n readonly materialShaderId: string | undefined;\n readonly paramSnapshot: Readonly<Record<string, number | number[] | string>> | undefined;\n /**\n * Stencil reference value from {@link MaterialPass.stencilReference}\n * (draw-call dynamic state). Folded during extract for per-draw consumption\n * in the record stage. `undefined` when the pass does not set a reference\n * value (record stage falls back to WebGPU default 0).\n */\n readonly stencilReference?: number;\n}\n\n/**\n * Stable-sort dispatch entries by `queue` value ascending.\n * Returns a new sorted array (does not mutate the input).\n * Same-queue entries preserve insertion order (AC-11 stable-order guarantee).\n */\nexport function sortDispatchByQueue<E extends { readonly queue: number }>(\n entries: readonly E[],\n): E[] {\n // Array.prototype.sort is stable per ES2019 spec (V8 7.0+ / Node 12+).\n return entries.slice().sort((a, b) => a.queue - b.queue);\n}\n\nexport const DEFAULT_FORWARD_PASS: MaterialPass = {\n name: 'forward',\n program: { module: 'forgeax::default-unlit', vertexEntry: 'vs_main', fragmentEntry: 'fs_main' },\n renderState: { tags: { LightMode: 'Forward' }, queue: 2000 },\n};\n\nexport function appendMaterialDispatchEntries(\n pendingDispatch: DispatchEntry[],\n passes: readonly MaterialPass[],\n entity: EntityHandle,\n materialHandle: number,\n renderableIndex: number,\n layer: number,\n paramSnapshot: Readonly<Record<string, number | number[] | string>> | undefined,\n passIndexOffset = 0,\n materialProgramKeys?: Readonly<Record<string, string>>,\n): void {\n const matchedPasses = selectPasses(passes, {});\n for (let pIdx = 0; pIdx < matchedPasses.length; pIdx++) {\n const pass = matchedPasses[pIdx];\n if (pass === undefined) continue;\n const passState = (pass.renderState ?? {}) as MaterialRenderState & {\n readonly tags?: Record<string, string>;\n readonly queue?: number;\n readonly stencilReference?: number;\n };\n const authoredShaderId = runtimeMaterialShaderId(pass.program.module, pass.name);\n const dispatchShaderId =\n materialProgramKeys === undefined ? authoredShaderId : materialProgramKeys[pass.name];\n if (materialProgramKeys !== undefined && dispatchShaderId === undefined)\n throw new Error(`Missing published material program for Pass ${pass.name}`);\n pendingDispatch.push({\n entityIndex: entity,\n materialHandle,\n renderableIndex,\n passIndex: passIndexOffset + pIdx,\n queue: passState.queue ?? 2000,\n layer,\n tags: passState.tags ?? {},\n renderState: pipelineRenderState(passState),\n // Material module identity is already closed in the cooked program.\n // It must never become a draw-time define map.\n defines: undefined,\n vertexEntry: pass.program.vertexEntry,\n fragmentEntry: pass.program.fragmentEntry,\n materialShaderId: dispatchShaderId,\n paramSnapshot,\n ...(passState.stencilReference !== undefined && {\n stencilReference: passState.stencilReference,\n }),\n });\n }\n}\n\nexport interface ExtractedFrame {\n readonly cameras: CameraSnapshot[];\n /** Auxiliary target cameras selected after the display camera is fixed. */\n readonly auxiliaryCameras: readonly CameraSnapshot[];\n /** Cube capture intents extracted beside the display camera in one pass. */\n readonly cubeCameras: readonly CubeCameraSnapshot[];\n /** Reflection probe facts projected from the same World extraction. */\n readonly reflectionProbes?: readonly ReflectionProbeFact[];\n readonly lights: ExtractedLights;\n /** Resource-owner environment facts selected once at the extract boundary. */\n readonly environment: EnvironmentFrame | undefined;\n /** False when the resource-owner world failed environment/fog selection. */\n readonly environmentReady: boolean;\n /** One resource-owner volume projection; absent means no authored fog. */\n readonly volumetricFog?: ExtractedVolumetricFog;\n readonly renderables: RenderableSnapshot[];\n /**\n * Single dispatch list sorted by queue value (ascending, stable sort).\n * Replaces the old opaqueDispatch / transparentDispatch / overlayDispatch\n * three-bucket model per plan-strategy D-3.\n */\n readonly dispatch: DispatchEntry[];\n readonly skylight: SkylightSnapshot | undefined;\n readonly skylightCount: number;\n /** World-local diffuse probe candidates; never a direct-light slot. */\n readonly lightProbes?: readonly LightProbeSnapshot[];\n readonly skybox: SkyboxSnapshot | undefined;\n readonly skyboxCount: number;\n /** Resource-owner Fog facts selected once at the frame boundary. */\n readonly fog: FogFrame | undefined;\n /** Last invalid Fog update retained alongside the current valid/LKG frame. */\n readonly fogFailure?: FogSelectionFailure;\n /**\n * feat-20260528-frustum-culling M3 / w11: frustum culling statistics\n * collected during the extract phase. `total` is the count of entities\n * that reached the culling decision point; `culled` is the count of\n * those that were removed from renderables by frustum culling.\n */\n readonly frustumStats: { readonly culled: number; readonly total: number };\n /** Candidate entities rejected by author visibility before resource parsing. */\n readonly visibilityStats: { readonly explicitlyHidden: number };\n /**\n * Per-frame post-process params snapshot collected from PostProcessParams\n * entities (D-1: data-driven params channel). Maps shader id to the\n * raw data bytes (Uint8Array = FieldValueType<'buffer'>). Last-one-wins\n * when multiple entities bear the same shader id.\n * Empty map when no PostProcessParams entities exist.\n */\n readonly postProcessParams: ReadonlyMap<string, Uint8Array>;\n /** Visibility snapshots prepared for each contributing World. */\n readonly visibilitySnapshots: readonly VisibilitySnapshot[];\n /** World-labelled snapshots passed to generic RenderFeature extraction. */\n readonly featureVisibilitySnapshots: readonly RenderFeatureWorldVisibilitySnapshot[];\n /** Built-in hidden candidates, retained for host-side producer deduplication. */\n readonly hiddenEntityReports: readonly RenderFeatureHiddenEntityReport[];\n}\n\nexport type CameraTargetUpdate = 'once' | 'on-demand' | 'continuous';\n\nexport interface CameraTargetCandidate {\n readonly worldId: number;\n readonly entityKey: number;\n readonly target?: RenderTarget;\n readonly requestVersion: number;\n readonly update: CameraTargetUpdate;\n}\n\nexport interface CameraTargetRejection {\n readonly entityKey: number;\n readonly reason: 'budget' | 'display-target' | 'duplicate-target';\n}\n\nexport interface CameraTargetSelection {\n readonly display: CameraTargetCandidate | undefined;\n readonly auxiliary: readonly CameraTargetCandidate[];\n readonly rejected: readonly CameraTargetRejection[];\n}\n\nexport function selectCameraTargetViews(\n candidates: readonly CameraTargetCandidate[],\n options: { readonly displayEntityKey?: number; readonly budget: number },\n): CameraTargetSelection {\n const display = candidates.find(\n (candidate) =>\n candidate.entityKey === options.displayEntityKey && candidate.target === undefined,\n );\n const rejected: CameraTargetRejection[] = [];\n const ordered = candidates\n .filter((candidate) => candidate.target !== undefined)\n .sort((left, right) => left.worldId - right.worldId || left.entityKey - right.entityKey);\n const auxiliary: CameraTargetCandidate[] = [];\n const seenTargets = new Set<RenderTarget>();\n for (const candidate of ordered) {\n const duplicate = candidate.target !== undefined && seenTargets.has(candidate.target);\n if (candidate.target !== undefined) seenTargets.add(candidate.target);\n if (candidate.entityKey === options.displayEntityKey) {\n rejected.push({ entityKey: candidate.entityKey, reason: 'display-target' });\n continue;\n }\n if (candidate.target === undefined || duplicate) {\n rejected.push({ entityKey: candidate.entityKey, reason: 'duplicate-target' });\n continue;\n }\n if (auxiliary.length >= Math.max(0, options.budget)) {\n rejected.push({ entityKey: candidate.entityKey, reason: 'budget' });\n continue;\n }\n auxiliary.push(candidate);\n }\n return {\n display,\n auxiliary: Object.freeze(auxiliary),\n rejected: Object.freeze(rejected),\n };\n}\n\n/**\n * Internal world surface used by extract for archetype-graph traversal and\n * error routing. The packed `Entity` handle for a row is read directly from\n * the essential id=0 `Entity` column (`arch.columns.get(Entity.id).get('self')`)\n * -- no generation lookup / encodeEntity rebuild (feat-20260602 M2).\n */\ntype RenderErrorContext = {\n readonly systemName: string;\n /** Retained as diagnostic metadata for legacy render call sites. */\n readonly severity?: 'error' | 'warning';\n};\n\ntype ArrayFieldView = ArrayLike<number>;\n\n/**\n * Render's old zero-copy ECS calls now use the explicit public projection\n * boundary. The optimized ECS owner keeps storage behind `World`; render\n * receives a detached array snapshot and routes failures through the same\n * projection owner.\n */\nexport type WorldInternalView = {\n _routeError(error: unknown, ctx: RenderErrorContext): void;\n _getArrayView<N extends string, S extends ComponentSchema>(\n entity: EntityHandle,\n component: Component<N, S>,\n fieldName: string,\n ): ArrayFieldView | undefined;\n};\n\nexport const Severity = Object.freeze({ Error: 'error', Warning: 'warning' } as const);\n\nexport function createWorldInternalView(world: World): WorldInternalView {\n return {\n _routeError(error, ctx) {\n routeWorldError(world, error, { systemName: ctx.systemName });\n },\n _getArrayView(entity, component, fieldName) {\n return readRenderArrayView(world, entity, component, fieldName) as ArrayFieldView | undefined;\n },\n };\n}\n\nexport function resolveCameraTarget(\n world: World,\n raw: number | undefined,\n): RenderTarget | undefined {\n if (raw === undefined || raw <= 0) return undefined;\n const resolved = world.sharedRefs.resolve<'RenderTarget', RenderTarget>(\n toShared<'RenderTarget'>(Math.round(raw)),\n );\n return resolved.ok ? resolved.value : undefined;\n}\n\n/**\n * The user-region texture fields the built-in standard-PBR material declares.\n * Used as the fallback texture-field set when the shader id is not registered\n * (cross-worktree shader-late-register, plan R-4) so a built-in material still\n * resolves its user-region textures. Mirrors `derive(default-standard-pbr).textureFieldNames`.\n */\nexport const BUILTIN_USER_REGION_TEXTURE_FIELDS: readonly string[] = [\n 'baseColorTexture',\n 'metallicRoughnessTexture',\n 'normalTexture',\n 'specularColorTexture',\n 'emissiveTexture',\n 'occlusionTexture',\n 'transmissionTexture',\n 'thicknessTexture',\n];\nconst BUILTIN_USER_REGION_TEXTURE_FIELD_SET = new Set(BUILTIN_USER_REGION_TEXTURE_FIELDS);\nconst BUILTIN_BASE_COLOR_TEXTURE_FIELD_SET = new Set(['baseColorTexture']);\n\nexport function materialTextureFields(\n shaderId: string | undefined,\n fields: ReadonlySet<string> | undefined,\n): ReadonlySet<string> | undefined {\n if (fields !== undefined && fields.size > 0) return fields;\n if (\n shaderId === 'forgeax::default-standard-pbr' ||\n shaderId === 'forgeax::default-standard-pbr-skin' ||\n shaderId === 'forgeax::pbr-skin'\n ) {\n return BUILTIN_USER_REGION_TEXTURE_FIELD_SET;\n }\n if (\n shaderId === 'forgeax::default-unlit' ||\n shaderId === 'forgeax::sprite' ||\n shaderId === 'forgeax::sprite-lit'\n ) {\n return BUILTIN_BASE_COLOR_TEXTURE_FIELD_SET;\n }\n return fields;\n}\n\n/**\n * The authored material surface uses the module IDs declared by built-in WGSL\n * sources. Runtime pipeline caches still use the existing engine registration\n * IDs, so this small projection keeps authored identity and renderer lookup\n * identity in one place during the migration.\n */\nexport function runtimeMaterialShaderId(\n module: string | undefined,\n passName?: string,\n): string | undefined {\n if (\n passName === 'shadow-caster' &&\n (module === 'forgeax_material::standard' ||\n module === 'forgeax_material::unlit' ||\n module === 'forgeax::default-standard-pbr' ||\n module === 'forgeax::default-unlit')\n ) {\n return 'forgeax::default-shadow-caster';\n }\n switch (module) {\n case 'forgeax_material::standard':\n return 'forgeax::default-standard-pbr';\n case 'forgeax_material::unlit':\n return 'forgeax::default-unlit';\n case 'forgeax_material::sprite':\n return 'forgeax::sprite';\n case 'forgeax_material::sprite-lit':\n return 'forgeax::sprite-lit';\n default:\n return module;\n }\n}\n\n/**\n * Select the runtime identity for one resolved material. A cooked publication\n * owns the composed material artifact identity; the authored pass module is\n * the built-in fallback used before that publication is ready.\n */\nexport function materialProgramKeysForMaterial(\n material: MaterialAsset,\n assets: AssetRegistry,\n context: MaterialCookProgramContext | undefined,\n): Readonly<Record<string, string>> | undefined {\n const projection = assets.getMaterialProjectionForPayload(material);\n if (projection === undefined) return undefined;\n if (context === undefined)\n throw new Error('Published material selection requires renderer-owned compiler context');\n return Object.fromEntries(\n projection.passes.map((pass) => {\n const mode = String(\n (pass.renderState?.tags as Record<string, unknown> | undefined)?.LightMode ?? pass.name,\n );\n const selectedContext: MaterialCookProgramContext = {\n ...context,\n pass: /shadow/i.test(mode) ? 'shadow' : /depth/i.test(mode) ? 'depth' : 'forward',\n pipeline: /deferred|gbuffer/i.test(mode) ? 'deferred' : context.pipeline,\n };\n return [\n pass.name,\n selectMaterialPassProgram(projection, pass.name, selectedContext).specializationKey,\n ];\n }),\n );\n}\n\nexport function runtimeMaterialShaderIdForMaterial(\n passes: readonly MaterialPass[],\n programs: Readonly<Record<string, string>> | undefined,\n): string | undefined {\n const pass =\n passes.find(\n (pass) =>\n !/shadow|depth/i.test(\n String(\n (pass.renderState?.tags as Record<string, unknown> | undefined)?.LightMode ?? pass.name,\n ),\n ),\n ) ?? passes[0];\n if (pass === undefined) return undefined;\n return programs === undefined\n ? runtimeMaterialShaderId(pass.program.module, pass.name)\n : programs[pass.name];\n}\n\nexport function pipelineRenderState(\n renderState:\n | (MaterialRenderState & {\n readonly tags?: Readonly<Record<string, string>>;\n readonly queue?: number;\n readonly stencilReference?: number;\n })\n | undefined,\n): MaterialRenderState | undefined {\n if (renderState === undefined) return undefined;\n const {\n cullMode,\n depthCompare,\n depthWriteEnabled,\n blend,\n alphaToCoverageEnabled,\n stencil,\n stencilReadMask,\n stencilWriteMask,\n frontFace,\n } = renderState;\n if (\n cullMode === undefined &&\n depthCompare === undefined &&\n depthWriteEnabled === undefined &&\n blend === undefined &&\n alphaToCoverageEnabled === undefined &&\n stencil === undefined &&\n stencilReadMask === undefined &&\n stencilWriteMask === undefined &&\n frontFace === undefined\n ) {\n return undefined;\n }\n return {\n ...(cullMode !== undefined && { cullMode }),\n ...(depthCompare !== undefined && { depthCompare }),\n ...(depthWriteEnabled !== undefined && { depthWriteEnabled }),\n ...(blend !== undefined && { blend }),\n ...(alphaToCoverageEnabled !== undefined && { alphaToCoverageEnabled }),\n ...(stencil !== undefined && { stencil }),\n ...(stencilReadMask !== undefined && { stencilReadMask }),\n ...(stencilWriteMask !== undefined && { stencilWriteMask }),\n ...(frontFace !== undefined && { frontFace }),\n };\n}\n\n/**\n * tweak-20260627-model-loading-smoke-build-perf M4: per-World intern cache for\n * the loadByGuid texture/sampler resolution path. A MaterialAsset's\n * texture/sampler values remain embedded GUID strings (dash-form) after\n * loadByGuid; the extract stage re-resolves each GUID to a column handle every\n * frame. Before this cache each resolution called `world.allocSharedRef`, which\n * mints a NEW monotonically-increasing slot id per call. Because the GPU\n * residency cache (`GpuResidencyCache.textureGpuHandles`) is keyed on\n * `handleSlot(handle)`, a fresh slot every frame meant the residency check\n * ALWAYS missed -> all textures re-uploaded to the GPU every frame, old GPU\n * textures never freed (refcount never hits 0). Unbounded GPU memory +\n * unbounded per-frame upload cost (628ms -> 2764ms over 12 frames, SIGKILL).\n *\n * The fix interns the GUID-string -> column-handle resolution: each unique\n * `(guid, brand)` pair mints EXACTLY ONE stable shared handle per World, reused\n * across frames (architecture-principle §6 idempotency: same GUID resolved N\n * times yields the same handle). The handle is intentionally long-lived -- it\n * lives as long as the World references the material, which is exactly the\n * desired lifetime; the `onLastRelease` -> `gpuStore.evictTexture` wiring stays\n * coherent because the handle is no longer churned per frame.\n *\n * Invariant boundary (asset-registry.ts:1958-1962): the AssetRegistry is a\n * GUID -> payload catalogue with NO handle/World concept -- it cannot mint a\n * column handle. So this intern cache lives in the extract/render layer, keyed\n * per-World via a WeakMap (the World owns the SharedRefStore that mints slots).\n *\n * Inner key is `${lowercasedGuid}\\u0000${brand}` -- a GUID catalogues to a\n * single asset kind in practice, but the brand keeps the key correct if the\n * same GUID is ever resolved under two brands.\n *\n * Cache hits are validated against the registry's current payload identity.\n * Re-cataloguing the same GUID therefore retires the cache's allocation grant\n * and mints a handle for the replacement payload. An invalidated GUID retires\n * the entry immediately instead of keeping a stale payload alive.\n */\ninterface GuidHandleInternEntry {\n readonly handle: number;\n readonly payload: Asset;\n}\n\nconst guidHandleInternByWorld = new WeakMap<World, Map<string, GuidHandleInternEntry>>();\n\nexport function internSharedRefFromGuid<B extends string>(\n world: World,\n assetsRef: AssetRegistry,\n guid: string,\n brand: B,\n): Handle<B, 'shared'> | undefined {\n let perWorld = guidHandleInternByWorld.get(world);\n if (perWorld === undefined) {\n perWorld = new Map<string, GuidHandleInternEntry>();\n guidHandleInternByWorld.set(world, perWorld);\n }\n const key = `${guid.toLowerCase()}\\u0000${brand}`;\n const cached = perWorld.get(key);\n const payload = assetsRef.lookup(guid);\n if (cached !== undefined && cached.payload === payload) {\n const cachedHandle = toShared<B>(cached.handle);\n if (world.sharedRefs.resolve(cachedHandle).ok) return cachedHandle;\n }\n if (cached !== undefined) {\n world.sharedRefs.release(toShared<B>(cached.handle));\n perWorld.delete(key);\n }\n if (payload === undefined) return undefined;\n // Mint exactly once per (world, guid, brand). ECS owns the allocation grant\n // and publishes release evidence through SharedRefStore; render does not\n // attach a second deleter lifecycle to the World.\n const handle = world.internSharedRef(brand, payload);\n perWorld.set(key, { handle, payload });\n return handle;\n}\n\n/**\n * feat-20260623-world-space-video-asset M4 / w14 (D-5): if a user-region\n * texture field's paramValue is an embedded GUID string that catalogues to a\n * VideoAsset (`kind === 'video'`), mint a `VideoAsset`-branded column handle for\n * it and return that handle; otherwise return undefined (the field is a static\n * texture / sampler / scalar and flows through the normal TextureAsset path).\n *\n * The video GUID occupies the same texture2d values slot a static texture\n * would (P4: identical binding shape) — extract just routes it to a different\n * GPU lifecycle (the transient DynamicTextureStore, D-3) instead of the static\n * `ensureResident` cache, whose switch has no `video` arm (AC-08). Minting a\n * brand-`VideoAsset` handle keeps the snapshot self-describing: the record stage\n * sees a video handle and resolves the per-frame view without reaching back into\n * the asset (charter P5).\n *\n * A `number` paramValue (already a minted column handle) is not a GUID string so\n * it cannot be a freshly-catalogued video; it passes through as undefined here.\n */\nexport function resolveVideoFieldHandle(\n value: unknown,\n world: World,\n assetsRef: AssetRegistry,\n): Handle<'VideoAsset', 'shared'> | undefined {\n const texture = materialTextureValue(value);\n const textureGuid = assetReferenceText(texture?.texture ?? value);\n if (textureGuid === undefined) return undefined;\n const payload = assetsRef.lookup(textureGuid);\n if (payload === undefined || payload.kind !== 'video') return undefined;\n // M4: intern so a video GUID mints one stable VideoAsset handle per World\n // instead of a fresh slot every frame. The transient per-frame view is\n // resolved downstream by this handle (DynamicTextureStore); minting the\n // handle once does not freeze the view (P5: handle != frame data).\n return internSharedRefFromGuid(world, assetsRef, textureGuid, 'VideoAsset');\n}\n\nexport function materialTextureValue(value: unknown): MaterialTextureValue | undefined {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined;\n const textureValue = value as Partial<MaterialTextureValue>;\n return typeof textureValue.texture === 'number' ||\n typeof textureValue.texture === 'string' ||\n textureValue.texture instanceof Uint8Array\n ? (textureValue as MaterialTextureValue)\n : undefined;\n}\n\nexport function assetReferenceText(value: unknown): string | undefined {\n if (typeof value === 'string') return value;\n if (value instanceof Uint8Array && isAssetGuidBytes(value)) return AssetGuid.format(value);\n return undefined;\n}\n\nexport function isAssetGuidBytes(value: Uint8Array): value is AssetGuidBytes {\n return value.byteLength === 16;\n}\n\nexport function materialNormalScale(values: Readonly<Record<string, unknown>>): number {\n for (const [field, value] of Object.entries(values)) {\n if (field !== 'normalTexture') continue;\n const scale = materialTextureValue(value)?.normalScale;\n return typeof scale === 'number' && Number.isFinite(scale) ? scale : 1;\n }\n return 1;\n}\n\nexport function materialTextureRef(value: unknown): unknown {\n return materialTextureValue(value)?.texture ?? value;\n}\n\nexport function collectMaterialTextureCoordinates(\n values: Readonly<Record<string, unknown>>,\n): Map<string, MaterialTextureCoordinates> {\n const out = new Map<string, MaterialTextureCoordinates>();\n // Texture transforms belong to the value itself. Walking every authored\n // value keeps the route closed when Standard gains another physical map\n // without adding another renderer-side field inventory.\n for (const [field, value] of Object.entries(values)) {\n if (!field.endsWith('Texture')) continue;\n const coordinates = materialTextureValue(value)?.coordinates;\n if (coordinates !== undefined) out.set(field, coordinates);\n }\n return out;\n}\n\nexport function collectMaterialTextureSources(\n values: Readonly<Record<string, unknown>>,\n world: World,\n): Map<string, RenderTargetTextureSource> {\n const out = new Map<string, RenderTargetTextureSource>();\n for (const [field, value] of Object.entries(values)) {\n const reference = materialTextureRef(value);\n if (typeof reference !== 'number') continue;\n const resolved = world.sharedRefs.resolve<\n 'RenderTargetTextureSource',\n RenderTargetTextureSource\n >(toShared<'RenderTargetTextureSource'>(reference));\n if (!resolved.ok || resolveRenderTargetMaterialSource(resolved.value) === undefined) continue;\n out.set(field, resolved.value);\n }\n return out;\n}\n\nexport function collectMaterialTextureSamplers(\n values: Readonly<Record<string, unknown>>,\n resolveSampler: (value: unknown) => Handle<'SamplerAsset', 'shared'> | undefined,\n): Map<string, Handle<'SamplerAsset', 'shared'>> {\n const out = new Map<string, Handle<'SamplerAsset', 'shared'>>();\n for (const [field, value] of Object.entries(values)) {\n const sampler = resolveSampler(materialTextureValue(value)?.sampler);\n if (sampler !== undefined) out.set(field, sampler);\n }\n const legacySampler = resolveSampler(values.sampler);\n if (legacySampler !== undefined && !out.has('baseColorTexture')) {\n out.set('baseColorTexture', legacySampler);\n }\n return out;\n}\n\n/**\n * feat-20260621-learn-render-5-5-parallax M2 / w7 (D-3): collect the\n * user-region texture handles for a material by iterating the shader's\n * `derive(paramSchema).textureFieldNames` SSOT (via\n * `AssetRegistry.materialShaderTextureFieldNames`). Each declared texture\n * field whose paramValue resolves to a handle lands in the returned map keyed\n * by field name; this is the single path through which an arbitrary number of user-region\n * textures (8 Standard or 9+ custom, e.g. parallax `heightTexture`) flow.\n *\n * When the shader is not registered the built-in Standard field set is used\n * so standard materials still resolve. Emissive and occlusion are ordinary\n * schema-driven user-region textures in that set.\n *\n * feat-20260623-world-space-video-asset M4 / w14 (D-5): a field whose paramValue\n * catalogues to a VideoAsset is routed into `videoOut` (a VideoAsset-branded\n * handle) instead of the TextureAsset map, so the record stage pulls its view\n * from the transient DynamicTextureStore (D-3) rather than the static\n * ensureResident cache (AC-08). The video GUID still has to be in this\n * `textureFieldNames` traversal set or it is never inspected (R-7) — that\n * membership is asserted in w13.\n */\nexport function collectUserRegionTextureHandles(\n pv: Readonly<Record<string, unknown>>,\n shaderId: string | undefined,\n paramSchema: readonly ParamSchemaEntry[] | undefined,\n assetsRef: AssetRegistry,\n world: World,\n resolveTex: (\n value: unknown,\n brand: 'TextureAsset',\n ) => Handle<'TextureAsset', 'shared'> | undefined,\n videoOut: Map<string, Handle<'VideoAsset', 'shared'>>,\n): Map<string, Handle<'TextureAsset', 'shared'>> {\n const fields =\n materialTextureFields(\n shaderId,\n paramSchema !== undefined\n ? derive(paramSchema).textureFieldNames\n : shaderId !== undefined\n ? assetsRef.materialShaderTextureFieldNames(shaderId)\n : undefined,\n ) ?? BUILTIN_USER_REGION_TEXTURE_FIELDS;\n const out = new Map<string, Handle<'TextureAsset', 'shared'>>();\n for (const field of fields) {\n // D-5: a video-kind paramValue is routed to the transient path (videoOut),\n // NOT minted as a TextureAsset (which would crash the record-stage\n // ensureResident, AC-08). A static field falls through to resolveTex.\n const videoHandle = resolveVideoFieldHandle(pv[field], world, assetsRef);\n if (videoHandle !== undefined) {\n videoOut.set(field, videoHandle);\n continue;\n }\n const handle = resolveTex(materialTextureRef(pv[field]), 'TextureAsset');\n if (handle !== undefined) out.set(field, handle);\n }\n return out;\n}\n\nconst ENGINE_INJECTED_TEXTURE_FIELDS = new Set(['emissiveTexture', 'occlusionTexture']);\n\nexport function isEngineInjectedTextureField(\n shaderId: string | undefined,\n fieldName: string,\n): boolean {\n return isStandardPbrMaterialShader(shaderId) && ENGINE_INJECTED_TEXTURE_FIELDS.has(fieldName);\n}\n\n/**\n * Project one material's authoring parameters into the runtime ABI.\n *\n * Engine-owned Standard roots are compiled against the canonical superset\n * schema even when the authoring asset omits optional physical fields. A\n * compact authored schema would move later UBO members (for example `ior`)\n * into the wrong slots. Custom material roots keep their own published\n * parameter projection.\n */\nexport function materialParametersToParamSchema(\n parameters: readonly MaterialParameter[],\n shaderId?: string,\n): readonly ParamSchemaEntry[] {\n if (isCanonicalStandardPbrMaterialShader(shaderId)) return STANDARD_PIPELINE_PARAM_SCHEMA;\n return projectMaterialParametersToParamSchema(parameters);\n}\n\n/**\n * Select the parameter ABI for one resolved material. The canonical Standard\n * schema is valid only for the engine-owned default Surface; a Standard root\n * with a project Surface keeps the custom fields that its cooked WGSL reads.\n */\nexport function materialParamSchemaForMaterial(\n parameters: readonly MaterialParameter[],\n authoredShaderId: string | undefined,\n passes: readonly MaterialPass[],\n): readonly ParamSchemaEntry[] {\n const firstPass =\n passes.find(\n (pass) =>\n !/shadow|depth/i.test(\n String(\n (pass.renderState?.tags as Record<string, unknown> | undefined)?.LightMode ?? pass.name,\n ),\n ),\n ) ?? passes[0];\n const surfaceModule = firstPass?.program.moduleSlots?.surface;\n const schemaShaderId =\n surfaceModule === undefined || surfaceModule === DEFAULT_STANDARD_SURFACE_MODULE\n ? authoredShaderId\n : undefined;\n return materialParametersToParamSchema(parameters, schemaShaderId);\n}\n\n/**\n * Resolve color semantics from the material asset first and the shader schema\n * for fields the asset does not redeclare. Generated and historical pack\n * materials commonly omit `parameters`, while the shader registry still owns\n * the complete parameter contract.\n */\nexport function materialColorParameterSchema(\n parameters: readonly MaterialParameter[],\n shaderId: string | undefined,\n assets: AssetRegistry,\n): readonly MaterialColorParameterSchema[] {\n if (shaderId === undefined) return parameters;\n const shader = assets.shaderRegistry.findMaterialArtifact(shaderId);\n if (!shader.ok) return parameters;\n\n const byName = new Map<string, MaterialColorParameterSchema>(\n shader.value.paramSchema.map((parameter) => [parameter.name, parameter]),\n );\n for (const parameter of parameters) byName.set(parameter.name, parameter);\n return [...byName.values()];\n}\n\nconst MATERIAL_PARENT_CHAIN_LIMIT = 128;\n\nexport function isDeepFrozen(value: unknown, seen = new Set<object>()): boolean {\n if (typeof value !== 'object' || value === null) return true;\n if (seen.has(value)) return true;\n if (!Object.isFrozen(value)) return false;\n seen.add(value);\n for (const child of Object.values(value)) {\n if (!isDeepFrozen(child, seen)) return false;\n }\n return true;\n}\n\n/**\n * Capture the object identities that make a resolved material stable. The\n * renderer owns this cache, but the AssetRegistry owns parent GUID lookup, so\n * validation must walk the same chain on every cross-frame read. A malformed\n * or cyclic chain is deliberately not cacheable.\n */\nexport function captureMaterialCacheChain(\n root: MaterialAsset,\n assets: AssetRegistry,\n): readonly MaterialCacheChainIdentity[] | undefined {\n const chain: MaterialCacheChainIdentity[] = [];\n const visitedParentGuids = new Set<string>();\n let current = root;\n for (let depth = 0; depth < MATERIAL_PARENT_CHAIN_LIMIT; depth += 1) {\n const parentRef = current.parent;\n const parentGuid = parentRef === undefined ? undefined : materialGuidText(parentRef);\n chain.push({ asset: current, parentGuid });\n if (parentGuid === undefined) return chain;\n if (parentRef === undefined) return undefined;\n if (visitedParentGuids.has(parentGuid)) return undefined;\n visitedParentGuids.add(parentGuid);\n const parent = assets.lookup<Asset>(parentRef);\n if (parent?.kind !== 'material') return undefined;\n current = parent;\n }\n return undefined;\n}\n\nexport function readPersistentMaterialSnapshot(\n cache: MaterialSnapshotCache | undefined,\n handleRaw: number,\n assets: AssetRegistry,\n): MaterialSnapshotCacheEntry | undefined {\n const entry = cache?.get(handleRaw);\n if (entry === undefined) return undefined;\n if (\n entry.crossFrameSafe &&\n entry.chain !== undefined &&\n entry.catalogEpoch === assets.catalogEpoch\n )\n return entry;\n // The snapshot contains resolved texture and sampler handles as well as the\n // material parent chain. Any registry mutation can replace one of those\n // referenced payloads, so an epoch mismatch is a hard miss even when the\n // material objects themselves are unchanged.\n cache?.delete(handleRaw);\n return undefined;\n}\n\n/**\n * Fast path for a cache entry whose chain was already validated at the\n * current registry epoch. The full reader needs the root asset only when an\n * epoch changed; asking ECS to resolve that root before checking the epoch\n * defeats the cross-frame cache on the ordinary stable frame.\n */\nexport function readStablePersistentMaterialSnapshot(\n cache: MaterialSnapshotCache | undefined,\n handleRaw: number,\n assets: AssetRegistry,\n): MaterialSnapshotCacheEntry | undefined {\n const entry = cache?.get(handleRaw);\n return entry?.crossFrameSafe === true &&\n entry.chain !== undefined &&\n entry.catalogEpoch === assets.catalogEpoch\n ? entry\n : undefined;\n}\n\nexport function storeMaterialSnapshot(\n cache: MaterialSnapshotCache,\n handleRaw: number,\n snapshot: MaterialSnapshot,\n passes: readonly MaterialPass[],\n root: MaterialAsset,\n assets: AssetRegistry,\n): MaterialSnapshotCacheEntry {\n const chain = captureMaterialCacheChain(root, assets);\n const entry: MaterialSnapshotCacheEntry = {\n snapshot,\n passes,\n crossFrameSafe: chain?.every(({ asset }) => isDeepFrozen(asset)) === true,\n ...(chain === undefined ? {} : { chain }),\n ...(chain === undefined ? {} : { catalogEpoch: assets.catalogEpoch }),\n };\n cache.set(handleRaw, entry);\n return entry;\n}\n\n/**\n * feat-20260608 M5 amend / w11-a: resolve a single MaterialAsset handle into\n * a per-submesh MaterialSnapshot. Used by the extractFrame archetype loop to\n * build `RenderableSnapshot.materials[]` for indices >= 1 (the entity-level\n * snapshot at index 0 is built inline because it also drives multi-pass\n * DispatchEntry creation + sprite-region overrides; per-submesh secondary\n * materials are non-sprite + single-pass-equivalent for the record stage's\n * UBO upload, so this helper produces a plain MaterialSnapshot only).\n *\n * Returns `defaultMaterialSnapshot()` (mid-grey unlit) for handle=0 (case-B\n * sentinel, mirroring the inline path) and on each unresolved / non-material\n * asset (so a partially-mis-registered multi-material entity still renders\n * the resolvable submeshes; the count-mismatch validator already filtered\n * the count-disagreement case earlier).\n */\nexport function resolveMaterialSnapshot(\n handleRaw: number,\n world: World,\n assetsRef: AssetRegistry,\n materialSnapshotCache?: MaterialSnapshotCache,\n persistentMaterialSnapshotCache?: MaterialSnapshotCache,\n materialContext?: MaterialCookProgramContext,\n): MaterialSnapshot {\n if (handleRaw === 0) return defaultMaterialSnapshot(handleRaw);\n const cached = materialSnapshotCache?.get(handleRaw);\n if (cached !== undefined) return cached.snapshot;\n const stablePersistentCached = readStablePersistentMaterialSnapshot(\n persistentMaterialSnapshotCache,\n handleRaw,\n assetsRef,\n );\n if (stablePersistentCached !== undefined) {\n materialSnapshotCache?.set(handleRaw, stablePersistentCached);\n return stablePersistentCached.snapshot;\n }\n const tagged = toShared<'MaterialAsset'>(handleRaw);\n const res = resolveAssetHandle(world, tagged);\n if (!res.ok) return defaultMaterialSnapshot(handleRaw);\n const asset = res.value;\n if (asset.kind !== 'material') return defaultMaterialSnapshot(handleRaw);\n const persistentCached = readPersistentMaterialSnapshot(\n persistentMaterialSnapshotCache,\n handleRaw,\n assetsRef,\n );\n if (persistentCached !== undefined) {\n materialSnapshotCache?.set(handleRaw, persistentCached);\n return persistentCached.snapshot;\n }\n const resolvedResult = walkMaterialPassesOverSharedRefs(world, tagged, assetsRef);\n if (!resolvedResult.ok) return defaultMaterialSnapshot(handleRaw);\n const resolved = resolvedResult.value;\n const allPasses = resolved.passes;\n const materialProgramKeys = materialProgramKeysForMaterial(asset, assetsRef, materialContext);\n const authoredFirstPassShader = runtimeMaterialShaderIdForMaterial(allPasses, undefined);\n const firstPassShader = runtimeMaterialShaderIdForMaterial(allPasses, materialProgramKeys);\n const pv = materialValuesToLinearRuntime(\n resolved.values,\n materialColorParameterSchema(resolved.parameters ?? [], firstPassShader, assetsRef),\n resolved.colorSpace,\n ) as Readonly<Record<string, unknown>>;\n const baseColorPv = pv.baseColor as readonly number[] | undefined;\n const baseColor = vec3.create(\n baseColorPv?.[0] ?? 1,\n baseColorPv?.[1] ?? 1,\n baseColorPv?.[2] ?? 1,\n );\n const metallicPv = typeof pv.metallic === 'number' ? pv.metallic : 0;\n const roughnessPv = typeof pv.roughness === 'number' ? pv.roughness : 0.5;\n const specularColorPv = pv.specularColor as readonly number[] | undefined;\n const normalScalePv = materialNormalScale(pv);\n\n const paramSnap: Record<string, number | number[] | string> = {};\n for (const [k, v] of Object.entries(pv)) {\n if (typeof v === 'number') paramSnap[k] = v;\n else if (typeof v === 'string') paramSnap[k] = v;\n else if (Array.isArray(v) && v.every((x) => typeof x === 'number')) {\n paramSnap[k] = v as number[];\n }\n }\n const materialParamSchema = materialParamSchemaForMaterial(\n resolved.parameters ?? [],\n authoredFirstPassShader,\n allPasses,\n );\n // feat-20260614 M8 (D-19): texture / sampler values are embedded GUIDs\n // (dash-form strings) after loadByGuid. Resolve each to a user-tier column\n // handle by looking up the catalogued payload and minting via\n // world.allocSharedRef; a numeric value (already a column handle from a\n // directly-minted material) passes through unchanged.\n const resolveTexLike = <B extends string>(\n value: unknown,\n brand: B,\n ): Handle<B, 'shared'> | undefined => {\n if (typeof value === 'number') return toShared<B>(value);\n if (typeof value === 'string') {\n // M4: intern the GUID -> column-handle resolution so each unique\n // (world, guid, brand) mints exactly ONE stable handle reused across\n // frames (stops the per-frame slot churn that defeated the GPU\n // residency cache). feat-20260619 M2 / w8: TextureAsset brand wires\n // onLastRelease -> gpuStore.evictTexture; other brands (SamplerAsset)\n // bypass (releaseUnreferenced-fallback lifecycle).\n return internSharedRefFromGuid(world, assetsRef, value, brand);\n }\n return undefined;\n };\n // feat-20260621-learn-render-5-5-parallax M2 / w7 (D-3): iterate the\n // shader's derive(paramSchema).textureFieldNames SSOT instead of a hardcoded\n // user-region field list, so an Nth texture (e.g. parallax heightTexture)\n // resolves through the same path, including emissive/occlusion fields.\n const videoTextureFields = new Map<string, Handle<'VideoAsset', 'shared'>>();\n const textureHandles = collectUserRegionTextureHandles(\n pv,\n firstPassShader,\n materialParamSchema.length > 0 ? materialParamSchema : undefined,\n assetsRef,\n world,\n resolveTexLike,\n videoTextureFields,\n );\n const samplerHandles = collectMaterialTextureSamplers(pv, (value) =>\n resolveTexLike(materialTextureRef(value), 'SamplerAsset'),\n );\n const textureSources = collectMaterialTextureSources(pv, world);\n const emissiveTextureHandle = resolveTexLike(\n materialTextureRef(pv.emissiveTexture),\n 'TextureAsset',\n );\n const occlusionTextureHandle = resolveTexLike(\n materialTextureRef(pv.occlusionTexture),\n 'TextureAsset',\n );\n const textureCoordinates = collectMaterialTextureCoordinates(pv);\n // Named user-region fields are derived from the map (sprite + legacy reads).\n const baseColorTextureHandle = textureHandles.get('baseColorTexture');\n const metallicRoughnessTextureHandle = textureHandles.get('metallicRoughnessTexture');\n const normalTextureHandle = textureHandles.get('normalTexture');\n const emissivePv = pv.emissive as readonly number[] | undefined;\n const snapshot: MaterialSnapshot = {\n baseColor,\n metallic: metallicPv,\n roughness: roughnessPv,\n ...(specularColorPv !== undefined && {\n specularColor: [\n specularColorPv[0] ?? 1,\n specularColorPv[1] ?? 1,\n specularColorPv[2] ?? 1,\n ] as readonly [number, number, number],\n }),\n normalScale: normalScalePv,\n materialShaderId: firstPassShader,\n materialProgramKeys,\n materialHandle: handleRaw,\n renderState: pipelineRenderState(allPasses[0]?.renderState),\n paramSnapshot: paramSnap,\n ...(materialParamSchema.length > 0 && { materialParamSchema }),\n ...(textureCoordinates.size > 0 && { textureCoordinates }),\n ...(textureHandles.size > 0 && { textureHandles }),\n ...(textureSources.size > 0 && { textureSources }),\n ...(videoTextureFields.size > 0 && { videoTextureFields }),\n ...(samplerHandles.size > 0 && { samplerHandles }),\n ...(baseColorTextureHandle !== undefined && { baseColorTexture: baseColorTextureHandle }),\n ...(metallicRoughnessTextureHandle !== undefined && {\n metallicRoughnessTexture: metallicRoughnessTextureHandle,\n }),\n ...(normalTextureHandle !== undefined && { normalTexture: normalTextureHandle }),\n ...(emissivePv !== undefined && {\n emissive: [emissivePv[0] ?? 0, emissivePv[1] ?? 0, emissivePv[2] ?? 0] as readonly [\n number,\n number,\n number,\n ],\n }),\n ...(typeof pv.emissiveIntensity === 'number' && { emissiveIntensity: pv.emissiveIntensity }),\n ...(emissiveTextureHandle !== undefined && { emissiveTexture: emissiveTextureHandle }),\n ...(occlusionTextureHandle !== undefined && { occlusionTexture: occlusionTextureHandle }),\n ...(typeof pv.occlusionStrength === 'number' && { occlusionStrength: pv.occlusionStrength }),\n // feat-city-glb Bug 5 (per-submesh transparency): derive `transparent`\n // from the first pass's `renderState.blend` presence, identical to the\n // entity-level snapshot builder (extractFrame archetype loop). Without\n // this, per-submesh materials (materials[i>=1], e.g. a glTF BLEND decal\n // submesh on a multi-material mesh) never carry the transparent flag, so\n // the record stage's LDR split + blend routing treats them as opaque and\n // their alpha=0 texels composite as black.\n transparent: allPasses[0]?.renderState?.blend !== undefined,\n };\n const stored =\n materialSnapshotCache !== undefined\n ? storeMaterialSnapshot(\n materialSnapshotCache,\n handleRaw,\n snapshot,\n allPasses,\n asset,\n assetsRef,\n )\n : undefined;\n const cacheEntry =\n stored ??\n (persistentMaterialSnapshotCache !== undefined\n ? storeMaterialSnapshot(\n persistentMaterialSnapshotCache,\n handleRaw,\n snapshot,\n allPasses,\n asset,\n assetsRef,\n )\n : undefined);\n if (cacheEntry?.crossFrameSafe === true) {\n persistentMaterialSnapshotCache?.set(handleRaw, cacheEntry);\n }\n return snapshot;\n}\n\n/**\n * feat-20260612-skin-palette-per-frame-upload M2 / m2-6: narrow per-frame\n * pipeline surface consumed by `extractFrame`. Today only `skinPaletteAllocator`\n * crosses the seam (the allocator owns the per-frame palette buffer + cursor;\n * extract calls `resetForFrame` at frame entry then `allocateSlice` +\n * `writeJointPalette` per skinned entity). Kept narrow on purpose — extract\n * does NOT see the rest of `PipelineState` to avoid a circular import via\n * `render-system.ts`.\n */\nexport interface ExtractPipelineSurface {\n readonly skinPaletteAllocator: SkinPaletteAllocator | null;\n}\n\n/**\n * PSSM (Parallel-Split Shadow Maps) split plane computation.\n *\n * Formula (plan-strategy D-8, research F1):\n * C_i = λ·n·(f/n)^(i/m) + (1-λ)·(n + i/m·(f-n))\n * where i = 1..m, n = near, f = far, m = cascadeCount\n *\n * The coverage range is [camera near, DirectionalLight.shadowDistance] — the\n * near end derives from the active camera, the far end is the shadowDistance\n * knob. Returns strictly monotonic view-space z depths (positive).\n *\n * When `far <= near + ε` (ε=1e-6), throws ShadowInvalidConfigError\n * (charter P3 explicit failure — research F2 guarantees formula stability\n * but degenerate configuration must be surfaced to the caller).\n *\n * @param nearPlane - near of the shadow casting range (from the camera near)\n * @param farPlane - far of the shadow casting range (DirectionalLight.shadowDistance)\n * @param cascadeCount - number of cascades (1..4)\n * @param splitLambda - PSSM split weight (0 = pure uniform, 1 = pure log)\n * @returns Array of m split depths (view-space z); length = cascadeCount,\n * guaranteed strictly monotonic, last element = far.\n *\n * @internal exported for w6/w7 testing only; production callers route through\n * extractFrame which validates cascadeCount/splitLambda via component schema.\n */\n/**\n * Compute the 8 world-space corner points of a camera frustum slice.\n *\n * Uses mat4.unproject to map NDC cube corners back to world space.\n * The slice is defined by view-space nearZ and farZ depths.\n *\n * For a WebGPU perspective matrix, ndcZ(viewZ) = camFar * (viewZ - camNear) /\n * (viewZ * (camFar - camNear)). We compute the ndcZ for each slice boundary\n * and unproject directly.\n *\n * @param vp - camera view-projection matrix (column-major 16 floats)\n * @param camNear - camera near plane (used to derive NDC mapping)\n * @param camFar - camera far plane (used to derive NDC mapping)\n * @param nearZ - near depth of the frustum slice (view-space, positive)\n * @param farZ - far depth of the frustum slice (view-space, positive)\n * @returns Array of 8 Vec3 world-space corner positions.\n */\nfunction computeFrustumCorners(\n vp: Mat4,\n camNear: number,\n camFar: number,\n nearZ: number,\n farZ: number,\n projection: 'perspective' | 'orthographic',\n): Vec3[] {\n const invVP = mat4.create();\n mat4.invert(invVP, vp);\n const corners: Vec3[] = [];\n\n // NDC z mapping is projection-dependent (WebGPU clip-space z in [0,1]):\n // perspective: ndc(z) = camFar * (z - camNear) / (z * (camFar - camNear))\n // orthographic: ndc(z) = (z - camNear) / (camFar - camNear)\n // feat-20260613-csm M6 / w22: orthographic cameras silently produced\n // garbage NDC z (perspective formula divides by viewZ, but ortho NDC is\n // linear), which mapped the cascade slab back to a degenerate world-space\n // corner set and the AABB-fit collapsed to near zero -- shadow_caster\n // wrote its triangles outside the [-1,1] clip volume so the depth\n // attachment stayed at clear=1.0 (root cause for shadow-m2 / shadow-m3 /\n // shadow-opt-out dawn red surfaced after w20's host-side ortho fix).\n const span = camFar - camNear;\n const ndcNear =\n projection === 'orthographic'\n ? (nearZ - camNear) / span\n : (camFar * (nearZ - camNear)) / (nearZ * span);\n const ndcFar =\n projection === 'orthographic'\n ? (farZ - camNear) / span\n : (camFar * (farZ - camNear)) / (farZ * span);\n\n const signs = [-1, 1];\n for (const sx of signs) {\n for (const sy of signs) {\n corners.push(unprojectNDC(invVP, sx, sy, ndcNear));\n }\n }\n for (const sx of signs) {\n for (const sy of signs) {\n corners.push(unprojectNDC(invVP, sx, sy, ndcFar));\n }\n }\n\n return corners;\n}\n\n/**\n * Unproject a single NDC point to world space.\n */\nfunction unprojectNDC(invVP: Mat4, ndcX: number, ndcY: number, ndcZ: number): Vec3 {\n const ndc = vec3.create(ndcX, ndcY, ndcZ);\n const ws = vec3.create();\n mat4.unproject(ws, ndc, invVP);\n return ws;\n}\n\nexport function pssmSplit(\n nearPlane: number,\n farPlane: number,\n cascadeCount: number,\n splitLambda: number,\n): Float32Array {\n const EPS = 1e-6;\n if (farPlane <= nearPlane + EPS) {\n throw new ShadowInvalidConfigError('shadowDistance', farPlane, nearPlane + EPS);\n }\n\n const result = new Float32Array(cascadeCount);\n const m = cascadeCount;\n const n = nearPlane;\n const f = farPlane;\n const ratio = f / n;\n\n for (let i = 1; i <= m; i++) {\n const t = i / m;\n const logPart = n * ratio ** t;\n const uniformPart = n + t * (f - n);\n result[i - 1] = splitLambda * logPart + (1 - splitLambda) * uniformPart;\n }\n\n return result;\n}\n\n// feat-20260612-point-light-shadows-urp-hdrp M1 / T-M1-5 (plan-strategy §D-3,\n// requirements §5.3): 6-face view-proj matrix table for one omnidirectional\n// shadow caster.\n//\n// Face order matches WebGPU cube layer convention (also LearnOpenGL 5.3.2):\n// 0 (+X) | look=(+1, 0, 0) | up=(0, -1, 0)\n// 1 (-X) | look=(-1, 0, 0) | up=(0, -1, 0)\n// 2 (+Y) | look=(0, +1, 0) | up=(0, 0, +1)\n// 3 (-Y) | look=(0, -1, 0) | up=(0, 0, -1)\n// 4 (+Z) | look=(0, 0, +1) | up=(0, -1, 0)\n// 5 (-Z) | look=(0, 0, -1) | up=(0, -1, 0)\n//\n// Projection: WebGPU [0, 1] NDC perspective (mat4.perspective short name).\n// fov=90deg, aspect=1, near/far from PointLightShadow component.\nconst POINT_SHADOW_FACE_LOOK: readonly Vec3[] = [\n vec3.create(1, 0, 0),\n vec3.create(-1, 0, 0),\n vec3.create(0, 1, 0),\n vec3.create(0, -1, 0),\n vec3.create(0, 0, 1),\n vec3.create(0, 0, -1),\n];\nconst POINT_SHADOW_FACE_UP: readonly Vec3[] = [\n vec3.create(0, -1, 0),\n vec3.create(0, -1, 0),\n vec3.create(0, 0, 1),\n vec3.create(0, 0, -1),\n vec3.create(0, -1, 0),\n vec3.create(0, -1, 0),\n];\n\n/**\n * Build 6 face view-proj matrices for an omnidirectional shadow caster\n * (point-light cube map). Returns 6 mat4 (column-major 16-float each) in face\n * order [+X, -X, +Y, -Y, +Z, -Z] matching WebGPU cube layer convention.\n *\n * Each matrix is `proj * view` where:\n * - `view = lookAt(lightPos, lightPos + faceLook[i], faceUp[i])`\n * - `proj = perspective(PI/2, 1, near, far)` (WebGPU [0, 1] NDC short name)\n *\n * The returned `Mat4[]` length is always exactly 6. Caller can flatten into a\n * 96-float (6 mat4) Float32Array for UBO upload (T-M1-7).\n *\n * @param lightPos world-space position of the point light (from companion Transform)\n * @param near near plane distance (PointLightShadow.nearPlane)\n * @param far far plane distance (PointLightShadow.farPlane)\n */\nexport function buildPointShadowMatrices(lightPos: Vec3, near: number, far: number): Mat4[] {\n const fovY = Math.PI / 2; // 90 deg\n const aspect = 1;\n const proj = mat4.create();\n mat4.perspective(proj, fovY, aspect, near, far);\n\n const out: Mat4[] = [];\n for (let i = 0; i < 6; i++) {\n // biome-ignore lint/style/noNonNullAssertion: i in [0..6) and arrays are length-6 const\n const look = POINT_SHADOW_FACE_LOOK[i]!;\n // biome-ignore lint/style/noNonNullAssertion: i in [0..6) and arrays are length-6 const\n const up = POINT_SHADOW_FACE_UP[i]!;\n const target = vec3.create(\n (lightPos[0] ?? 0) + (look[0] ?? 0),\n (lightPos[1] ?? 0) + (look[1] ?? 0),\n (lightPos[2] ?? 0) + (look[2] ?? 0),\n );\n const view = mat4.create();\n mat4.lookAt(view, lightPos, target, up);\n const vp = mat4.create();\n mat4.multiply(vp, proj, view);\n out.push(vp);\n }\n return out;\n}\n\n/**\n * bug-20260710-editor-cross-world-shadow: the camera-frustum subset of\n * {@link CameraSnapshot} that the directional-CSM matrix builder consumes.\n * Extracted so the builder can run both inside {@link extractFrame} (single\n * world) AND at the {@link extractFrames} merge layer, where the camera and the\n * directional light may originate in DIFFERENT worlds (the editor\n * editorWorld/sceneWorld super-composite). A cameraless world produces zero\n * lightViewProj matrices, so the merge layer MUST recompute using the surfaced\n * camera — see {@link computeDirectionalCsm}.\n */\nexport interface CsmCameraData {\n readonly world: Float32Array;\n readonly fov: number;\n readonly aspect: number;\n readonly near: number;\n readonly far: number;\n readonly projection: 'perspective' | 'orthographic';\n readonly orthoLeft: number;\n readonly orthoRight: number;\n readonly orthoBottom: number;\n readonly orthoTop: number;\n}\n\n/**\n * bug-20260710-editor-cross-world-shadow: the raw directional-shadow config a\n * DirectionalLight carries, threaded onto {@link ExtractedLights} so the merge\n * layer can recompute CSM matrices against the surfaced camera. Distinct from\n * the *computed* outputs (lightViewProj / splitPlanes) also on ExtractedLights.\n */\nexport interface DirectionalCsmConfig {\n readonly cascadeCount: number;\n readonly splitLambda: number;\n readonly cascadeBlend: number;\n readonly mapSize: number;\n readonly shadowDistance: number;\n readonly shadowFilter: number;\n readonly shadowAngularRadius: number;\n readonly maxPenumbraTexels: number;\n}\n\n/**\n * bug-20260710-editor-cross-world-shadow: computed directional-CSM output —\n * the per-cascade light-view-projection matrices plus the derived cascade\n * metadata. Returned by {@link computeDirectionalCsm}; `undefined` when the\n * config or camera is missing (caller leaves the fields undefined).\n */\nexport interface DirectionalCsmResult {\n readonly lightViewProj: Float32Array[];\n readonly splitPlanes: Float32Array;\n readonly cascadeCount: number;\n readonly cascadeBlend: number;\n readonly shadowMapSize: number;\n readonly directionalShadowQuality: DirectionalShadowQuality;\n}\n\n/**\n * bug-20260710-editor-cross-world-shadow: pure directional-CSM matrix builder,\n * extracted verbatim from the former inline block in {@link extractFrame} (the\n * PSSM split + per-cascade frustum-slice AABB fit + orthographic light\n * projection). It is now a free function so BOTH the per-world extract and the\n * cross-world merge layer can call it — the merge layer is the only place that\n * pairs the first-hit directional light of one world with the surfaced camera\n * of another (editor super-composite). Returns `null` when there is no camera\n * to fit against (a cameraless world's directional light yields no matrices —\n * the caller leaves lightViewProj undefined rather than emitting zero matrices\n * that the WGSL reader would sample as NaN → \"fully lit\").\n *\n * Byte-identical to the prior inline computation for the single-world case\n * (same PSSM lambda, same toward-light Z reach RC-2 fix, same clip-space\n * matrix / tile-placement-in-shader split).\n */\nexport function computeDirectionalCsm(\n direction: Vec3,\n config: DirectionalCsmConfig,\n cameraData: CsmCameraData | undefined,\n): DirectionalCsmResult | null {\n const cascadeCount = Math.round(config.cascadeCount);\n // Coverage range: near from the active camera near (no separate near knob);\n // far is the component's shadowDistance. Fallback near (0.1) only when no\n // camera exists — but matrices are gated on cameraData below anyway.\n const sNear = cameraData?.near ?? 0.1;\n const sFar = config.shadowDistance;\n\n // PSSM split planes: [camera near, shadowDistance], not the camera far.\n const splits = pssmSplit(sNear, sFar, cascadeCount, config.splitLambda);\n // Light view matrix: camera at origin, looking along the light direction.\n const lightDirN = vec3.normalize(vec3.create(), direction);\n const lightTarget = vec3.create(lightDirN[0] ?? 0, lightDirN[1] ?? 0, lightDirN[2] ?? 0);\n const lightView = mat4.create();\n mat4.lookAt(lightView, vec3.create(0, 0, 0), lightTarget, vec3.create(0, 1, 0));\n\n // Camera view-projection for frustum-corner computation. Without a camera the\n // frustum cannot be fit — bail so the caller emits no matrices (undefined),\n // NOT zero matrices (which read as NaN in the shadow shader → no shadow).\n if (cameraData === undefined) return null;\n const camProj = mat4.create();\n if (cameraData.projection === 'orthographic') {\n mat4.orthographic(\n camProj,\n cameraData.orthoLeft,\n cameraData.orthoRight,\n cameraData.orthoTop,\n cameraData.orthoBottom,\n cameraData.near,\n cameraData.far,\n );\n } else {\n mat4.perspective(camProj, cameraData.fov, cameraData.aspect, cameraData.near, cameraData.far);\n }\n const camView = mat4.create();\n mat4.invert(camView, cameraData.world);\n const cameraVP = mat4.create();\n mat4.multiply(cameraVP, camProj, camView);\n\n const resultLightViewProjs: Float32Array[] = [];\n const cascadeFits: DirectionalShadowCascadeFit[] = [];\n\n // bug-20260619 RC-2 (AC-05): toward-light Z reach. Extend the near (toward-\n // light) bound of EVERY cascade to the toward-light extreme of the WHOLE\n // shadow frustum (sNear..sFar) so casters between the light and a slice are\n // admitted; X/Y stays per-cascade tight. Larger light-space z == closer to\n // the light (lookAt forward = eye-target), so the full-frustum max-z is the\n // toward-light reach used as -maxZ (the ortho near plane) per cascade.\n let lightSpaceMaxZFull = -Infinity;\n const fullCorners = computeFrustumCorners(\n cameraVP,\n cameraData.near,\n cameraData.far,\n sNear,\n sFar,\n cameraData.projection,\n );\n for (const ws of fullCorners) {\n const ls = vec3.create();\n mat4.transformVec3(ls, lightView, ws);\n if ((ls[2] ?? 0) > lightSpaceMaxZFull) lightSpaceMaxZFull = ls[2] ?? 0;\n }\n\n // Pre-allocate 4-cascade array; fill in the effective cascades.\n for (let cIdx = 0; cIdx < 4; cIdx++) {\n if (cIdx >= cascadeCount) {\n resultLightViewProjs.push(new Float32Array(16));\n continue;\n }\n const cascadeNear = cIdx === 0 ? sNear : (splits[cIdx - 1] ?? sFar);\n const cascadeFar = splits[cIdx] ?? sFar;\n const corners = computeFrustumCorners(\n cameraVP,\n cameraData.near,\n cameraData.far,\n cascadeNear,\n cascadeFar,\n cameraData.projection,\n );\n const lightMVP = mat4.clone(lightView);\n let minX = Infinity;\n let maxX = -Infinity;\n let minY = Infinity;\n let maxY = -Infinity;\n let minZ = Infinity;\n let maxZ = -Infinity;\n for (const ws of corners) {\n const ls = vec3.create();\n mat4.transformVec3(ls, lightMVP, ws);\n if ((ls[0] ?? 0) < minX) minX = ls[0] ?? 0;\n if ((ls[0] ?? 0) > maxX) maxX = ls[0] ?? 0;\n if ((ls[1] ?? 0) < minY) minY = ls[1] ?? 0;\n if ((ls[1] ?? 0) > maxY) maxY = ls[1] ?? 0;\n if ((ls[2] ?? 0) < minZ) minZ = ls[2] ?? 0;\n if ((ls[2] ?? 0) > maxZ) maxZ = ls[2] ?? 0;\n }\n // Orthographic projection from light-space AABB. RC-2: whole-frustum\n // toward-light extreme for the near bound; per-cascade far (minZ) + X/Y.\n const nearZ = Math.max(maxZ, lightSpaceMaxZFull);\n const orthoProj = mat4.create();\n mat4.orthographic(orthoProj, minX, maxX, maxY, minY, -nearZ, -minZ);\n // lightViewProj = orthoProj * lightView — pure clip-space [-1,1]. Atlas\n // tile placement is handled by the per-cascade viewport + fragment-side UV\n // math (evalDirectional), so shadow_caster.gl_Position stays clip-space.\n cascadeFits.push({\n split: splits[cIdx] ?? sFar,\n minX,\n maxX,\n minY,\n maxY,\n minZ,\n maxZ,\n });\n resultLightViewProjs.push(new Float32Array(mat4.multiply(mat4.create(), orthoProj, lightView)));\n }\n\n const projection = projectDirectionalShadow(\n cascadeFits,\n config.mapSize,\n config.shadowFilter ?? 2,\n config.shadowAngularRadius ?? 0.00465,\n config.maxPenumbraTexels ?? 32,\n );\n if (projection === undefined) return null;\n\n return {\n lightViewProj: resultLightViewProjs,\n splitPlanes: projection.splitPlanes,\n cascadeCount,\n cascadeBlend: config.cascadeBlend,\n shadowMapSize: config.mapSize,\n directionalShadowQuality: projection.directionalShadowQuality,\n };\n}\n\n/**\n * feat-20260709-editor-world-partition M1 / w4 (AC-08, plan-strategy §2 D-3):\n * the owner index that previously served BOTH cameras and singleton render\n * resources (skylight / skybox / postProcessParams) is split into two\n * independent indices. `cameraOwner` selects the world whose cameras are\n * surfaced; `resourceOwner` selects the world whose singleton resources are\n * surfaced. A single number is accepted as the backward-compatible legacy form\n * where `cameraOwner === resourceOwner === owner` (single-world callers +\n * frame-loop stay byte-identical; the hard `{ owner }` cutover lands in M2).\n */\nexport interface ExtractFramesOwner {\n readonly cameraOwner: number;\n readonly resourceOwner: number;\n}\n\nexport interface PreparedExtractContext {\n readonly materialContext?: MaterialCookProgramContext | undefined;\n readonly assets: AssetRegistry | null | undefined;\n readonly pipelineState: ExtractPipelineSurface | null | undefined;\n readonly materialSnapshotCache: MaterialSnapshotCache | undefined;\n /** `undefined` keeps direct extractFrame's local Fog semantics; `null` means\n * the frame owner already selected that no Fog is present for this world. */\n readonly resourceOwnerFog: FogFrame | null | undefined;\n readonly cull: 'self' | 'none' | 'external';\n readonly cullCameras: readonly CameraSnapshot[] | undefined;\n readonly renderables: 'full' | 'none';\n /** Restrict renderable extraction to these entities while still reading frame resources. */\n readonly renderableEntities: ReadonlySet<number> | undefined;\n /** Keep authored-hidden renderables in the persistent source projection. */\n readonly retainHidden: boolean;\n readonly visibility: VisibilitySnapshot;\n /** Producer-owned artifact lookup; extraction only, never record-time asset reads. */\n readonly getMaterialShaderArtifact:\n | ((materialShaderId: string) => MaterialShaderArtifact | undefined)\n | undefined;\n /** Renderer-owned canonical source for explicit large instance collections. */\n readonly instanceCollections: InstanceProjectionStore | undefined;\n}\n\nconst ALL_VISIBLE: VisibilitySnapshot = {\n diagnostics: [],\n hasAnyIntent: false,\n hasAnyHiddenIntent: false,\n get: () => undefined,\n effective: () => 'visible',\n};\n\nfunction collectCameraSnapshots(world: World): CameraSnapshot[] {\n const worldInternal = createWorldInternalView(world);\n const cameras: CameraSnapshot[] = [];\n const cameraQuery = world\n .query({ read: [Camera], optional: [MotionBlur], with: [Transform, GlobalTransform] })\n .unwrap();\n for (const row of cameraQuery) {\n const cam = row.get(Camera);\n const motionBlur = row.get(MotionBlur);\n const entity = row.entity;\n const view = worldInternal._getArrayView(entity, GlobalTransform, 'world');\n if (view === undefined) continue;\n const worldMat = new Float32Array(view);\n const target = resolveCameraTarget(world, cam.target);\n cameras.push({\n entityKey: entity as number,\n ...(target === undefined ? {} : { target }),\n historyVersion: cam.historyVersion,\n position: mat4.getTranslation(vec3.create(), worldMat),\n world: worldMat,\n fov: cam.fov,\n aspect: cam.aspect,\n near: cam.near,\n far: cam.far,\n projection: cameraProjectionFromF32(cam.projection),\n orthoLeft: cam.left,\n orthoRight: cam.right,\n orthoBottom: cam.bottom,\n orthoTop: cam.top,\n tonemap: tonemapFromF32(cam.tonemap),\n exposure: cam.exposure,\n whitePoint: cam.whitePoint,\n antialias: antialiasFromF32(cam.antialias),\n bloom: bloomEnabledFromF32(cam.bloom),\n bloomThreshold: cam.bloomThreshold,\n bloomIntensity: cam.bloomIntensity,\n bloomBlurRadius: cam.bloomBlurRadius,\n clearColor: [\n cam.clearColor[0] ?? 0,\n cam.clearColor[1] ?? 0,\n cam.clearColor[2] ?? 0,\n cam.clearColor[3] ?? 1,\n ],\n ...(motionBlur === undefined\n ? {}\n : {\n motionBlur: {\n shutterAngle: motionBlur.shutterAngle,\n maxRadiusPixels: motionBlur.maxRadiusPixels,\n sampleCount: motionBlur.sampleCount,\n },\n }),\n });\n }\n return cameras;\n}\n\nexport function collectCubeCameraSnapshots(world: World): CubeCameraSnapshot[] {\n const worldInternal = createWorldInternalView(world);\n const snapshots: CubeCameraSnapshot[] = [];\n const query = world.query({ read: [CubeCamera], with: [Transform, GlobalTransform] }).unwrap();\n for (const row of query) {\n const camera = row.get(CubeCamera);\n const target = resolveCameraTarget(world, camera.target);\n if (target === undefined) continue;\n const view = worldInternal._getArrayView(row.entity, GlobalTransform, 'world');\n if (view === undefined) continue;\n snapshots.push({\n entityKey: row.entity as number,\n target,\n position: [view[12] ?? 0, view[13] ?? 0, view[14] ?? 0],\n near: camera.near,\n far: camera.far,\n updateIntent: cubeCameraUpdateIntentFromF32(camera.updateIntent),\n requestVersion: camera.requestVersion,\n faceBudget: camera.faceBudget,\n });\n }\n return snapshots;\n}\n\nexport function collectReflectionProbeFacts(world: World): ReflectionProbeFact[] {\n const worldInternal = createWorldInternalView(world);\n const facts: ReflectionProbeFact[] = [];\n const query = world\n .query({ read: [ReflectionProbe], with: [Transform, GlobalTransform] })\n .unwrap();\n for (const row of query) {\n const probe = row.get(ReflectionProbe);\n const view = worldInternal._getArrayView(row.entity, GlobalTransform, 'world');\n if (view === undefined) {\n continue;\n }\n facts.push({\n worldId: 0,\n entityKey: row.entity as number,\n center: [view[12] ?? 0, view[13] ?? 0, view[14] ?? 0],\n halfExtents: [\n probe.halfExtents[0] ?? 0,\n probe.halfExtents[1] ?? 0,\n probe.halfExtents[2] ?? 0,\n ],\n priority: probe.priority,\n intensity: probe.intensity,\n resolution: probe.resolution,\n revision: probe.invalidationVersion,\n updateIntent: reflectionProbeUpdateIntentFromF32(probe.updateIntent),\n invalidationVersion: probe.invalidationVersion,\n });\n }\n return facts;\n}\n\ninterface CameraRoleSelection {\n readonly display: readonly CameraSnapshot[];\n readonly auxiliary: readonly CameraSnapshot[];\n}\n\nexport function selectCameraRoles(world: World): CameraRoleSelection {\n const cameras = collectCameraSnapshots(world);\n const displayEntities = cameras\n .filter((camera) => camera.target === undefined)\n .map((camera) => camera.entityKey ?? 0);\n const activeCameraIndex = selectActiveCameraIndex(\n displayEntities,\n getActiveCamera(world)?.entity,\n );\n const displayEntityKey = displayEntities[activeCameraIndex] ?? displayEntities[0];\n const display =\n displayEntityKey === undefined\n ? []\n : cameras.filter((camera) => camera.entityKey === displayEntityKey);\n const candidates: CameraTargetCandidate[] = cameras.map((camera) => ({\n worldId: 0,\n entityKey: camera.entityKey ?? 0,\n ...(camera.target === undefined ? {} : { target: camera.target }),\n requestVersion: 0,\n update: 'continuous',\n }));\n const selected = selectCameraTargetViews(candidates, {\n ...(displayEntityKey === undefined ? {} : { displayEntityKey }),\n budget: 1,\n });\n const auxiliary = selected.auxiliary.flatMap((candidate) =>\n cameras.filter((camera) => camera.entityKey === candidate.entityKey),\n );\n return { display, auxiliary };\n}\n\nexport function extractCameraSnapshots(world: World): CameraSnapshot[] {\n return [...selectCameraRoles(world).display];\n}\n\nexport function extractCameraTargetSnapshots(world: World): readonly CameraSnapshot[] {\n return selectCameraRoles(world).auxiliary;\n}\n\nexport function tonemapParams(camera: CameraSnapshot): Uint8Array {\n const bytes = new ArrayBuffer(16);\n const floats = new Float32Array(bytes);\n const integers = new Uint32Array(bytes);\n floats[0] = camera.exposure;\n floats[1] = camera.whitePoint;\n integers[2] = tonemapToU32(camera.tonemap);\n return new Uint8Array(bytes);\n}\n\nexport function prepareExtractContext(\n world: World,\n options: {\n readonly materialContext?: MaterialCookProgramContext;\n readonly assets?: AssetRegistry | null;\n readonly pipelineState?: ExtractPipelineSurface | null;\n readonly materialSnapshotCache?: MaterialSnapshotCache;\n readonly resourceOwnerFog?: FogFrame | null;\n readonly cull?: 'self' | 'none' | 'external';\n readonly cullCameras?: readonly CameraSnapshot[];\n readonly renderables?: 'full' | 'none';\n readonly renderableEntities?: ReadonlySet<number>;\n readonly retainHidden?: boolean;\n readonly getMaterialShaderArtifact?: (\n materialShaderId: string,\n ) => MaterialShaderArtifact | undefined;\n readonly instanceCollections?: InstanceProjectionStore;\n } = {},\n): PreparedExtractContext {\n const renderables = options.renderables ?? 'full';\n return {\n materialContext: options.materialContext,\n assets: options.assets,\n pipelineState: options.pipelineState,\n materialSnapshotCache: options.materialSnapshotCache,\n resourceOwnerFog: options.resourceOwnerFog,\n cull: options.cull ?? 'self',\n cullCameras: options.cullCameras,\n renderables,\n renderableEntities: options.renderableEntities,\n retainHidden: options.retainHidden ?? false,\n visibility: renderables === 'none' ? ALL_VISIBLE : resolveVisibility(world),\n getMaterialShaderArtifact: options.getMaterialShaderArtifact,\n instanceCollections: options.instanceCollections,\n };\n}\n\nconst fogQueries = new WeakMap<World, Query<readonly [typeof Fog]>>();\nconst fogLkgStates = new WeakMap<\n World,\n { lkg: FogFrame | undefined; failure: FogSelectionFailure | undefined }\n>();\n\nexport function fogState(world: World): {\n lkg: FogFrame | undefined;\n failure: FogSelectionFailure | undefined;\n} {\n const existing = fogLkgStates.get(world);\n if (existing !== undefined) return existing;\n const created = { lkg: undefined, failure: undefined };\n fogLkgStates.set(world, created);\n return created;\n}\n\nexport function selectFogFrame(world: World): FogFrame | undefined {\n // Query compilation is owned once per World; Query refreshes its matched\n // tables when the ECS structure changes, while iteration reads current Fog\n // values. This keeps the frame boundary free of repeated descriptor work.\n const fogCandidates: FogCandidate[] = [];\n let fogQuery = fogQueries.get(world);\n if (fogQuery === undefined) {\n fogQuery = world.query({ read: [Fog] }).unwrap();\n fogQueries.set(world, fogQuery);\n }\n for (const row of fogQuery) {\n const value = row.get(Fog);\n fogCandidates.push({\n entityKey: row.entity,\n color: [value.color[0] ?? 0, value.color[1] ?? 0, value.color[2] ?? 0],\n density: value.density,\n heightFalloff: value.heightFalloff,\n maxOpacity: value.maxOpacity,\n });\n }\n const fogSelection = selectEnvironment({\n environments: [],\n fogs: fogCandidates,\n suns: [],\n lane: 'direct',\n });\n const state = fogState(world);\n if (fogSelection.ok) {\n state.lkg = fogSelection.value.fog;\n state.failure = undefined;\n return fogSelection.value.fog;\n }\n state.failure = {\n code: fogSelection.error.code,\n expected: fogSelection.error.expected,\n hint: fogSelection.error.hint,\n detail: Object.freeze({ ...fogSelection.error.detail }),\n };\n routeWorldError(world, fogSelection.error, {\n systemName: 'RenderSystem.extract (fog-selection)',\n });\n if (state.lkg !== undefined) return state.lkg;\n throw fogSelection.error;\n}\n\nexport function textureDigest(texture: TextureAsset): string {\n // The render inspection needs a stable identity token, not a second byte\n // store. FNV-1a is deterministic, synchronous, and deliberately labelled\n // as a non-cryptographic digest so it cannot be mistaken for Catalog proof.\n let hash = 2166136261;\n for (const byte of texture.data) hash = Math.imul(hash ^ byte, 16777619) >>> 0;\n return `fnv1a:${hash.toString(16).padStart(8, '0')}`;\n}\n\nexport function extractVolumeSnapshot(\n world: World,\n assets: AssetRegistry | null | undefined,\n worldInternal: WorldInternalView,\n): ExtractedVolumetricFog | undefined {\n const query = world.query({ read: [VolumetricFog] }).unwrap();\n const authorings: VolumetricFogAuthoring[] = [];\n let selectedLight:\n | {\n readonly entity: EntityHandle;\n readonly kind: 'directional' | 'point' | 'spot';\n readonly pointLightEntity?: EntityHandle;\n readonly spotLightEntity?: EntityHandle;\n }\n | undefined;\n let first:\n | {\n readonly densityHandle: Handle<'TextureAsset', 'shared'>;\n readonly densityAsset: TextureAsset;\n readonly guid: string;\n }\n | undefined;\n\n for (const row of query) {\n const source = row.get(VolumetricFog);\n if (source.light === null) continue;\n const selected = resolveSelectedVolumetricLight(world, source.light);\n if (selected.status === 'available') {\n const pairSpot = source.spotLight === null ? undefined : source.spotLight;\n selectedLight ??= {\n entity: selected.entity,\n kind: selected.kind,\n ...(selected.kind === 'point' ? { pointLightEntity: selected.entity } : {}),\n ...(pairSpot === undefined ? {} : { spotLightEntity: pairSpot }),\n };\n }\n const densityHandle = toShared<'TextureAsset'>(Math.round(Number(source.density)));\n const resolved = resolveAssetHandle<TextureAsset>(world, densityHandle);\n if (!resolved.ok || resolved.value.kind !== 'texture') {\n worldInternal._routeError(\n resolved.ok\n ? new RhiError({\n code: 'asset-not-registered',\n expected: 'VolumetricFog.density resolves to a TextureAsset',\n hint: 'load a TextureAsset before assigning it to VolumetricFog.density',\n detail: { assetHandle: Number(densityHandle) },\n })\n : resolved.error,\n { severity: Severity.Error, systemName: 'RenderSystem.extract (volumetric-density)' },\n );\n return { status: 'degraded' };\n }\n const densityAsset = resolved.value;\n const guid = assets?.guidOf(densityAsset) ?? `handle:${Number(densityHandle)}`;\n const shape = densityAsset.shape;\n const density: VolumeDensityBinding =\n shape.viewDimension === '3d'\n ? {\n guid,\n generation: 1,\n shape: {\n viewDimension: '3d',\n extent: {\n width: shape.extent.width,\n height: shape.extent.height,\n depth: shape.extent.depth,\n },\n },\n format: densityAsset.format,\n colorSpace: densityAsset.colorSpace,\n }\n : {\n guid,\n generation: 1,\n shape: {\n viewDimension: shape.viewDimension,\n extent:\n shape.viewDimension === '2d-array'\n ? {\n width: shape.extent.width,\n height: shape.extent.height,\n layers: shape.extent.layers,\n }\n : { width: shape.extent.width, height: shape.extent.height },\n },\n format: densityAsset.format,\n colorSpace: densityAsset.colorSpace,\n };\n const authoring: VolumetricFogAuthoring = {\n light: source.light,\n density,\n bounds: {\n min: [source.boundsMin[0] ?? 0, source.boundsMin[1] ?? 0, source.boundsMin[2] ?? 0],\n max: [source.boundsMax[0] ?? 0, source.boundsMax[1] ?? 0, source.boundsMax[2] ?? 0],\n },\n extinction: [source.extinction[0] ?? 0, source.extinction[1] ?? 0, source.extinction[2] ?? 0],\n albedo: [source.albedo[0] ?? 0, source.albedo[1] ?? 0, source.albedo[2] ?? 0],\n emission: [source.emission[0] ?? 0, source.emission[1] ?? 0, source.emission[2] ?? 0],\n anisotropy: source.anisotropy,\n maxDistance: source.maxDistance,\n };\n authorings.push(authoring);\n first ??= { densityHandle, densityAsset, guid };\n }\n\n if (authorings.length === 0) return undefined;\n const extracted = extractVolumetricFog(authorings);\n if (!extracted.ok) {\n worldInternal._routeError(extracted.error, {\n severity: Severity.Error,\n systemName: 'RenderSystem.extract (volumetric-fog)',\n });\n return {\n status: 'degraded',\n ...(first === undefined\n ? {}\n : {\n densityHandle: first.densityHandle,\n densityAsset: first.densityAsset,\n guid: first.guid,\n generation: 1,\n digest: textureDigest(first.densityAsset),\n ...(selectedLight === undefined\n ? {}\n : {\n lightEntity: selectedLight.entity,\n lightKind: selectedLight.kind,\n ...(selectedLight.pointLightEntity === undefined\n ? {}\n : { pointLightEntity: selectedLight.pointLightEntity }),\n ...(selectedLight.spotLightEntity === undefined\n ? {}\n : { spotLightEntity: selectedLight.spotLightEntity }),\n }),\n }),\n };\n }\n if (extracted.value.status === 'off' || first === undefined) return { status: 'off' };\n const selectedLightFields =\n selectedLight === undefined\n ? {}\n : {\n lightEntity: selectedLight.entity,\n lightKind: selectedLight.kind,\n ...(selectedLight.pointLightEntity === undefined\n ? {}\n : { pointLightEntity: selectedLight.pointLightEntity }),\n ...(selectedLight.spotLightEntity === undefined\n ? {}\n : { spotLightEntity: selectedLight.spotLightEntity }),\n };\n return {\n status: 'available',\n fog: extracted.value.fog,\n densityHandle: first.densityHandle,\n densityAsset: first.densityAsset,\n guid: first.guid,\n generation: 1,\n digest: textureDigest(first.densityAsset),\n ...selectedLightFields,\n };\n}\n\n// Source contract anchor: the spot-light query remains single-source in this\n// extraction boundary (`const spotLightQuery = world.query({ read: [SpotLight] })`)\n// and snapshots retain the\n// normalized `const dirN = vec3.create(` then `direction: dirN` fields; the implementation body lives in the\n// tail module to keep this owner below the physical line budget. The tail keeps\n// the extract integration bound to deriveInstancesUnionBounds, rather than\n// introducing a second bounds ledger in this forwarding owner.\n\nexport { defaultMaterialSnapshot, extractFrame, extractFrames } from './render-system-extract-tail';\n","import { R_MIN } from '@forgeax/engine-types';\nimport type { ProbeBlendInspection } from '../inspection-types';\nimport {\n PROBE_BLEND_RECORD_BYTE_SIZE,\n PROBE_BLEND_RECORD_CAPACITY,\n type ProbeBlendRecord,\n type ProbeBlendRecordSentinel,\n} from './probe-blend-record';\n\nexport const PROBE_R_MIN = R_MIN;\nexport const PROBE_MAX_CONTRIBUTORS = PROBE_BLEND_RECORD_CAPACITY;\n\nexport interface ProbeBlendContributor {\n readonly identity: string;\n readonly admitted: boolean;\n readonly distance: number;\n readonly radius: number;\n readonly irradiance: ArrayLike<number>;\n}\n\nexport interface ProbeBlendInput {\n readonly contributors: readonly ProbeBlendContributor[];\n readonly normal: readonly [number, number, number];\n readonly skyIrradiance: readonly [number, number, number];\n readonly radiusMinimum?: number;\n}\n\nexport interface ProbeSceneObjectInput {\n readonly objectKey: number;\n readonly generation: number;\n readonly position: readonly [number, number, number];\n}\n\nexport interface ProbeSceneProbeInput {\n readonly identity: string;\n readonly position: readonly [number, number, number];\n readonly radius: number;\n readonly irradiance: ArrayLike<number>;\n readonly admitted: boolean;\n}\n\nexport interface ProbeAdmissionReceipt {\n readonly activeIdentities: readonly string[];\n readonly admittedIdentities: readonly string[];\n readonly rejectedIdentities: readonly string[];\n readonly stableOrder: readonly string[];\n readonly capacity: number;\n readonly overflowReason?: 'active-count-exceeds-capacity';\n readonly scaleRadius: number;\n readonly finite: boolean;\n}\n\nexport type ProbeAdmissionError = {\n readonly code: 'capacity-exceeded' | 'invalid-admitted-prefix';\n readonly activeCount: number;\n readonly capacity: number;\n readonly receipt: ProbeAdmissionReceipt;\n};\n\nexport interface ProbeAdmissionResult {\n readonly admitted: readonly ProbeBlendContributor[];\n readonly active: readonly ProbeBlendContributor[];\n readonly rejected: readonly ProbeBlendContributor[];\n readonly receipt: ProbeAdmissionReceipt;\n readonly error?: ProbeAdmissionError;\n}\n\nexport interface ProbeSceneProjectionInput {\n readonly objects: readonly ProbeSceneObjectInput[];\n readonly probes: readonly ProbeSceneProbeInput[];\n /** Optional analytic oracle input; records never store or replace Sky. */\n readonly skyIrradiance?: readonly [number, number, number];\n readonly sky?: {\n readonly available: boolean;\n readonly identity?: string;\n readonly sourceKey?: string;\n readonly irradiance: readonly [number, number, number];\n readonly fallbackReason?: string;\n };\n readonly worldRevision?: number;\n readonly lastKnownGood?: boolean;\n}\n\nexport interface ProbeSceneProjectionResult {\n readonly records: readonly ProbeBlendRecord[];\n readonly contributors: readonly ProbeBlendTerm[];\n readonly activeContributorCount: number;\n readonly admittedProbeCount: number;\n readonly coverage: number;\n readonly skyResidualFraction: number;\n readonly dirtyReasons: readonly ProbeSceneDirtyReason[];\n readonly affectedObjectKeys: readonly number[];\n readonly visits: number;\n readonly allocations: number;\n readonly uploads: number;\n readonly receipt: ProbeAdmissionReceipt;\n readonly error?: ProbeAdmissionError;\n}\n\nexport type ProbeSceneDirtyReason =\n | 'object-boundary'\n | 'probe-fact'\n | 'sky'\n | 'object-position'\n | 'world'\n | 'generation';\n\nexport interface ProbeBlendTerm {\n readonly identity: string;\n readonly distance: number;\n readonly radius: number;\n readonly coverage: number;\n readonly q: number;\n readonly scaledQ: number;\n readonly qHat: number;\n readonly alpha: number;\n}\n\nexport interface ProbeBlendResult {\n readonly terms: readonly ProbeBlendTerm[];\n readonly rStar: number;\n readonly Q: number;\n readonly C: number;\n readonly S: number;\n readonly SHPreblend: readonly number[];\n readonly skyIrradiance: readonly [number, number, number];\n readonly diffuse: readonly [number, number, number];\n readonly finite: boolean;\n readonly receipt: ProbeAdmissionReceipt;\n readonly error?: ProbeAdmissionError;\n readonly scaledQLogOffset: number;\n}\n\nconst SH_C0 = 0.28209479177387814;\nconst SH_C1 = 0.4886025119029199;\nconst SH_C2 = 1.0925484305920792;\nconst SH_C20 = 0.31539156525252005;\nconst SH_C22 = 0.5462742152960396;\n\nfunction finiteVector(values: ArrayLike<number>, length: number): boolean {\n if (values.length !== length) return false;\n for (let index = 0; index < values.length; index += 1) {\n if (!Number.isFinite(values[index])) return false;\n }\n return true;\n}\n\nfunction contributorIsActive(probe: ProbeBlendContributor, radiusMinimum: number): boolean {\n return (\n probe.admitted &&\n Number.isFinite(probe.distance) &&\n probe.distance >= 0 &&\n Number.isFinite(probe.radius) &&\n probe.radius >= radiusMinimum &&\n probe.distance < probe.radius &&\n finiteVector(probe.irradiance, 27)\n );\n}\n\nfunction emptyReceipt(radiusMinimum: number): ProbeAdmissionReceipt {\n return {\n activeIdentities: [],\n admittedIdentities: [],\n rejectedIdentities: [],\n stableOrder: [],\n capacity: PROBE_MAX_CONTRIBUTORS,\n scaleRadius: radiusMinimum,\n finite: true,\n };\n}\n\n/** Admission is the only owner allowed to order and bound probe candidates. */\nexport function admitProbeContributors(\n candidates: readonly ProbeBlendContributor[],\n radiusMinimum = PROBE_R_MIN,\n): ProbeAdmissionResult {\n const active = candidates.filter((candidate) => contributorIsActive(candidate, radiusMinimum));\n const overflowed = active.length > PROBE_MAX_CONTRIBUTORS;\n // Admission is a deterministic stable prefix, not an all-or-nothing gate.\n // Sort the complete active set by identity before clipping so query order\n // cannot change the selected contributors.\n const stableActive = active\n .slice()\n .sort((left, right) => left.identity.localeCompare(right.identity));\n const admitted = stableActive.slice(0, PROBE_MAX_CONTRIBUTORS);\n const rejected = stableActive.slice(PROBE_MAX_CONTRIBUTORS);\n const scaleRadius = active.reduce(\n (minimum, candidate) => Math.min(minimum, candidate.radius),\n active[0]?.radius ?? radiusMinimum,\n );\n const receipt: ProbeAdmissionReceipt = {\n activeIdentities: stableActive.map((candidate) => candidate.identity),\n admittedIdentities: admitted.map((candidate) => candidate.identity),\n rejectedIdentities: rejected.map((candidate) => candidate.identity),\n stableOrder: admitted.map((candidate) => candidate.identity),\n capacity: PROBE_MAX_CONTRIBUTORS,\n ...(overflowed ? { overflowReason: 'active-count-exceeds-capacity' as const } : {}),\n scaleRadius,\n finite: stableActive.every((candidate) => Number.isFinite(candidate.radius)),\n };\n return {\n active: stableActive,\n admitted,\n rejected,\n receipt,\n ...(overflowed\n ? {\n error: {\n code: 'capacity-exceeded' as const,\n activeCount: active.length,\n capacity: PROBE_MAX_CONTRIBUTORS,\n receipt,\n },\n }\n : {}),\n };\n}\n\nfunction invalidInputResult(\n radiusMinimum: number,\n code: ProbeAdmissionError['code'],\n): ProbeBlendResult {\n const receipt = emptyReceipt(radiusMinimum);\n return {\n terms: [],\n rStar: radiusMinimum,\n Q: 0,\n C: 0,\n S: 1,\n SHPreblend: new Array<number>(27).fill(0),\n skyIrradiance: [0, 0, 0],\n diffuse: [0, 0, 0],\n finite: false,\n receipt,\n scaledQLogOffset: 0,\n error: { code, activeCount: 0, capacity: PROBE_MAX_CONTRIBUTORS, receipt },\n };\n}\n\n/** Neumaier compensated sum in JavaScript's IEEE-754 binary64 number type. */\nexport function neumaierSum(values: readonly number[]): number {\n let sum = 0;\n let correction = 0;\n for (const value of values) {\n const next = sum + value;\n if (Math.abs(sum) >= Math.abs(value)) correction += sum - next + value;\n else correction += value - next + sum;\n sum = next;\n }\n return sum + correction;\n}\n\n/** Round a finite analytic value at the single f32 boundary. */\nexport function roundProbeToF32(value: number): number | undefined {\n return Number.isFinite(value) ? new Float32Array([value])[0] : undefined;\n}\n\nexport function scaledProbeWeight(\n distance: number,\n radius: number,\n radiusMinimum = PROBE_R_MIN,\n): { readonly coverage: number; readonly q: number } {\n if (\n !Number.isFinite(distance) ||\n distance < 0 ||\n !Number.isFinite(radius) ||\n radius < radiusMinimum ||\n distance >= radius\n ) {\n return { coverage: 0, q: 0 };\n }\n const ratio = distance / radius;\n const coverage = 1 - ratio * ratio;\n // q is intentionally diagnostic only. The kernel consumes scaledQ below.\n return { coverage, q: coverage / (radius * radius) };\n}\n\nfunction sh9Irradiance(\n coefficients: readonly number[],\n normal: readonly [number, number, number],\n): number[] {\n const x = normal[0];\n const y = normal[1];\n const z = normal[2];\n const basis = [\n SH_C0,\n SH_C1 * y,\n SH_C1 * z,\n SH_C1 * x,\n SH_C2 * x * y,\n SH_C2 * y * z,\n SH_C20 * (3 * z * z - 1),\n SH_C2 * x * z,\n SH_C22 * (x * x - y * y),\n ];\n const result = [0, 0, 0];\n for (let band = 0; band < basis.length; band += 1) {\n const factor = basis[band] ?? 0;\n const offset = band * 3;\n result[0] = (result[0] ?? 0) + (coefficients[offset] ?? 0) * factor;\n result[1] = (result[1] ?? 0) + (coefficients[offset + 1] ?? 0) * factor;\n result[2] = (result[2] ?? 0) + (coefficients[offset + 2] ?? 0) * factor;\n }\n return result;\n}\n\nfunction vectorNeumaierSum(values: readonly (readonly number[])[], width: number): number[] {\n return Array.from({ length: width }, (_, channel) =>\n neumaierSum(values.map((value) => value[channel] ?? 0)),\n );\n}\n\ninterface ProbeBlendCoefficients {\n readonly terms: readonly ProbeBlendTerm[];\n readonly rStar: number;\n readonly Q: number;\n readonly C: number;\n readonly S: number;\n readonly SHPreblend: readonly number[];\n readonly receipt: ProbeAdmissionReceipt;\n readonly finite: boolean;\n readonly scaledQLogOffset: number;\n}\n\nfunction blendProbeCoefficients(\n contributors: readonly ProbeBlendContributor[],\n radiusMinimum: number,\n): ProbeBlendCoefficients | undefined {\n if (\n contributors.length > PROBE_MAX_CONTRIBUTORS ||\n contributors.some((contributor) => !contributorIsActive(contributor, radiusMinimum))\n ) {\n return undefined;\n }\n const rStar = contributors.reduce(\n (minimum, contributor) => Math.min(minimum, contributor.radius),\n contributors[0]?.radius ?? radiusMinimum,\n );\n const rawTerms = contributors.map((contributor) => {\n const { coverage } = scaledProbeWeight(contributor.distance, contributor.radius, radiusMinimum);\n const scaledRatio = rStar / contributor.radius;\n return {\n contributor,\n coverage,\n // Diagnostic q is never used for Q, alpha, C, or SH accumulation.\n q: coverage / (contributor.radius * contributor.radius),\n scaledQ: coverage * scaledRatio * scaledRatio,\n };\n });\n // The frozen minimum radius bounds rStar/r_i by one. The kernel consumes\n // only scaledQ, never diagnostic q or a reciprocal-square value.\n const scaledQLogOffset = 0;\n const finiteTerms = rawTerms;\n if (finiteTerms.some((term) => !Number.isFinite(term.scaledQ))) return undefined;\n const Q = neumaierSum(finiteTerms.map((term) => term.scaledQ));\n const terms = finiteTerms.map((term) => ({\n identity: term.contributor.identity,\n distance: term.contributor.distance,\n radius: term.contributor.radius,\n coverage: term.coverage,\n q: term.q,\n scaledQ: term.scaledQ,\n qHat: term.scaledQ,\n alpha: Q > 0 ? term.scaledQ / Q : 0,\n }));\n let product = 1;\n for (const term of finiteTerms) product *= 1 - term.coverage;\n const C = 1 - product;\n const S = 1 - C;\n const weightedSh = finiteTerms.map((term) =>\n Array.from(term.contributor.irradiance, (value) => value * (Q > 0 ? term.scaledQ / Q : 0)),\n );\n const SHPreblend = vectorNeumaierSum(weightedSh, 27).map((value) => value * C);\n const finite =\n Number.isFinite(Q) &&\n Number.isFinite(C) &&\n Number.isFinite(S) &&\n SHPreblend.every(Number.isFinite) &&\n finiteTerms.every((term) => Number.isFinite(term.scaledQ));\n const receipt: ProbeAdmissionReceipt = {\n activeIdentities: contributors.map((contributor) => contributor.identity),\n admittedIdentities: contributors.map((contributor) => contributor.identity),\n rejectedIdentities: [],\n stableOrder: contributors.map((contributor) => contributor.identity),\n capacity: PROBE_MAX_CONTRIBUTORS,\n scaleRadius: rStar,\n finite,\n };\n return {\n terms,\n rStar,\n Q,\n C,\n S,\n SHPreblend,\n finite,\n receipt,\n scaledQLogOffset,\n };\n}\n\n/**\n * Evaluate the CPU analytic oracle. Sky is deliberately an explicit residual\n * input and never becomes a contributor or a q/Q term.\n */\nexport function blendLightProbes(input: ProbeBlendInput): ProbeBlendResult {\n const radiusMinimum = input.radiusMinimum ?? PROBE_R_MIN;\n const normal = input.normal;\n const sky = input.skyIrradiance;\n if (!finiteVector(normal, 3) || !finiteVector(sky, 3)) {\n return invalidInputResult(radiusMinimum, 'invalid-admitted-prefix');\n }\n const coefficients = blendProbeCoefficients(input.contributors, radiusMinimum);\n if (coefficients === undefined)\n return invalidInputResult(radiusMinimum, 'invalid-admitted-prefix');\n const shIrradiance = sh9Irradiance(coefficients.SHPreblend, normal);\n const diffuse = [0, 1, 2].map(\n (channel) => Math.max(shIrradiance[channel] ?? 0, 0) + coefficients.S * (sky[channel] ?? 0),\n ) as [number, number, number];\n return {\n ...coefficients,\n skyIrradiance: [sky[0], sky[1], sky[2]],\n diffuse,\n finite: coefficients.finite && diffuse.every(Number.isFinite),\n };\n}\n\nfunction vectorDistance(\n left: readonly [number, number, number],\n right: readonly [number, number, number],\n): number {\n const dx = left[0] - right[0];\n const dy = left[1] - right[1];\n const dz = left[2] - right[2];\n return Math.hypot(dx, dy, dz);\n}\n\nfunction encodeProbeRecord(\n objectKey: number,\n generation: number,\n localBlendFraction: number,\n shPreblend: readonly number[],\n candidate: boolean,\n accepted: boolean,\n lastKnownGood: boolean,\n sentinel: ProbeBlendRecordSentinel | undefined,\n): ProbeBlendRecord {\n const values = new Float32Array(PROBE_BLEND_RECORD_BYTE_SIZE / Float32Array.BYTES_PER_ELEMENT);\n values[0] = objectKey;\n values[1] = generation;\n values[2] = roundProbeToF32(localBlendFraction) ?? 0;\n values[3] = (candidate ? 1 : 0) | (accepted ? 2 : 0) | (lastKnownGood ? 4 : 0);\n for (let band = 0; band < 9; band += 1) {\n const lane = 4 + band * 4;\n values[lane] = roundProbeToF32(shPreblend[band * 3] ?? 0) ?? 0;\n values[lane + 1] = roundProbeToF32(shPreblend[band * 3 + 1] ?? 0) ?? 0;\n values[lane + 2] = roundProbeToF32(shPreblend[band * 3 + 2] ?? 0) ?? 0;\n values[lane + 3] = 0;\n }\n const packedSh = new Array<number>(27);\n for (let band = 0; band < 9; band += 1) {\n packedSh[band * 3] = values[4 + band * 4] ?? 0;\n packedSh[band * 3 + 1] = values[5 + band * 4] ?? 0;\n packedSh[band * 3 + 2] = values[6 + band * 4] ?? 0;\n }\n return {\n objectKey,\n generation,\n localBlendFraction: values[2] ?? 0,\n shPreblend: packedSh,\n bytes: new Uint8Array(values.buffer),\n byteLength: values.byteLength,\n candidate,\n accepted,\n lastKnownGood,\n ...(sentinel === undefined ? {} : { sentinel }),\n };\n}\n\nfunction sameList(left: readonly string[], right: readonly string[]): boolean {\n return left.length === right.length && left.every((value, index) => value === right[index]);\n}\n\nfunction sameVector3(\n left: readonly [number, number, number],\n right: readonly [number, number, number],\n): boolean {\n return left[0] === right[0] && left[1] === right[1] && left[2] === right[2];\n}\n\nfunction sameProbeFacts(\n left: readonly ProbeSceneProbeInput[],\n right: readonly ProbeSceneProbeInput[],\n): boolean {\n if (left.length !== right.length) return false;\n return left.every((probe, index) => {\n const other = right[index];\n if (\n other === undefined ||\n probe.identity !== other.identity ||\n probe.radius !== other.radius ||\n probe.admitted !== other.admitted ||\n !sameVector3(probe.position, other.position) ||\n probe.irradiance.length !== other.irradiance.length\n )\n return false;\n for (let value = 0; value < probe.irradiance.length; value += 1) {\n if (probe.irradiance[value] !== other.irradiance[value]) return false;\n }\n return true;\n });\n}\n\nfunction sameSkyFacts(left: ProbeSceneProjectionInput, right: ProbeSceneProjectionInput): boolean {\n const leftSky = left.sky;\n const rightSky = right.sky;\n if ((leftSky === undefined) !== (rightSky === undefined)) return false;\n if (\n leftSky !== undefined &&\n rightSky !== undefined &&\n (leftSky.available !== rightSky.available ||\n leftSky.identity !== rightSky.identity ||\n leftSky.sourceKey !== rightSky.sourceKey ||\n leftSky.fallbackReason !== rightSky.fallbackReason ||\n !sameVector3(leftSky.irradiance, rightSky.irradiance))\n )\n return false;\n if ((left.skyIrradiance === undefined) !== (right.skyIrradiance === undefined)) return false;\n return (\n left.skyIrradiance === undefined ||\n (right.skyIrradiance !== undefined && sameVector3(left.skyIrradiance, right.skyIrradiance))\n );\n}\n\n/** Renderer-owned bounded projection; admission is explicit and fail-closed. */\nexport class ProbeBlendSceneProjection {\n private previous?: ProbeSceneProjectionInput;\n private records = new Map<number, ProbeBlendRecord>();\n private lastError: ProbeAdmissionError | undefined;\n private lastReceipt = emptyReceipt(PROBE_R_MIN);\n private lastActiveContributorCount = 0;\n private lastAdmittedProbeCount = 0;\n private lastCoverage = 0;\n private lastFinite = true;\n private lastSky: ProbeSceneProjectionInput['sky'] = {\n available: false,\n irradiance: [0, 0, 0],\n fallbackReason: 'no-skylight',\n };\n private lastDirtyVisitCount = 0;\n private lastDirtyReasons: readonly ProbeSceneDirtyReason[] = [];\n private recordFacts = new Map<\n number,\n {\n readonly contributors: readonly ProbeBlendTerm[];\n readonly qHatSum: number;\n readonly rStar: number;\n readonly fallbackReason: string | undefined;\n }\n >();\n\n getRecord(objectKey: number): ProbeBlendRecord | undefined {\n return this.records.get(objectKey);\n }\n\n hasRecords(): boolean {\n return this.records.size > 0;\n }\n\n inspect(): ProbeBlendInspection {\n return {\n activeContributorCount: this.lastActiveContributorCount,\n admittedProbeCount: this.lastAdmittedProbeCount,\n coverage: this.lastCoverage,\n skyResidualFraction: 1 - this.lastCoverage,\n finite: this.lastFinite,\n errorCode: this.lastError?.code,\n records: [...this.records.values()].map((record) => {\n const facts = this.recordFacts.get(record.objectKey);\n return {\n objectKey: record.objectKey,\n generation: record.generation,\n localBlendFraction: record.localBlendFraction,\n shPreblend: [...record.shPreblend],\n byteLength: record.byteLength,\n candidate: record.candidate,\n accepted: record.accepted,\n lastKnownGood: record.lastKnownGood,\n sentinel: record.sentinel,\n probeBlendIndex: record.objectKey,\n contributors: (facts?.contributors ?? []).map((term) => ({\n identity: term.identity,\n distance: term.distance,\n radius: term.radius,\n coverage: term.coverage,\n q: term.q,\n qHat: term.qHat,\n alpha: term.alpha,\n })),\n qHatSum: facts?.qHatSum ?? 0,\n rStar: facts?.rStar ?? PROBE_R_MIN,\n fallbackReason: facts?.fallbackReason,\n };\n }),\n sky: {\n available: this.lastSky?.available ?? false,\n identity: this.lastSky?.identity,\n sourceKey: this.lastSky?.sourceKey,\n irradiance: [...(this.lastSky?.irradiance ?? [0, 0, 0])] as [number, number, number],\n fallbackReason: this.lastSky?.fallbackReason,\n },\n dirtyVisitCount: this.lastDirtyVisitCount,\n dirtyReasons: [...this.lastDirtyReasons],\n receipt: {\n activeIdentities: [...this.lastReceipt.activeIdentities],\n admittedIdentities: [...this.lastReceipt.admittedIdentities],\n rejectedIdentities: [...this.lastReceipt.rejectedIdentities],\n stableOrder: [...this.lastReceipt.stableOrder],\n capacity: this.lastReceipt.capacity,\n scaleRadius: this.lastReceipt.scaleRadius,\n finite: this.lastReceipt.finite,\n overflowReason: this.lastReceipt.overflowReason,\n },\n };\n }\n\n apply(input: ProbeSceneProjectionInput): ProbeSceneProjectionResult {\n const dirtyReasons: ProbeSceneDirtyReason[] = [];\n const affectedObjectKeys = new Set<number>();\n const previous = this.previous;\n const objectKeys = input.objects.map((object) => String(object.objectKey)).sort();\n const previousObjectKeys =\n previous?.objects.map((object) => String(object.objectKey)).sort() ?? [];\n if (previous === undefined || !sameList(objectKeys, previousObjectKeys)) {\n dirtyReasons.push('object-boundary');\n for (const object of input.objects) affectedObjectKeys.add(object.objectKey);\n }\n if (previous !== undefined && input.worldRevision !== previous.worldRevision)\n dirtyReasons.push('world');\n if (previous !== undefined && !sameProbeFacts(input.probes, previous.probes))\n dirtyReasons.push('probe-fact');\n if (previous !== undefined && !sameSkyFacts(input, previous)) dirtyReasons.push('sky');\n const previousObjects = new Map(previous?.objects.map((object) => [object.objectKey, object]));\n for (const object of input.objects) {\n const oldObject = previousObjects.get(object.objectKey);\n if (oldObject === undefined) {\n affectedObjectKeys.add(object.objectKey);\n continue;\n }\n if (!sameVector3(object.position, oldObject.position)) {\n dirtyReasons.push('object-position');\n affectedObjectKeys.add(object.objectKey);\n }\n if (object.generation !== oldObject.generation) {\n dirtyReasons.push('generation');\n affectedObjectKeys.add(object.objectKey);\n }\n }\n if (\n dirtyReasons.includes('world') ||\n dirtyReasons.includes('probe-fact') ||\n dirtyReasons.includes('sky')\n )\n for (const object of input.objects) affectedObjectKeys.add(object.objectKey);\n const uniqueDirtyReasons = [...new Set(dirtyReasons)];\n if (previous !== undefined && uniqueDirtyReasons.length === 0) {\n return {\n records: [...this.records.values()],\n contributors: [],\n activeContributorCount: this.lastActiveContributorCount,\n admittedProbeCount: this.lastAdmittedProbeCount,\n coverage: this.lastCoverage,\n skyResidualFraction: 1 - this.lastCoverage,\n dirtyReasons: [],\n affectedObjectKeys: [],\n visits: 0,\n allocations: 0,\n uploads: 0,\n receipt: this.lastReceipt,\n ...(this.lastError === undefined ? {} : { error: this.lastError }),\n };\n }\n const nextRecords = new Map(this.records);\n const currentObjectKeys = new Set(input.objects.map((object) => object.objectKey));\n for (const objectKey of nextRecords.keys()) {\n if (!currentObjectKeys.has(objectKey)) {\n nextRecords.delete(objectKey);\n this.recordFacts.delete(objectKey);\n }\n }\n let firstTerms: readonly ProbeBlendTerm[] = [];\n let firstReceipt = emptyReceipt(PROBE_R_MIN);\n let firstError: ProbeAdmissionError | undefined;\n let firstActiveCount = 0;\n let firstAdmittedCount = 0;\n let firstCoverage = 0;\n let firstObjectSeen = false;\n let visited = 0;\n for (const object of input.objects) {\n if (!affectedObjectKeys.has(object.objectKey)) continue;\n visited += 1;\n const candidates = input.probes.map((probe) => ({\n identity: probe.identity,\n admitted: probe.admitted,\n distance: vectorDistance(object.position, probe.position),\n radius: probe.radius,\n irradiance: probe.irradiance,\n }));\n const admission = admitProbeContributors(candidates);\n if (!firstObjectSeen) {\n firstObjectSeen = true;\n firstActiveCount = admission.active.length;\n firstAdmittedCount = admission.admitted.length;\n firstReceipt = admission.receipt;\n }\n const previousRecord = this.records.get(object.objectKey);\n const lastKnownGood = input.lastKnownGood ?? previousRecord?.lastKnownGood ?? false;\n let record: ProbeBlendRecord;\n if (admission.error !== undefined) firstError ??= admission.error;\n if (admission.admitted.length === 0) {\n if (input.probes.length === 0) {\n nextRecords.delete(object.objectKey);\n this.recordFacts.delete(object.objectKey);\n continue;\n }\n const sentinel: ProbeBlendRecordSentinel = lastKnownGood ? 'no-active' : 'no-lkg';\n record = encodeProbeRecord(\n object.objectKey,\n object.generation,\n 0,\n new Array(27).fill(0),\n true,\n false,\n lastKnownGood,\n sentinel,\n );\n this.recordFacts.set(object.objectKey, {\n contributors: [],\n qHatSum: 0,\n rStar: PROBE_R_MIN,\n fallbackReason: admission.error?.code ?? sentinel,\n });\n } else {\n const blend = blendProbeCoefficients(admission.admitted, PROBE_R_MIN);\n if (blend === undefined) {\n firstError ??= {\n code: 'invalid-admitted-prefix',\n activeCount: admission.active.length,\n capacity: PROBE_MAX_CONTRIBUTORS,\n receipt: admission.receipt,\n };\n firstReceipt = admission.receipt;\n continue;\n }\n record = encodeProbeRecord(\n object.objectKey,\n object.generation,\n blend.C,\n blend.SHPreblend,\n true,\n true,\n true,\n undefined,\n );\n this.recordFacts.set(object.objectKey, {\n contributors: blend.terms,\n qHatSum: blend.Q,\n rStar: blend.rStar,\n fallbackReason:\n admission.error === undefined ? undefined : 'capacity-exceeded-stable-prefix',\n });\n if (firstTerms.length === 0) firstTerms = blend.terms;\n firstCoverage = blend.C;\n }\n nextRecords.set(object.objectKey, record);\n firstError ??= admission.error;\n }\n const allocations = previous === undefined ? nextRecords.size : 0;\n const result = {\n records: [...nextRecords.values()],\n contributors: firstTerms,\n activeContributorCount: firstActiveCount,\n admittedProbeCount: firstAdmittedCount,\n coverage: firstCoverage,\n skyResidualFraction: 1 - firstCoverage,\n dirtyReasons: uniqueDirtyReasons,\n affectedObjectKeys: [...affectedObjectKeys].sort((left, right) => left - right),\n visits: visited,\n allocations,\n uploads: nextRecords.size,\n receipt: firstReceipt,\n ...(firstError === undefined ? {} : { error: firstError }),\n };\n this.previous = input;\n this.records = nextRecords;\n this.lastError = firstError;\n this.lastReceipt = firstReceipt;\n this.lastActiveContributorCount = firstActiveCount;\n this.lastAdmittedProbeCount = firstAdmittedCount;\n this.lastCoverage = firstCoverage;\n this.lastFinite = [...nextRecords.values()].every(\n (record) => record.bytes.length === PROBE_BLEND_RECORD_BYTE_SIZE,\n );\n this.lastSky =\n input.sky ??\n (input.skyIrradiance === undefined\n ? { available: false, irradiance: [0, 0, 0] as const, fallbackReason: 'no-skylight' }\n : { available: true, irradiance: input.skyIrradiance });\n this.lastDirtyVisitCount = visited;\n this.lastDirtyReasons = uniqueDirtyReasons;\n return result;\n }\n}\n"]}
|