@forgeax/engine-render 0.1.3 → 0.1.6
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 +130 -641
- package/dist/.tsbuildinfo +1 -1
- package/dist/__tests__/device-scope-lifecycle.unit.test.d.ts +2 -0
- package/dist/__tests__/device-scope-lifecycle.unit.test.d.ts.map +1 -0
- package/dist/__tests__/device-scope-stale-matrix.unit.test.d.ts +2 -0
- package/dist/__tests__/device-scope-stale-matrix.unit.test.d.ts.map +1 -0
- package/dist/__tests__/fullscreen-feature-plan.unit.test.d.ts +2 -0
- package/dist/__tests__/fullscreen-feature-plan.unit.test.d.ts.map +1 -0
- package/dist/__tests__/gpu-driven-indirect-raster-evidence.d.ts.map +1 -1
- package/dist/__tests__/gpu-driven-view-gpu-evidence.d.ts +6 -0
- package/dist/__tests__/gpu-driven-view-gpu-evidence.d.ts.map +1 -1
- package/dist/{gpu-driven/view-reference.d.ts → __tests__/gpu-driven-view-reference.d.ts} +4 -4
- package/dist/__tests__/gpu-driven-view-reference.d.ts.map +1 -0
- package/dist/__tests__/gpu-scene-render-graph-gpu.d.ts.map +1 -1
- package/dist/__tests__/ibl/face-uniforms.unit.test.d.ts +2 -0
- package/dist/__tests__/ibl/face-uniforms.unit.test.d.ts.map +1 -0
- package/dist/__tests__/morph-feature-plan.unit.test.d.ts +2 -0
- package/dist/__tests__/morph-feature-plan.unit.test.d.ts.map +1 -0
- package/dist/__tests__/render-feature-plan.test-d.d.ts +2 -0
- package/dist/__tests__/render-feature-plan.test-d.d.ts.map +1 -0
- package/dist/__tests__/render-feature-plan.unit.test.d.ts +2 -0
- package/dist/__tests__/render-feature-plan.unit.test.d.ts.map +1 -0
- package/dist/__tests__/ssao-config.unit.test.d.ts +2 -0
- package/dist/__tests__/ssao-config.unit.test.d.ts.map +1 -0
- package/dist/__tests__/standard-clustered-pipeline.unit.test.d.ts +2 -0
- package/dist/__tests__/standard-clustered-pipeline.unit.test.d.ts.map +1 -0
- package/dist/__tests__/standard-descriptors.test-d.d.ts +2 -0
- package/dist/__tests__/standard-descriptors.test-d.d.ts.map +1 -0
- package/dist/__tests__/standard-pipeline.dawn.test.d.ts +2 -0
- package/dist/__tests__/standard-pipeline.dawn.test.d.ts.map +1 -0
- package/dist/__tests__/standard-pipeline.integration.test.d.ts +2 -0
- package/dist/__tests__/standard-pipeline.integration.test.d.ts.map +1 -0
- package/dist/__tests__/standard-profile-oracle.unit.test.d.ts +2 -0
- package/dist/__tests__/standard-profile-oracle.unit.test.d.ts.map +1 -0
- package/dist/__tests__/visibility-resource-short-circuit.unit.test.d.ts +2 -0
- package/dist/__tests__/visibility-resource-short-circuit.unit.test.d.ts.map +1 -0
- package/dist/{renderer/backend-selection.d.ts → assembly/backend-contract.d.ts} +15 -4
- package/dist/assembly/backend-contract.d.ts.map +1 -0
- package/dist/assembly/factory.d.ts +207 -0
- package/dist/assembly/factory.d.ts.map +1 -0
- package/dist/assembly/host-contract.d.ts +84 -0
- package/dist/assembly/host-contract.d.ts.map +1 -0
- package/dist/{renderer → assembly}/material/assembly.d.ts +1 -2
- package/dist/{renderer → assembly}/material/assembly.d.ts.map +1 -1
- package/dist/assembly/material/pipeline-projection.d.ts +30 -0
- package/dist/assembly/material/pipeline-projection.d.ts.map +1 -0
- package/dist/authoring.d.ts +10 -11
- package/dist/authoring.d.ts.map +1 -1
- package/dist/authoring.mjs +25 -3
- package/dist/authoring.mjs.map +1 -1
- package/dist/chunk-CQXZC5XI.mjs +182 -0
- package/dist/chunk-CQXZC5XI.mjs.map +1 -0
- package/dist/chunk-QC4VW3XJ.mjs +79 -0
- package/dist/chunk-QC4VW3XJ.mjs.map +1 -0
- package/dist/chunk-SCRSAK5B.mjs +480 -0
- package/dist/chunk-SCRSAK5B.mjs.map +1 -0
- package/dist/components/__tests__/schema-contract.unit.test.d.ts +2 -0
- package/dist/components/__tests__/schema-contract.unit.test.d.ts.map +1 -0
- package/dist/components/glyph-text.d.ts +1 -1
- package/dist/components/glyph-text.d.ts.map +1 -1
- package/dist/components/index.d.ts +2 -2
- package/dist/components/index.d.ts.map +1 -1
- package/dist/components/instances.d.ts +1 -1
- package/dist/components/instances.d.ts.map +1 -1
- package/dist/components/light-helpers.d.ts +1 -1
- package/dist/components/light-helpers.d.ts.map +1 -1
- package/dist/components/mesh-filter.d.ts +7 -7
- package/dist/components/mesh-filter.d.ts.map +1 -1
- package/dist/components/scene-instance.d.ts +11 -11
- package/dist/components/skybox-background.d.ts +56 -0
- package/dist/components/skybox-background.d.ts.map +1 -0
- package/dist/components/skylight.d.ts +55 -0
- package/dist/components/skylight.d.ts.map +1 -0
- package/dist/components/sprite-animation.d.ts +2 -3
- package/dist/components/sprite-animation.d.ts.map +1 -1
- package/dist/components/sprite-instances.d.ts +1 -1
- package/dist/components/sprite-playback-mode.d.ts +6 -1
- package/dist/components/sprite-playback-mode.d.ts.map +1 -1
- package/dist/components/sprite-region-override.d.ts +2 -3
- package/dist/components/sprite-region-override.d.ts.map +1 -1
- package/dist/components/tile-layer.d.ts +5 -0
- package/dist/components/tile-layer.d.ts.map +1 -1
- package/dist/construct-renderer.d.ts +18 -1
- package/dist/construct-renderer.d.ts.map +1 -1
- package/dist/construct-renderer.mjs +27008 -4
- package/dist/construct-renderer.mjs.map +1 -1
- package/dist/debug-draw-glue.d.ts +2 -53
- package/dist/debug-draw-glue.d.ts.map +1 -1
- package/dist/device/device-scope.d.ts +83 -0
- package/dist/device/device-scope.d.ts.map +1 -0
- package/dist/{gpu-resource-store.d.ts → device/gpu-residency.d.ts} +91 -48
- package/dist/device/gpu-residency.d.ts.map +1 -0
- package/dist/device/resource-types.d.ts +8 -0
- package/dist/device/resource-types.d.ts.map +1 -0
- package/dist/engine-metrics.d.ts +2 -2
- package/dist/engine-metrics.d.ts.map +1 -1
- package/dist/errors/recover.d.ts +28 -1
- package/dist/errors/recover.d.ts.map +1 -1
- package/dist/errors/render.d.ts +249 -258
- package/dist/errors/render.d.ts.map +1 -1
- package/dist/features/fullscreen.d.ts +19 -0
- package/dist/features/fullscreen.d.ts.map +1 -0
- package/dist/features/host.d.ts +32 -26
- package/dist/features/host.d.ts.map +1 -1
- package/dist/features/morph/morph-feature.d.ts +39 -5
- package/dist/features/morph/morph-feature.d.ts.map +1 -1
- package/dist/features/plan.d.ts +182 -0
- package/dist/features/plan.d.ts.map +1 -0
- package/dist/features/prepared-gpu-work.d.ts +21 -17
- package/dist/features/prepared-gpu-work.d.ts.map +1 -1
- package/dist/features/prepared-graphics-store.d.ts +2 -1
- package/dist/features/prepared-graphics-store.d.ts.map +1 -1
- package/dist/features/prepared-graphics.d.ts +11 -21
- package/dist/features/prepared-graphics.d.ts.map +1 -1
- package/dist/features/render-graph-compute.d.ts +2 -2
- package/dist/features/render-graph-compute.d.ts.map +1 -1
- package/dist/features/render-graph-contribution.d.ts +4 -7
- package/dist/features/render-graph-contribution.d.ts.map +1 -1
- package/dist/features/render-graph-raster.d.ts +2 -2
- package/dist/features/render-graph-raster.d.ts.map +1 -1
- package/dist/features/render-graph-resources.d.ts +6 -6
- package/dist/features/render-graph-resources.d.ts.map +1 -1
- package/dist/features/targets.d.ts +5 -5
- package/dist/features/targets.d.ts.map +1 -1
- package/dist/features/types.d.ts +11 -190
- package/dist/features/types.d.ts.map +1 -1
- package/dist/features/vocabulary.d.ts +14 -0
- package/dist/features/vocabulary.d.ts.map +1 -0
- package/dist/fullscreen-post-process-pass.d.ts +4 -25
- package/dist/fullscreen-post-process-pass.d.ts.map +1 -1
- package/dist/glyph-text-layout-system.d.ts +3 -2
- package/dist/glyph-text-layout-system.d.ts.map +1 -1
- package/dist/gpu-driven/batch-topology.d.ts +6 -75
- package/dist/gpu-driven/batch-topology.d.ts.map +1 -1
- package/dist/gpu-driven/production-raster.d.ts +13 -112
- package/dist/gpu-driven/production-raster.d.ts.map +1 -1
- package/dist/gpu-driven/view-gpu.d.ts +10 -66
- package/dist/gpu-driven/view-gpu.d.ts.map +1 -1
- package/dist/gpu-resource.d.ts +3 -3
- package/dist/gpu-scene-schema.d.ts +1 -94
- package/dist/gpu-scene-schema.d.ts.map +1 -1
- package/dist/gpu-scene.d.ts +7 -33
- package/dist/gpu-scene.d.ts.map +1 -1
- package/dist/hdrp-buffers.d.ts +3 -53
- package/dist/hdrp-buffers.d.ts.map +1 -1
- package/dist/ibl/IblPipelineCache.d.ts +74 -180
- package/dist/ibl/IblPipelineCache.d.ts.map +1 -1
- package/dist/ibl/skylight-bind-group.d.ts +1 -1
- package/dist/index.d.ts +13 -43
- package/dist/index.d.ts.map +1 -1
- package/dist/index.mjs +165 -3
- package/dist/index.mjs.map +1 -1
- package/dist/inspection-types.d.ts +69 -0
- package/dist/inspection-types.d.ts.map +1 -0
- package/dist/instance-buffer-cache.d.ts +1 -4
- package/dist/instance-buffer-cache.d.ts.map +1 -1
- package/dist/internal.d.ts +1 -73
- package/dist/internal.d.ts.map +1 -1
- package/dist/internal.mjs +1 -43
- package/dist/internal.mjs.map +1 -1
- package/dist/lifecycle.d.ts +36 -2
- package/dist/lifecycle.d.ts.map +1 -1
- package/dist/materials.d.ts +0 -3
- package/dist/materials.d.ts.map +1 -1
- package/dist/mesh-material-bindings.d.ts +0 -1
- package/dist/mesh-material-bindings.d.ts.map +1 -1
- package/dist/pbr-pipeline.d.ts +75 -29
- package/dist/pbr-pipeline.d.ts.map +1 -1
- package/dist/pipeline/standard-forward-lane.d.ts +5 -0
- package/dist/pipeline/standard-forward-lane.d.ts.map +1 -0
- package/dist/pipeline/standard-pipeline.d.ts +31 -0
- package/dist/pipeline/standard-pipeline.d.ts.map +1 -0
- package/dist/pipeline/standard-profile.d.ts +40 -0
- package/dist/pipeline/standard-profile.d.ts.map +1 -0
- package/dist/pipeline-builder.d.ts +3 -3
- package/dist/pipeline-builder.d.ts.map +1 -1
- package/dist/pipeline-spec-types.d.ts +24 -0
- package/dist/pipeline-spec-types.d.ts.map +1 -0
- package/dist/pipeline-spec.d.ts +16 -155
- package/dist/pipeline-spec.d.ts.map +1 -1
- package/dist/plugin.d.ts +1 -14
- package/dist/plugin.d.ts.map +1 -1
- package/dist/post-process-errors.d.ts +18 -18
- package/dist/post-process-errors.d.ts.map +1 -1
- package/dist/prepare/prepared-graphics-resolver.d.ts +2 -5
- package/dist/prepare/prepared-graphics-resolver.d.ts.map +1 -1
- package/dist/record/__tests__/typed-frame-graph-plan.unit.test.d.ts +2 -0
- package/dist/record/__tests__/typed-frame-graph-plan.unit.test.d.ts.map +1 -0
- package/dist/record/frame-lighting.d.ts +7 -73
- package/dist/record/frame-lighting.d.ts.map +1 -1
- package/dist/record/frame-snapshot.d.ts +44 -44
- package/dist/record/frame-snapshot.d.ts.map +1 -1
- package/dist/record/frame-targets.d.ts +5 -38
- package/dist/record/frame-targets.d.ts.map +1 -1
- package/dist/record/frame.d.ts +64 -52
- package/dist/record/frame.d.ts.map +1 -1
- package/dist/record/helpers.d.ts +3 -2
- package/dist/record/helpers.d.ts.map +1 -1
- package/dist/record/main-pass-geometry.d.ts +5 -4
- package/dist/record/main-pass-geometry.d.ts.map +1 -1
- package/dist/record/main-pass-material.d.ts +90 -59
- package/dist/record/main-pass-material.d.ts.map +1 -1
- package/dist/record/main-pass-sprite-draws.d.ts +28 -3
- package/dist/record/main-pass-sprite-draws.d.ts.map +1 -1
- package/dist/record/main-pass.d.ts +1 -1
- package/dist/record/main-pass.d.ts.map +1 -1
- package/dist/record/mesh-ssbo.d.ts +276 -3
- package/dist/record/mesh-ssbo.d.ts.map +1 -1
- package/dist/record/render-context.d.ts +235 -0
- package/dist/record/render-context.d.ts.map +1 -0
- package/dist/record/shadow-pass.d.ts +15 -88
- 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 +29 -7
- package/dist/record/typed-frame-graph.d.ts.map +1 -1
- package/dist/record/view-ubo.d.ts +3 -3
- package/dist/record/view-ubo.d.ts.map +1 -1
- package/dist/render-contract.d.ts +416 -0
- package/dist/render-contract.d.ts.map +1 -0
- package/dist/render-data.d.ts.map +1 -1
- package/dist/render-graph-primitives.d.ts +14 -362
- package/dist/render-graph-primitives.d.ts.map +1 -1
- package/dist/render-pipeline.d.ts +25 -64
- package/dist/render-pipeline.d.ts.map +1 -1
- package/dist/render-system-extract.d.ts +107 -338
- package/dist/render-system-extract.d.ts.map +1 -1
- package/dist/render-system.d.ts +21 -713
- package/dist/render-system.d.ts.map +1 -1
- package/dist/scene/render-scene-types.d.ts +58 -0
- package/dist/scene/render-scene-types.d.ts.map +1 -0
- package/dist/scene/render-scene.d.ts +105 -0
- package/dist/scene/render-scene.d.ts.map +1 -0
- package/dist/scene-instances/post-spawn-resolve-joints.d.ts +2 -5
- package/dist/scene-instances/post-spawn-resolve-joints.d.ts.map +1 -1
- package/dist/ssao-buffers.d.ts +22 -3
- package/dist/ssao-buffers.d.ts.map +1 -1
- package/dist/systems/skin-palette-allocator.d.ts +2 -4
- package/dist/systems/skin-palette-allocator.d.ts.map +1 -1
- package/dist/systems/skin-palette-types.d.ts +14 -0
- package/dist/systems/skin-palette-types.d.ts.map +1 -0
- package/dist/systems/transparent-sort-config.d.ts +23 -2
- package/dist/systems/transparent-sort-config.d.ts.map +1 -1
- package/dist/tilemap-chunk-extract-system.d.ts +4 -3
- package/dist/tilemap-chunk-extract-system.d.ts.map +1 -1
- package/dist/typed-render-graph-primitives.d.ts +2 -4
- package/dist/typed-render-graph-primitives.d.ts.map +1 -1
- package/dist/typed-shadow-passes.d.ts +3 -3
- package/dist/typed-shadow-passes.d.ts.map +1 -1
- package/package.json +23 -23
- package/src/__tests__/backend-selection-rhi-capture.test-d.ts +1 -1
- package/src/__tests__/callback-inference.test-d.ts +6 -3
- package/src/__tests__/cluster-grid-default-surface.unit.test.ts +7 -4
- package/src/__tests__/construct-renderer-identity.unit.test.ts +15 -2
- package/src/__tests__/device-scope-lifecycle.unit.test.ts +151 -0
- package/src/__tests__/device-scope-stale-matrix.unit.test.ts +42 -0
- package/src/__tests__/direct-extract-consumer-contract.test-d.ts +8 -19
- package/src/__tests__/direct-light-snapshot.unit.test.ts +3 -13
- package/src/__tests__/factory-contract.integration.test.ts +158 -209
- package/src/__tests__/fallback-row-stride-surface.unit.test.ts +1 -4
- package/src/__tests__/frame-observation.contract.test.ts +17 -8
- package/src/__tests__/fullscreen-feature-plan.unit.test.ts +32 -0
- package/src/__tests__/glyph-text-layout-recovery.unit.test.ts +6 -11
- package/src/__tests__/gpu-driven-indirect-raster-evidence.ts +9 -16
- package/src/__tests__/gpu-driven-production.integration.test.ts +32 -205
- package/src/__tests__/gpu-driven-scaling.unit.test.ts +4 -7
- package/src/__tests__/gpu-driven-view-gpu-evidence.ts +87 -8
- package/src/__tests__/gpu-driven-view-graph.integration.test.ts +170 -8
- package/src/{gpu-driven/view-reference.ts → __tests__/gpu-driven-view-reference.ts} +4 -3
- package/src/__tests__/gpu-driven-view.browser.test.ts +12 -1
- package/src/__tests__/gpu-driven-view.dawn.test.ts +12 -1
- package/src/__tests__/gpu-driven-view.unit.test.ts +11 -267
- package/src/__tests__/gpu-resource-store-stride.unit.test.ts +3 -3
- package/src/__tests__/gpu-scene-render-graph-gpu.ts +2 -3
- package/src/__tests__/gpu-scene.dawn.test.ts +2 -6
- package/src/__tests__/gpu-scene.unit.test.ts +10 -24
- package/src/__tests__/ibl/face-uniforms.unit.test.ts +46 -0
- package/src/__tests__/infinite-grid-no-vertex-probe.unit.test.ts +34 -66
- package/src/__tests__/ktx2-basis-gpu-consumer.dawn.test.ts +14 -5
- package/src/__tests__/light-buffer-layout.unit.test.ts +4 -49
- package/src/__tests__/material-cooked-projection.unit.test.ts +2 -51
- package/src/__tests__/material-snapshot-mutation.integration.test.ts +10 -15
- package/src/__tests__/material-static-dynamic-route.unit.test.ts +4 -23
- package/src/__tests__/material-stride-surface.unit.test.ts +2 -2
- package/src/__tests__/mesh-buffer-usage-surface.unit.test.ts +7 -8
- package/src/__tests__/morph-culling-reentry.dawn.test.ts +29 -38
- package/src/__tests__/morph-feature-gpu-work.integration.test.ts +45 -43
- package/src/__tests__/morph-feature-plan.unit.test.ts +53 -0
- package/src/__tests__/morph-visual-evidence.integration.test.ts +47 -33
- package/src/__tests__/nineslice-handle-surface.unit.test.ts +11 -6
- package/src/__tests__/post-process-error-policy-owner.unit.test.ts +6 -13
- package/src/__tests__/prepared-graphics-capability.unit.test.ts +6 -81
- package/src/__tests__/prepared-graphics-generation.unit.test.ts +3 -17
- package/src/__tests__/prepared-graphics-lifecycle.unit.test.ts +6 -74
- package/src/__tests__/prepared-graphics-resolver.unit.test.ts +1 -3
- package/src/__tests__/prepared-graphics-snapshot.unit.test.ts +2 -2
- package/src/__tests__/profiler-default-off.test.ts +1 -1
- package/src/__tests__/profiler-phase-catalog.test.ts +2 -2
- package/src/__tests__/profiler-phase-integration.test.ts +5 -13
- package/src/__tests__/profiler-phase-token.test.ts +3 -8
- package/src/__tests__/public-surface.test-d.ts +65 -3
- package/src/__tests__/recover-error-policy-owner.unit.test.ts +1 -21
- package/src/__tests__/render-error-code-owner.test-d.ts +18 -23
- package/src/__tests__/render-error-detail-ssot.test-d.ts +0 -95
- package/src/__tests__/render-error-exhaustive.test-d.ts +8 -1
- package/src/__tests__/render-feature-assembly.test-d.ts +8 -16
- package/src/__tests__/render-feature-context.test-d.ts +16 -40
- package/src/__tests__/render-feature-contract.test-d.ts +9 -18
- package/src/__tests__/render-feature-diagnostics.unit.test.ts +6 -8
- package/src/__tests__/render-feature-docs.unit.test.ts +8 -7
- package/src/__tests__/render-feature-gpu-work.integration.test.ts +14 -75
- package/src/__tests__/render-feature-plan.test-d.ts +161 -0
- package/src/__tests__/render-feature-plan.unit.test.ts +170 -0
- package/src/__tests__/render-feature-prepared-diagnostics.unit.test.ts +8 -19
- package/src/__tests__/render-feature-prepared-errors.test-d.ts +3 -6
- package/src/__tests__/render-feature-prepared-graphics-docs.unit.test.ts +10 -71
- package/src/__tests__/render-feature-prepared-graphics-isolation.unit.test.ts +11 -61
- package/src/__tests__/render-feature-prepared-graphics-negative.test-d.ts +20 -43
- package/src/__tests__/render-feature-prepared-graphics.test-d.ts +56 -78
- package/src/__tests__/render-feature-public-surface.test-d.ts +6 -24
- package/src/__tests__/render-feature-retry.unit.test.ts +7 -48
- package/src/__tests__/render-feature-scheduling.unit.test.ts +15 -27
- package/src/__tests__/render-feature-stage-failed-policy-owner.unit.test.ts +0 -9
- package/src/__tests__/render-feature-stage-fault-recovery.unit.test.ts +19 -109
- package/src/__tests__/render-feature-visibility-context.test-d.ts +1 -6
- package/src/__tests__/render-feature-visibility-context.unit.test.ts +1 -2
- package/src/__tests__/render-feature-zero-work.unit.test.ts +14 -20
- package/src/__tests__/render-scene-projection.unit.test.ts +73 -111
- package/src/__tests__/renderer-factory-material-contract.unit.test.ts +46 -50
- package/src/__tests__/renderer-lifecycle.integration.test.ts +49 -1
- package/src/__tests__/shader-stage-surface.unit.test.ts +14 -9
- package/src/__tests__/ssao-config.unit.test.ts +36 -0
- package/src/__tests__/ssao-kernel-surface.unit.test.ts +4 -5
- package/src/__tests__/standard-clustered-pipeline.unit.test.ts +28 -0
- package/src/__tests__/standard-descriptors.test-d.ts +22 -0
- package/src/__tests__/standard-pipeline.dawn.test.ts +61 -0
- package/src/__tests__/standard-pipeline.integration.test.ts +124 -0
- package/src/__tests__/standard-profile-oracle.unit.test.ts +62 -0
- package/src/__tests__/surface-configuration.unit.test.ts +1 -2
- package/src/__tests__/texture-usage-surface.unit.test.ts +3 -6
- package/src/__tests__/typed-pipeline-topology.unit.test.ts +40 -206
- package/src/__tests__/urp-pipeline-targets.unit.test.ts +1 -11
- package/src/__tests__/urp-pipeline.unit.test.ts +2 -2
- package/src/__tests__/vertex-color-pipeline.unit.test.ts +10 -2
- package/src/__tests__/vertex-layout-consumer.unit.test.ts +1 -1
- package/src/__tests__/visibility-diagnostics.integration.test.ts +7 -11
- package/src/__tests__/visibility-extract.integration.test.ts +20 -11
- package/src/__tests__/visibility-extract.perf.test.ts +66 -32
- package/src/__tests__/visibility-feature-dedup.integration.test.ts +2 -4
- package/src/__tests__/visibility-hidden-report.unit.test.ts +1 -2
- package/src/__tests__/visibility-instances.integration.test.ts +7 -11
- package/src/__tests__/visibility-multi-world.integration.test.ts +38 -6
- package/src/__tests__/visibility-producer-matrix.integration.test.ts +18 -41
- package/src/__tests__/visibility-public-surface.test-d.ts +10 -9
- package/src/__tests__/visibility-resolver.unit.test.ts +2 -1
- package/src/__tests__/visibility-resource-short-circuit.unit.test.ts +80 -0
- package/src/__tests__/visibility-snapshot-contract.unit.test.ts +2 -1
- package/src/__tests__/vocabulary.unit.test.ts +1 -1
- package/src/assembly/backend-contract.ts +57 -0
- package/src/{renderer/renderer-factory.ts → assembly/factory.ts} +1709 -2693
- package/src/assembly/host-contract.ts +101 -0
- package/src/{renderer → assembly}/material/assembly.ts +1 -3
- package/src/assembly/material/pipeline-projection.ts +63 -0
- package/src/authoring.ts +14 -22
- package/src/components/__tests__/schema-contract.unit.test.ts +10 -0
- package/src/components/glyph-text.ts +3 -2
- package/src/components/index.ts +7 -9
- package/src/components/instances.ts +4 -5
- package/src/components/light-helpers.ts +1 -1
- package/src/components/mesh-filter.ts +11 -10
- package/src/components/post-process-params.ts +3 -3
- package/src/components/scene-instance.ts +12 -12
- package/src/components/skybox-background.ts +103 -0
- package/src/components/{environment.ts → skylight.ts} +2 -111
- package/src/components/sprite-animation.ts +3 -4
- package/src/components/sprite-instances.ts +2 -2
- package/src/components/sprite-playback-mode.ts +7 -1
- package/src/components/sprite-region-override.ts +2 -3
- package/src/components/tile-layer.ts +8 -2
- package/src/construct-renderer.ts +67 -4
- package/src/debug-draw-glue.ts +8 -129
- package/src/device/device-scope.ts +306 -0
- package/src/{gpu-resource-store.ts → device/gpu-residency.ts} +540 -639
- package/src/device/resource-types.ts +20 -0
- package/src/engine-metrics.ts +12 -19
- package/src/errors/recover.ts +45 -3
- package/src/errors/render.ts +357 -460
- package/src/features/fullscreen.ts +46 -0
- package/src/features/host.ts +575 -309
- package/src/features/morph/morph-feature.ts +195 -105
- package/src/features/plan.ts +447 -0
- package/src/features/prepared-gpu-work.ts +72 -15
- package/src/features/prepared-graphics-store.ts +20 -6
- package/src/features/prepared-graphics.ts +12 -71
- package/src/features/render-graph-compute.ts +14 -5
- package/src/features/render-graph-contribution.ts +43 -63
- package/src/features/render-graph-raster.ts +11 -6
- package/src/features/render-graph-resources.ts +25 -23
- package/src/features/targets.ts +8 -21
- package/src/features/types.ts +39 -227
- package/src/features/vocabulary.ts +24 -0
- package/src/fullscreen-post-process-pass.ts +14 -57
- package/src/glyph-text-layout-system.ts +70 -96
- package/src/gpu-driven/batch-topology.ts +24 -202
- package/src/gpu-driven/production-raster.ts +93 -1108
- package/src/gpu-driven/view-gpu.ts +46 -192
- package/src/gpu-resource.ts +4 -4
- package/src/gpu-scene-schema.ts +11 -99
- package/src/gpu-scene.ts +231 -364
- package/src/hdrp-buffers.ts +12 -221
- package/src/ibl/IblPipelineCache.ts +471 -711
- package/src/ibl/skylight-bind-group.ts +4 -4
- package/src/index.ts +58 -217
- package/src/inspection-types.ts +76 -0
- package/src/instance-buffer-cache.ts +1 -29
- package/src/internal.ts +6 -85
- package/src/lifecycle.ts +64 -19
- package/src/materials.ts +7 -29
- package/src/mesh-material-bindings.ts +0 -1
- package/src/pbr-pipeline.ts +434 -53
- package/src/{urp-pipeline.ts → pipeline/standard-forward-lane.ts} +38 -149
- package/src/{hdrp-pipeline.ts → pipeline/standard-pipeline.ts} +221 -191
- package/src/pipeline/standard-profile.ts +65 -0
- package/src/pipeline-builder.ts +60 -64
- package/src/pipeline-spec-types.ts +28 -0
- package/src/pipeline-spec.ts +72 -609
- package/src/plugin.ts +3 -75
- package/src/post-process-errors.ts +31 -33
- package/src/prepare/prepared-graphics-resolver.ts +5 -4
- package/src/record/__tests__/material-slot-plan.unit.test.ts +1 -33
- package/src/record/__tests__/typed-frame-graph-plan.unit.test.ts +41 -0
- package/src/record/__tests__/video-texture-view.unit.test.ts +1 -1
- package/src/record/frame-lighting.ts +74 -195
- package/src/record/frame-snapshot.ts +45 -60
- package/src/record/frame-targets.ts +8 -243
- package/src/record/frame.ts +509 -796
- package/src/record/helpers.ts +6 -11
- package/src/record/main-pass-geometry.ts +106 -147
- package/src/record/main-pass-material.ts +517 -190
- package/src/record/main-pass-sprite-draws.ts +198 -117
- package/src/record/main-pass.ts +162 -143
- package/src/record/mesh-ssbo.ts +517 -38
- package/src/record/render-context.ts +364 -0
- package/src/record/shadow-pass.ts +138 -1838
- package/src/record/skybox-post-pass.ts +12 -14
- package/src/record/typed-frame-graph.ts +215 -254
- package/src/record/view-ubo.ts +6 -37
- package/src/render-contract.ts +571 -0
- package/src/render-data.ts +3 -3
- package/src/render-graph-primitives.ts +76 -851
- package/src/render-pipeline.ts +104 -188
- package/src/render-system-extract.ts +1048 -1729
- package/src/render-system.ts +330 -1957
- package/src/scene/render-scene-types.ts +64 -0
- package/src/scene/render-scene.ts +1032 -0
- package/src/scene-instances/post-spawn-resolve-joints.ts +4 -7
- package/src/ssao-buffers.ts +167 -8
- package/src/systems/skin-palette-allocator.ts +21 -64
- package/src/systems/skin-palette-types.ts +14 -0
- package/src/systems/transparent-sort-config.ts +25 -3
- package/src/tilemap-chunk-extract-system.ts +53 -70
- package/src/typed-render-graph-primitives.ts +35 -24
- package/src/typed-shadow-passes.ts +26 -56
- package/dist/__tests__/analytic-sky-contract.test.d.ts +0 -2
- package/dist/__tests__/analytic-sky-contract.test.d.ts.map +0 -1
- package/dist/__tests__/analytic-sky-falsify.test.d.ts +0 -2
- package/dist/__tests__/analytic-sky-falsify.test.d.ts.map +0 -1
- package/dist/__tests__/assets-runtime-handoff.integration.test.d.ts +0 -2
- package/dist/__tests__/assets-runtime-handoff.integration.test.d.ts.map +0 -1
- package/dist/__tests__/backend-selection.integration.test.d.ts +0 -2
- package/dist/__tests__/backend-selection.integration.test.d.ts.map +0 -1
- package/dist/__tests__/camera-temporal.test-d.d.ts +0 -2
- package/dist/__tests__/camera-temporal.test-d.d.ts.map +0 -1
- package/dist/__tests__/camera-temporal.test.d.ts +0 -2
- package/dist/__tests__/camera-temporal.test.d.ts.map +0 -1
- package/dist/__tests__/directional-shadow-probe-atlas-layout.unit.test.d.ts +0 -2
- package/dist/__tests__/directional-shadow-probe-atlas-layout.unit.test.d.ts.map +0 -1
- package/dist/__tests__/environment-inspection.test.d.ts +0 -2
- package/dist/__tests__/environment-inspection.test.d.ts.map +0 -1
- package/dist/__tests__/fog-ai-user.fixture.d.ts +0 -2
- package/dist/__tests__/fog-ai-user.fixture.d.ts.map +0 -1
- package/dist/__tests__/fog-custom-render-feature.fixture.d.ts +0 -16
- package/dist/__tests__/fog-custom-render-feature.fixture.d.ts.map +0 -1
- package/dist/__tests__/fog-custom-render-feature.integration.test.d.ts +0 -2
- package/dist/__tests__/fog-custom-render-feature.integration.test.d.ts.map +0 -1
- package/dist/__tests__/fog-inspection.integration.test.d.ts +0 -2
- package/dist/__tests__/fog-inspection.integration.test.d.ts.map +0 -1
- package/dist/__tests__/fog-owner-state.integration.test.d.ts +0 -2
- package/dist/__tests__/fog-owner-state.integration.test.d.ts.map +0 -1
- package/dist/__tests__/fog-pipeline-topology.integration.test.d.ts +0 -2
- package/dist/__tests__/fog-pipeline-topology.integration.test.d.ts.map +0 -1
- package/dist/__tests__/fog-public-surface.integration.test.d.ts +0 -2
- package/dist/__tests__/fog-public-surface.integration.test.d.ts.map +0 -1
- package/dist/__tests__/fog-ray-contract.integration.test.d.ts +0 -2
- package/dist/__tests__/fog-ray-contract.integration.test.d.ts.map +0 -1
- package/dist/__tests__/fog-source-absence.integration.test.d.ts +0 -2
- package/dist/__tests__/fog-source-absence.integration.test.d.ts.map +0 -1
- package/dist/__tests__/fog-temporal.integration.test.d.ts +0 -2
- package/dist/__tests__/fog-temporal.integration.test.d.ts.map +0 -1
- package/dist/__tests__/frame-chain.unit.test.d.ts +0 -2
- package/dist/__tests__/frame-chain.unit.test.d.ts.map +0 -1
- package/dist/__tests__/gpu-scene-field-type-owner.test-d.d.ts +0 -2
- package/dist/__tests__/gpu-scene-field-type-owner.test-d.d.ts.map +0 -1
- package/dist/__tests__/hdrp-pipeline.unit.test.d.ts +0 -2
- package/dist/__tests__/hdrp-pipeline.unit.test.d.ts.map +0 -1
- package/dist/__tests__/ibl/ibl-fallback.unit.test.d.ts +0 -2
- package/dist/__tests__/ibl/ibl-fallback.unit.test.d.ts.map +0 -1
- package/dist/__tests__/material-derived-error-stop-draw.integration.test.d.ts +0 -2
- package/dist/__tests__/material-derived-error-stop-draw.integration.test.d.ts.map +0 -1
- package/dist/__tests__/material-derived-payload.integration.test.d.ts +0 -2
- package/dist/__tests__/material-derived-payload.integration.test.d.ts.map +0 -1
- package/dist/__tests__/materials.unit.test.d.ts +0 -2
- package/dist/__tests__/materials.unit.test.d.ts.map +0 -1
- package/dist/__tests__/param-schema-projection-census.unit.test.d.ts +0 -2
- package/dist/__tests__/param-schema-projection-census.unit.test.d.ts.map +0 -1
- package/dist/__tests__/persistent-render-scene.unit.test.d.ts +0 -2
- package/dist/__tests__/persistent-render-scene.unit.test.d.ts.map +0 -1
- package/dist/__tests__/pipeline-error-policy-owner.unit.test.d.ts +0 -2
- package/dist/__tests__/pipeline-error-policy-owner.unit.test.d.ts.map +0 -1
- package/dist/__tests__/pipeline-pass-trace.test.d.ts +0 -2
- package/dist/__tests__/pipeline-pass-trace.test.d.ts.map +0 -1
- package/dist/__tests__/pipeline-stage-owner.test-d.d.ts +0 -2
- package/dist/__tests__/pipeline-stage-owner.test-d.d.ts.map +0 -1
- package/dist/__tests__/plugin.test.d.ts +0 -2
- package/dist/__tests__/plugin.test.d.ts.map +0 -1
- package/dist/__tests__/prepared-graphics-backend-matrix.unit.test.d.ts +0 -2
- package/dist/__tests__/prepared-graphics-backend-matrix.unit.test.d.ts.map +0 -1
- package/dist/__tests__/prepared-graphics-resolver-recording.unit.test.d.ts +0 -2
- package/dist/__tests__/prepared-graphics-resolver-recording.unit.test.d.ts.map +0 -1
- package/dist/__tests__/public-pipeline-id.test-d.d.ts +0 -2
- package/dist/__tests__/public-pipeline-id.test-d.d.ts.map +0 -1
- package/dist/__tests__/render-dispatch-membership.unit.test.d.ts +0 -2
- package/dist/__tests__/render-dispatch-membership.unit.test.d.ts.map +0 -1
- package/dist/__tests__/render-feature-construction.unit.test.d.ts +0 -2
- package/dist/__tests__/render-feature-construction.unit.test.d.ts.map +0 -1
- package/dist/__tests__/render-feature-error-code-owner.test-d.d.ts +0 -2
- package/dist/__tests__/render-feature-error-code-owner.test-d.d.ts.map +0 -1
- package/dist/__tests__/render-feature-gpu-buffer-usage-owner.test-d.d.ts +0 -2
- package/dist/__tests__/render-feature-gpu-buffer-usage-owner.test-d.d.ts.map +0 -1
- package/dist/__tests__/render-feature-graph.integration.test.d.ts +0 -2
- package/dist/__tests__/render-feature-graph.integration.test.d.ts.map +0 -1
- package/dist/__tests__/render-feature-graphics-staging.unit.test.d.ts +0 -2
- package/dist/__tests__/render-feature-graphics-staging.unit.test.d.ts.map +0 -1
- package/dist/__tests__/render-feature-order.unit.test.d.ts +0 -2
- package/dist/__tests__/render-feature-order.unit.test.d.ts.map +0 -1
- package/dist/__tests__/render-feature-prepared-graphics-recording.unit.test.d.ts +0 -2
- package/dist/__tests__/render-feature-prepared-graphics-recording.unit.test.d.ts.map +0 -1
- package/dist/__tests__/render-feature-staging.unit.test.d.ts +0 -2
- package/dist/__tests__/render-feature-staging.unit.test.d.ts.map +0 -1
- package/dist/__tests__/renderer-render-scene-public.test-d.d.ts +0 -2
- package/dist/__tests__/renderer-render-scene-public.test-d.d.ts.map +0 -1
- package/dist/__tests__/scene-temporal-coverage.unit.test.d.ts +0 -2
- package/dist/__tests__/scene-temporal-coverage.unit.test.d.ts.map +0 -1
- package/dist/__tests__/sun-snapshot-consumers.test.d.ts +0 -2
- package/dist/__tests__/sun-snapshot-consumers.test.d.ts.map +0 -1
- package/dist/__tests__/surface-backend-kind-owner.test-d.d.ts +0 -2
- package/dist/__tests__/surface-backend-kind-owner.test-d.d.ts.map +0 -1
- package/dist/__tests__/taa-history-store.unit.test.d.ts +0 -2
- package/dist/__tests__/taa-history-store.unit.test.d.ts.map +0 -1
- package/dist/__tests__/temporal-frame-transaction.integration.test.d.ts +0 -2
- package/dist/__tests__/temporal-frame-transaction.integration.test.d.ts.map +0 -1
- package/dist/__tests__/temporal-inspection.unit.test.d.ts +0 -2
- package/dist/__tests__/temporal-inspection.unit.test.d.ts.map +0 -1
- package/dist/assets/__tests__/asset-decoders.unit.test.d.ts +0 -2
- package/dist/assets/__tests__/asset-decoders.unit.test.d.ts.map +0 -1
- package/dist/assets/__tests__/mipmap-generator.unit.test.d.ts +0 -2
- package/dist/assets/__tests__/mipmap-generator.unit.test.d.ts.map +0 -1
- package/dist/assets/__tests__/render-asset-port.unit.test.d.ts +0 -2
- package/dist/assets/__tests__/render-asset-port.unit.test.d.ts.map +0 -1
- package/dist/assets/__tests__/resolve-render-asset.unit.test.d.ts +0 -2
- package/dist/assets/__tests__/resolve-render-asset.unit.test.d.ts.map +0 -1
- package/dist/chunk-33UF5SAO.mjs +0 -7397
- package/dist/chunk-33UF5SAO.mjs.map +0 -1
- package/dist/chunk-A5QCJSNL.mjs +0 -29913
- package/dist/chunk-A5QCJSNL.mjs.map +0 -1
- package/dist/chunk-JMSB7AR4.mjs +0 -3
- package/dist/chunk-JMSB7AR4.mjs.map +0 -1
- package/dist/chunk-LXNGO6AO.mjs +0 -569
- package/dist/chunk-LXNGO6AO.mjs.map +0 -1
- package/dist/chunk-QRXPSX4X.mjs +0 -659
- package/dist/chunk-QRXPSX4X.mjs.map +0 -1
- package/dist/chunk-YAKEQPWO.mjs +0 -1439
- package/dist/chunk-YAKEQPWO.mjs.map +0 -1
- package/dist/components/__tests__/atmosphere-red.test.d.ts +0 -2
- package/dist/components/__tests__/atmosphere-red.test.d.ts.map +0 -1
- package/dist/components/__tests__/atmosphere.test.d.ts +0 -2
- package/dist/components/__tests__/atmosphere.test.d.ts.map +0 -1
- package/dist/components/__tests__/fog.test-d.d.ts +0 -2
- package/dist/components/__tests__/fog.test-d.d.ts.map +0 -1
- package/dist/components/__tests__/fog.test.d.ts +0 -2
- package/dist/components/__tests__/fog.test.d.ts.map +0 -1
- package/dist/components/atmosphere.d.ts +0 -18
- package/dist/components/atmosphere.d.ts.map +0 -1
- package/dist/components/environment.d.ts +0 -116
- package/dist/components/environment.d.ts.map +0 -1
- package/dist/deferred-lighting.d.ts +0 -13
- package/dist/deferred-lighting.d.ts.map +0 -1
- package/dist/dynamic-texture-store.d.ts +0 -42
- package/dist/dynamic-texture-store.d.ts.map +0 -1
- package/dist/environment/__tests__/failure-injection.test.d.ts +0 -2
- package/dist/environment/__tests__/failure-injection.test.d.ts.map +0 -1
- package/dist/environment/__tests__/generation-red.test.d.ts +0 -2
- package/dist/environment/__tests__/generation-red.test.d.ts.map +0 -1
- package/dist/environment/__tests__/generation.test.d.ts +0 -2
- package/dist/environment/__tests__/generation.test.d.ts.map +0 -1
- package/dist/environment/__tests__/graph-transaction.test.d.ts +0 -2
- package/dist/environment/__tests__/graph-transaction.test.d.ts.map +0 -1
- package/dist/environment/__tests__/inspection-red.test.d.ts +0 -2
- package/dist/environment/__tests__/inspection-red.test.d.ts.map +0 -1
- package/dist/environment/__tests__/lifecycle-evidence.test.d.ts +0 -2
- package/dist/environment/__tests__/lifecycle-evidence.test.d.ts.map +0 -1
- package/dist/environment/__tests__/pipeline-topology.test.d.ts +0 -2
- package/dist/environment/__tests__/pipeline-topology.test.d.ts.map +0 -1
- package/dist/environment/__tests__/readiness.test.d.ts +0 -2
- package/dist/environment/__tests__/readiness.test.d.ts.map +0 -1
- package/dist/environment/__tests__/recovery.test.d.ts +0 -2
- package/dist/environment/__tests__/recovery.test.d.ts.map +0 -1
- package/dist/environment/__tests__/resize-dispose.test.d.ts +0 -2
- package/dist/environment/__tests__/resize-dispose.test.d.ts.map +0 -1
- package/dist/environment/__tests__/signature-red.test.d.ts +0 -2
- package/dist/environment/__tests__/signature-red.test.d.ts.map +0 -1
- package/dist/environment/__tests__/signature.test.d.ts +0 -2
- package/dist/environment/__tests__/signature.test.d.ts.map +0 -1
- package/dist/environment/descriptors.d.ts +0 -2
- package/dist/environment/descriptors.d.ts.map +0 -1
- package/dist/environment/extracted-environment.d.ts +0 -53
- package/dist/environment/extracted-environment.d.ts.map +0 -1
- package/dist/environment/generation.d.ts +0 -62
- package/dist/environment/generation.d.ts.map +0 -1
- package/dist/environment/gpu-bundle.d.ts +0 -23
- package/dist/environment/gpu-bundle.d.ts.map +0 -1
- package/dist/environment/graph.d.ts +0 -108
- package/dist/environment/graph.d.ts.map +0 -1
- package/dist/environment/inspection.d.ts +0 -48
- package/dist/environment/inspection.d.ts.map +0 -1
- package/dist/environment/lifecycle.d.ts +0 -22
- package/dist/environment/lifecycle.d.ts.map +0 -1
- package/dist/environment/readiness.d.ts +0 -29
- package/dist/environment/readiness.d.ts.map +0 -1
- package/dist/environment/signature.d.ts +0 -70
- package/dist/environment/signature.d.ts.map +0 -1
- package/dist/extract/__tests__/directional-csm-domain.unit.test.d.ts +0 -2
- package/dist/extract/__tests__/directional-csm-domain.unit.test.d.ts.map +0 -1
- package/dist/extract/__tests__/environment-source.test.d.ts +0 -2
- package/dist/extract/__tests__/environment-source.test.d.ts.map +0 -1
- package/dist/extract/__tests__/schema-readers.unit.test.d.ts +0 -2
- package/dist/extract/__tests__/schema-readers.unit.test.d.ts.map +0 -1
- package/dist/extract/directional-csm.d.ts +0 -129
- package/dist/extract/directional-csm.d.ts.map +0 -1
- package/dist/extract/index.d.ts +0 -5
- package/dist/extract/index.d.ts.map +0 -1
- package/dist/extract/material-interface.d.ts +0 -56
- package/dist/extract/material-interface.d.ts.map +0 -1
- package/dist/extract/schema-readers.d.ts +0 -20
- package/dist/extract/schema-readers.d.ts.map +0 -1
- package/dist/features/graph-contribution.d.ts +0 -64
- package/dist/features/graph-contribution.d.ts.map +0 -1
- package/dist/features/index.d.ts +0 -21
- package/dist/features/index.d.ts.map +0 -1
- package/dist/features/morph/index.d.ts +0 -3
- package/dist/features/morph/index.d.ts.map +0 -1
- package/dist/features/morph/morph-bounds.d.ts +0 -42
- package/dist/features/morph/morph-bounds.d.ts.map +0 -1
- package/dist/features/scene-temporal.d.ts +0 -45
- package/dist/features/scene-temporal.d.ts.map +0 -1
- package/dist/features/taa-resolve.d.ts +0 -21
- package/dist/features/taa-resolve.d.ts.map +0 -1
- package/dist/frame-chain.d.ts +0 -14
- package/dist/frame-chain.d.ts.map +0 -1
- package/dist/gpu-driven/view-reference.d.ts.map +0 -1
- package/dist/gpu-resource-store.d.ts.map +0 -1
- package/dist/hdrp-cluster-membership.d.ts +0 -2
- package/dist/hdrp-cluster-membership.d.ts.map +0 -1
- package/dist/hdrp-pipeline.d.ts +0 -36
- package/dist/hdrp-pipeline.d.ts.map +0 -1
- package/dist/ibl/cubemap-projection.d.ts +0 -23
- package/dist/ibl/cubemap-projection.d.ts.map +0 -1
- package/dist/ibl/face-uniforms.d.ts +0 -65
- package/dist/ibl/face-uniforms.d.ts.map +0 -1
- package/dist/mesh-update-errors.d.ts +0 -71
- package/dist/mesh-update-errors.d.ts.map +0 -1
- package/dist/mipmap-generator.d.ts +0 -39
- package/dist/mipmap-generator.d.ts.map +0 -1
- package/dist/param-schema-projection-census.d.ts +0 -18
- package/dist/param-schema-projection-census.d.ts.map +0 -1
- package/dist/persistent-render-scene.d.ts +0 -158
- package/dist/persistent-render-scene.d.ts.map +0 -1
- package/dist/pipeline/index.d.ts +0 -11
- package/dist/pipeline/index.d.ts.map +0 -1
- package/dist/pipeline-errors.d.ts +0 -110
- package/dist/pipeline-errors.d.ts.map +0 -1
- package/dist/prepare/__tests__/schema-readers.unit.test.d.ts +0 -2
- package/dist/prepare/__tests__/schema-readers.unit.test.d.ts.map +0 -1
- package/dist/prepare/index.d.ts +0 -4
- package/dist/prepare/index.d.ts.map +0 -1
- package/dist/prepare/schema-readers.d.ts +0 -11
- package/dist/prepare/schema-readers.d.ts.map +0 -1
- package/dist/record/__tests__/environment-record.test.d.ts +0 -2
- package/dist/record/__tests__/environment-record.test.d.ts.map +0 -1
- package/dist/record/__tests__/frame-targets.unit.test.d.ts +0 -2
- package/dist/record/__tests__/frame-targets.unit.test.d.ts.map +0 -1
- package/dist/record/__tests__/membership-timing.unit.test.d.ts +0 -2
- package/dist/record/__tests__/membership-timing.unit.test.d.ts.map +0 -1
- package/dist/record/__tests__/render-submission.integration.test.d.ts +0 -2
- package/dist/record/__tests__/render-submission.integration.test.d.ts.map +0 -1
- package/dist/record/__tests__/render-submission.perf.test.d.ts +0 -2
- package/dist/record/__tests__/render-submission.perf.test.d.ts.map +0 -1
- package/dist/record/__tests__/shadow-submit-mode.unit.test.d.ts +0 -2
- package/dist/record/__tests__/shadow-submit-mode.unit.test.d.ts.map +0 -1
- package/dist/record/__tests__/view-ubo-layout.unit.test.d.ts +0 -2
- package/dist/record/__tests__/view-ubo-layout.unit.test.d.ts.map +0 -1
- package/dist/record/frame-observation.d.ts +0 -38
- package/dist/record/frame-observation.d.ts.map +0 -1
- package/dist/record/index.d.ts +0 -15
- package/dist/record/index.d.ts.map +0 -1
- package/dist/record/main-pass-skin.d.ts +0 -46
- package/dist/record/main-pass-skin.d.ts.map +0 -1
- package/dist/record/main-pass-sprite.d.ts +0 -69
- package/dist/record/main-pass-sprite.d.ts.map +0 -1
- package/dist/record/material-payload.d.ts +0 -43
- package/dist/record/material-payload.d.ts.map +0 -1
- package/dist/record/material-slot-plan.d.ts +0 -26
- package/dist/record/material-slot-plan.d.ts.map +0 -1
- package/dist/record/membership-timing.d.ts +0 -232
- package/dist/record/membership-timing.d.ts.map +0 -1
- package/dist/record/shadow-caster-uniform.d.ts +0 -8
- package/dist/record/shadow-caster-uniform.d.ts.map +0 -1
- package/dist/record/shadow-submit-mode.d.ts +0 -66
- package/dist/record/shadow-submit-mode.d.ts.map +0 -1
- package/dist/render-dispatch-membership.d.ts +0 -47
- package/dist/render-dispatch-membership.d.ts.map +0 -1
- package/dist/render-pipeline-context.d.ts +0 -289
- package/dist/render-pipeline-context.d.ts.map +0 -1
- package/dist/render-pipeline-target.d.ts +0 -16
- package/dist/render-pipeline-target.d.ts.map +0 -1
- package/dist/render-scene-projection.d.ts +0 -174
- package/dist/render-scene-projection.d.ts.map +0 -1
- package/dist/render-system-fold.d.ts +0 -266
- package/dist/render-system-fold.d.ts.map +0 -1
- package/dist/renderer/asset-service.d.ts +0 -10
- package/dist/renderer/asset-service.d.ts.map +0 -1
- package/dist/renderer/backend-selection.d.ts.map +0 -1
- package/dist/renderer/environment-classify.d.ts +0 -6
- package/dist/renderer/environment-classify.d.ts.map +0 -1
- package/dist/renderer/environment-error.d.ts +0 -13
- package/dist/renderer/environment-error.d.ts.map +0 -1
- package/dist/renderer/material/pipeline-projection.d.ts +0 -91
- package/dist/renderer/material/pipeline-projection.d.ts.map +0 -1
- package/dist/renderer/renderer-factory.d.ts +0 -283
- package/dist/renderer/renderer-factory.d.ts.map +0 -1
- package/dist/renderer.d.ts +0 -771
- package/dist/renderer.d.ts.map +0 -1
- package/dist/scene-utils/collect-subtree.d.ts +0 -11
- package/dist/scene-utils/collect-subtree.d.ts.map +0 -1
- package/dist/ssao-data.d.ts +0 -34
- package/dist/ssao-data.d.ts.map +0 -1
- package/dist/surface-format.d.ts +0 -10
- package/dist/surface-format.d.ts.map +0 -1
- package/dist/taa-history-store.d.ts +0 -88
- package/dist/taa-history-store.d.ts.map +0 -1
- package/dist/temporal-coverage.d.ts +0 -35
- package/dist/temporal-coverage.d.ts.map +0 -1
- package/dist/temporal-frame-transaction.d.ts +0 -92
- package/dist/temporal-frame-transaction.d.ts.map +0 -1
- package/dist/temporal-inspection.d.ts +0 -57
- package/dist/temporal-inspection.d.ts.map +0 -1
- package/dist/temporal-view.d.ts +0 -43
- package/dist/temporal-view.d.ts.map +0 -1
- package/dist/tilemap/resolve-tileset-runtime.d.ts +0 -23
- package/dist/tilemap/resolve-tileset-runtime.d.ts.map +0 -1
- package/dist/urp-pipeline.d.ts +0 -4
- package/dist/urp-pipeline.d.ts.map +0 -1
- package/src/__tests__/analytic-sky-contract.test.ts +0 -27
- package/src/__tests__/analytic-sky-falsify-carriers.mjs +0 -43
- package/src/__tests__/analytic-sky-falsify.test.ts +0 -94
- package/src/__tests__/assets-runtime-handoff.integration.test.ts +0 -36
- package/src/__tests__/backend-selection.integration.test.ts +0 -11
- package/src/__tests__/camera-temporal.test-d.ts +0 -8
- package/src/__tests__/camera-temporal.test.ts +0 -188
- package/src/__tests__/directional-shadow-probe-atlas-layout.unit.test.ts +0 -18
- package/src/__tests__/environment-inspection.test.ts +0 -45
- package/src/__tests__/fog-ai-user.fixture.ts +0 -350
- package/src/__tests__/fog-custom-render-feature.fixture.ts +0 -33
- package/src/__tests__/fog-custom-render-feature.integration.test.ts +0 -76
- package/src/__tests__/fog-inspection.integration.test.ts +0 -127
- package/src/__tests__/fog-owner-state.integration.test.ts +0 -112
- package/src/__tests__/fog-pipeline-topology.integration.test.ts +0 -93
- package/src/__tests__/fog-public-surface.integration.test.ts +0 -60
- package/src/__tests__/fog-ray-contract.integration.test.ts +0 -73
- package/src/__tests__/fog-source-absence.integration.test.ts +0 -51
- package/src/__tests__/fog-temporal.integration.test.ts +0 -115
- package/src/__tests__/frame-chain.unit.test.ts +0 -26
- package/src/__tests__/gpu-scene-field-type-owner.test-d.ts +0 -27
- package/src/__tests__/hdrp-pipeline.unit.test.ts +0 -100
- package/src/__tests__/ibl/ibl-fallback.unit.test.ts +0 -23
- package/src/__tests__/material-derived-error-stop-draw.integration.test.ts +0 -69
- package/src/__tests__/material-derived-payload.integration.test.ts +0 -164
- package/src/__tests__/materials.unit.test.ts +0 -25
- package/src/__tests__/param-schema-projection-census.unit.test.ts +0 -40
- package/src/__tests__/persistent-render-scene.unit.test.ts +0 -1311
- package/src/__tests__/pipeline-error-policy-owner.unit.test.ts +0 -167
- package/src/__tests__/pipeline-pass-trace.test.ts +0 -92
- package/src/__tests__/pipeline-stage-owner.test-d.ts +0 -13
- package/src/__tests__/plugin.test.ts +0 -25
- package/src/__tests__/prepared-graphics-backend-matrix.unit.test.ts +0 -129
- package/src/__tests__/prepared-graphics-resolver-recording.unit.test.ts +0 -180
- package/src/__tests__/public-pipeline-id.test-d.ts +0 -6
- package/src/__tests__/render-dispatch-membership.unit.test.ts +0 -117
- package/src/__tests__/render-feature-construction.unit.test.ts +0 -124
- package/src/__tests__/render-feature-error-code-owner.test-d.ts +0 -27
- package/src/__tests__/render-feature-gpu-buffer-usage-owner.test-d.ts +0 -46
- package/src/__tests__/render-feature-graph.integration.test.ts +0 -205
- package/src/__tests__/render-feature-graphics-staging.unit.test.ts +0 -200
- package/src/__tests__/render-feature-order.unit.test.ts +0 -66
- package/src/__tests__/render-feature-prepared-graphics-recording.unit.test.ts +0 -107
- package/src/__tests__/render-feature-staging.unit.test.ts +0 -94
- package/src/__tests__/renderer-render-scene-public.test-d.ts +0 -27
- package/src/__tests__/scene-temporal-coverage.unit.test.ts +0 -259
- package/src/__tests__/sun-snapshot-consumers.test.ts +0 -35
- package/src/__tests__/surface-backend-kind-owner.test-d.ts +0 -42
- package/src/__tests__/taa-history-store.unit.test.ts +0 -196
- package/src/__tests__/temporal-frame-transaction.integration.test.ts +0 -537
- package/src/__tests__/temporal-inspection.unit.test.ts +0 -138
- package/src/assets/__tests__/asset-decoders.unit.test.ts +0 -92
- package/src/assets/__tests__/mipmap-generator.unit.test.ts +0 -52
- package/src/assets/__tests__/render-asset-port.unit.test.ts +0 -54
- package/src/assets/__tests__/resolve-render-asset.unit.test.ts +0 -47
- package/src/components/__tests__/atmosphere-red.test.ts +0 -51
- package/src/components/__tests__/atmosphere.test.ts +0 -79
- package/src/components/__tests__/fog.test-d.ts +0 -49
- package/src/components/__tests__/fog.test.ts +0 -60
- package/src/components/atmosphere.ts +0 -64
- package/src/deferred-lighting.ts +0 -92
- package/src/dynamic-texture-store.ts +0 -111
- package/src/environment/README.md +0 -76
- package/src/environment/__tests__/failure-injection.test.ts +0 -50
- package/src/environment/__tests__/generation-red.test.ts +0 -64
- package/src/environment/__tests__/generation.test.ts +0 -37
- package/src/environment/__tests__/graph-transaction.test.ts +0 -85
- package/src/environment/__tests__/inspection-red.test.ts +0 -53
- package/src/environment/__tests__/lifecycle-evidence.test.ts +0 -40
- package/src/environment/__tests__/pipeline-topology.test.ts +0 -33
- package/src/environment/__tests__/readiness.test.ts +0 -42
- package/src/environment/__tests__/recovery.test.ts +0 -62
- package/src/environment/__tests__/resize-dispose.test.ts +0 -30
- package/src/environment/__tests__/signature-red.test.ts +0 -45
- package/src/environment/__tests__/signature.test.ts +0 -60
- package/src/environment/descriptors.ts +0 -7
- package/src/environment/extracted-environment.ts +0 -239
- package/src/environment/generation.ts +0 -158
- package/src/environment/gpu-bundle.ts +0 -144
- package/src/environment/graph.ts +0 -588
- package/src/environment/inspection.ts +0 -107
- package/src/environment/lifecycle.ts +0 -124
- package/src/environment/readiness.ts +0 -76
- package/src/environment/signature.ts +0 -185
- package/src/extract/__tests__/directional-csm-domain.unit.test.ts +0 -391
- package/src/extract/__tests__/environment-source.test.ts +0 -105
- package/src/extract/__tests__/schema-readers.unit.test.ts +0 -16
- package/src/extract/directional-csm.ts +0 -959
- package/src/extract/index.ts +0 -10
- package/src/extract/material-interface.ts +0 -604
- package/src/extract/schema-readers.ts +0 -27
- package/src/features/graph-contribution.ts +0 -577
- package/src/features/index.ts +0 -100
- package/src/features/morph/index.ts +0 -24
- package/src/features/morph/morph-bounds.ts +0 -123
- package/src/features/scene-temporal.ts +0 -274
- package/src/features/taa-resolve.ts +0 -244
- package/src/frame-chain.ts +0 -21
- package/src/hdrp-cluster-membership.ts +0 -70
- package/src/ibl/cubemap-projection.ts +0 -60
- package/src/ibl/face-uniforms.ts +0 -150
- package/src/mesh-update-errors.ts +0 -113
- package/src/mipmap-generator.ts +0 -244
- package/src/param-schema-projection-census.ts +0 -73
- package/src/persistent-render-scene.ts +0 -1752
- package/src/pipeline/index.ts +0 -40
- package/src/pipeline-errors.ts +0 -172
- package/src/prepare/__tests__/schema-readers.unit.test.ts +0 -16
- package/src/prepare/index.ts +0 -8
- package/src/prepare/schema-readers.ts +0 -20
- package/src/record/__tests__/environment-record.test.ts +0 -35
- package/src/record/__tests__/frame-targets.unit.test.ts +0 -54
- package/src/record/__tests__/membership-timing.unit.test.ts +0 -524
- package/src/record/__tests__/render-submission.integration.test.ts +0 -76
- package/src/record/__tests__/render-submission.perf.test.ts +0 -141
- package/src/record/__tests__/shadow-submit-mode.unit.test.ts +0 -88
- package/src/record/__tests__/view-ubo-layout.unit.test.ts +0 -101
- package/src/record/frame-observation.ts +0 -122
- package/src/record/index.ts +0 -15
- package/src/record/main-pass-skin.ts +0 -51
- package/src/record/main-pass-sprite.ts +0 -166
- package/src/record/material-payload.ts +0 -292
- package/src/record/material-slot-plan.ts +0 -68
- package/src/record/membership-timing.ts +0 -1012
- package/src/record/shadow-caster-uniform.ts +0 -37
- package/src/record/shadow-submit-mode.ts +0 -277
- package/src/render-dispatch-membership.ts +0 -155
- package/src/render-pipeline-context.ts +0 -332
- package/src/render-pipeline-target.ts +0 -96
- package/src/render-scene-projection.ts +0 -1738
- package/src/render-system-fold.ts +0 -531
- package/src/renderer/asset-service.ts +0 -32
- package/src/renderer/backend-selection.ts +0 -121
- package/src/renderer/environment-classify.ts +0 -30
- package/src/renderer/environment-error.ts +0 -19
- package/src/renderer/material/pipeline-projection.ts +0 -140
- package/src/renderer.ts +0 -940
- package/src/scene-utils/collect-subtree.ts +0 -40
- package/src/ssao-data.ts +0 -106
- package/src/surface-format.ts +0 -37
- package/src/taa-history-store.ts +0 -429
- package/src/temporal-coverage.ts +0 -106
- package/src/temporal-frame-transaction.ts +0 -301
- package/src/temporal-inspection.ts +0 -194
- package/src/temporal-view.ts +0 -174
- package/src/tilemap/resolve-tileset-runtime.ts +0 -72
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/engine-metrics.ts","../src/ibl/face-uniforms.ts","../src/gpu-resource-store.ts","../src/lifecycle.ts","../src/pipeline-builder.ts","../src/systems/skin-palette-allocator.ts","../src/renderer/environment-error.ts","../src/renderer/asset-service.ts","../src/renderer/material/assembly.ts","../src/assets/render-asset-port.ts","../src/dynamic-texture-store.ts","../src/hdrp-cluster-membership.ts","../src/renderer/backend-selection.ts","../src/renderer/environment-classify.ts","../src/renderer/renderer-factory.ts"],"names":["expectedByteLength","err","RhiError","buffer","previousBuffer","ok","handleSlot","RhiErrorClass","loadRhiPack","v"],"mappings":";;;;;;;;;;;;;AA6DO,IAAM,oBAAN,MAAiD;AAAA,EACrC,QAAA,uBAAe,GAAA,EAAoB;AAAA,EAEpD,UAAU,IAAA,EAAoB;AAC5B,IAAA,IAAA,CAAK,QAAA,CAAS,IAAI,IAAA,EAAA,CAAO,IAAA,CAAK,SAAS,GAAA,CAAI,IAAI,CAAA,IAAK,CAAA,IAAK,CAAC,CAAA;AAAA,EAC5D;AAAA,EAEA,QAAA,GAA6C;AAC3C,IAAA,MAAM,MAA8B,EAAC;AACrC,IAAA,KAAA,MAAW,CAAC,CAAA,EAAG,CAAC,CAAA,IAAK,KAAK,QAAA,EAAU;AAClC,MAAA,GAAA,CAAI,CAAC,CAAA,GAAI,CAAA;AAAA,IACX;AACA,IAAA,OAAO,MAAA,CAAO,OAAO,GAAG,CAAA;AAAA,EAC1B;AAAA,EAEA,KAAA,GAAc;AACZ,IAAA,IAAA,CAAK,SAAS,KAAA,EAAM;AAAA,EACtB;AACF,CAAA;AAOO,SAAS,mBAAA,GAAqC;AACnD,EAAA,OAAO,IAAI,iBAAA,EAAkB;AAC/B;;;ACpEA,IAAM,qBAAA,GAAwB,GAAA;AAC9B,IAAM,UAAA,GAAa,CAAA;AACnB,IAAM,0BAA0B,oBAAA,GAAuB,UAAA;AAmBhD,SAAS,yBACd,MAAA,EAE0D;AAC1D,EAAA,OAAO,OAAO,YAAA,CAAa;AAAA,IACzB,KAAA,EAAO,mBAAA;AAAA,IACP,MAAM,UAAA,GAAa,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MAAM,SAAS,MAAA,YAAkB,KAAA,GAAQ,MAAA,CAAO,OAAA,GAAU,OAAO,MAAM,CAAA;AACvE,IAAA,OAAOA,GAAAA;AAAA,MACL,IAAIC,QAAAA,CAAS;AAAA,QACX,IAAA,EAAM,YAAA;AAAA,QACN,QAAA;AAAA,QACA,IAAA,EAAM,CAAA,EAAG,IAAI,CAAA,SAAA,EAAY,MAAM,CAAA,CAAA;AAAA,OAChC;AAAA,KACH;AAAA,EACF;AACF","file":"chunk-33UF5SAO.mjs","sourcesContent":["import type { EngineMetrics } from '@forgeax/engine-types';\n\n// @forgeax/engine-runtime — EngineMetrics public API (feat-20260527-sprite-nineslice\n// M4 / w16). A per-Renderer counter Map exposed through `renderer.metrics` so AI\n// users observe runtime-time soft signals (e.g. nineslice scale too small,\n// nineslice tile mode without sampler repeat) without parsing console.warn text\n// or reaching into engine internals (charter F1 minimum surface, P3 machine-\n// readable signals over text logs).\n//\n// Surface — three methods:\n//\n// | Method | Purpose |\n// |:-------------------------------|:--------------------------------------------|\n// | `increment(name)` | Bump the counter for `name` by 1. |\n// | `snapshot()` | Read all counters as an immutable object. |\n// | `reset()` | Drop every counter (test isolation hook). |\n//\n// Naming convention (charter P5 consistent abstraction): counter keys use a\n// dot-delimited namespace `<feature>.<event>`. Two features own keys today:\n//\n// - `nineslice.scale-too-small` — Transform.scale below the four\n// corner anchors at draw time (AC-16, w17 end-to-end test).\n// - `nineslice.tile-needs-repeat-sampler` — sliceMode=1 (tile) bound to a\n// sampler whose addressMode is not `'repeat'`; the visual silently\n// degrades to clamp-stretch (D-9, w18 register-time soft-warn).\n// - `render.instancing.foldedDraws` — feat-20260622-chunk-gpu-\n// instancing-sprite-tilemap M3 / D-3. Count of instanced drawIndexed\n// calls the fold operator emits this frame; one increment per non-\n// singleton head bucket retained after the M2 / w11 cap-fallback\n// filter. NOT entity count, NOT pre-filter bucket count. AI users\n// read it via `renderer.metrics.snapshot()['render.instancing.foldedDraws']`\n// to verify fold actually reduced draw count under mode-0 (LAYER_Z)\n// transparent sort. The key is exported as `FOLDED_DRAWS_METRIC_KEY`\n// from `render-system-fold.ts` (single source of truth — engine\n// calls increment via the helper, never the literal string).\n// - `shadow.csm.*` — debug-only semantic census for\n// directional shadow token construction and atlas cache hit/miss reasons.\n// These counters are emitted only when RHI semantic observation is enabled;\n// they are not a production performance or rendering contract.\n//\n// Multi-Renderer isolation (D-5 candidate 1): each Renderer instance owns its\n// own EngineMetrics; counters from one renderer never bleed into another.\n// `createRenderer.ts` constructs a fresh instance per call; tests that spin\n// up multiple renderers can read each `renderer.metrics.snapshot()` in\n// isolation.\n\n// The EngineMetrics interface (3-method contract, zero type dependencies) sank\n// into @forgeax/engine-types (feat-20260705-runtime-tier2-decomposition M1 / w2,\n// D-3). Re-exported here so existing `import { EngineMetrics } from\n// './engine-metrics'` consumers keep resolving; EngineMetricsImpl +\n// createEngineMetrics remain runtime-owned.\nexport type { EngineMetrics };\n\n/**\n * Default `EngineMetrics` implementation — a thin `Map<string, number>` with\n * the three-method surface bolted on. The map is private; readers consume\n * the snapshot accessor.\n *\n * @internal — instances are constructed by `createRenderer` and surfaced\n * through `Renderer.metrics`; AI users do not import this class directly.\n */\nexport class EngineMetricsImpl implements EngineMetrics {\n private readonly counters = new Map<string, number>();\n\n increment(name: string): void {\n this.counters.set(name, (this.counters.get(name) ?? 0) + 1);\n }\n\n snapshot(): Readonly<Record<string, number>> {\n const out: Record<string, number> = {};\n for (const [k, v] of this.counters) {\n out[k] = v;\n }\n return Object.freeze(out);\n }\n\n reset(): void {\n this.counters.clear();\n }\n}\n\n/**\n * Fresh `EngineMetrics` factory; the only construction path used by\n * `createRenderer`. Keeping the constructor private (via the factory) leaves\n * room to swap the backing store without touching call sites.\n */\nexport function createEngineMetrics(): EngineMetrics {\n return new EngineMetricsImpl();\n}\n","// face-uniforms.ts -- M3.5 t55.\n//\n// CPU-side helpers that allocate + populate the per-face viewProj uniform\n// buffer (6 entries) and the per-prefilter-sub-pass roughness uniform\n// buffer (5 mip x 6 face = 30 entries). Both are 256-byte stride to honour\n// the WebGPU dynamic-offset alignment SSOT (plan-strategy section 3.2\n// sequence diagram, D-9 face-uniforms layout cross-pipeline reuse).\n//\n// The buffer payloads are:\n// faceUniforms[face] = mat4x4<f32> viewProj (64 byte usable; 256 byte stride)\n// prefilterUniforms[idx] = { roughness: f32, faceSize: f32, _pad0, _pad1 }\n// (16 byte usable; 256 byte stride)\n//\n// Indexed as:\n// face = 0..5\n// prefilter = mip * 6 + face (mip 0..4, face 0..5)\n\nimport { GPU_BUFFER_USAGE_COPY_DST, GPU_BUFFER_USAGE_UNIFORM } from '../gpu-usage';\nimport { CAPTURE_VIEW_PROJS, PREFILTER_MIP_LEVELS, PREFILTER_SIZE } from './IblPipelineCache';\n\nconst DYNAMIC_OFFSET_STRIDE = 256;\nconst FACE_COUNT = 6;\nconst PREFILTER_SUBPASS_COUNT = PREFILTER_MIP_LEVELS * FACE_COUNT;\n\n/**\n * Minimal device shape consumed by the helpers -- mirrors\n * `IblPipelineDevice` createBuffer surface plus queue.writeBuffer.\n */\nexport interface FaceUniformsDevice {\n // biome-ignore lint/suspicious/noExplicitAny: shim shape\n createBuffer(desc: any): { ok: true; value: any } | { ok: false; error: unknown };\n readonly queue: {\n // biome-ignore lint/suspicious/noExplicitAny: shim shape\n writeBuffer?: (...args: any[]) => unknown;\n };\n}\n\n/**\n * Allocate the 6-face viewProj uniform buffer. Size = 6 * 256 bytes so\n * each face slot is dynamic-offset addressable.\n */\nexport function createFaceUniformsBuffer(\n device: FaceUniformsDevice,\n // biome-ignore lint/suspicious/noExplicitAny: opaque GPU buffer\n): { ok: true; value: any } | { ok: false; error: unknown } {\n return device.createBuffer({\n label: 'ibl-face-uniforms',\n size: FACE_COUNT * DYNAMIC_OFFSET_STRIDE,\n usage: GPU_BUFFER_USAGE_UNIFORM | GPU_BUFFER_USAGE_COPY_DST,\n mappedAtCreation: false,\n });\n}\n\n/**\n * Allocate the prefilter sub-pass uniform buffer. Size = 30 * 256 bytes.\n */\nexport function createPrefilterUniformsBuffer(\n device: FaceUniformsDevice,\n // biome-ignore lint/suspicious/noExplicitAny: opaque GPU buffer\n): { ok: true; value: any } | { ok: false; error: unknown } {\n return device.createBuffer({\n label: 'ibl-prefilter-uniforms',\n size: PREFILTER_SUBPASS_COUNT * DYNAMIC_OFFSET_STRIDE,\n usage: GPU_BUFFER_USAGE_UNIFORM | GPU_BUFFER_USAGE_COPY_DST,\n mappedAtCreation: false,\n });\n}\n\n/**\n * Write a single face's viewProj matrix at the dynamic-offset slot.\n *\n * @param device device with queue.writeBuffer\n * @param buffer face-uniforms buffer from createFaceUniformsBuffer\n * @param faceIdx 0..5\n * @param viewProj 16-element column-major mat4\n */\nexport function writeFaceUniforms(\n device: FaceUniformsDevice,\n // biome-ignore lint/suspicious/noExplicitAny: opaque GPU buffer\n buffer: any,\n faceIdx: number,\n viewProj: Float32Array,\n): void {\n if (typeof device.queue.writeBuffer !== 'function') return;\n if (faceIdx < 0 || faceIdx >= FACE_COUNT) {\n throw new Error(`writeFaceUniforms: faceIdx ${faceIdx} out of range [0,5]`);\n }\n if (viewProj.length !== 16) {\n throw new Error(`writeFaceUniforms: viewProj must be 16 floats, got ${viewProj.length}`);\n }\n device.queue.writeBuffer(buffer, faceIdx * DYNAMIC_OFFSET_STRIDE, viewProj);\n}\n\n/**\n * Write all 6 capture viewProj matrices into the face-uniforms buffer.\n * Uses the static CAPTURE_VIEW_PROJS SSOT from IblPipelineCache.\n */\nexport function writeAllFaceUniforms(\n device: FaceUniformsDevice,\n // biome-ignore lint/suspicious/noExplicitAny: opaque GPU buffer\n buffer: any,\n): void {\n for (let face = 0; face < FACE_COUNT; face++) {\n const vp = CAPTURE_VIEW_PROJS[face];\n if (vp === undefined) continue;\n writeFaceUniforms(device, buffer, face, vp);\n }\n}\n\n/**\n * Write a single prefilter sub-pass uniform slot (roughness + faceSize).\n * subPassIdx = mip * 6 + face.\n */\nexport function writePrefilterUniforms(\n device: FaceUniformsDevice,\n // biome-ignore lint/suspicious/noExplicitAny: opaque GPU buffer\n buffer: any,\n subPassIdx: number,\n roughness: number,\n mipFaceSize: number,\n): void {\n if (typeof device.queue.writeBuffer !== 'function') return;\n if (subPassIdx < 0 || subPassIdx >= PREFILTER_SUBPASS_COUNT) {\n throw new Error(`writePrefilterUniforms: subPassIdx ${subPassIdx} out of range`);\n }\n const payload = new Float32Array([roughness, mipFaceSize, 0, 0]);\n device.queue.writeBuffer(buffer, subPassIdx * DYNAMIC_OFFSET_STRIDE, payload);\n}\n\n/**\n * Write all 30 prefilter sub-pass uniforms (5 mip x 6 face) with\n * roughness = mip / (mipLevels - 1) and mipFaceSize halved per mip.\n */\nexport function writeAllPrefilterUniforms(\n device: FaceUniformsDevice,\n // biome-ignore lint/suspicious/noExplicitAny: opaque GPU buffer\n buffer: any,\n): void {\n for (let mip = 0; mip < PREFILTER_MIP_LEVELS; mip++) {\n const roughness = mip / (PREFILTER_MIP_LEVELS - 1);\n const mipFaceSize = PREFILTER_SIZE / 2 ** mip;\n for (let face = 0; face < FACE_COUNT; face++) {\n writePrefilterUniforms(device, buffer, mip * FACE_COUNT + face, roughness, mipFaceSize);\n }\n }\n}\n\nexport const FACE_UNIFORMS_STRIDE = DYNAMIC_OFFSET_STRIDE;\nexport const FACE_UNIFORMS_BUFFER_SIZE = FACE_COUNT * DYNAMIC_OFFSET_STRIDE;\nexport const PREFILTER_UNIFORMS_BUFFER_SIZE = PREFILTER_SUBPASS_COUNT * DYNAMIC_OFFSET_STRIDE;\n","// @forgeax/engine-runtime - GpuResourceStore\n// (feat-20260601-gpu-resource-store-extraction M1; M2 added the deriveRenderData\n// projection seam — see render-data.ts).\n//\n// Owns the GPU residency layer extracted from AssetRegistry: per-handle GPU\n// texture / cubemap / mesh buffer caches plus the upload primitives that\n// build them. The store is engine-agnostic by default (no @webgpu/types\n// imports) and holds ZERO reference to AssetRegistry (D-2): every upload\n// primitive receives its source POD from the caller, never reaches back into\n// a registry. The cubemap path mints its EquirectAsset POD handle through\n// a wire-injected `registerCube` callback (D-3) so CPU cataloguing stays the\n// registry's job while the store keeps the single-call upload contract. The\n// cubemap projection (`_uploadCubemapFromEquirect`) is internal (@internal,\n// feat-20260630): AI users declare `Skylight{equirect}` and the render-system\n// record arm drives the projection; the method is never reached from user code.\n//\n// Residency model (D-2 pull): consumers call `ensureResident(handle, pod)`\n// at first draw-time access; the store builds the GPU resource on a miss and\n// returns the cached handles on subsequent O(1) hits. There is no global\n// replay queue -- the pull model is purely lazy (user ruling). Builtin\n// meshes are NOT routed through `ensureResident`; createRenderer seeds them\n// via its step-3 direct upload + pipelineState.meshes (D-1).\n//\n// Texture residency is SYNCHRONOUS (D-9): `uploadTexture`'s only async source\n// was the one-time per-device mipmap shader-module build, which is hoisted to\n// `prewarmMipmapPipeline` (called from `createRenderer.ready`, already async).\n// After prewarm the per-texture mipmap blit is pure synchronous encoder work,\n// so the sync `draw(world)` frame contract is preserved. A format that was\n// not prewarmed surfaces a structured RhiError on the sync path -- it is never\n// lazily awaited (that would break the sync draw contract).\n\nimport type { World } from '@forgeax/engine-ecs';\nimport type { VertexLayoutProjection } from '@forgeax/engine-geometry';\nimport { halfFloat } from '@forgeax/engine-math';\nimport {\n type Buffer,\n err,\n ok,\n type Result,\n type RhiCaps,\n type RhiDevice,\n RhiError,\n type Sampler,\n type Texture,\n type TextureView,\n} from '@forgeax/engine-rhi';\nimport {\n ASSET_ERROR_HINTS,\n type AssetError,\n type DecodedImage,\n type EquirectAsset,\n type Handle,\n handleSlot,\n IMAGE_ERROR_HINTS,\n type ImageError,\n type ImageErrorCode,\n type ImageErrorDetailFor,\n type ImageErrorFor,\n type PrimitiveTopology,\n type SamplerAsset,\n type Submesh,\n type TextureAsset,\n type MeshAsset as TypesMeshAsset,\n} from '@forgeax/engine-types';\nimport { GpuBuffer, GpuTexture } from './gpu-resource';\nimport { GPU_TEXTURE_USAGE_COPY_DST, GPU_TEXTURE_USAGE_TEXTURE_BINDING } from './gpu-texture-usage';\nimport {\n GPU_BUFFER_USAGE_COPY_DST,\n GPU_BUFFER_USAGE_INDEX,\n GPU_BUFFER_USAGE_VERTEX,\n} from './gpu-usage';\nimport {\n createFaceUniformsBuffer,\n createPrefilterUniformsBuffer,\n writeAllFaceUniforms,\n writeAllPrefilterUniforms,\n} from './ibl/face-uniforms';\nimport {\n CUBEMAP_FACE_VERTICES,\n createIblPipelines,\n runIblPrecompute,\n} from './ibl/IblPipelineCache';\nimport type { RhiErrorListenerRegistry } from './lifecycle';\nimport {\n type MeshRangeInvalidReason,\n MeshUpdateError,\n type MeshUpdateError as MeshUpdateErrorType,\n} from './mesh-update-errors';\nimport {\n blitMipmapsSync,\n getOrCreateMipmapPipeline,\n type MipmapBlitDevice,\n type MipmapShaderModuleFactory,\n} from './mipmap-generator';\nimport {\n type CubeRenderData,\n deriveMipUploadLayout,\n deriveRenderDataCubemap,\n deriveRenderDataMesh,\n deriveRenderDataTexture,\n type MeshRenderData,\n type TextureRenderData,\n} from './render-data';\n\n// AssetError is constructed without importing the AssetRegistry's class; the\n// store builds the 4-field surface (.code / .expected / .hint / .detail)\n// directly against the @forgeax/engine-types SSOT (charter P5 producer /\n// consumer split; mirrors AssetRegistry's local RuntimeImageError).\nclass RuntimeAssetError extends Error implements AssetError {\n readonly code: AssetError['code'];\n readonly expected: string;\n readonly hint: string;\n constructor(fields: { code: AssetError['code']; expected: string; hint: string }) {\n super(`[AssetError ${fields.code}] expected: ${fields.expected}; hint: ${fields.hint}`);\n this.name = 'AssetError';\n this.code = fields.code;\n this.expected = fields.expected;\n this.hint = fields.hint;\n }\n}\n\nfunction makeAssetError(fields: {\n code: AssetError['code'];\n expected: string;\n hint: string;\n}): AssetError {\n return new RuntimeAssetError(fields);\n}\n\nconst IMAGE_ERROR_EXPECTED_LOCAL: Readonly<Record<string, string>> = {\n 'image-decode-failed': 'PNG / JPG byte stream decodes successfully',\n 'image-format-unsupported': \"format ends in '-srgb' iff colorSpace is 'srgb' (linear otherwise)\",\n 'image-dimension-out-of-bounds':\n 'width and height fall under device caps maxTextureDimension2D (or 16384 hard cap)',\n};\n\nclass RuntimeImageError<C extends ImageErrorCode> extends Error implements ImageErrorFor<C> {\n readonly code: C;\n readonly expected: string;\n readonly hint: string;\n readonly detail: ImageErrorDetailFor<C>;\n constructor(detail: ImageErrorDetailFor<C>) {\n const code = detail.code;\n const expected = IMAGE_ERROR_EXPECTED_LOCAL[code] ?? '';\n const hint = IMAGE_ERROR_HINTS[code];\n super(`[ImageError ${code}] expected: ${expected}; hint: ${hint}`);\n this.name = 'ImageError';\n this.code = code;\n this.expected = expected;\n this.hint = hint;\n this.detail = detail;\n }\n}\n\nfunction makeImageError<C extends ImageErrorCode>(\n detail: ImageErrorDetailFor<C>,\n): ImageErrorFor<C> {\n return new RuntimeImageError<C>(detail);\n}\n\n// Extended device shape adding `queue.writeTexture` on top of\n// `MipmapBlitDevice` (the mipmap-generator only needs the encoder + queue\n// submit surface; uploadTexture additionally writes pixel bytes via\n// `queue.writeTexture` -- spec anchor: WebGPU 26.6.4.4).\ntype MipmapBlitDeviceWithWriteTexture = MipmapBlitDevice & {\n readonly queue: MipmapBlitDevice['queue'] & {\n // biome-ignore lint/suspicious/noExplicitAny: shim accepts any descriptor\n writeTexture(dst: any, data: any, layout: any, size: any): Result<void, any>;\n };\n};\n\n// Extended device shape adding `createBuffer` + `queue.writeBuffer` on top of\n// `MipmapBlitDevice` for the user-mesh GPU upload path.\ntype MipmapBlitDeviceWithBuffer = MipmapBlitDevice & {\n // biome-ignore lint/suspicious/noExplicitAny: shim accepts any descriptor\n createBuffer(desc: any): Result<any, any>;\n readonly queue: MipmapBlitDevice['queue'] & {\n // biome-ignore lint/suspicious/noExplicitAny: shim accepts any descriptor\n writeBuffer(buffer: any, offset: number, data: any): Result<void, any>;\n };\n};\n\n/** Cube-POD register-relay injected by the wire layer (D-3). */\ntype RegisterCube = (\n world: World,\n pod: EquirectAsset,\n) => Result<Handle<'EquirectAsset', 'shared'>, AssetError>;\n\n// feat-20260612-rhi-destroy-renderer-dispose-gpu-lifecycle / M-3 / w11:\n// the three handle map value types now hold GpuTexture / GpuBuffer wrappers\n// (plan-strategy D-9). Views (TextureView) stay raw RHI handles -- they are\n// not destroyable on their own; their lifetime is bound to the parent\n// GpuTexture, which the wrapper owns. destroyAll() walks the GpuResource\n// fields and forwards .destroy() to the RHI shim.\ninterface TextureGpuEntry {\n readonly texture: GpuTexture;\n /** Opaque RHI view handle; lifetime is bound to the parent texture. */\n readonly view: TextureView;\n}\n\n// feat-20260630-equirect-kind-internalized-ibl-declarative-skyligh M2 / w11\n// (D-3): the projection-status truth lives here (the store's cubemap map is the\n// single authority — the SkylightSnapshot carries no status, D-3). `status`:\n// - 'pending' — projection launched (fire-and-forget) but not complete; the\n// record arm binds the white-cube fallback for this frame.\n// - 'ready' — texture + cube view + 6 face views are live; bind the real\n// IBL cube.\n// - 'failed' — projection errored; recorded EXPLICITLY so the record arm\n// stops and does NOT retry every frame (R-2 / AC-09). A failed entry has\n// no GPU resources (texture/view are placeholders never bound).\n// `texture`/`view`/`faceViews` are non-readonly so a 'pending' entry can be\n// promoted to 'ready' in place (rebuilds the same slot). A 'failed' entry holds\n// no GPU resources (`texture:null` / `view:undefined`): it exists only to mark\n// the source as terminally failed so the record arm stops retrying (R-2).\ninterface CubemapGpuEntry {\n status: 'pending' | 'ready' | 'failed';\n texture: GpuTexture | null;\n // biome-ignore lint/suspicious/noExplicitAny: opaque GPU cubemap view (not a GpuResource)\n view: any;\n // biome-ignore lint/suspicious/noExplicitAny: per-face 2D views (6 faces; not GpuResources)\n faceViews: readonly any[];\n}\n\ninterface MeshGpuEntry {\n readonly vertexBuffer: GpuBuffer;\n /**\n * Index buffer wrapper, or `null` for a vertex-only mesh\n * (no `MeshAsset.indices`). When `null` the record stage takes the\n * non-indexed `pass.draw(vertexCount)` path and never calls\n * `setIndexBuffer`. Gated on `indexed` below.\n */\n readonly indexBuffer: GpuBuffer | null;\n /**\n * Allocation byte sizes for the vbo / ibo (mirrors GPUBuffer.size). Used\n * by `updateMeshById` to decide reuse vs reallocation; tracked here so\n * the runtime never reads `.size` off the opaque RHI handle (which is\n * not on the spec-aligned RHI Buffer interface; charter §RHI form rules).\n */\n readonly vboBytes: number;\n /** Allocation byte size for the ibo, or 0 when indexBuffer is null. */\n readonly iboBytes: number;\n /** Immutable geometry-owned layout projection used for all resident stride checks. */\n readonly layoutProjection: VertexLayoutProjection;\n readonly indexCount: number;\n readonly indexFormat: 'uint16' | 'uint32';\n /** Vertex count is derived from the geometry-owned projection stride. */\n readonly vertexCount: number;\n /** True when `MeshAsset.indices` is present (indexed draw path). */\n readonly indexed: boolean;\n /** Primitive topology (default 'triangle-list'). Mirrors MeshGpuHandles. */\n readonly topology: PrimitiveTopology;\n /**\n * Submeshes from MeshAsset.submeshes, carried through to the record stage\n * so per-submesh drawIndexed can iterate independently (feat-20260608 M4 / w16).\n * For single-submesh meshes this is a 1-element array (byte-identical to pre-M4).\n */\n readonly submeshes: readonly import('@forgeax/engine-types').Submesh[];\n}\n\nfunction meshStrideBytes(layoutProjection: VertexLayoutProjection): number {\n if (layoutProjection.arrayStride <= 0) {\n throw new Error('mesh layout projection must have a positive array stride');\n }\n return layoutProjection.arrayStride;\n}\n\nfunction submeshesEqual(a: readonly Submesh[], b: readonly Submesh[]): boolean {\n return (\n a.length === b.length &&\n a.every((left, index) => {\n const right = b[index];\n return (\n right !== undefined &&\n left.indexOffset === right.indexOffset &&\n left.indexCount === right.indexCount &&\n left.vertexCount === right.vertexCount &&\n left.topology === right.topology &&\n left.materialSlot === right.materialSlot\n );\n })\n );\n}\n\n/**\n * GPU residency store. Owns the per-handle GPU caches and the upload\n * primitives that build them. Constructed once per renderer; wired with the\n * GPU device via `configureGpuDevice` after `Renderer.ready` resolves.\n */\nexport class GpuResourceStore {\n /** Monotonic token for mesh GPU residency or contents changes. */\n meshResidencyEpoch = 0;\n /** Monotonic token for texture/sampler identities used by material bind groups. */\n materialResourceEpoch = 0;\n private gpuDevice: MipmapBlitDevice | undefined = undefined;\n // Shader-module factory injected at `configureGpuDevice`; threaded into the\n // mipmap-pipeline prewarm + the IBL precompute path. `undefined` until wired.\n private asyncCreateShaderModule: MipmapShaderModuleFactory | undefined = undefined;\n // Cube-POD register relay injected at `configureGpuDevice` (D-3); the store\n // never imports AssetRegistry, so CPU cataloguing flows through this fn.\n private registerCube: RegisterCube | undefined = undefined;\n // Error registry injected by createRenderer; evict / releaseUnreferenced\n // fire structured errors through this channel (feat-20260619 D-1/D-6).\n private errorRegistry: RhiErrorListenerRegistry | undefined = undefined;\n // Hardware-probe caps injected at `configureGpuDevice`; guards the HDR cubemap\n // path (_uploadCubemapFromEquirect) when `rgba16floatRenderable` is false.\n private caps: RhiCaps | undefined = undefined;\n\n private readonly textureGpuHandles: Map<number, TextureGpuEntry> = new Map();\n private readonly samplerGpuHandles: Map<number, Sampler> = new Map();\n private readonly cubemapGpuHandles: Map<number, CubemapGpuEntry> = new Map();\n // Maps source EquirectAsset handle id -> minted cubemap handle so the same\n // equirect source always resolves to the same cubemap (idempotent, A2).\n private readonly cubemapIdempotentMap: Map<number, Handle<'EquirectAsset', 'shared'>> = new Map();\n private readonly meshGpuHandles: Map<number, MeshGpuEntry> = new Map();\n\n /**\n * feat-20260723-cross-world-gpu-cache-collision: compose a cache key from\n * the raw handle slot and the worldId so two worlds that independently\n * allocate assets at the same slot number never collide in the GPU store.\n * worldId=0 produces the bare slot (backward compat with single-world path).\n */\n private worldKey(slot: number, worldId: number): number {\n return worldId === 0 ? slot : worldId * 0x1000000 + slot;\n }\n\n /**\n * Wire the GPU device, shader-module factory, and cube-POD register relay.\n * Called once by createRenderer after `Renderer.ready` resolves. This\n * performs NO replay of CPU asset state:\n * the pull model builds resources lazily at first `ensureResident` access.\n */\n configureGpuDevice(\n device: MipmapBlitDevice,\n asyncCreateShaderModule: MipmapShaderModuleFactory | undefined,\n registerCube: RegisterCube,\n caps: RhiCaps,\n ): void {\n this.meshResidencyEpoch += 1;\n this.gpuDevice = device;\n this.asyncCreateShaderModule = asyncCreateShaderModule;\n this.registerCube = registerCube;\n this.caps = caps;\n }\n\n /**\n * Wrap a raw RHI Buffer handle into a GpuBuffer. The wrapper holds a\n * reference to the device so `.destroy()` forwards to\n * `device.destroyBuffer(handle)` (M-3 / w11; plan-strategy D-2).\n *\n * Pre: `configureGpuDevice` has been called. Callers that build a buffer\n * via `device.createBuffer` already gate on a wired device, so this private\n * helper trusts the caller; an unwired call is a programmer error and\n * surfaces as a non-null assertion rather than a structured error.\n */\n private wrapBuf(rawHandle: Buffer): GpuBuffer {\n const device = this.gpuDevice as MipmapBlitDevice & RhiDevice;\n return new GpuBuffer(device, rawHandle);\n }\n\n private destroyMeshBuffer(buffer: GpuBuffer): void {\n const result = buffer.destroy();\n if (!result.ok) this.errorRegistry?.fire(result.error);\n }\n\n /** Wrap a raw RHI Texture handle into a GpuTexture (mirror of wrapBuf). */\n private wrapTex(rawHandle: Texture): GpuTexture {\n const device = this.gpuDevice as MipmapBlitDevice & RhiDevice;\n return new GpuTexture(device, rawHandle);\n }\n\n /**\n * Walk the three handle maps and destroy every GpuResource, then clear\n * the maps. Called from `Renderer.dispose()` (M-5) as the first step of\n * the dispose chain (plan-strategy D-2: dispose chain walks\n * `gpuStore.destroyAll()` → `graph.drain()` → `instanceBuffers.clear()`\n * → ...).\n *\n * Idempotent: a second call after the maps were cleared is a no-op\n * (architecture-principles §6 idempotency). Each `.destroy()` call\n * routes through the RHI shim's per-handle bookkeeping, so a stray\n * second-destroy on a handle the runtime did not flip to destroyed\n * surfaces as the structured `'destroy-after-destroy'` error from the\n * RHI shim; that error is *not* re-thrown here -- destroyAll is a\n * sweep that tolerates per-handle failures so the dispose chain can\n * make progress (plan-strategy D-3 / D-8).\n */\n destroyAll(): void {\n if (this.meshGpuHandles.size > 0) this.meshResidencyEpoch += 1;\n // The cubemap path registers two entries (sourceId + cubeId) sharing one\n // GpuTexture wrapper, so destroyAll must dedupe on the wrapper identity\n // before forwarding `.destroy()` -- otherwise the second call surfaces\n // `'destroy-after-destroy'` from the RHI shim. The `isDestroyed` getter\n // on the wrapper is the dedupe gate (architecture-principles §6).\n const destroyTex = (gpuTex: GpuTexture): void => {\n if (!gpuTex.isDestroyed) gpuTex.destroy();\n };\n const destroyBuf = (gpuBuf: GpuBuffer): void => {\n if (!gpuBuf.isDestroyed) gpuBuf.destroy();\n };\n\n for (const entry of this.textureGpuHandles.values()) {\n destroyTex(entry.texture);\n }\n if (this.textureGpuHandles.size > 0 || this.samplerGpuHandles.size > 0) {\n this.materialResourceEpoch += 1;\n }\n this.textureGpuHandles.clear();\n this.samplerGpuHandles.clear();\n\n for (const entry of this.cubemapGpuHandles.values()) {\n if (entry.texture !== null) destroyTex(entry.texture);\n }\n this.cubemapGpuHandles.clear();\n this.cubemapIdempotentMap.clear();\n\n for (const entry of this.meshGpuHandles.values()) {\n destroyBuf(entry.vertexBuffer);\n if (entry.indexBuffer !== null) destroyBuf(entry.indexBuffer);\n }\n this.meshGpuHandles.clear();\n }\n\n /**\n * Set the error registry channel (wired by createRenderer). evict /\n * releaseUnreferenced fire structured errors here instead of throwing -\n * sweeps continue past individual failures (feat-20260619 D-1/D-6).\n */\n setErrorRegistry(registry: RhiErrorListenerRegistry): void {\n this.errorRegistry = registry;\n }\n\n /**\n * evictTexture / evictMesh / evictCubemap — per-handle evict primitives.\n *\n * Reuses destroyAll's isDestroyed dedup logic + cubemap wrapper\n * shared-dedup (feat-20260619 D-1). Returns {freed, errors} so callers\n * can consume the aggregate result (D-3). Key not present -> no-op\n * returning {freed:0, errors:[]}.\n */\n evictTexture(\n handle: Handle<'TextureAsset', 'shared'>,\n worldId: number = 0,\n ): { freed: number; errors: RhiError[] } {\n const id = this.worldKey(handleSlot(handle), worldId);\n const entry = this.textureGpuHandles.get(id);\n if (entry === undefined) return { freed: 0, errors: [] };\n\n let freed = 0;\n const errors: RhiError[] = [];\n\n if (!entry.texture.isDestroyed) {\n const r = entry.texture.destroy();\n if (r.ok) {\n freed = 1;\n } else {\n errors.push(r.error);\n if (this.errorRegistry) this.errorRegistry.fire(r.error);\n }\n }\n\n this.textureGpuHandles.delete(id);\n this.materialResourceEpoch += 1;\n return { freed, errors };\n }\n\n evictMesh(\n handle: Handle<'MeshAsset', 'shared'>,\n worldId: number = 0,\n ): { freed: number; errors: RhiError[] } {\n const id = this.worldKey(handleSlot(handle), worldId);\n const entry = this.meshGpuHandles.get(id);\n if (entry === undefined) return { freed: 0, errors: [] };\n\n let freed = 0;\n const errors: RhiError[] = [];\n\n const destroyBuf = (gpuBuf: GpuBuffer): void => {\n if (!gpuBuf.isDestroyed) {\n const r = gpuBuf.destroy();\n if (r.ok) {\n freed += 1;\n } else {\n errors.push(r.error);\n if (this.errorRegistry) this.errorRegistry.fire(r.error);\n }\n }\n };\n\n destroyBuf(entry.vertexBuffer);\n if (entry.indexBuffer !== null) destroyBuf(entry.indexBuffer);\n\n this.meshGpuHandles.delete(id);\n this.meshResidencyEpoch += 1;\n return { freed: freed > 0 ? 1 : 0, errors };\n }\n\n evictCubemap(id: number): { freed: number; errors: RhiError[] } {\n const entry = this.cubemapGpuHandles.get(id);\n if (entry === undefined) return { freed: 0, errors: [] };\n\n let freed = 0;\n const errors: RhiError[] = [];\n\n // cubemap wrapper shared-dedup (D-1): sourceId and cubeId may share one\n // GpuTexture wrapper. The isDestroyed gate ensures the underlying RHI\n // texture is destroyed at most once, even when both entries are evicted.\n // A 'failed' entry holds no GPU texture (texture:null) — nothing to free.\n if (entry.texture !== null && !entry.texture.isDestroyed) {\n const r = entry.texture.destroy();\n if (r.ok) {\n freed = 1;\n } else {\n errors.push(r.error);\n if (this.errorRegistry) this.errorRegistry.fire(r.error);\n }\n }\n\n this.cubemapGpuHandles.delete(id);\n return { freed, errors };\n }\n\n /**\n * releaseUnreferenced — iterate the three handle maps and evict entries\n * whose key is NOT in `liveSet`.\n *\n * Iterates Map keys (not liveSet — store has no reverse index, D-8).\n * IDs in liveSet that don't exist in the store are naturally ignored.\n * Empty liveSet -> full release; second call -> no-op (maps empty,\n * evict primitives are key-not-present no-op).\n */\n releaseUnreferenced(liveSet: Set<number>): { freed: number; errors: RhiError[] } {\n let freed = 0;\n const errors: RhiError[] = [];\n let meshResidencyChanged = false;\n let materialResidencyChanged = false;\n\n for (const key of this.textureGpuHandles.keys()) {\n if (!liveSet.has(key)) {\n const entry = this.textureGpuHandles.get(key);\n if (entry !== undefined) {\n if (!entry.texture.isDestroyed) {\n const r = entry.texture.destroy();\n if (r.ok) {\n freed += 1;\n } else {\n errors.push(r.error);\n if (this.errorRegistry) this.errorRegistry.fire(r.error);\n }\n }\n this.textureGpuHandles.delete(key);\n materialResidencyChanged = true;\n }\n }\n }\n\n for (const key of this.samplerGpuHandles.keys()) {\n if (!liveSet.has(key)) {\n this.samplerGpuHandles.delete(key);\n materialResidencyChanged = true;\n }\n }\n\n for (const key of this.cubemapGpuHandles.keys()) {\n if (!liveSet.has(key)) {\n const entry = this.cubemapGpuHandles.get(key);\n if (entry !== undefined) {\n // A 'failed' entry holds no GPU texture (texture:null) — nothing to free.\n if (entry.texture !== null && !entry.texture.isDestroyed) {\n const r = entry.texture.destroy();\n if (r.ok) {\n freed += 1;\n } else {\n errors.push(r.error);\n if (this.errorRegistry) this.errorRegistry.fire(r.error);\n }\n }\n this.cubemapGpuHandles.delete(key);\n }\n }\n }\n\n for (const key of this.meshGpuHandles.keys()) {\n if (!liveSet.has(key)) {\n const entry = this.meshGpuHandles.get(key);\n if (entry !== undefined) {\n if (!entry.vertexBuffer.isDestroyed) {\n const r = entry.vertexBuffer.destroy();\n if (r.ok) {\n freed += 1;\n } else {\n errors.push(r.error);\n if (this.errorRegistry) this.errorRegistry.fire(r.error);\n }\n }\n if (entry.indexBuffer !== null && !entry.indexBuffer.isDestroyed) {\n const r = entry.indexBuffer.destroy();\n if (r.ok) {\n freed += 1;\n } else {\n errors.push(r.error);\n if (this.errorRegistry) this.errorRegistry.fire(r.error);\n }\n }\n this.meshGpuHandles.delete(key);\n meshResidencyChanged = true;\n }\n }\n }\n\n if (meshResidencyChanged) this.meshResidencyEpoch += 1;\n if (materialResidencyChanged) this.materialResourceEpoch += 1;\n\n return { freed, errors };\n }\n\n /**\n * Prewarm the mipmap pipeline cache for the given texture formats (D-9).\n * Called from `createRenderer.ready` (already async): builds the one-time\n * mipmap shader module + per-format render pipeline into the mipmap-generator\n * deviceCache so the per-texture mipmap blit at record-stage `ensureResident`\n * is pure synchronous encoder work. A format absent from this list will make\n * the sync `ensureResident` texture arm return a structured RhiError rather\n * than lazily await a build (which would break the sync draw contract).\n */\n async prewarmMipmapPipeline(\n device: MipmapBlitDevice,\n formats: readonly GPUTextureFormat[],\n ): Promise<Result<void, RhiError>> {\n const factory = this.asyncCreateShaderModule;\n if (factory === undefined) {\n return err(\n new RhiError({\n code: 'rhi-not-available',\n expected: 'asyncCreateShaderModule wired by configureGpuDevice before prewarm',\n hint: 'call gpuStore.configureGpuDevice(device, packShaderFactory, registerCube) before prewarmMipmapPipeline',\n }),\n );\n }\n for (const format of formats) {\n const res = await getOrCreateMipmapPipeline(device, format, factory);\n if (!res.ok) {\n return err(\n new RhiError({\n code: 'rhi-not-available',\n expected: `mipmap pipeline for format ${format} builds during prewarm`,\n hint: `prewarmMipmapPipeline failed building the mipmap pipeline for ${format}; the format may be unsupported by the device`,\n }),\n );\n }\n }\n return ok(undefined);\n }\n\n /**\n * Return the GpuTexture wrapper for a `Handle<TextureAsset>` if it has been\n * made resident, else `undefined`.\n *\n * @internal — test-only seam for cow-survivor / AC-02 integration tests; not\n * part of the engine's public API surface.\n */\n _getTextureGpuTexture(\n handle: Handle<'TextureAsset', 'shared'>,\n worldId: number = 0,\n ): GpuTexture | undefined {\n return this.textureGpuHandles.get(this.worldKey(handleSlot(handle), worldId))?.texture;\n }\n\n /**\n * Return the GPU texture-view for a `Handle<TextureAsset>` if it has been\n * made resident, else `undefined`.\n */\n getTextureGpuView(\n handle: Handle<'TextureAsset', 'shared'>,\n worldId: number = 0,\n ): TextureView | undefined {\n return this.textureGpuHandles.get(this.worldKey(handleSlot(handle), worldId))?.view;\n }\n\n /**\n * Lazily materialise and cache a sampler descriptor for a material texture.\n * Samplers are opaque, non-destroyable RHI handles, so disposal only drops\n * this store's cache and lets the device own their lifetime.\n */\n ensureSamplerResident(\n handle: Handle<'SamplerAsset', 'shared'>,\n pod: SamplerAsset,\n worldId: number = 0,\n ): Result<Sampler, RhiError> {\n const key = this.worldKey(handleSlot(handle), worldId);\n const existing = this.samplerGpuHandles.get(key);\n if (existing !== undefined) return ok(existing);\n const device = this.gpuDevice as (MipmapBlitDevice & RhiDevice) | undefined;\n if (device === undefined) {\n return err(\n new RhiError({\n code: 'rhi-not-available',\n expected: 'GPU device configured before SamplerAsset residency',\n hint: 'call gpuStore.configureGpuDevice before drawing a material with a sampler',\n }),\n );\n }\n const { kind: _kind, ...descriptor } = pod;\n const created = device.createSampler(descriptor);\n if (!created.ok) return created;\n this.samplerGpuHandles.set(key, created.value);\n this.materialResourceEpoch += 1;\n return created;\n }\n\n /**\n * Return the GpuTexture wrapper for the cubemap, or `undefined` if not\n * uploaded yet. Consumers that need the raw RHI Texture handle (e.g.\n * `device.createTextureView` arguments) read `.handle` on the wrapper;\n * `.destroy()` routes through the destroy chain (M-3 / w11).\n */\n getCubemapGpuTexture(handle: Handle<'EquirectAsset', 'shared'>): GpuTexture | undefined {\n // A 'failed' entry has texture:null; normalise to undefined (not resident).\n return this.cubemapGpuHandles.get(handleSlot(handle))?.texture ?? undefined;\n }\n\n /** Return the full-cube texture view, or `undefined` if not uploaded yet. */\n // biome-ignore lint/suspicious/noExplicitAny: opaque GPU texture view\n getCubemapGpuView(handle: Handle<'EquirectAsset', 'shared'>): any | undefined {\n return this.cubemapGpuHandles.get(handleSlot(handle))?.view;\n }\n\n /** Return per-face 2D views (6 faces), or `undefined` if not uploaded yet. */\n // biome-ignore lint/suspicious/noExplicitAny: opaque GPU texture views\n getCubemapFaceViews(handle: Handle<'EquirectAsset', 'shared'>): readonly any[] | undefined {\n return this.cubemapGpuHandles.get(handleSlot(handle))?.faceViews;\n }\n\n /**\n * Query the projection status for an equirect source handle (D-3 SSOT: the\n * store's CubemapGpuEntry is the single authority). Returns `undefined` when\n * no projection has been launched for this source yet (the record arm reads\n * this to decide whether to fire the lazy projection; feat-20260630 M3 / w18):\n * - undefined -> no entry: caller may launch projection (fire-and-forget)\n * - 'pending' -> projection launched, not complete: bind white-cube fallback\n * - 'ready' -> projected cube + IBL views live: bind real IBL\n * - 'failed' -> projection errored: bind white fallback, do NOT retry (R-2)\n */\n getCubemapStatus(\n handle: Handle<'EquirectAsset', 'shared'>,\n ): 'pending' | 'ready' | 'failed' | undefined {\n return this.cubemapGpuHandles.get(handleSlot(handle))?.status;\n }\n\n /**\n * Return the GPU vertex / index buffer handles + index count for a\n * `Handle<MeshAsset>` if resident, else `undefined`. Consumers treat this\n * as the canonical \"mesh asset has GPU residency\" probe.\n */\n getMeshGpuHandles(\n handle: Handle<'MeshAsset', 'shared'>,\n worldId: number = 0,\n ): MeshGpuEntry | undefined {\n return this.meshGpuHandles.get(this.worldKey(handleSlot(handle), worldId));\n }\n\n /**\n * Pull-model residency: build the GPU resource for `handle` from the\n * caller-provided POD on a miss, return the cached handles on a hit (D-2).\n *\n * - mesh POD -> synchronous vertex / index buffer upload (mirrors the\n * pre-extraction `uploadMeshById`).\n * - texture POD -> synchronous texture upload + mipmap blit (D-9). The\n * mipmap pipeline MUST have been prewarmed via `prewarmMipmapPipeline`;\n * an un-prewarmed format returns a structured RhiError (never awaits).\n *\n * Cubemap is NOT routed here -- it is an eager user call\n * (`_uploadCubemapFromEquirect`). Builtin meshes are NOT routed here either\n * (createRenderer step-3 owns them; D-1).\n */\n ensureResident(\n handle: Handle<'MeshAsset', 'shared'> | Handle<'TextureAsset', 'shared'>,\n pod: TypesMeshAsset | TextureAsset,\n worldId: number = 0,\n // biome-ignore lint/suspicious/noExplicitAny: opaque GPU handle entry union\n ): Result<any, RhiError | AssetError | ImageError> {\n const id = handleSlot(handle);\n // Hit: O(1) cache lookup, never re-projects (AC-09 -- deriveRenderData*\n // runs only on a miss). The miss arms below dispatch on `pod.kind` with NO\n // default: only the two GPU-resource kinds reachable here (mesh / texture)\n // have arms, so a third reachable kind would surface as a `tsc -b`\n // exhaustiveness error at the switch rather than a silent fallthrough\n // (AC-06; the cube-texture kind is the eager `_uploadCubemapFromEquirect`\n // path, not routed here).\n switch (pod.kind) {\n case 'mesh': {\n const key = this.worldKey(id, worldId);\n const existing = this.meshGpuHandles.get(key);\n if (existing !== undefined) return ok(existing);\n const projected = deriveRenderDataMesh(pod);\n if (!projected.ok) return projected;\n return this.uploadMeshById(key, pod, projected.value);\n }\n case 'texture': {\n const texKey = this.worldKey(id, worldId);\n const existing = this.textureGpuHandles.get(texKey);\n if (existing !== undefined) return ok(existing);\n const projected = deriveRenderDataTexture(pod);\n if (!projected.ok) return projected;\n const decoded: DecodedImage = decodedFromTexture(pod);\n return this.uploadTextureSync(\n handle as Handle<'TextureAsset', 'shared'>,\n pod,\n decoded,\n projected.value,\n worldId,\n );\n }\n }\n }\n\n /**\n * Eager public surface: upload decoded image bytes into a GPU texture and\n * cache (texture + view) under the handle. The TextureAsset POD supplies the\n * GPU format (D-2: caller provides POD, store never reaches a registry); the\n * DecodedImage supplies the pixel bytes + colorSpace. Retains the async\n * signature so callers that have not prewarmed can drive a mipmap build here\n * (the one async source).\n */\n async uploadTexture(\n handle: Handle<'TextureAsset', 'shared'>,\n pod: TextureAsset,\n decoded: DecodedImage,\n worldId: number = 0,\n ): Promise<Result<void, AssetError | ImageError | RhiError>> {\n const device = this.gpuDevice;\n const projected = deriveRenderDataTexture(pod);\n if (!projected.ok) return projected;\n const prepared = this.prepareTextureUpload(handle, pod, decoded, projected.value);\n if (!prepared.ok) return prepared;\n if (device === undefined) return ok(undefined);\n const { tex, levels, gpuTexture } = prepared.value;\n const cacheKey = this.worldKey(handleSlot(handle), worldId);\n if (gpuTexture === undefined) return ok(undefined);\n\n if (!projected.value.compressed && decoded.mipmap === true && levels > 1) {\n const factory = this.asyncCreateShaderModule;\n if (factory === undefined) {\n return err(\n new RhiError({\n code: 'rhi-not-available',\n expected: 'asyncCreateShaderModule wired by configureGpuDevice',\n hint: 'GpuResourceStore.uploadTexture mipmap branch needs a shader-module factory; rhi-webgpu / rhi-wgpu shims expose it via pack.createShaderModule. Explicit-rhi instances must surface the factory on the RhiInstance.',\n }),\n );\n }\n const pipelineRes = await getOrCreateMipmapPipeline(device, tex.format, factory);\n if (!pipelineRes.ok) {\n return err(\n new RhiError({\n code: 'rhi-not-available',\n expected: `mipmap pipeline for format ${tex.format} builds`,\n hint: 'GpuResourceStore.uploadTexture could not build the mipmap pipeline',\n }),\n );\n }\n const blitRes = blitMipmapsSync(device, gpuTexture, {\n format: tex.format,\n width: tex.width,\n height: tex.height,\n levels,\n });\n if (!blitRes.ok) return blitRes as Result<void, RhiError>;\n }\n\n const viewRes = device.createTextureView(gpuTexture, {\n label: `texture-view-${cacheKey}`,\n dimension: '2d',\n });\n if (!viewRes.ok) return viewRes;\n const previous = this.textureGpuHandles.get(cacheKey);\n const next = {\n texture: this.wrapTex(gpuTexture),\n view: viewRes.value,\n };\n this.textureGpuHandles.set(cacheKey, next);\n this.materialResourceEpoch += 1;\n if (\n previous !== undefined &&\n previous.texture !== next.texture &&\n !previous.texture.isDestroyed\n ) {\n previous.texture.destroy();\n }\n return ok(undefined);\n }\n\n /**\n * Synchronous texture upload used by `ensureResident` (D-9). Identical to\n * `uploadTexture` except the mipmap pipeline is read from the prewarmed\n * cache via the synchronous `blitMipmapsSync` -- an un-prewarmed format\n * returns a structured RhiError instead of awaiting a build.\n */\n private uploadTextureSync(\n handle: Handle<'TextureAsset', 'shared'>,\n pod: TextureAsset,\n decoded: DecodedImage,\n renderData: TextureRenderData,\n worldId: number = 0,\n ): Result<TextureGpuEntry, AssetError | ImageError | RhiError> {\n const device = this.gpuDevice;\n const prepared = this.prepareTextureUpload(handle, pod, decoded, renderData);\n if (!prepared.ok) return prepared;\n if (device === undefined || prepared.value.gpuTexture === undefined) {\n return err(\n new RhiError({\n code: 'rhi-not-available',\n expected: 'GpuResourceStore.configureGpuDevice wired before ensureResident',\n hint: 'a texture ensureResident ran before the GPU device was wired; call gpuStore.configureGpuDevice in createRenderer',\n }),\n );\n }\n const { tex, levels, gpuTexture } = prepared.value;\n const cacheKey = this.worldKey(handleSlot(handle), worldId);\n\n if (!renderData.compressed && decoded.mipmap === true && levels > 1) {\n const blitRes = blitMipmapsSync(device, gpuTexture, {\n format: tex.format,\n width: tex.width,\n height: tex.height,\n levels,\n });\n if (!blitRes.ok) return blitRes as Result<TextureGpuEntry, RhiError>;\n }\n\n const viewRes = device.createTextureView(gpuTexture, {\n label: `texture-view-${cacheKey}`,\n dimension: '2d',\n });\n if (!viewRes.ok) return viewRes;\n const entry: TextureGpuEntry = { texture: this.wrapTex(gpuTexture), view: viewRes.value };\n const previous = this.textureGpuHandles.get(cacheKey);\n this.textureGpuHandles.set(cacheKey, entry);\n this.materialResourceEpoch += 1;\n if (\n previous !== undefined &&\n previous.texture !== entry.texture &&\n !previous.texture.isDestroyed\n ) {\n previous.texture.destroy();\n }\n return ok(entry);\n }\n\n /**\n * Shared texture-upload prelude: format / colorSpace consistency assertion,\n * GPU texture allocation + writeTexture. Returns `gpuTexture: undefined`\n * (with ok) when no device is wired (deferred path).\n */\n private prepareTextureUpload(\n handle: Handle<'TextureAsset', 'shared'>,\n pod: TextureAsset,\n decoded: DecodedImage,\n renderData: TextureRenderData,\n ): Result<\n // biome-ignore lint/suspicious/noExplicitAny: opaque GPU texture handle\n { id: number; tex: TextureAsset; levels: number; gpuTexture: any | undefined },\n AssetError | ImageError | RhiError\n > {\n const id = handleSlot(handle);\n // The store does not hold the registry (D-2); the caller-provided POD is\n // the GPU-format SSOT and `renderData` is its projection (format / usage /\n // mipLevelCount). `decoded` supplies the pixel bytes + colorSpace; the\n // assertion below guards the actual upload-source colorSpace against the\n // projected format (the projection already checked the POD's own colorSpace).\n const tex = pod;\n const levels = renderData.mipLevelCount;\n\n const formatExpected: 'srgb' | 'linear' = renderData.format.endsWith('-srgb')\n ? 'srgb'\n : 'linear';\n if (decoded.colorSpace !== formatExpected) {\n const detail: ImageErrorDetailFor<'image-format-unsupported'> = {\n code: 'image-format-unsupported',\n actualMime: decoded.mime,\n formatColorSpaceConflict: {\n format: renderData.format,\n colorSpace: decoded.colorSpace,\n expected: formatExpected,\n },\n };\n return err(makeImageError(detail));\n }\n\n const device = this.gpuDevice;\n if (device === undefined) {\n return ok({ id, tex, levels, gpuTexture: undefined });\n }\n\n // WebGL2/wgpu exposes texture limits that are lower than many source\n // images (for example the 2085px LearnOpenGL Mars texture). Reject the\n // upload before allocating a handle; binding a texture that the backend\n // accepted syntactically but cannot use later surfaces only as a generic\n // invalid-bind-group submit error.\n const maxDimension =\n (device as unknown as { readonly limits?: { readonly maxTextureDimension2D?: number } })\n .limits?.maxTextureDimension2D ?? 16_384;\n if (tex.width > maxDimension || tex.height > maxDimension) {\n return err(\n makeImageError({\n code: 'image-dimension-out-of-bounds',\n requested: { width: tex.width, height: tex.height },\n limit: maxDimension,\n }),\n );\n }\n\n const createTexRes = device.createTexture({\n label: `texture-${id}`,\n size: {\n width: renderData.physicalExtent.width,\n height: renderData.physicalExtent.height,\n depthOrArrayLayers: 1,\n },\n mipLevelCount: levels,\n sampleCount: 1,\n dimension: '2d',\n format: renderData.format,\n usage: renderData.usage,\n viewFormats: [],\n });\n if (!createTexRes.ok) return createTexRes;\n const gpuTexture = createTexRes.value;\n const queue = (device as unknown as MipmapBlitDeviceWithWriteTexture).queue;\n\n if (renderData.compressed) {\n // feat-20260707 M5 / w36 (AC-08): block-compressed textures carry their\n // mip chain in `data` (offline-baked -- the GPU cannot generate compressed\n // mips). Upload each level with its own block-padded bytesPerRow /\n // rowsPerImage and mip-major byte offset (deriveMipUploadLayout, SSOT\n // block math). Full-subresource copies retain their logical size, including\n // non-block-aligned dimensions. queue.writeTexture avoids the 256 B\n // copyBufferToTexture alignment trap.\n const layout = deriveMipUploadLayout(renderData.format, tex.width, tex.height, levels);\n for (const lvl of layout) {\n const slice = decoded.bytes.subarray(lvl.byteOffset, lvl.byteOffset + lvl.byteLength);\n const writeRes = queue.writeTexture(\n { texture: gpuTexture, mipLevel: lvl.level, origin: { x: 0, y: 0, z: 0 } },\n slice,\n { offset: 0, bytesPerRow: lvl.bytesPerRow, rowsPerImage: lvl.rowsPerImage },\n { width: lvl.copyWidth, height: lvl.copyHeight, depthOrArrayLayers: 1 },\n );\n if (!writeRes.ok) return writeRes;\n }\n return ok({ id, tex, levels, gpuTexture });\n }\n\n // Uncompressed base-mip write; higher mips (when mipmap) are GPU-generated by\n // the caller's blit pass. rowsPerImage is the pixel height for linear RGBA.\n const bytesPerRow = renderData.bytesPerRow;\n const writeTextureRes = queue.writeTexture(\n { texture: gpuTexture, mipLevel: 0, origin: { x: 0, y: 0, z: 0 } },\n decoded.bytes,\n { offset: 0, bytesPerRow, rowsPerImage: tex.height },\n { width: tex.width, height: tex.height, depthOrArrayLayers: 1 },\n );\n if (!writeTextureRes.ok) return writeTextureRes;\n\n return ok({ id, tex, levels, gpuTexture });\n }\n\n /**\n * Project an equirectangular HDR `EquirectAsset` into a GPU cubemap + IBL\n * precompute. NOT part of the `ensureResident` pull path.\n *\n * @internal — feat-20260630 D-3 / F-9: the cubemap projection is engine\n * internals, not a user surface. AI users declare `Skylight{equirect}` and\n * the render-system record arm (same package) drives this method per-frame;\n * the `_` prefix + `@internal` mark it package-internal (lint:internal gate)\n * so it never appears as a user-facing call. (A cross-file `private` is not\n * reachable by the record arm; package-internal is the correct visibility.)\n *\n * Idempotent: a second call with the same source handle returns the cached\n * cubemap handle (no second GPU texture). The minted cubemap handle is an\n * `EquirectAsset` shared ref catalogued via the injected `registerCube` relay\n * (D-3); the store never imports AssetRegistry.\n *\n * Status (D-3): every entry written carries `status`. A failed projection\n * records `status:'failed'` EXPLICITLY (R-2 / AC-09) so the caller never\n * retries by inferring \"no entry => try again\".\n */\n async _uploadCubemapFromEquirect(\n world: World,\n sourceHandle: Handle<'EquirectAsset', 'shared'>,\n sourcePod: EquirectAsset,\n ): Promise<Result<Handle<'EquirectAsset', 'shared'>, AssetError | RhiError>> {\n const sourceId = handleSlot(sourceHandle);\n\n const existing = this.cubemapIdempotentMap.get(sourceId);\n if (existing !== undefined) {\n return ok(existing);\n }\n\n // R-2 / AC-09: a previously-failed projection is recorded EXPLICITLY as a\n // 'failed' entry. Short-circuit here so the record arm never retries the\n // upload every frame (the missing-key inference would loop forever).\n if (this.cubemapGpuHandles.get(sourceId)?.status === 'failed') {\n return err(\n new RhiError({\n code: 'feature-not-enabled',\n expected: 'a prior cubemap projection for this equirect source did not fail',\n hint: 'this equirect source already failed projection; the record arm must not retry (R-2). Inspect the original failure on the error channel',\n }),\n );\n }\n\n // feat-20260630 M3 / w18: a projection already in flight is marked\n // 'pending' synchronously below (before the first await). A re-entry while\n // pending short-circuits so the fire-and-forget record arm launches the\n // async projection exactly once per source (D-4 idempotent; the record arm\n // calls this every frame until status flips to ready/failed). The pending\n // entry holds no live GPU resources yet; the record arm binds the white\n // fallback while pending.\n if (this.cubemapGpuHandles.get(sourceId)?.status === 'pending') {\n return ok(sourceHandle);\n }\n\n // Record a failed projection explicitly so a re-query short-circuits and the\n // record arm never retries every frame (R-2 / AC-09). The placeholder\n // texture wrapper is never bound (a 'failed' entry has no live GPU view).\n const recordFailed = <E>(error: E): Result<never, E> => {\n this.cubemapGpuHandles.set(sourceId, {\n status: 'failed',\n texture: null,\n view: undefined,\n faceViews: [],\n });\n return err(error);\n };\n\n const registerCube = this.registerCube;\n if (registerCube === undefined) {\n return recordFailed(\n makeAssetError({\n code: 'asset-not-found',\n expected: 'GpuResourceStore.configureGpuDevice wired with registerCube',\n hint: 'call gpuStore.configureGpuDevice(device, factory, registerCube) before _uploadCubemapFromEquirect',\n }),\n );\n }\n\n if (sourcePod.kind !== 'equirect') {\n return recordFailed(\n makeAssetError({\n code: 'asset-not-found',\n expected: `source POD for handle id ${sourceId} is an EquirectAsset`,\n hint: ASSET_ERROR_HINTS['asset-not-found'],\n }),\n );\n }\n\n // feat-20260630 M3 / w18: mark the source 'pending' SYNCHRONOUSLY (this runs\n // before the first `await` below, so the fire-and-forget record arm that\n // never awaits still observes the pending entry on the next frame's\n // getCubemapStatus). All sync fail-fast gates (idempotent / failed / pending\n // / registerCube / caps / kind) have passed, so the projection is committed;\n // a re-entry while async work is in flight short-circuits on the 'pending'\n // guard above. The entry holds no live GPU resources yet (record binds the\n // white fallback while pending); the texture/views are filled in below when\n // the projection completes (status flips to 'ready'), or replaced by a\n // 'failed' entry via recordFailed if any later step errors.\n this.cubemapGpuHandles.set(sourceId, {\n status: 'pending',\n texture: null,\n view: undefined,\n faceViews: [],\n });\n\n // The cubemap projection + IBL precompute consume a 2D-image view of the\n // source. EquirectAsset mirrors the TextureAsset 2D surface (width / height\n // / format / data / colorSpace) but has no CPU mip chain, so the derived\n // texture view declares `mipmap:false` (the IBL prefilter mip chain is a\n // GPU-side pass, not a CPU-authored level set).\n const sourceTex: TextureAsset = {\n kind: 'texture',\n width: sourcePod.width,\n height: sourcePod.height,\n format: sourcePod.format,\n data: sourcePod.data,\n colorSpace: sourcePod.colorSpace,\n mipmap: false,\n };\n\n // Project the equirect source POD into the cubemap descriptor (D-5): the\n // asset-semantic decisions (format / colorSpace validation, square cube\n // face size, rgba32f->rgba16f narrowing) live in the pure projection; the\n // resource build (texture / views / IBL precompute) + the byte conversion\n // stay here in the store.\n const projected: CubeRenderData | undefined = (() => {\n const p = deriveRenderDataCubemap(sourceTex);\n return p.ok ? p.value : undefined;\n })();\n if (projected === undefined) {\n return recordFailed(\n makeAssetError({\n code: 'invalid-source-format',\n expected: \"format 'rgba16float' or 'rgba32float' with colorSpace 'linear'\",\n hint: ASSET_ERROR_HINTS['invalid-source-format'],\n }),\n );\n }\n\n const tex: TextureAsset = projected.needsHalfConversion\n ? {\n kind: 'texture',\n width: sourceTex.width,\n height: sourceTex.height,\n format: projected.outputFormat,\n data: halfFloat.f32ToF16Bytes(\n sourceTex.data instanceof Uint8ClampedArray\n ? new Uint8Array(\n sourceTex.data.buffer,\n sourceTex.data.byteOffset,\n sourceTex.data.byteLength,\n )\n : sourceTex.data,\n ),\n colorSpace: 'linear',\n mipmap: false,\n }\n : sourceTex;\n\n const cubeFaceSize = projected.cubeFaceSize;\n // The source equirect stays float for filtering, but WebGL2 cannot render\n // rgba16float attachments. Downlevel only the precompute outputs to the\n // universally renderable rgba8 path; the same format is threaded through\n // the cubemap and all three IBL side textures by IblPipelineCache.\n const outputFormat = this.caps?.rgba16floatRenderable === false ? 'rgba8unorm' : tex.format;\n\n // Lazy projection runs from the record arm, where the device is always\n // wired (research R-5). The device-not-wired queue + placeholder cube path\n // is removed (D-7); a missing device here is a fail-fast, not a queue.\n const device = this.gpuDevice;\n if (device === undefined) {\n return recordFailed(\n new RhiError({\n code: 'rhi-not-available',\n expected: 'GpuResourceStore.configureGpuDevice wired before cubemap projection',\n hint: 'a cubemap projection ran before the GPU device was wired; the record arm projects only after the device is configured',\n }),\n );\n }\n\n // Usage flags for the small equirect helper texture (sampled source for the\n // IBL precompute pass); the cube texture's usage comes from the projection.\n // biome-ignore lint/suspicious/noExplicitAny: union of shim/raw return shapes\n const unwrap = (r: any): any => {\n if (r === null || r === undefined) return undefined;\n if (typeof r === 'object' && 'ok' in r) return r.ok ? r.value : undefined;\n return r;\n };\n // biome-ignore lint/suspicious/noExplicitAny: shim/raw device split\n const makeTextureView = (dev: any, texture: any, desc: any): any => {\n if (typeof dev.createTextureView === 'function') {\n const u = unwrap(dev.createTextureView(texture, desc));\n if (u !== undefined) return u;\n }\n if (texture !== null && texture !== undefined && typeof texture.createView === 'function') {\n try {\n return texture.createView(desc);\n } catch {\n return undefined;\n }\n }\n return undefined;\n };\n\n const gpuTextureRet = device.createTexture({\n label: `cubemap-${sourceId}`,\n size: { width: cubeFaceSize, height: cubeFaceSize, depthOrArrayLayers: 6 },\n mipLevelCount: 1,\n sampleCount: 1,\n dimension: '2d',\n format: outputFormat,\n usage: projected.cubeUsage,\n viewFormats: [],\n });\n const gpuTexture = unwrap(gpuTextureRet);\n if (gpuTexture === undefined) {\n return recordFailed(\n makeAssetError({\n code: 'ibl-precompute-not-dispatched',\n expected: `device.createTexture cubemap-${sourceId} to return a valid texture`,\n hint: ASSET_ERROR_HINTS['ibl-precompute-not-dispatched'],\n }),\n );\n }\n\n const cubeView = makeTextureView(device, gpuTexture, {\n label: `cubemap-view-${sourceId}`,\n dimension: 'cube',\n arrayLayerCount: 6,\n });\n if (cubeView === undefined) {\n return recordFailed(\n makeAssetError({\n code: 'ibl-precompute-not-dispatched',\n expected: `device.createTextureView cubemap-view-${sourceId} to return a valid view`,\n hint: ASSET_ERROR_HINTS['ibl-precompute-not-dispatched'],\n }),\n );\n }\n\n // biome-ignore lint/suspicious/noExplicitAny: opaque GPU texture views\n const faceViews: any[] = [];\n for (let face = 0; face < 6; face++) {\n const fv = makeTextureView(device, gpuTexture, {\n label: `cubemap-face-${sourceId}-${face}`,\n dimension: '2d',\n baseArrayLayer: face,\n arrayLayerCount: 1,\n });\n if (fv === undefined) {\n return recordFailed(\n makeAssetError({\n code: 'ibl-precompute-not-dispatched',\n expected: `device.createTextureView cubemap-face-${sourceId}-${face} to return a valid view`,\n hint: ASSET_ERROR_HINTS['ibl-precompute-not-dispatched'],\n }),\n );\n }\n faceViews.push(fv);\n }\n\n // M-3 / w11: a single GpuTexture wrapper is shared between sourceId\n // and cubeId entries (the underlying RHI handle is the same physical\n // texture). destroyAll() walks each entry, so attempting to destroy\n // twice via two wrappers would surface 'destroy-after-destroy' on\n // the second pass; sharing one wrapper keeps the destroy chain\n // surfacing exactly one destroy call per physical resource.\n const gpuTextureWrapper = this.wrapTex(gpuTexture);\n\n this.cubemapGpuHandles.set(sourceId, {\n status: 'ready',\n texture: gpuTextureWrapper,\n view: cubeView,\n faceViews,\n });\n\n // The minted cubemap handle is a synthetic shared ref (identity token for\n // the GPU cube residency); its POD is an EquirectAsset placeholder matching\n // the projected dimensions/format (D-3: the retired cube-texture asset kind\n // is gone; the relay mints an EquirectAsset shared ref instead).\n const cubeAsset: EquirectAsset = {\n kind: 'equirect',\n width: cubeFaceSize,\n height: cubeFaceSize,\n format: tex.format,\n data: tex.data,\n colorSpace: 'linear',\n };\n const regResult = registerCube(world, cubeAsset);\n if (!regResult.ok) return recordFailed(regResult.error);\n const cubeHandle = regResult.value;\n const cubeId = handleSlot(cubeHandle);\n\n this.cubemapGpuHandles.set(cubeId, {\n status: 'ready',\n texture: gpuTextureWrapper,\n view: cubeView,\n faceViews,\n });\n\n this.cubemapIdempotentMap.set(sourceId, cubeHandle);\n\n if (this.asyncCreateShaderModule !== undefined) {\n // biome-ignore lint/suspicious/noExplicitAny: device shim narrowed at runtime\n const ipDevice = device as any;\n const pipelinesRes = await createIblPipelines(\n ipDevice,\n // biome-ignore lint/suspicious/noExplicitAny: factory signatures are interoperable; device shim is structural\n this.asyncCreateShaderModule as any,\n outputFormat,\n );\n if (pipelinesRes.ok) {\n // biome-ignore lint/suspicious/noExplicitAny: device shim\n const fdevice = device as any;\n const equirectGpuTexRet = fdevice.createTexture({\n label: `equirect-${sourceId}`,\n size: { width: tex.width, height: tex.height, depthOrArrayLayers: 1 },\n mipLevelCount: 1,\n sampleCount: 1,\n dimension: '2d',\n format: tex.format,\n usage: GPU_TEXTURE_USAGE_TEXTURE_BINDING | GPU_TEXTURE_USAGE_COPY_DST,\n viewFormats: [],\n });\n const equirectGpuTex = unwrap(equirectGpuTexRet);\n if (equirectGpuTex !== undefined && typeof fdevice.queue?.writeTexture === 'function') {\n const bytesPerPixel =\n tex.format === 'rgba32float' ? 16 : tex.format === 'rgba16float' ? 8 : 4;\n fdevice.queue.writeTexture(\n { texture: equirectGpuTex },\n tex.data,\n { bytesPerRow: tex.width * bytesPerPixel, rowsPerImage: tex.height },\n { width: tex.width, height: tex.height, depthOrArrayLayers: 1 },\n );\n }\n const equirectView =\n equirectGpuTex !== undefined\n ? makeTextureView(fdevice, equirectGpuTex, {\n label: `equirect-view-${sourceId}`,\n dimension: '2d',\n })\n : undefined;\n const faceBuf = unwrap(createFaceUniformsBuffer(ipDevice));\n const prefBuf = unwrap(createPrefilterUniformsBuffer(ipDevice));\n const cubeVertex = unwrap(\n fdevice.createBuffer({\n label: 'ibl-cube-verts',\n size: CUBEMAP_FACE_VERTICES.byteLength,\n usage: GPU_BUFFER_USAGE_VERTEX | GPU_BUFFER_USAGE_COPY_DST,\n mappedAtCreation: false,\n }),\n );\n if (\n equirectGpuTex !== undefined &&\n equirectView !== undefined &&\n faceBuf !== undefined &&\n prefBuf !== undefined &&\n cubeVertex !== undefined &&\n typeof fdevice.queue?.writeBuffer === 'function'\n ) {\n fdevice.queue.writeBuffer(cubeVertex, 0, CUBEMAP_FACE_VERTICES);\n writeAllFaceUniforms(ipDevice, faceBuf);\n writeAllPrefilterUniforms(ipDevice, prefBuf);\n const runRes = runIblPrecompute({\n device: ipDevice,\n equirectGpuTex,\n equirectView,\n cubeGpuTex: gpuTexture,\n cubeView,\n cubeFaceViews: faceViews,\n faceUniformsBuffer: faceBuf,\n prefilterUniformsBuffer: prefBuf,\n cubeVertexBuffer: cubeVertex,\n });\n if (!runRes.ok) {\n return recordFailed(\n makeAssetError({\n code: 'ibl-precompute-not-dispatched',\n expected: runRes.error.expected,\n hint: runRes.error.hint,\n }),\n );\n }\n }\n }\n }\n\n return ok(cubeHandle);\n }\n\n /**\n * Upload `MeshAsset.vertices` + `MeshAsset.indices` to GPU buffers and cache\n * the handles under the asset id. Synchronous; mirrors the pre-extraction\n * `uploadMeshById` byte-for-byte. Returns the cached entry on success.\n */\n private uploadMeshById(\n id: number,\n mesh: TypesMeshAsset,\n renderData: MeshRenderData,\n ): Result<MeshGpuEntry, RhiError> {\n const device = this.gpuDevice as MipmapBlitDeviceWithBuffer | undefined;\n if (device === undefined) {\n return err(\n new RhiError({\n code: 'rhi-not-available',\n expected: 'GpuResourceStore.configureGpuDevice wired before mesh ensureResident',\n hint: 'a mesh ensureResident ran before the GPU device was wired; call gpuStore.configureGpuDevice in createRenderer',\n }),\n );\n }\n\n // biome-ignore lint/suspicious/noExplicitAny: union of shim/raw return shapes\n const unwrapBuffer = (r: any): any => {\n if (r === null || r === undefined) return undefined;\n if (typeof r === 'object' && 'ok' in r) return r.ok ? r.value : undefined;\n return r;\n };\n // biome-ignore lint/suspicious/noExplicitAny: union of shim/raw write return\n const writeOk = (r: any): boolean => {\n if (r === undefined) return true;\n if (typeof r === 'object' && 'ok' in r) return r.ok === true;\n return true;\n };\n\n const indices = mesh.indices;\n const indexBytesUnpadded = indices === undefined ? 0 : indices.byteLength;\n const indexBytes = renderData.indexByteLength;\n\n const vboRet = device.createBuffer({\n label: `mesh-${id}-vbo`,\n size: renderData.vertexByteLength,\n usage: renderData.vertexUsage,\n mappedAtCreation: false,\n });\n const vbo = unwrapBuffer(vboRet);\n if (vbo === undefined) {\n return err(\n new RhiError({\n code: 'webgpu-runtime-error',\n expected: `device.createBuffer mesh-${id}-vbo to return a valid buffer`,\n hint: 'mesh vertex buffer allocation returned undefined',\n }),\n );\n }\n // Vertex-only mesh: skip the index buffer entirely. The indexed path below\n // is unchanged byte-for-byte when `indices` is present.\n let ibo: unknown = null;\n if (indices !== undefined) {\n const iboRet = device.createBuffer({\n label: `mesh-${id}-ibo`,\n size: indexBytes,\n usage: renderData.indexUsage,\n mappedAtCreation: false,\n });\n ibo = unwrapBuffer(iboRet);\n if (ibo === undefined) {\n return err(\n new RhiError({\n code: 'webgpu-runtime-error',\n expected: `device.createBuffer mesh-${id}-ibo to return a valid buffer`,\n hint: 'mesh index buffer allocation returned undefined',\n }),\n );\n }\n }\n\n const vboWriteRet = device.queue.writeBuffer(vbo, 0, mesh.vertices);\n if (!writeOk(vboWriteRet)) {\n return err(\n new RhiError({\n code: 'webgpu-runtime-error',\n expected: `queue.writeBuffer mesh-${id}-vbo to succeed`,\n hint: 'mesh vertex buffer write failed',\n }),\n );\n }\n\n if (indices !== undefined) {\n const indexSrc = new Uint8Array(indexBytes);\n indexSrc.set(new Uint8Array(indices.buffer, indices.byteOffset, indexBytesUnpadded));\n const iboWriteRet = device.queue.writeBuffer(ibo, 0, indexSrc);\n if (!writeOk(iboWriteRet)) {\n return err(\n new RhiError({\n code: 'webgpu-runtime-error',\n expected: `queue.writeBuffer mesh-${id}-ibo to succeed`,\n hint: 'mesh index buffer write failed',\n }),\n );\n }\n }\n\n const layoutProjection = renderData.layoutProjection;\n const strideBytes = meshStrideBytes(layoutProjection);\n const entry: MeshGpuEntry = {\n vertexBuffer: this.wrapBuf(vbo as Buffer),\n indexBuffer: ibo === null ? null : this.wrapBuf(ibo as Buffer),\n vboBytes: renderData.vertexByteLength,\n iboBytes: indices === undefined ? 0 : indexBytes,\n indexCount: renderData.indexCount,\n indexFormat: renderData.indexFormat,\n vertexCount: mesh.vertices.byteLength / strideBytes,\n indexed: indices !== undefined,\n topology: renderData.submeshes[0]?.topology ?? 'triangle-list',\n submeshes: renderData.submeshes,\n layoutProjection,\n };\n this.meshGpuHandles.set(id, entry);\n this.meshResidencyEpoch += 1;\n return ok(entry);\n }\n\n /**\n * Update an existing resident mesh without changing its shape or metadata.\n * A shape change must use a new asset handle; this method never reallocates\n * or silently changes the draw contract.\n */\n private updateMeshById(\n id: number,\n newVertices: Float32Array,\n newIndices: Uint16Array | Uint32Array | undefined,\n submeshes?: readonly Submesh[],\n ): Result<void, MeshUpdateErrorType | RhiError> {\n const device = this.gpuDevice as MipmapBlitDeviceWithBuffer | undefined;\n if (device === undefined) {\n return err(\n new RhiError({\n code: 'rhi-not-available',\n expected: 'GpuResourceStore.configureGpuDevice wired before mesh update',\n hint: 'configure the renderer GPU device before updating a mesh',\n }),\n );\n }\n const entry = this.meshGpuHandles.get(id);\n if (entry === undefined) {\n return err(\n new MeshUpdateError({\n code: 'mesh-not-resident',\n detail: { handle: id },\n }),\n );\n }\n\n const strideBytes = meshStrideBytes(entry.layoutProjection);\n const expectedVertexBytes = entry.vertexCount * strideBytes;\n const shapeMismatch = (expected: string, actual: string) =>\n err(\n new MeshUpdateError({\n code: 'mesh-shape-mismatch',\n detail: { handle: id, expected, actual },\n }),\n );\n if (\n newVertices.byteLength !== expectedVertexBytes ||\n newVertices.byteLength % strideBytes !== 0\n ) {\n return shapeMismatch(\n `${expectedVertexBytes} vertex bytes at ${strideBytes}-byte stride`,\n `${newVertices.byteLength} vertex bytes`,\n );\n }\n\n if (entry.indexed !== (newIndices !== undefined)) {\n return shapeMismatch(\n entry.indexed ? 'indexed mesh data' : 'vertex-only mesh data',\n newIndices === undefined ? 'vertex-only mesh data' : 'indexed mesh data',\n );\n }\n if (newIndices !== undefined) {\n const indexFormat = newIndices instanceof Uint32Array ? 'uint32' : 'uint16';\n const indexBytes = ((newIndices.byteLength + 3) >> 2) << 2;\n if (\n entry.indexBuffer === null ||\n indexFormat !== entry.indexFormat ||\n newIndices.length !== entry.indexCount ||\n indexBytes !== entry.iboBytes\n ) {\n return shapeMismatch(\n `${entry.indexFormat} index format with ${entry.indexCount} indices`,\n `${indexFormat} index format with ${newIndices.length} indices`,\n );\n }\n } else if (entry.indexBuffer !== null) {\n return shapeMismatch('indexed mesh data', 'vertex-only mesh data');\n }\n\n const nextSubmeshes = submeshes ?? entry.submeshes;\n if (!submeshesEqual(entry.submeshes, nextSubmeshes)) {\n return shapeMismatch('unchanged submesh descriptors', 'different submesh descriptors');\n }\n\n const vertexWrite = device.queue.writeBuffer(entry.vertexBuffer.handle, 0, newVertices);\n if (!vertexWrite.ok) return err(vertexWrite.error);\n if (newIndices !== undefined && entry.indexBuffer !== null) {\n const indexSrc = new Uint8Array(entry.iboBytes);\n indexSrc.set(new Uint8Array(newIndices.buffer, newIndices.byteOffset, newIndices.byteLength));\n const indexWrite = device.queue.writeBuffer(entry.indexBuffer.handle, 0, indexSrc);\n if (!indexWrite.ok) return err(indexWrite.error);\n }\n this.meshResidencyEpoch += 1;\n return ok(undefined);\n }\n\n /**\n * Internal explicit rebuild path used when an owner has deliberately\n * replaced a mesh shape. Public callers should register a new MeshAsset\n * handle so CPU recovery data and GPU residency remain one authority.\n */\n private replaceMeshById(\n id: number,\n newVertices: Float32Array,\n newIndices: Uint16Array | Uint32Array | undefined,\n submeshes?: readonly Submesh[],\n ): Result<void, MeshUpdateErrorType | RhiError> {\n const device = this.gpuDevice as MipmapBlitDeviceWithBuffer | undefined;\n const entry = this.meshGpuHandles.get(id);\n if (device === undefined) {\n return err(\n new RhiError({\n code: 'rhi-not-available',\n expected: 'GpuResourceStore.configureGpuDevice wired before mesh replacement',\n hint: 'configure the renderer GPU device before replacing a mesh',\n }),\n );\n }\n if (entry === undefined) {\n return err(new MeshUpdateError({ code: 'mesh-not-resident', detail: { handle: id } }));\n }\n const strideBytes = meshStrideBytes(entry.layoutProjection);\n if (newVertices.byteLength === 0 || newVertices.byteLength % strideBytes !== 0) {\n return err(\n new MeshUpdateError({\n code: 'mesh-shape-mismatch',\n detail: {\n handle: id,\n expected: `vertex bytes divisible by ${strideBytes}`,\n actual: `${newVertices.byteLength} vertex bytes`,\n },\n }),\n );\n }\n const newVertexBytes = newVertices.byteLength;\n const newIndexBytes = newIndices === undefined ? 0 : ((newIndices.byteLength + 3) >> 2) << 2;\n const unwrapBuffer = (r: unknown): unknown => {\n if (r === null || r === undefined) return undefined;\n if (typeof r === 'object' && 'ok' in r) {\n return (r as { ok: boolean; value?: unknown }).ok\n ? (r as unknown as { value: unknown }).value\n : undefined;\n }\n return r;\n };\n const vbo = unwrapBuffer(\n device.createBuffer({\n label: `mesh-${id}-vbo`,\n size: newVertexBytes,\n usage: GPU_BUFFER_USAGE_VERTEX | GPU_BUFFER_USAGE_COPY_DST,\n mappedAtCreation: false,\n }),\n );\n if (vbo === undefined) {\n return err(\n new RhiError({\n code: 'webgpu-runtime-error',\n expected: `device.createBuffer mesh-${id}-vbo to return a valid buffer`,\n hint: 'mesh replacement vertex buffer allocation failed',\n }),\n );\n }\n const ibo =\n newIndices === undefined\n ? null\n : unwrapBuffer(\n device.createBuffer({\n label: `mesh-${id}-ibo`,\n size: newIndexBytes,\n usage: GPU_BUFFER_USAGE_INDEX | GPU_BUFFER_USAGE_COPY_DST,\n mappedAtCreation: false,\n }),\n );\n if (newIndices !== undefined && ibo === undefined) {\n this.destroyMeshBuffer(this.wrapBuf(vbo as Buffer));\n return err(\n new RhiError({\n code: 'webgpu-runtime-error',\n expected: `device.createBuffer mesh-${id}-ibo to return a valid buffer`,\n hint: 'mesh replacement index buffer allocation failed',\n }),\n );\n }\n const vertexBuffer = this.wrapBuf(vbo as Buffer);\n const indexBuffer = ibo === null ? null : this.wrapBuf(ibo as Buffer);\n const vertexWrite = device.queue.writeBuffer(vertexBuffer.handle, 0, newVertices);\n if (!vertexWrite.ok) {\n this.destroyMeshBuffer(vertexBuffer);\n if (indexBuffer !== null) this.destroyMeshBuffer(indexBuffer);\n return err(vertexWrite.error);\n }\n if (newIndices !== undefined && indexBuffer !== null) {\n const indexSrc = new Uint8Array(newIndexBytes);\n indexSrc.set(new Uint8Array(newIndices.buffer, newIndices.byteOffset, newIndices.byteLength));\n const indexWrite = device.queue.writeBuffer(indexBuffer.handle, 0, indexSrc);\n if (!indexWrite.ok) {\n this.destroyMeshBuffer(vertexBuffer);\n this.destroyMeshBuffer(indexBuffer);\n return err(indexWrite.error);\n }\n }\n const nextSubmeshes = submeshes ?? entry.submeshes;\n const nextEntry: MeshGpuEntry = {\n vertexBuffer,\n indexBuffer,\n vboBytes: newVertexBytes,\n iboBytes: newIndexBytes,\n indexCount: newIndices?.length ?? 0,\n indexFormat: newIndices instanceof Uint32Array ? 'uint32' : 'uint16',\n layoutProjection: entry.layoutProjection,\n vertexCount: newVertexBytes / strideBytes,\n indexed: newIndices !== undefined,\n topology: nextSubmeshes[0]?.topology ?? entry.topology,\n submeshes: nextSubmeshes,\n };\n this.meshGpuHandles.set(id, nextEntry);\n this.meshResidencyEpoch += 1;\n this.destroyMeshBuffer(entry.vertexBuffer);\n if (entry.indexBuffer !== null) this.destroyMeshBuffer(entry.indexBuffer);\n return ok(undefined);\n }\n\n /**\n * Public surface for updating an existing unmanaged mesh handle's GPU buffer\n * data in-place. The handle must have been made resident.\n */\n updateMesh(\n handle: Handle<'MeshAsset', 'shared'>,\n newVertices: Float32Array,\n newIndices: Uint16Array | Uint32Array | undefined,\n worldId: number = 0,\n submeshes?: readonly Submesh[],\n ): Result<void, MeshUpdateErrorType | RhiError> {\n const id = this.worldKey(handleSlot(handle), worldId);\n return this.updateMeshById(id, newVertices, newIndices, submeshes);\n }\n\n /** Explicit internal rebuild path; public callers should use a new asset handle. */\n replaceMesh(\n handle: Handle<'MeshAsset', 'shared'>,\n newVertices: Float32Array,\n newIndices: Uint16Array | Uint32Array | undefined,\n worldId: number = 0,\n submeshes?: readonly Submesh[],\n ): Result<void, MeshUpdateErrorType | RhiError> {\n const id = this.worldKey(handleSlot(handle), worldId);\n return this.replaceMeshById(id, newVertices, newIndices, submeshes);\n }\n\n /** Upload a contiguous vertex range using the resident mesh stride. */\n updateMeshVertexRange(\n handle: Handle<'MeshAsset', 'shared'>,\n vertices: Float32Array,\n firstVertex: number,\n vertexCount: number,\n worldId: number = 0,\n ): Result<void, MeshUpdateErrorType | RhiError> {\n const id = this.worldKey(handleSlot(handle), worldId);\n const device = this.gpuDevice as MipmapBlitDeviceWithBuffer | undefined;\n if (device === undefined) {\n return err(\n new RhiError({\n code: 'rhi-not-available',\n expected: 'GpuResourceStore.configureGpuDevice wired before mesh range update',\n hint: 'configure the renderer GPU device before updating a mesh range',\n }),\n );\n }\n const entry = this.meshGpuHandles.get(id);\n if (entry === undefined) {\n return err(new MeshUpdateError({ code: 'mesh-not-resident', detail: { handle: id } }));\n }\n const strideBytes = meshStrideBytes(entry.layoutProjection);\n const invalidLocation = (\n reason: Exclude<MeshRangeInvalidReason, 'stride-mismatch'>,\n ): Result<void, MeshUpdateErrorType | RhiError> =>\n err(\n new MeshUpdateError({\n code: 'mesh-range-invalid',\n detail: {\n handle: id,\n firstVertex,\n vertexCount,\n residentVertexCount: entry.vertexCount,\n reason,\n },\n }),\n );\n const invalidStride = (\n expectedByteLength: number,\n actualByteLength: number,\n ): Result<void, MeshUpdateErrorType | RhiError> =>\n err(\n new MeshUpdateError({\n code: 'mesh-range-invalid',\n detail: {\n handle: id,\n firstVertex,\n vertexCount,\n residentVertexCount: entry.vertexCount,\n reason: 'stride-mismatch',\n expectedByteLength,\n actualByteLength,\n },\n }),\n );\n if (!Number.isInteger(firstVertex) || !Number.isInteger(vertexCount)) {\n return invalidLocation('non-integer');\n }\n if (firstVertex < 0 || vertexCount < 0) return invalidLocation('negative');\n if (vertexCount === 0) return invalidLocation('empty');\n if (firstVertex + vertexCount > entry.vertexCount) return invalidLocation('out-of-bounds');\n const expectedByteLength = vertexCount * strideBytes;\n if (vertices.byteLength !== expectedByteLength) {\n return invalidStride(expectedByteLength, vertices.byteLength);\n }\n const result = device.queue.writeBuffer(\n entry.vertexBuffer.handle,\n firstVertex * strideBytes,\n vertices,\n );\n if (!result.ok) return err(result.error);\n this.meshResidencyEpoch += 1;\n return ok(undefined);\n }\n}\n\n/**\n * Synthesize the `DecodedImage` view the texture-upload prelude consumes from\n * a `TextureAsset` POD (the record-stage pull path holds only the POD). The\n * POD's `data` is the pixel bytes; `colorSpace` + `mipmap` drive the\n * consistency assertion + mip count.\n */\nfunction decodedFromTexture(tex: TextureAsset): DecodedImage {\n const bytes =\n tex.data instanceof Uint8ClampedArray\n ? new Uint8Array(tex.data.buffer, tex.data.byteOffset, tex.data.byteLength)\n : tex.data;\n return {\n bytes,\n width: tex.width,\n height: tex.height,\n mime: 'image/png',\n colorSpace: tex.colorSpace,\n mipmap: tex.mipmap,\n };\n}\n","import type {\n HealthChangeListener,\n HealthReason,\n HealthSnapshot,\n RendererError,\n RendererErrorListener,\n RendererLostInfo,\n RendererLostListener,\n} from './renderer';\n\nexport function deriveRecoverable(reason: HealthReason): boolean {\n switch (reason) {\n case 'alive':\n return false;\n case 'device-lost':\n return true;\n case 'internal-fault':\n return false;\n }\n}\n\nexport class LostListenerRegistry {\n private readonly listeners = new Set<RendererLostListener>();\n private fired = false;\n private lastInfo: RendererLostInfo | null = null;\n\n add(listener: RendererLostListener): () => void {\n this.listeners.add(listener);\n if (this.fired && this.lastInfo) listener(this.lastInfo);\n return () => this.listeners.delete(listener);\n }\n\n fire(info: RendererLostInfo): void {\n this.fired = true;\n this.lastInfo = info;\n for (const listener of this.listeners) listener(info);\n }\n\n clear(): void {\n this.listeners.clear();\n }\n}\n\nexport class RhiErrorListenerRegistry {\n private readonly listeners: RendererErrorListener[] = [];\n private fired = false;\n private lastError: RendererError | null = null;\n\n add(listener: RendererErrorListener): () => void {\n this.listeners.push(listener);\n if (this.fired && this.lastError) {\n try {\n listener(this.lastError);\n } catch (error) {\n console.error('[RhiErrorListenerRegistry] late-attach listener threw:', error);\n }\n }\n return () => {\n const index = this.listeners.indexOf(listener);\n if (index >= 0) this.listeners.splice(index, 1);\n };\n }\n\n fire(error: RendererError): void {\n this.fired = true;\n this.lastError = error;\n if (this.listeners.length === 0) {\n console.error(`[RhiError ${error.code}] expected: ${error.expected}; hint: ${error.hint}`);\n return;\n }\n for (const listener of this.listeners) {\n try {\n listener(error);\n } catch (cause) {\n console.error('[RhiErrorListenerRegistry] listener threw:', cause);\n }\n }\n }\n\n clear(): void {\n this.listeners.length = 0;\n }\n}\n\nexport class HealthListenerRegistry {\n private readonly listeners = new Set<HealthChangeListener>();\n private fired = false;\n private lastSnapshot: HealthSnapshot | null = null;\n\n add(listener: HealthChangeListener): () => void {\n this.listeners.add(listener);\n if (this.fired && this.lastSnapshot) {\n try {\n listener(this.lastSnapshot);\n } catch (error) {\n console.error('[HealthListenerRegistry] late-attach listener threw:', error);\n }\n }\n return () => this.listeners.delete(listener);\n }\n\n fire(snapshot: HealthSnapshot): void {\n this.fired = true;\n this.lastSnapshot = snapshot;\n for (const listener of this.listeners) {\n try {\n listener(snapshot);\n } catch (error) {\n console.error('[HealthListenerRegistry] listener threw:', error);\n }\n }\n }\n\n clear(): void {\n this.listeners.clear();\n }\n\n getLastSnapshot(): HealthSnapshot {\n return this.fired && this.lastSnapshot\n ? this.lastSnapshot\n : { reason: 'alive', recoverable: false };\n }\n}\n","// pipeline-builder.ts -- runtime-internal helper for building per-MaterialShader\n// render pipelines (feat-20260523-shader-template-instance-split M9-T01).\n//\n// Anchors:\n// - plan-strategy D-PipelineBuilder: M9 introduces a runtime-internal\n// pipeline builder helper. `render-system-record` calls it once per\n// `materialShaderId` cache miss; the cache (M9-T03) is owned by the\n// record stage, not this helper.\n// - requirements AC-08: record on cache miss correctly constructs pipeline.\n// - requirements AC-14: the visible-pulse demo's per-frame values.time\n// mutation depends on a real GPU pipeline being built for the user\n// shader (`my-game::pulse-material`).\n// - plan-strategy R-H: pipeline construction must reuse the existing\n// 4-BindGroupLayout chain so existing PBR-heavy demos do not regress.\n//\n// API shape (per plan-task M9-T01 acceptanceCheck):\n// buildPipelineForMaterialShader(id, entry, ctx) -> Result<RenderPipeline, RhiError>\n//\n// The helper is intentionally **pure**: it does not cache, does not look up\n// the registry, does not maintain state. The caller (render-system-record's\n// per-MaterialShader pipeline cache, M9-T03) is responsible for both the\n// `ShaderRegistry.findMaterialArtifact(id)` call and the\n// `Map<materialShaderId, RenderPipeline>` cache. Splitting the concerns\n// keeps the helper trivially mockable (M9-T02 covers it with vi.fn-based\n// mocks; no real device required).\n//\n// Pipeline shape:\n// - layout = caller-supplied PipelineLayout (forgeax R-H: same\n// 4-BGL chain `[view, material, mesh-array, instances]`\n// reused across all MaterialShader entries; D-5 round-4)\n// - vertex stage = entry.source compiled as a ShaderModule, entry point\n// `vs_main`, vertex buffer layout from ctx\n// - fragment = same ShaderModule, entry point `fs_main`, color\n// attachment format from ctx\n// - depth = ctx.depthFormat with `less` compare + `depthWriteEnabled`\n// - primitive = `geometry.topology` (default `triangle-list`) + `back`\n// cull + `ccw` front face; strip topologies also bake\n// `stripIndexFormat`\n//\n// Capability gating: device.caps deviates only at the call site that\n// computes ctx; the helper consumes the resolved `ctx` without further\n// branching (charter P4 consistent abstraction).\n\nimport {\n err,\n type PipelineLayout,\n type RenderPipeline,\n type Result,\n type RhiDevice,\n RhiError,\n type ShaderModule,\n} from '@forgeax/engine-rhi';\nimport type { MaterialShaderEntry } from '@forgeax/engine-shader';\nimport {\n AssetError,\n type MaterialRenderState,\n type PassKind,\n type PrimitiveTopology,\n} from '@forgeax/engine-types';\nimport {\n buildPipelineDescriptor,\n colorFormatsForPassKind,\n type PipelineSpec,\n} from './pipeline-spec';\n\n/**\n * feat-20260604-mesh-topology-debug-draw M3 / w8: per-mesh geometry facts that\n * are baked into the immutable GPURenderPipeline `primitive` block. Distinct\n * from {@link MaterialRenderState} (material-authored state); these are\n * geometry properties of the mesh being drawn (requirements D-2 / D-A3).\n */\nexport interface PipelineGeometry {\n /** Primitive topology baked into `primitive.topology`. Defaults to 'triangle-list'. */\n readonly topology?: PrimitiveTopology;\n /**\n * Index format for strip topologies (`line-strip` / `triangle-strip`), baked\n * into `primitive.stripIndexFormat`. WebGPU spec: only valid for strip\n * topologies; ignored (left undefined in the descriptor) for list topologies.\n */\n readonly stripIndexFormat?: 'uint16' | 'uint32';\n}\n\n/**\n * Sync shader-module factory consumed by `buildPipelineForMaterialShader`.\n * Mirrors `ShaderRegistryDevice.createShaderModule` (sync Result shape) so\n * the same `makeShaderDeviceAdapter` in `createRenderer.ts` can satisfy\n * both surfaces (charter P4 consistent abstraction). The adapter caches\n * the underlying async `pack.createShaderModule` so subsequent sync calls\n * return cached modules; first call typically returns\n * `Result.err('rhi-not-available')` while the async build is in flight,\n * letting the caller fall back to the existing `standardPipeline` for\n * one frame and retry on the next (matches `render-system-record`'s\n * 1-frame-warmup idiom).\n */\nexport interface PipelineBuilderShaderModuleFactory {\n createShaderModule(desc: {\n readonly code: string;\n readonly label?: string | undefined;\n }): Result<ShaderModule, RhiError>;\n}\n\n/**\n * Build context for `buildPipelineForMaterialShader`. Caller (createRenderer\n * + render-system-record) computes this once per renderer and reuses across\n * cache misses; the values mirror the existing PBR pipeline construction\n * (createRenderer.ts ~line 2712 standardPipelineResult) so user shaders\n * land on the same 4-BindGroupLayout chain (charter P4 + plan-strategy\n * R-H).\n */\nexport interface PipelineBuilderContext {\n /** RHI device that owns the pipeline allocation. */\n readonly device: RhiDevice;\n /**\n * Sync shader-module factory (see {@link PipelineBuilderShaderModuleFactory}).\n * In production the engine wires the same `makeShaderDeviceAdapter` it\n * already uses for `ShaderRegistry.get(hash)`; tests pass a\n * `vi.fn`-based stub.\n */\n readonly shaderModuleFactory: PipelineBuilderShaderModuleFactory;\n /**\n * Shared pipeline layout (4 BindGroupLayouts: view + material + mesh-array\n * + instances). User shaders bind through the same slots as\n * default-standard-pbr; D-5 round-4 SSOT.\n */\n readonly pipelineLayout: PipelineLayout;\n /**\n * Color attachment format. The LDR / HDR variants pick `bgra8unorm-srgb` /\n * `rgba16float` respectively; record-stage gate matches the camera's\n * tonemap field (M9 keeps the LDR shape; HDR variants are OOS-M9).\n */\n readonly colorFormat: GPUTextureFormat;\n /** Depth attachment format, or `undefined` for a color-only pass. */\n readonly depthFormat: GPUTextureFormat | undefined;\n /**\n * Vertex buffer layout descriptors. Procedural geometry uses the 12-floats\n * stride (position + normal + uv + tangent); user shaders share this\n * layout for v1 (OOS-9 leaves alternative vertex layouts for a follow-up\n * feat).\n */\n readonly vertexBuffers: readonly GPUVertexBufferLayout[];\n /** Pipeline label (for GPU debug captures); defaults to `pbr-pipeline-${id}`. */\n readonly label?: string | undefined;\n /**\n * feat-20260604-mesh-topology-debug-draw w16-b: the shader-MODULE cache\n * identity, decoupled from the PSO `label` and the `id` arg. The WGSL module\n * depends ONLY on (source + defines), NOT on topology / renderState / isHdr /\n * indexFormat -- all of which WebGPU bakes into the immutable PSO, never the\n * module. `makeShaderDeviceAdapter` keys its `moduleCache` on this label, so\n * passing a stable per-(shader-source, defines) value here lets every\n * topology / renderState / HDR pipeline variant of the same shader SHARE one\n * compiled module: the first variant warms it, every later variant reuses it\n * synchronously (no per-variant async recompile, no event-loop yield).\n * Falls back to `shader-${id}` when omitted (pre-w16-b behaviour: the `id`\n * arg doubled as both PSO cache key and module label). The defines dimension\n * is NOT folded in here because the engine pre-resolves define variants into\n * distinct registered `source` strings (createRenderer.ts variant\n * resolution); callers that thread `defines` directly must include them in\n * `moduleLabel` so two `#define` prefixes do not collide on one module.\n */\n readonly moduleLabel?: string | undefined;\n}\n\n/**\n * Build a render pipeline for a material shader entry. Returns\n * `Result.err(RhiError)` on shader-module compile failure or pipeline\n * descriptor rejection (closed union RhiErrorCode pattern; AGENTS.md\n * \"Errors are structured\" + charter P3 explicit failure).\n *\n * Caller flow (M9-T03):\n * ```ts\n * let pipeline = pipelineCache.get(materialShaderId);\n * if (pipeline === undefined) {\n * const lookup = registry.findMaterialArtifact(materialShaderId);\n * if (!lookup.ok) {\n * // fallback to default-standard-pbr pipelineState.standardPipeline\n * } else {\n * const built = buildPipelineForMaterialShader(materialShaderId, lookup.value, ctx);\n * if (built.ok) pipelineCache.set(materialShaderId, built.value);\n * else if (built.error.code === 'rhi-not-available') {\n * // shader module still compiling async; retry next frame.\n * }\n * }\n * }\n * ```\n */\nexport function buildPipelineForMaterialShader(\n id: string,\n entry: MaterialShaderEntry,\n ctx: PipelineBuilderContext,\n renderState?: MaterialRenderState,\n geometry?: PipelineGeometry,\n vertexEntry?: string,\n fragmentEntry?: string,\n defines?: Record<string, string>,\n passKind: PassKind = 'forward',\n // bug-20260615 M2 / m2-1: sampleCount is a CAMERA fact (per-frame antialias\n // setting) threaded from getMaterialShaderPipeline -> buildAndCachePipeline\n // -> here. Default 1 produces `multisample: undefined` — byte-identical to\n // the pre-M2 descriptor for every existing count=1 caller. count > 1 sets\n // `multisample: { count: sampleCount }` matching the `createMsaaVariant`\n // shape on the built-in geometry side.\n sampleCount: number = 1,\n): Result<RenderPipeline, RhiError> {\n const label = ctx.label ?? `pbr-pipeline-${id}`;\n const vsEntry = vertexEntry ?? (passKind === 'temporal' ? 'vs_temporal' : 'vs_main');\n const fsEntry =\n fragmentEntry ??\n (passKind === 'deferred' ? 'fs_gbuffer' : passKind === 'temporal' ? 'fs_temporal' : 'fs_main');\n\n let source = entry.source;\n if (defines !== undefined && Object.keys(defines).length > 0) {\n const defineKeyRe = /^[A-Z_][A-Z0-9_]*$/;\n for (const key of Object.keys(defines)) {\n if (!defineKeyRe.test(key)) {\n return err(\n new AssetError({\n code: 'asset-invalid-value',\n expected: `define key matching /^[A-Z_][A-Z0-9_]*$/`,\n hint: `illegal define key '${key}' — must be uppercase letters, digits, and underscores, starting with a letter or underscore`,\n detail: { key, legalPattern: '^[A-Z_][A-Z0-9_]*$' },\n }),\n ) as unknown as ReturnType<typeof buildPipelineForMaterialShader>;\n }\n }\n const prefix = `${Object.entries(defines)\n .map(([k, v]) => `#define ${k} ${v}`)\n .join('\\n')}\\n`;\n source = prefix + source;\n }\n\n const moduleResult = ctx.shaderModuleFactory.createShaderModule({\n code: source,\n label: ctx.moduleLabel ?? `shader-${id}`,\n });\n if (!moduleResult.ok) {\n return moduleResult;\n }\n const shaderModule = moduleResult.value;\n\n // feat-20260609 M4 / R3-fixup: shadow-caster branch.\n // The shadow render pass beginRenderPass desc is `{ colorAttachments: [],\n // depthStencilAttachment: { format: 'depth32float', ... } }` (see\n // recordShadowPass / pipelineState.shadowTexture allocation). The PSO's\n // attachment state must match exactly — no color targets, depth32float\n // depth — otherwise WebGPU emits \"Attachment state of [pipeline] is not\n // compatible with [RenderPassEncoder]\". Ground truth descriptor was the\n // hardcoded shadowCasterPipeline removed in T-009 (commit 6416e9de~);\n // this branch reconstructs that exact shape via the lazy cache path.\n // Vertex layout is position-only (12-float stride, shaderLocation 0 vec3)\n // — the shadow_caster.wgsl vs_main reads only @location(0) position.\n if (passKind === 'shadow-caster') {\n // bug-20260619-csm RC-3 (AC-10): a material may supply a custom\n // ShadowCaster pass shader that carries a fragment stage (e.g. an\n // alpha-test cutout that calls `discard` and returns\n // `@builtin(frag_depth)`). The built-in `forgeax::default-shadow-caster`\n // is vertex-only — the GPU writes depth from `gl_Position.z` with no\n // fragment. To run the cutout discard, the PSO MUST include the\n // fragment stage when the shader declares one; otherwise the fragment\n // never executes and the shadow comes out solid. The depth pass has no\n // color attachments, so the fragment stage targets an empty list (it\n // only writes `@builtin(frag_depth)`).\n const hasFragmentStage = source.includes('@fragment');\n const shadowPipelineResult = ctx.device.createRenderPipeline({\n label,\n layout: ctx.pipelineLayout as unknown as GPUPipelineLayout,\n vertex: {\n module: shaderModule as unknown as GPUShaderModule,\n entryPoint: vsEntry,\n buffers: [\n {\n arrayStride: 12 * 4,\n attributes: [{ shaderLocation: 0, offset: 0, format: 'float32x3' as const }],\n },\n ],\n } as unknown as GPUVertexState,\n // Vertex-only depth pass writes `fragment: undefined` (GPU derives\n // depth from gl_Position.z). A custom ShadowCaster shader with a\n // fragment stage (cutout discard) gets the empty-target fragment\n // stage so its `discard` / `@builtin(frag_depth)` actually run.\n fragment: hasFragmentStage\n ? ({\n module: shaderModule as unknown as GPUShaderModule,\n entryPoint: fsEntry,\n targets: [],\n } as unknown as GPUFragmentState)\n : undefined,\n primitive: {\n topology: geometry?.topology ?? 'triangle-list',\n // Shadow caster matrices are allowed to mirror the view basis. A\n // default back-face cull therefore can reject every projected face\n // even though the same mesh is visible in the forward pass. Keep\n // authored culling when a custom ShadowCaster pass requests it, but\n // make the built-in depth pass two-sided so it always writes the\n // actual caster geometry into the shadow map.\n cullMode: renderState?.cullMode ?? 'none',\n frontFace: renderState?.frontFace ?? 'ccw',\n },\n depthStencil: {\n // depth32float (matches shadow RT format), NOT ctx.depthFormat\n // (which is depth24plus-stencil8 for the main pass).\n format: 'depth32float',\n depthWriteEnabled: true,\n depthCompare: 'less',\n },\n multisample: sampleCount > 1 ? { count: sampleCount } : undefined,\n });\n if (!shadowPipelineResult.ok) {\n if (shadowPipelineResult.error.code === 'shader-compile-failed') {\n return shadowPipelineResult;\n }\n return err(\n new RhiError({\n code: 'shader-compile-failed',\n expected: `shadow-caster pipeline for material shader '${id}' builds successfully`,\n hint: `inspect compiler messages on the shader module; verify pipeline layout matches shader bindings (cause: ${shadowPipelineResult.error.code})`,\n }),\n );\n }\n return shadowPipelineResult;\n }\n\n // feat-20260615-pipeline-spec-ssot M2-T3: delegate PSO descriptor assembly\n // to buildPipelineDescriptor(spec, modules). The spec is derived from the\n // forward-branch parameters; multisample is derived from sampleCount (1 → absent,\n // 4 → {count:4}). This replaces the inline literal formerly at :290-344.\n const forwardSpec: PipelineSpec = {\n shader: { id, passKind, variantSet: undefined },\n attachments: {\n colorFormats: colorFormatsForPassKind(passKind, ctx.colorFormat),\n depthFormat: ctx.depthFormat,\n sampleCount: (sampleCount === 4 ? 4 : 1) as 1 | 4,\n },\n geometry: {\n topology: geometry?.topology ?? 'triangle-list',\n stripIndexFormat: geometry?.stripIndexFormat,\n vertexLayout: {}, // vertexLayout not used at this layer; caller provides vertexBuffers\n },\n renderState,\n };\n const baseDesc = buildPipelineDescriptor(forwardSpec, {\n vertex: shaderModule,\n fragment: shaderModule,\n }) as Record<string, unknown>;\n\n // Merge pipeline-builder-specific fields (label, layout, vertexBuffers, entryPoint names)\n const pipelineResult = ctx.device.createRenderPipeline({\n label,\n layout: ctx.pipelineLayout as unknown as GPUPipelineLayout,\n vertex: {\n ...(baseDesc.vertex as Record<string, unknown>),\n entryPoint: vsEntry,\n buffers: ctx.vertexBuffers as unknown as GPUVertexBufferLayout[],\n } as unknown as GPUVertexState,\n fragment: (baseDesc.fragment !== undefined\n ? {\n ...(baseDesc.fragment as Record<string, unknown>),\n entryPoint: fsEntry,\n }\n : undefined) as unknown as GPUFragmentState,\n primitive: baseDesc.primitive as unknown as GPUPrimitiveState,\n ...(baseDesc.depthStencil !== undefined\n ? { depthStencil: baseDesc.depthStencil as unknown as GPUDepthStencilState }\n : {}),\n ...(baseDesc.multisample !== undefined\n ? { multisample: baseDesc.multisample as unknown as GPUMultisampleState }\n : {}),\n });\n\n if (!pipelineResult.ok) {\n // Wrap the underlying RhiError with a `shader-compile-failed` envelope\n // when the originating code is not already canonical -- this preserves\n // the canonical error code consumers expect at the standard-pipeline\n // build site (createRenderer.ts standardPipelineResult).\n if (pipelineResult.error.code === 'shader-compile-failed') {\n return pipelineResult;\n }\n return err(\n new RhiError({\n code: 'shader-compile-failed',\n expected: `pipeline for material shader '${id}' builds successfully`,\n hint: `inspect compiler messages on the shader module; verify pipeline layout matches shader bindings (cause: ${pipelineResult.error.code})`,\n }),\n );\n }\n return pipelineResult;\n}\n","// @forgeax/engine-runtime - Skin palette buffer allocator (M2 / T-24).\n//\n// Per-renderer mutable state: vertex-stage palette buffer(s) holding\n// pre-multiplied joint matrices (M_i = joint_world * IBM_i) for every\n// skinned entity in a frame. Two backends (split at construction by\n// `useStorageBuffer`):\n//\n// STORAGE PATH (`useStorageBuffer = true`, `maxStorageBuffersPerShaderStage\n// >= 8` — i.e. WebGPU spec default device).\n// One shared GPU buffer grows at 1.5x (Bevy skin.rs alignment,\n// plan-strategy D-4). Every entity's slice is `{ buffer: shared,\n// byteOffset: cursor }`. Record-stage builds ONE BG against the\n// shared buffer + `bindingWindowBytes` entry size; per-draw\n// `setBindGroup(_, bg, [_, dynOffset = slice.byteOffset])` slides\n// the static window across the buffer. WebGPU rule\n// `dynOffset + entry.size <= buffer.size` is satisfied because the\n// allocator extends `buffer.size` to `cursor + bindingWindowBytes`\n// after every slice.\n//\n// UNIFORM PATH (`useStorageBuffer = false`, browser uniform fallback —\n// `maxStorageBuffersPerShaderStage = 0`).\n// `maxUniformBufferBindingSize` floor is 16 KiB; the static binding\n// window alone is 16320 B, leaving room for ZERO additional\n// entities behind a shared dynOffset. The shared-BG model collapses,\n// so each entity gets its OWN small UBO of size = `bindingWindowBytes`\n// (= MAX_JOINTS * 64 = 16320, which is `<= maxUniformBufferBindingSize`).\n// Slice returns `{ buffer: per-entity, byteOffset: 0 }`. Record-stage\n// BG cache key includes `slice.buffer` so each entity gets its own\n// BG (cached per-buffer pointer; pool reuse keeps createBuffer\n// amortized across frames).\n//\n// Concept that does NOT branch by path: `bindingWindowBytes`. It is\n// the static `pbr-skin-mesh-array-bgl @binding(1/2)` BG entry size,\n// identical on both paths (WGSL declares the same layout). Record-\n// stage uses it verbatim for both palettes when constructing the BG.\n// dynOffset[1/2] on the uniform path is always 0 (entry size already\n// equals buffer size); on the storage path both walk 0, 1536, 3072, ... .\n//\n// CPU pre-multiply (path-agnostic): writeJointPalette(slice, ibm, jointWorld)\n// -> mat4 per joint: M_i = joint_world_i * IBM_i\n// -> queue.writeBuffer(slice.buffer, slice.byteOffset, payload).\n//\n// feat-20260523-skin-skeleton-animation M2 / T-24;\n// feat-20260612-skin-palette-per-frame-upload M6 (uniform fallback split).\n\nimport type { Mat4 } from '@forgeax/engine-math';\nimport { mat4 } from '@forgeax/engine-math';\nimport type { Buffer, RhiDevice } from '@forgeax/engine-rhi';\nimport { SkinPaletteOverflowError } from '../errors';\nimport {\n GPU_BUFFER_USAGE_COPY_DST,\n GPU_BUFFER_USAGE_STORAGE,\n GPU_BUFFER_USAGE_UNIFORM,\n} from '../gpu-usage';\nimport type { SkinPaletteSlice } from '../render-system-extract';\n\nconst MAT4_BYTES = 64; // 16 f32 * 4 bytes\n// MAX_JOINTS = 255 matches `pbr-skin-mesh-array-bgl @binding(1/2)` static BG\n// entry size: 255 * 64 = 16320 B. The number is the MAX joints any single\n// skinned entity may have. On the storage path the shared buffer holds\n// many entities back-to-back; on the uniform path each entity owns one\n// 16320 B buffer.\nconst MAX_JOINTS = 255;\nconst BINDING_WINDOW_BYTES = MAX_JOINTS * MAT4_BYTES; // 16320\n// WebGPU `minStorageBufferOffsetAlignment` default (spec floor) — every\n// dynamic offset passed to setBindGroup must be a multiple of this. The shared\n// storage path packs many entities back-to-back, so each slice's start must be\n// rounded up to this boundary; otherwise a slice whose predecessor's joint\n// footprint (jointCount * 64) is not a multiple of 256 (e.g. 33 joints -> 2112)\n// lands on an unaligned offset and trips `Dynamic Offset[1] is not 256 byte\n// aligned` at draw time.\nconst PALETTE_OFFSET_ALIGN = 256;\n\nexport interface SkinPaletteAllocator {\n /**\n * Static BG entry size for `pbr-skin-mesh-array-bgl @binding(1/2)`. Always\n * `MAX_JOINTS * 64 = 16320`; consumers (record stage) bind this size\n * when building the BG. Path-independent.\n */\n readonly bindingWindowBytes: number;\n /**\n * True when this allocator is in storage-path mode (single shared\n * buffer + dynOffset). False on the uniform fallback (per-entity\n * buffer + dynOffset always 0). Record-stage reads this only for\n * shape assertions in tests; production code branches via\n * `slice.buffer` identity (shared vs per-entity), not this flag.\n */\n readonly useStorageBuffer: boolean;\n /**\n * Allocate a slice for `jointCount` joints. Returns the buffer + byte\n * offset the record stage should bind. Storage path returns the same\n * shared buffer for every call; uniform path mints (or pool-reuses) a\n * per-entity buffer and returns it with `byteOffset: 0`. Both paths\n * guarantee BG validation: storage extends the shared buffer's size,\n * uniform sizes the per-entity buffer to exactly `bindingWindowBytes`.\n *\n * @throws if storage path buffer would exceed\n * `device.limits.maxStorageBufferBindingSize`\n */\n allocateSlice(jointCount: number): SkinPaletteSlice;\n /**\n * Write joint matrices into the slice's buffer at the slice's offset.\n * Computes M_i = jointWorldTransforms[i] * ibm[i] per joint.\n *\n * `jointWorlds[i]` is taken straight from `Skin.joints[i]` entity's\n * `Transform.world` view (a 16-float column-major Float32Array\n * written by propagateTransforms); zero recompose, premultiplies\n * directly against the IBM.\n */\n writeJointPalette(\n slice: SkinPaletteSlice,\n ibms: readonly Float32Array[],\n jointWorlds: readonly Mat4[],\n ): void;\n /** Upload the renderer projection's previous successful-submit palette. */\n writePreviousJointPalette(slice: SkinPaletteSlice, jointMatrices: Float32Array): void;\n /**\n * Reset for next frame. Storage path: cursor rewinds, shared buffer\n * stays. Uniform path: per-entity buffer cursor rewinds (pool entries\n * stay allocated and round-robin to the next frame's first entity).\n */\n resetForFrame(): void;\n}\n\nexport function createSkinPaletteAllocator(\n device: RhiDevice,\n maxBindingSize: number,\n useStorageBuffer = true,\n): SkinPaletteAllocator {\n // Storage path: shared buffer state.\n let storageBuffer: Buffer | null = null;\n let previousStorageBuffer: Buffer | null = null;\n let storageCapacity = 0;\n let storageCursor = 0;\n\n // Uniform path: per-entity buffer pool. `pool` is the pre-allocated\n // 16320 B UBO ring; `poolCursor` advances per allocateSlice within a\n // frame and rewinds in resetForFrame, so a 3-entity scene reuses 3\n // entries across frames (createBuffer fires only when the per-frame\n // entity count grows past the historical max). 16320 B / entry\n // bounded by maxUniformBufferBindingSize (>= 16384 by spec floor).\n const pool: Buffer[] = [];\n const previousPool: Buffer[] = [];\n let poolCursor = 0;\n\n function ensureStorageCapacity(needed: number): void {\n if (storageBuffer !== null && previousStorageBuffer !== null && needed <= storageCapacity)\n return;\n let newCapacity = storageCapacity === 0 ? BINDING_WINDOW_BYTES : storageCapacity;\n while (newCapacity < needed) {\n // 1.5x grow, then next multiple of 256 for alignment (plan-strategy D-4).\n newCapacity = (newCapacity + (newCapacity >> 1) + 255) & ~255;\n }\n if (newCapacity > maxBindingSize) {\n throw new SkinPaletteOverflowError(newCapacity, maxBindingSize);\n }\n const bufRes = device.createBuffer({\n label: 'skin-palette',\n size: newCapacity,\n usage: GPU_BUFFER_USAGE_STORAGE | GPU_BUFFER_USAGE_COPY_DST,\n mappedAtCreation: false,\n });\n if (!bufRes.ok) throw bufRes.error;\n const previousBufRes = device.createBuffer({\n label: 'skin-palette-previous',\n size: newCapacity,\n usage: GPU_BUFFER_USAGE_STORAGE | GPU_BUFFER_USAGE_COPY_DST,\n mappedAtCreation: false,\n });\n if (!previousBufRes.ok) throw previousBufRes.error;\n storageBuffer = bufRes.value;\n previousStorageBuffer = previousBufRes.value;\n storageCapacity = newCapacity;\n }\n\n function acquirePoolBuffer(buffers: Buffer[], label: string): Buffer {\n if (poolCursor < buffers.length) {\n const reused = buffers[poolCursor];\n // biome-ignore lint/style/noNonNullAssertion: poolCursor < buffers.length guarantees the slot is set\n return reused!;\n }\n if (BINDING_WINDOW_BYTES > maxBindingSize) {\n throw new SkinPaletteOverflowError(BINDING_WINDOW_BYTES, maxBindingSize);\n }\n const bufRes = device.createBuffer({\n label,\n size: BINDING_WINDOW_BYTES,\n usage: GPU_BUFFER_USAGE_UNIFORM | GPU_BUFFER_USAGE_COPY_DST,\n mappedAtCreation: false,\n });\n if (!bufRes.ok) throw bufRes.error;\n buffers.push(bufRes.value);\n return bufRes.value;\n }\n\n function allocateSlice(jointCount: number): SkinPaletteSlice {\n if (useStorageBuffer) {\n // Storage path: shared buffer + dynOffset window.\n // WebGPU validates `dynOffset + entry.size <= buffer.size` per\n // setBindGroup, so the buffer must extend a full BINDING_WINDOW_BYTES\n // past `byteOffset` -- not just `jointCount * 64`. Pre-M6 used the\n // latter and tripped `Dynamic Offset[1] out of bounds` on entity 2+.\n const offset = storageCursor;\n const needed = offset + BINDING_WINDOW_BYTES;\n ensureStorageCapacity(needed);\n // biome-ignore lint/style/noNonNullAssertion: ensureStorageCapacity throws if buffer cannot be created\n const buffer = storageBuffer!;\n // biome-ignore lint/style/noNonNullAssertion: ensureStorageCapacity creates the pair atomically or throws\n const previousBuffer = previousStorageBuffer!;\n // Cursor advances by the actual joint footprint, then rounds up to\n // PALETTE_OFFSET_ALIGN so the NEXT slice's byteOffset stays a valid\n // dynamic offset (WebGPU requires 256-byte alignment). Slices still pack\n // near-tightly (at most 255 B slack between them). Only the last slice's\n // window may overhang into uninitialized buffer space, which is benign\n // (shader reads only `jointCount` matrices).\n storageCursor =\n (offset + jointCount * MAT4_BYTES + (PALETTE_OFFSET_ALIGN - 1)) &\n ~(PALETTE_OFFSET_ALIGN - 1);\n return {\n jointCount,\n jointMatrices: new Float32Array(jointCount * 16),\n byteOffset: offset,\n buffer,\n previousBuffer,\n };\n }\n // Uniform fallback: each slice gets its own 16320 B UBO.\n const buffer = acquirePoolBuffer(pool, 'skin-palette');\n const previousBuffer = acquirePoolBuffer(previousPool, 'skin-palette-previous');\n poolCursor += 1;\n return {\n jointCount,\n jointMatrices: new Float32Array(jointCount * 16),\n byteOffset: 0,\n buffer,\n previousBuffer,\n };\n }\n\n function writeJointPalette(\n slice: SkinPaletteSlice,\n ibms: readonly Float32Array[],\n jointWorlds: readonly Mat4[],\n ): void {\n const count = Math.min(slice.jointCount, ibms.length, jointWorlds.length);\n if (count === 0) return;\n const payload = new Float32Array(count * 16);\n const temp = mat4.create();\n const ibm = mat4.create();\n const ibmNums = ibm as unknown as number[];\n for (let i = 0; i < count; i++) {\n const ibmFlat = ibms[i];\n const jw = jointWorlds[i];\n if (ibmFlat === undefined || jw === undefined) continue;\n for (let k = 0; k < 16; k++) {\n ibmNums[k] = ibmFlat[k] ?? 0;\n }\n mat4.multiply(temp, jw, ibm);\n const base = i * 16;\n for (let j = 0; j < 16; j++) {\n payload[base + j] = (temp as unknown as number[])[j] ?? 0;\n }\n }\n slice.jointMatrices.set(payload);\n const res = device.queue.writeBuffer(slice.buffer, slice.byteOffset, payload);\n if (!res.ok) throw res.error;\n }\n\n function writePreviousJointPalette(slice: SkinPaletteSlice, jointMatrices: Float32Array): void {\n const count = Math.min(slice.jointCount * 16, jointMatrices.length);\n if (count === 0) return;\n const payload = jointMatrices.subarray(0, count);\n const result = device.queue.writeBuffer(\n slice.previousBuffer ?? slice.buffer,\n slice.byteOffset,\n payload,\n );\n if (!result.ok) throw result.error;\n }\n\n function resetForFrame(): void {\n storageCursor = 0;\n poolCursor = 0;\n }\n\n return {\n bindingWindowBytes: BINDING_WINDOW_BYTES,\n useStorageBuffer,\n allocateSlice,\n writeJointPalette,\n writePreviousJointPalette,\n resetForFrame,\n };\n}\n","import type { RhiError } from '@forgeax/engine-rhi';\nexport interface EngineEnvironmentErrorDetail {\n readonly webgpuError?: RhiError | Error | undefined;\n readonly wgpuError?: RhiError | Error | undefined;\n}\nexport class EngineEnvironmentError extends Error {\n readonly reason: string;\n readonly webgpuError?: RhiError | Error | undefined;\n readonly wgpuError?: RhiError | Error | undefined;\n readonly detail: EngineEnvironmentErrorDetail;\n constructor(reason: string, detail: EngineEnvironmentErrorDetail = {}) {\n super(`forgeax-engine: no usable backend (${reason})`);\n this.name = 'EngineEnvironmentError';\n this.reason = reason;\n this.webgpuError = detail.webgpuError;\n this.wgpuError = detail.wgpuError;\n this.detail = detail;\n }\n}\n","import type { CookedMaterialRecord } from '@forgeax/engine-pack';\nimport {\n type MaterialArtifactConflictError,\n MaterialArtifactRegistry,\n type MaterialRuntimeArtifact,\n registerMaterialArtifact,\n} from '@forgeax/engine-shader';\nimport { err, ok, type Result } from '@forgeax/engine-types';\n\nexport interface MaterialAssetService {\n publish(\n record: CookedMaterialRecord,\n ): Result<CookedMaterialRecord, MaterialArtifactConflictError>;\n inspect(key: string): ReturnType<MaterialArtifactRegistry['inspect']>;\n}\n\n/** Render owns the CPU material artifact handoff; no GPU cache is introduced. */\nexport function createMaterialAssetService(): MaterialAssetService {\n const artifacts = new MaterialArtifactRegistry();\n return {\n publish(record) {\n const artifact: MaterialRuntimeArtifact = {\n key: record.specializationKey ?? record.receipt.inputDigest,\n bytes: record.artifact.bytes,\n digest: record.artifact.digest,\n };\n const registered = registerMaterialArtifact(artifacts, artifact);\n return registered.ok ? ok(record) : err(registered.error);\n },\n inspect: (key) => artifacts.inspect(key),\n };\n}\n","import type { CookedMaterialRecord } from '@forgeax/engine-pack';\nimport type { MaterialValue } from '@forgeax/engine-types';\n\nexport interface MaterialRenderPassProjection {\n readonly name: string;\n readonly module: string;\n readonly vertexEntry?: string;\n readonly fragmentEntry?: string;\n readonly moduleSlots?: Readonly<Record<string, string>>;\n readonly renderState?: Readonly<Record<string, unknown>>;\n readonly artifactHash: string;\n}\n\nexport interface MaterialRenderProjection {\n readonly materialGuid: string;\n readonly specializationKey: string;\n readonly artifactHash: string;\n readonly layoutIdentity: string;\n readonly passes: readonly MaterialRenderPassProjection[];\n readonly runtimeValues: Readonly<Record<string, MaterialValue | null>>;\n readonly staticSelection: readonly string[];\n}\n\nfunction projectPass(\n record: CookedMaterialRecord,\n pass: CookedMaterialRecord['resolved']['passes'][number],\n): MaterialRenderPassProjection {\n const program = pass.program;\n return {\n name: pass.name,\n module: program.module,\n ...(program.vertexEntry === undefined ? {} : { vertexEntry: program.vertexEntry }),\n ...(program.fragmentEntry === undefined ? {} : { fragmentEntry: program.fragmentEntry }),\n ...(program.moduleSlots === undefined ? {} : { moduleSlots: program.moduleSlots }),\n ...(pass.renderState === undefined ? {} : { renderState: pass.renderState }),\n artifactHash: record.artifact.digest,\n };\n}\n\nexport function assembleMaterialProjection(record: CookedMaterialRecord): MaterialRenderProjection {\n return {\n materialGuid: record.guid,\n specializationKey: record.receipt.inputDigest,\n artifactHash: record.artifact.digest,\n layoutIdentity: record.receipt.layoutIdentity,\n passes: record.resolved.passes.map((pass) => projectPass(record, pass)),\n runtimeValues: record.resolved.values,\n staticSelection: record.resolved.parameters\n .filter((parameter) => parameter.static)\n .map((parameter) => parameter.name)\n .sort(),\n };\n}\n","import type { ShaderRegistry } from '@forgeax/engine-shader';\nimport type { Asset } from '@forgeax/engine-types';\n\n/** Render-only projection supplied by the owner of decoded asset payloads. */\nexport interface RenderAssetResolver {\n readonly epoch: number;\n lookup<T extends Asset>(guid: string): T | undefined;\n guidOf(asset: Asset): string | undefined;\n}\n\nexport interface RenderAssetPort {\n readonly epoch: number;\n readonly shaderRegistry: ShaderRegistry;\n lookup<T extends Asset>(guid: string): T | undefined;\n guidOf(asset: Asset): string | undefined;\n materialShaderTextureFieldNames(shaderId: string): readonly string[];\n}\n\nexport function createRenderAssetPort(\n shaderRegistry: ShaderRegistry,\n resolver: RenderAssetResolver = emptyResolver,\n): RenderAssetPort {\n return {\n get epoch() {\n return resolver.epoch;\n },\n shaderRegistry,\n lookup: <T extends Asset>(guid: string) => resolver.lookup<T>(guid),\n guidOf: (asset: Asset) => resolver.guidOf(asset),\n materialShaderTextureFieldNames(shaderId: string): readonly string[] {\n const artifact = shaderRegistry.findMaterialArtifact(shaderId);\n if (!artifact.ok) return [];\n return artifact.value.paramSchema\n .filter((parameter) => parameter.type === 'texture2d')\n .map((parameter) => parameter.name);\n },\n };\n}\n\nconst emptyResolver: RenderAssetResolver = Object.freeze({\n epoch: 0,\n lookup: () => undefined,\n guidOf: () => undefined,\n});\n","import type { Result, RhiError, Texture, TextureView } from '@forgeax/engine-rhi';\nimport { ok } from '@forgeax/engine-rhi';\nimport type { Handle } from '@forgeax/engine-types';\nimport { handleSlot } from '@forgeax/engine-types';\n\nexport type CopyExternalImageSource = GPUCopyExternalImageSourceInfo['source'];\n\nconst VIDEO_TEXTURE_USAGE = 0x2 | 0x4 | 0x10;\nconst VIDEO_TEXTURE_FORMAT = 'rgba8unorm-srgb' as const;\n\nexport interface DynamicTextureDevice {\n createTexture(desc: {\n readonly size: {\n readonly width: number;\n readonly height: number;\n readonly depthOrArrayLayers: number;\n };\n readonly format: typeof VIDEO_TEXTURE_FORMAT;\n readonly usage: number;\n readonly label?: string;\n }): Result<Texture, RhiError>;\n createTextureView(texture: Texture, desc: Record<string, never>): Result<TextureView, RhiError>;\n destroyTexture(texture: Texture): Result<void, RhiError>;\n readonly queue: {\n copyExternalImageToTexture(\n source: { readonly source: CopyExternalImageSource; readonly flipY?: boolean },\n destination: { readonly texture: Texture },\n copySize: {\n readonly width: number;\n readonly height: number;\n readonly depthOrArrayLayers: number;\n },\n ): Result<void, RhiError>;\n };\n}\n\ninterface TransientEntry {\n texture: Texture;\n view: TextureView;\n width: number;\n height: number;\n}\n\n/** Renderer-owned transient GPU texture cache for host-provided video frames. */\nexport class DynamicTextureStore {\n private device: DynamicTextureDevice | undefined = undefined;\n private readonly entries = new Map<number, TransientEntry>();\n\n configureGpuDevice(device: DynamicTextureDevice): void {\n if (this.device !== undefined && this.device !== device) this.destroyAll();\n this.device = device;\n }\n\n uploadFrame(\n clip: Handle<'VideoAsset', 'shared'>,\n source: CopyExternalImageSource,\n width: number,\n height: number,\n ): Result<TextureView, RhiError> | undefined {\n const device = this.device;\n if (device === undefined || width <= 0 || height <= 0) return undefined;\n\n const ensured = this.ensureEntry(device, handleSlot(clip), width, height);\n if (!ensured.ok) return ensured;\n const copyRes = device.queue.copyExternalImageToTexture(\n { source, flipY: true },\n { texture: ensured.value.texture },\n { width, height, depthOrArrayLayers: 1 },\n );\n return copyRes.ok ? ok(ensured.value.view) : copyRes;\n }\n\n getView(clip: Handle<'VideoAsset', 'shared'>): TextureView | undefined {\n return this.entries.get(handleSlot(clip))?.view;\n }\n\n destroyAll(): void {\n const device = this.device;\n for (const entry of this.entries.values()) device?.destroyTexture(entry.texture);\n this.entries.clear();\n }\n\n private ensureEntry(\n device: DynamicTextureDevice,\n id: number,\n width: number,\n height: number,\n ): Result<TransientEntry, RhiError> {\n const existing = this.entries.get(id);\n if (existing !== undefined && existing.width === width && existing.height === height) {\n return ok(existing);\n }\n if (existing !== undefined) device.destroyTexture(existing.texture);\n\n const texRes = device.createTexture({\n size: { width, height, depthOrArrayLayers: 1 },\n format: VIDEO_TEXTURE_FORMAT,\n usage: VIDEO_TEXTURE_USAGE,\n label: `video-transient-${id}`,\n });\n if (!texRes.ok) return texRes;\n const viewRes = device.createTextureView(texRes.value, {});\n if (!viewRes.ok) {\n device.destroyTexture(texRes.value);\n return viewRes;\n }\n const entry: TransientEntry = { texture: texRes.value, view: viewRes.value, width, height };\n this.entries.set(id, entry);\n return ok(entry);\n }\n}\n","// @forgeax/engine-runtime - WebGPU HDRP cluster membership producer.\n//\n// The CPU binner remains the owner of bounds, occupancy, ordering, and\n// overflow validation. This compute entry only materializes the already\n// reserved ordered list on storage-buffer devices. Keeping the source here\n// makes the producer boot-time compiled and avoids adding a material shader\n// artifact or a second manifest identity.\n\nexport const HDRP_CLUSTER_MEMBERSHIP_WGSL = /* wgsl */ `\nstruct ClusterUniform {\n grid : vec4<u32>,\n near_far_log : vec4<f32>,\n};\n\n@group(0) @binding(0) var<storage, read> cluster_grid : array<u32>;\n@group(0) @binding(1) var<storage, read_write> light_index_list : array<u32>;\n@group(0) @binding(2) var<uniform> cluster_uniform : ClusterUniform;\n@group(0) @binding(3) var<storage, read> light_bounds : array<i32>;\n\n@compute @workgroup_size(64)\nfn cs_cluster_membership(@builtin(global_invocation_id) global_id : vec3<u32>) {\n let cluster_index = global_id.x;\n let grid_x = cluster_uniform.grid.x;\n let grid_y = cluster_uniform.grid.y;\n let grid_z = cluster_uniform.grid.z;\n let cluster_count = grid_x * grid_y * grid_z;\n if (cluster_index >= cluster_count) {\n return;\n }\n\n let cluster_x = cluster_index % grid_x;\n let cluster_yz = cluster_index / grid_x;\n let cluster_y = cluster_yz % grid_y;\n let cluster_z = cluster_yz / grid_y;\n let grid_offset = cluster_index * 2u;\n let output_offset = cluster_grid[grid_offset];\n let output_count = cluster_grid[grid_offset + 1u];\n let cluster_x_i = i32(cluster_x);\n let cluster_y_i = i32(cluster_y);\n let cluster_z_i = i32(cluster_z);\n var output_index = output_offset;\n\n var light_index = 0u;\n loop {\n if (light_index >= cluster_uniform.grid.w || light_index >= 256u) {\n break;\n }\n let bounds_offset = light_index * 6u;\n let min_x = light_bounds[bounds_offset];\n if (min_x >= 0) {\n let min_y = light_bounds[bounds_offset + 1u];\n let min_z = light_bounds[bounds_offset + 2u];\n let max_x = light_bounds[bounds_offset + 3u];\n let max_y = light_bounds[bounds_offset + 4u];\n let max_z = light_bounds[bounds_offset + 5u];\n if (\n cluster_x_i >= min_x && cluster_x_i <= max_x &&\n cluster_y_i >= min_y && cluster_y_i <= max_y &&\n cluster_z_i >= min_z && cluster_z_i <= max_z\n ) {\n if (output_index < output_offset + output_count) {\n light_index_list[output_index] = light_index;\n output_index += 1u;\n }\n }\n }\n light_index += 1u;\n }\n}\n`;\n","import type {\n Result,\n RhiCanvasContext,\n RhiDevice,\n RhiError,\n RhiInstance,\n ShaderModule,\n} from '@forgeax/engine-rhi';\nimport { err, ok, RhiError as RhiErrorClass } from '@forgeax/engine-rhi';\nimport * as rhiWebgpu from '@forgeax/engine-rhi-webgpu';\nimport type { RendererOptions } from '../renderer';\n\nexport interface RhiBackendInstrumentation {\n readonly resolveSurfaceDevice?: (device: RhiDevice) => Result<RhiDevice, RhiError>;\n readonly onFrameBoundary?: () => void;\n readonly onDeviceLost?: () => void;\n}\n\nexport interface RhiBackendPack {\n readonly rhi: RhiInstance & {\n readonly acquireCanvasContext: (\n canvas: HTMLCanvasElement | OffscreenCanvas,\n ) => Result<RhiCanvasContext, RhiError>;\n };\n readonly createShaderModule?: (\n device: RhiDevice,\n desc: { code: string; label?: string | undefined },\n ) => Promise<Result<ShaderModule, RhiError>>;\n readonly translateErrorEventToRhiError?: (event: unknown) => {\n readonly ok: false;\n readonly error: RhiError;\n };\n /** @internal */\n readonly _internal_getRawDevice?: (device: RhiDevice) => unknown | undefined;\n readonly instrumentation?: RhiBackendInstrumentation;\n}\n\nfunction readOptionalExport(mod: Record<string, unknown>, key: string): unknown {\n try {\n return mod[key];\n } catch {\n return undefined;\n }\n}\n\nexport function loadRhiPack(mod: Record<string, unknown>): RhiBackendPack {\n const createShaderModule = readOptionalExport(mod, 'createShaderModule');\n const translateErrorEventToRhiError = readOptionalExport(mod, 'translateErrorEventToRhiError');\n const rawDeviceExport = readOptionalExport(mod, '_internal_getRawDevice');\n const instrumentation = readOptionalExport(mod, 'instrumentation');\n return {\n rhi: mod.rhi as RhiBackendPack['rhi'],\n ...(createShaderModule !== undefined\n ? {\n createShaderModule: createShaderModule as NonNullable<\n RhiBackendPack['createShaderModule']\n >,\n }\n : {}),\n ...(translateErrorEventToRhiError !== undefined\n ? {\n translateErrorEventToRhiError: translateErrorEventToRhiError as NonNullable<\n RhiBackendPack['translateErrorEventToRhiError']\n >,\n }\n : {}),\n ...(rawDeviceExport !== undefined\n ? {\n _internal_getRawDevice: rawDeviceExport as NonNullable<\n RhiBackendPack['_internal_getRawDevice']\n >,\n }\n : {}),\n ...(instrumentation !== undefined\n ? { instrumentation: instrumentation as RhiBackendInstrumentation }\n : {}),\n };\n}\n\nfunction applyInstrumentation(\n pack: RhiBackendPack,\n instrumentation: RhiBackendInstrumentation | undefined,\n): RhiBackendPack {\n return instrumentation === undefined ? pack : { ...pack, instrumentation };\n}\n\nexport async function loadBackendPack(\n options: RendererOptions | undefined,\n): Promise<Result<RhiBackendPack, RhiError>> {\n const explicit = options?.rhi;\n if (explicit !== undefined && explicit !== null) {\n const extras = explicit as unknown as Record<string, unknown>;\n return ok(\n applyInstrumentation(loadRhiPack({ rhi: explicit, ...extras }), options?.rhiInstrumentation),\n );\n }\n const nav =\n typeof globalThis === 'undefined'\n ? undefined\n : (globalThis as { navigator?: { gpu?: unknown } }).navigator;\n if (nav?.gpu !== undefined && nav.gpu !== null)\n return ok(\n applyInstrumentation(\n loadRhiPack(rhiWebgpu as unknown as Record<string, unknown>),\n options?.rhiInstrumentation,\n ),\n );\n try {\n const mod = (await import('@forgeax/engine-rhi-wgpu')) as Record<string, unknown>;\n await (mod.ensureReady as () => Promise<unknown>)();\n return ok(applyInstrumentation(loadRhiPack(mod), options?.rhiInstrumentation));\n } catch (cause) {\n return err(\n new RhiErrorClass({\n code: 'rhi-not-available',\n expected: 'a usable RHI backend is available',\n hint: `failed to load wgpu backend: ${String(cause)}`,\n }),\n );\n }\n}\n","const GPU_CODES = new Set([\n 'adapter-unavailable',\n 'feature-not-enabled',\n 'limit-exceeded',\n 'rhi-not-available',\n 'device-lost',\n 'oom',\n]);\nexport function classifyEnvErrorReason(\n base: string,\n primary: { code?: unknown; name?: unknown } | undefined,\n): string {\n if (!primary || typeof primary !== 'object') return base;\n const code = primary.code;\n if (typeof code === 'string' && GPU_CODES.has(code)) return base;\n const name = typeof primary.name === 'string' ? primary.name : 'inner';\n return typeof code === 'string' && code.length > 0\n ? `engine init failed (${name}: ${code})`\n : `engine init failed (${name})`;\n}\nexport function composeEnvErrorHint(webgpuError: unknown, wgpuError: unknown): string | undefined {\n const a = (webgpuError as { code?: unknown } | undefined)?.code;\n const b = (wgpuError as { code?: unknown } | undefined)?.code;\n if (\n (a === 'adapter-unavailable' || a === 'rhi-not-available') &&\n (b === 'adapter-unavailable' || b === 'rhi-not-available')\n )\n return 'both channels report environmental failure';\n return undefined;\n}\n","// @forgeax/engine-render — concrete Renderer lifecycle and frame interpreter.\n//\n// Behaviour (bug-20260526-channel2-adapter-fail-no-channel3-fallback):\n// Channel 1. `options.rhi` supplied → use it verbatim (escape hatch, D-R5).\n// Channel 2. `navigator.gpu` present → static `@forgeax/engine-rhi-webgpu`.\n// If adapter/device/context fails → fall back to Channel 3.\n// Channel 3. Dynamic `import('@forgeax/engine-rhi-wgpu')` + `await ensureReady()`.\n// Failure → throw `EngineEnvironmentError` with `detail.webgpuError` +\n// `detail.wgpuError` (compound failure from both channels).\n//\n// **D-P4 three-channel error propagation** (RK-04 + plan-strategy §7.3):\n// (a) Construction-time → `createRenderer(...)` rejects with\n// `EngineEnvironmentError` whose `detail.webgpuError` is the Channel 2\n// `RhiError` and `detail.wgpuError` is the Channel 3 failure (when both\n// channels fail; AI users `try { await createRenderer(...) } catch (e) {\n// switch (e.detail.webgpuError?.code) { ... } }`).\n// (b) Run-time pipeline build → `renderer.ready` rejects with the\n// structured `RhiError` (`shader-compile-failed` / `limit-exceeded` /\n// `webgpu-runtime-error` / ...); AI users `await renderer.ready`.\n// (c) onError fan-out → `renderer.onError(listener)` captures the same\n// errors as a fallback observability channel (charter proposition 4\n// structured + proposition 9 graceful degradation).\n//\n// AC-15 source-level: this file uses `globalThis.navigator` rather than\n// `navigator` directly; it never touches `window` or `document`.\n\nimport type { World } from '@forgeax/engine-ecs';\nimport {\n deriveVertexBufferLayout,\n deriveVertexBufferLayoutFromProjection,\n type VertexLayoutProjection,\n} from '@forgeax/engine-geometry';\nimport { INPUT_SNAPSHOT_RESOURCE_KEY, type InputSnapshot } from '@forgeax/engine-input';\nimport type {\n BindGroupLayout,\n Buffer,\n ComputePipeline,\n PipelineLayout,\n RenderPipeline,\n Result,\n RhiAdapter,\n RhiCanvasContext,\n RhiDevice,\n RhiInstance,\n Sampler,\n ShaderModule,\n TextureView,\n} from '@forgeax/engine-rhi';\nimport { err, ok, RhiError, validateDrawArgs } from '@forgeax/engine-rhi';\n// Static rhi-webgpu import — channel 2 (navigator.gpu present) consumes this\n// namespace synchronously. rhi-webgpu is **already** a static dep via\n// `engine-runtime/src/index.ts:export { acquireCanvasContext } from\n// '@forgeax/engine-rhi-webgpu'` (M3 D-P3 single-entry SSOT for vite apps), so\n// the bundler treats it as eager-loaded regardless of how this file refers to\n// it. Channel 3 (rhi-wgpu) stays dynamic — only rhi-wgpu has no static\n// reference in engine-runtime and therefore tree-shakes out of browser-only\n// bundles. See file-header comment (revision F-01) and `loadBackendPack`\n// JSDoc for the full rationale.\nimport * as rhiWebgpu from '@forgeax/engine-rhi-webgpu';\nimport { registerPropagateTransforms } from '@forgeax/engine-scene';\nimport {\n findVariantByKey,\n type MaterialShaderManifestEntry,\n type MaterialShaderManifestVariant,\n ShaderRegistry,\n type ShaderRegistryDevice,\n} from '@forgeax/engine-shader';\nimport type {\n ImmutableParamSchemaProjection,\n ImportTransport,\n ManifestEntry,\n MaterialRenderState,\n ParamSchemaEntry,\n PassKind,\n PrimitiveTopology,\n VertexAttributeMap,\n} from '@forgeax/engine-types';\nimport { derive } from '@forgeax/engine-types';\nimport { createRenderAssetPort, type RenderAssetResolver } from '../assets/render-asset-port';\nimport { HDRP_DEFERRED_LIGHTING_POST_PROCESS_ID } from '../deferred-lighting';\nimport { DynamicTextureStore } from '../dynamic-texture-store';\nimport { createEngineMetrics } from '../engine-metrics';\nimport {\n ATMOSPHERE_PARAMS_BYTES,\n ATMOSPHERE_PARAMS_SLOT_BYTES,\n ATMOSPHERE_PARAMS_SLOT_COUNT,\n} from '../environment/graph';\nimport { RecoverError } from '../errors/recover';\nimport {\n MeshSsboCapacityExceededError,\n MeshSsboCeilingReachedError,\n type RenderError,\n RenderFeatureCapabilityMissingError,\n RenderFeatureStageFailedError,\n} from '../errors/render';\nimport { directionalCascadeAtlasSize } from '../extract/directional-csm';\nimport { createRenderFeatureHost, type RenderFeatureHost } from '../features/host';\nimport { RENDER_FEATURE_VERTEX_LAYOUTS } from '../features/prepared-graphics';\nimport {\n createTaaResolvePipelineResources,\n type TaaResolvePipelineResources,\n} from '../features/taa-resolve';\nimport type { RenderFeature } from '../features/types';\nimport type { PostProcessShaderEntry } from '../fullscreen-post-process-pass';\nimport { glyphTextLayoutSystem } from '../glyph-text-layout-system';\nimport { GpuResourceStore } from '../gpu-resource-store';\nimport { GPU_SHADER_STAGE_FRAGMENT, GPU_SHADER_STAGE_VERTEX } from '../gpu-stage';\nimport {\n GPU_TEXTURE_USAGE_COPY_DST,\n GPU_TEXTURE_USAGE_COPY_SRC,\n GPU_TEXTURE_USAGE_RENDER_ATTACHMENT_AND_TEXTURE_BINDING,\n GPU_TEXTURE_USAGE_TEXTURE_BINDING,\n} from '../gpu-texture-usage';\nimport {\n GPU_BUFFER_USAGE_COPY_DST,\n GPU_BUFFER_USAGE_MAP_READ,\n GPU_BUFFER_USAGE_STORAGE,\n GPU_BUFFER_USAGE_UNIFORM,\n GPU_BUFFER_USAGE_VERTEX,\n} from '../gpu-usage';\nimport {\n createHdrpBindGroupLayoutDescriptor,\n createHdrpClusterMembershipBindGroupLayoutDescriptor,\n} from '../hdrp-buffers';\nimport { HDRP_CLUSTER_MEMBERSHIP_WGSL } from '../hdrp-cluster-membership';\nimport { HDRP_PIPELINE_ID, hdrpPipeline } from '../hdrp-pipeline';\nimport { clearIblCacheForDevice, setIblComposedShaders } from '../ibl/IblPipelineCache';\nimport {\n createSkylightFallback,\n FALLBACK_BYTES_PER_ROW,\n type SkylightFallback,\n} from '../ibl/skylight-bind-group';\nimport {\n HealthListenerRegistry,\n LostListenerRegistry,\n RhiErrorListenerRegistry,\n} from '../lifecycle';\nimport {\n assertStorageBufferCap,\n LIGHT_ARRAY_HEADER_BYTES,\n LIGHT_ARRAY_MAX_SLOTS,\n POINT_LIGHT_STD430_BYTES,\n SPOT_LIGHT_STD430_BYTES,\n} from '../light-buffer-layout';\nimport type { MipmapShaderModuleFactory } from '../mipmap-generator';\nimport { createParamSchemaProjectionCensus } from '../param-schema-projection-census';\nimport {\n buildPbrPipelineLayouts,\n buildPbrSkinLayouts,\n SKIN_MATERIAL_SHADER_ID,\n} from '../pbr-pipeline';\nimport { buildPipelineForMaterialShader } from '../pipeline-builder';\nimport {\n buildBindGroupLayoutDescriptor,\n buildLinearLdrMaterialSpecTable,\n buildSpecConstTable,\n cacheKeyOf,\n colorFormatsForPassKind,\n getOrBuildPipeline,\n type PipelineCache,\n type PipelineDeviceProvider,\n type PipelineSpec,\n PipelineSpecError,\n} from '../pipeline-spec';\nimport {\n createMembershipTiming,\n type MembershipTimingController,\n} from '../record/membership-timing';\nimport { SHADOW_CASTER_BUFFER_SIZE } from '../record/shadow-caster-uniform';\nimport { VIEW_UNIFORM_BUFFER_SIZE } from '../record/view-ubo';\nimport { TONEMAP_POST_PROCESS_ID } from '../render-graph-primitives';\nimport {\n configureSurface,\n createRenderSystem,\n MATERIAL_PER_ENTITY_STRIDE,\n type PipelineState,\n type RenderSystem,\n} from '../render-system';\nimport type {\n DrawOwnerOptions,\n HealthChangeListener,\n HealthSnapshot,\n Renderer,\n RendererError,\n RendererErrorListener,\n RendererLostListener,\n RendererOptions,\n RenderResult,\n} from '../renderer';\nimport {\n createSkinPaletteAllocator,\n type SkinPaletteAllocator,\n} from '../systems/skin-palette-allocator';\nimport { tilemapChunkExtractSystem } from '../tilemap-chunk-extract-system';\nimport { URP_PIPELINE_ID, urpPipeline } from '../urp-pipeline';\nimport {\n loadBackendPack as loadAssemblyBackendPack,\n type RhiBackendInstrumentation,\n} from './backend-selection';\nimport { classifyEnvErrorReason, composeEnvErrorHint } from './environment-classify';\nimport { EngineEnvironmentError } from './environment-error';\n\nexport { createMaterialAssetService } from './asset-service';\nexport { assembleMaterialProjection } from './material/assembly';\nexport {\n projectMaterialPipeline,\n routeMaterialPipeline,\n updateMaterialRuntimeValues,\n} from './material/pipeline-projection';\n\n// Re-export registerAdvanceAnimationPlayer so consumers can wire it.\n// Re-export registerPropagateTransforms so consumers can wire the\n// Transform.world mat4 derivation (audio listener sync + picking read the\n// derived Transform.world from scripts).\n\n// feat-20260611-fox-skinning-vertex-attribute-chain M4 / w16 (D-4): a single\n// shared empty ArrayBuffer used by `buildPipelineContext` to synthesize the\n// 6-key VertexAttributeMap when no caller-supplied attributes are available\n// for the pbr-skin path. `deriveVertexBufferLayout` is the SSOT for the layout\n// (vertex-attribute-layout.ts) and reads only key presence -- value identity\n// never matters -- so a zero-byte ArrayBuffer per key produces the exact\n// 6-attribute / 72-byte stride layout that the @forgeax::pbr-skin shader's\n// @location(0..5) declarations expect.\nconst PBR_SKIN_SENTINEL_ATTR_BUFFER = new ArrayBuffer(0);\n\n/** Default 4-attribute vertex layout used as fallback when meshAttributes is undefined. */\nconst DEFAULT_VERTEX_ATTRS: VertexAttributeMap = {\n position: new Float32Array(0),\n normal: new Float32Array(0),\n uv: new Float32Array(0),\n tangent: new Float32Array(0),\n};\n\nconst PREPARED_INSTANCE_VERTEX_ATTRS: VertexAttributeMap = {\n position: new Float32Array(0),\n normal: new Float32Array(0),\n uv: new Float32Array(0),\n tangent: new Float32Array(0),\n uv1: new Float32Array(0),\n};\n\nconst PREPARED_MATERIAL_INSTANCE_VERTEX_ATTRS: VertexAttributeMap = {\n position: new Float32Array(0),\n normal: new Float32Array(0),\n uv: new Float32Array(0),\n tangent: new Float32Array(0),\n skinIndex: new Uint16Array(0),\n skinWeight: new Float32Array(0),\n};\n\nconst POSITION_SIZE_COLOR_INSTANCE_VERTEX_BUFFERS = [\n {\n arrayStride: 9 * 4,\n stepMode: 'instance' as const,\n attributes: [\n { shaderLocation: 0, offset: 0, format: 'float32x3' as const },\n { shaderLocation: 1, offset: 3 * 4, format: 'float32x2' as const },\n { shaderLocation: 2, offset: 5 * 4, format: 'float32x4' as const },\n ],\n },\n] as unknown as readonly GPUVertexBufferLayout[];\n\nconst BILLBOARD_MATERIAL_INSTANCE_VERTEX_BUFFERS = [\n {\n arrayStride: 31 * 4,\n stepMode: 'instance' as const,\n attributes: [\n { shaderLocation: 0, offset: 0, format: 'float32x3' as const },\n { shaderLocation: 1, offset: 3 * 4, format: 'float32x2' as const },\n { shaderLocation: 2, offset: 5 * 4, format: 'float32x2' as const },\n { shaderLocation: 3, offset: 7 * 4, format: 'float32x4' as const },\n { shaderLocation: 4, offset: 11 * 4, format: 'float32x4' as const },\n { shaderLocation: 5, offset: 15 * 4, format: 'float32x4' as const },\n { shaderLocation: 6, offset: 19 * 4, format: 'float32x4' as const },\n { shaderLocation: 7, offset: 23 * 4, format: 'float32x4' as const },\n { shaderLocation: 8, offset: 27 * 4, format: 'float32x4' as const },\n ],\n },\n] as unknown as readonly GPUVertexBufferLayout[];\n\nconst TOPOLOGY_SEGMENT_INSTANCE_VERTEX_BUFFERS = [\n {\n arrayStride: 12 * 4,\n stepMode: 'instance' as const,\n attributes: [\n { shaderLocation: 0, offset: 0, format: 'float32x3' as const },\n { shaderLocation: 1, offset: 3 * 4, format: 'float32x3' as const },\n { shaderLocation: 2, offset: 6 * 4, format: 'float32x4' as const },\n { shaderLocation: 3, offset: 10 * 4, format: 'float32x2' as const },\n ],\n },\n] as unknown as readonly GPUVertexBufferLayout[];\n\nconst MESH_GEOMETRY_MATERIAL_INSTANCE_VERTEX_BUFFERS = [\n {\n arrayStride: 12 * 4,\n stepMode: 'vertex' as const,\n attributes: [\n { shaderLocation: 0, offset: 0, format: 'float32x3' as const },\n { shaderLocation: 1, offset: 3 * 4, format: 'float32x3' as const },\n { shaderLocation: 2, offset: 6 * 4, format: 'float32x2' as const },\n { shaderLocation: 3, offset: 8 * 4, format: 'float32x4' as const },\n ],\n },\n {\n arrayStride: 28 * 4,\n stepMode: 'instance' as const,\n attributes: [\n { shaderLocation: 4, offset: 0, format: 'float32x3' as const },\n { shaderLocation: 5, offset: 3 * 4, format: 'float32x3' as const },\n { shaderLocation: 6, offset: 6 * 4, format: 'float32x3' as const },\n { shaderLocation: 7, offset: 9 * 4, format: 'float32x3' as const },\n { shaderLocation: 8, offset: 12 * 4, format: 'float32x4' as const },\n { shaderLocation: 9, offset: 16 * 4, format: 'float32x4' as const },\n { shaderLocation: 10, offset: 20 * 4, format: 'float32x4' as const },\n { shaderLocation: 11, offset: 24 * 4, format: 'float32x4' as const },\n ],\n },\n] as unknown as readonly GPUVertexBufferLayout[];\n\n/**\n * Bundler-layer injection accepted by `createRenderer` (and proxied by\n * `createApp`) as the optional third argument.\n *\n * feat-20260608-create-app-param-surface-trim / M2 / D-3: aggregates the two\n * host-injected build-tool channels:\n *\n * - shaderManifestUrl: the URL the host's vite-plugin-shader emit step\n * wrote `manifest.json` to. When this field is omitted (or `bundler`\n * itself is omitted), createRenderer falls back to\n * '/shaders/manifest.json' (D-2 q5-A) so the LO 1.1 zero-config takeoff\n * path keeps working without explicit injection. Tests can inject via a\n * `data:application/json,...` URL to bypass fetch.\n *\n * - importTransport: dev-only ImportTransport forwarded verbatim to the\n * AssetRegistry third ctor slot so DDC-miss assets can lazy-import.\n * Absent => shipped form (a DDC miss fails fast with `asset-not-imported`).\n *\n * The interface is duplicated structurally in `@forgeax/engine-app`\n * (BundlerOptions exported from packages/app); demos consume through the app\n * package, the engine accepts via this local minimal shape so packages/runtime\n * does NOT depend on packages/app (charter P4 + reverse-coupling deny-list).\n * TypeScript structural typing makes the two interchangeable at every call\n * site (M3 forgeaxBundlerAdapter() returns the same shape).\n */\nexport interface BundlerOptions {\n readonly importTransport?: ImportTransport | undefined;\n readonly shaderManifestUrl?: string | undefined;\n /** Render-only projection resolver owned by the active asset owner. */\n readonly assetResolver?: RenderAssetResolver | undefined;\n}\n\n// ─── Backend pack — M3 auto-select internal shape ───────────────────────────\n\n/**\n * Internal \"backend pack\" carries the two dynamic-import-loaded entries the\n * engine consumes (rhi singleton + the optional top-level async\n * `createShaderModule`). Defining this interface in the engine layer keeps\n * the rhi-webgpu / rhi-wgpu shim surfaces structurally aligned without\n * forcing both shims to grow an identical top-level factory — when the\n * wgpu-wasm path does not expose a top-level `createShaderModule`, the\n * facade falls back to the synchronous `device.createShaderModule` path\n * inside `makeShaderDeviceAdapter` (charter proposition 9 graceful\n * degradation).\n */\ninterface RhiBackendPack {\n readonly rhi: RhiInstance & {\n readonly acquireCanvasContext: (\n canvas: HTMLCanvasElement | OffscreenCanvas,\n ) => Result<RhiCanvasContext, RhiError>;\n };\n /** Async top-level shader module factory; rhi-webgpu exposes this; rhi-wgpu falls back to device.createShaderModule. */\n readonly createShaderModule?:\n | ((\n device: RhiDevice,\n desc: { code: string; label?: string | undefined },\n ) => Promise<Result<ShaderModule, RhiError>>)\n | undefined;\n /**\n * D-VD2 dispatch translator (feat-20260511-rhi-spec-realign-aggressive\n * Round 2): translates spec `GPUUncapturedErrorEvent` / `GPUDeviceLostInfo`\n * shapes into the 17-member `RhiErrorCode` union. rhi-webgpu provides this;\n * other backends (rhi-wgpu, explicit escape hatch) may omit — when undefined\n * the engine falls back to a minimal device-lost-only translator inline so\n * the AGENTS.md break-point #4 fan-out promise still holds on the lost path\n * (charter proposition 5 consistent abstraction — both `Renderer.onError`\n * channel members fire across all three load channels).\n */\n readonly translateErrorEventToRhiError?:\n | ((event: unknown) => { readonly ok: false; readonly error: RhiError })\n | undefined;\n /**\n * D-VD2 raw GPUDevice escape hatch (feat-20260511-rhi-spec-realign-aggressive\n * Round 2): given a forgeax `RhiDevice`, returns the underlying raw\n * `GPUDevice` so the engine can register `onuncapturederror` listener on\n * the spec event target. Only the rhi-webgpu pack exposes this entry; the\n * rhi-wgpu wasm pack and explicit escape hatch skip the listener\n * registration (graceful degradation — device.lost dual-channel still\n * fires through the forgeax RhiDevice.lost Promise on every path).\n * @internal\n */\n readonly _internal_getRawDevice?: ((device: RhiDevice) => unknown | undefined) | undefined;\n readonly instrumentation?: RhiBackendInstrumentation;\n}\n\n/**\n * Fold a raw module object (from a static import, dynamic import, or explicit\n * escape-hatch wrapper) into a typed `RhiBackendPack` by probing for known\n * optional fields via the `'x' in mod` pattern (existing convention).\n *\n * For the explicit escape hatch (Channel 1) where the instance IS the rhi\n * singleton, wrap it as `{ rhi: instance, ...extras }` before calling this\n * helper — the function always reads `mod.rhi` for the singleton.\n *\n * @param mod Raw module object with at least `rhi: RhiInstance & { acquireCanvasContext }`\n * @returns Typed RhiBackendPack with optional fields populated when present on mod\n * @internal — exported for unit test access (w20)\n */\nexport function loadRhiPack(mod: Record<string, unknown>): RhiBackendPack {\n const rhi = mod.rhi as unknown as RhiBackendPack['rhi'];\n const csm =\n 'createShaderModule' in mod\n ? (mod.createShaderModule as NonNullable<RhiBackendPack['createShaderModule']>)\n : undefined;\n const tx =\n 'translateErrorEventToRhiError' in mod\n ? (mod.translateErrorEventToRhiError as NonNullable<\n RhiBackendPack['translateErrorEventToRhiError']\n >)\n : undefined;\n const rd =\n '_internal_getRawDevice' in mod\n ? (mod._internal_getRawDevice as NonNullable<RhiBackendPack['_internal_getRawDevice']>)\n : undefined;\n const instrumentation =\n 'instrumentation' in mod\n ? (mod.instrumentation as RhiBackendPack['instrumentation'])\n : undefined;\n return {\n rhi,\n ...(csm !== undefined ? { createShaderModule: csm } : {}),\n ...(tx !== undefined ? { translateErrorEventToRhiError: tx } : {}),\n ...(rd !== undefined ? { _internal_getRawDevice: rd } : {}),\n ...(instrumentation === undefined ? {} : { instrumentation }),\n };\n}\n\n/**\n * D-P4 auto-select facade — decides which @forgeax/engine-rhi-* backend implementation\n * to use at runtime.\n *\n * Priority (matches plan-strategy §6 M3 pseudocode):\n * 1. `options.rhi` (escape hatch, D-R5) — verbatim use; neither rhi backend\n * pack is consulted.\n * 2. `'gpu' in globalThis.navigator && globalThis.navigator.gpu` →\n * **static** `rhiWebgpu` namespace (already eager-loaded via the\n * index.ts `acquireCanvasContext` re-export; revision F-01 cleared the\n * Rollup `[INEFFECTIVE_DYNAMIC_IMPORT]` warning by aligning the import\n * shape with the bundler's observed eager-load reality).\n * 3. Otherwise → dynamic `import('@forgeax/engine-rhi-wgpu')` + `await ensureReady()`\n * (R-04 + R-05). This dynamic import remains **effective** — rhi-wgpu\n * has no static reference in engine-runtime, so the wgpu-wasm artefact\n * tree-shakes out of webgpu-only browser bundles.\n *\n * Returns `Result.err(RhiError)` on rhi-wgpu wasm load failure (channel (a),\n * D-P4 RK-04). AI users branch on `.code === 'rhi-not-available'` to display\n * a degradation banner or retry.\n */\n/** Legacy implementation retained privately while assembly callers migrate. */\nasync function legacyLoadBackendPack(\n options: RendererOptions | undefined,\n): Promise<Result<RhiBackendPack, RhiError>> {\n // Channel 1 — escape hatch (D-R5): explicit rhi instance overrides auto-detect.\n // Cast to the extended shape; AI users supplying their own instance accept\n // that the facade may call `acquireCanvasContext` on it (charter\n // proposition 5 single-import surface).\n //\n // M4 / w25: if the explicit instance carries a top-level `createShaderModule`\n // (rhi-webgpu / rhi-wgpu both do), surface it through the pack so the\n // pipeline build step uses the async factory path symmetrically with\n // channel 2/3 — without this the escape hatch falls back to the structural\n // device probe in `invokeDeviceCreateShaderModule` which returns\n // 'rhi-not-available' for instances that keep createShaderModule on the\n // RhiInstance rather than the RhiDevice (charter proposition 5 consistent\n // abstraction across all three load channels).\n const explicit = options?.rhi;\n if (explicit !== undefined && explicit !== null) {\n // Channel 1 wraps the explicit instance as a module-shaped object so\n // loadRhiPack can probe optional fields uniformly. The instance IS the\n // rhi singleton + optionally carries createShaderModule /\n // translateErrorEventToRhiError / _internal_getRawDevice directly.\n const explicitMod: Record<string, unknown> = { rhi: explicit };\n const extras = explicit as unknown as Record<string, unknown>;\n if ('createShaderModule' in extras) explicitMod.createShaderModule = extras.createShaderModule;\n if ('translateErrorEventToRhiError' in extras)\n explicitMod.translateErrorEventToRhiError = extras.translateErrorEventToRhiError;\n if ('_internal_getRawDevice' in extras)\n explicitMod._internal_getRawDevice = extras._internal_getRawDevice;\n return ok(loadRhiPack(explicitMod));\n }\n\n // Channel 2 — navigator.gpu present → rhi-webgpu (no wasm download; AC-11).\n //\n // Revision F-01 (post-implement-review): switched from `await import(...)`\n // to the static `rhiWebgpu` namespace re-binding. `engine-runtime/src/\n // index.ts` already does `export { acquireCanvasContext } from\n // '@forgeax/engine-rhi-webgpu'` (M3 D-P3 single-entry SSOT), which makes\n // rhi-webgpu a static dependency of the runtime bundle. Rollup correctly\n // flagged the combined static + dynamic edges with\n // [INEFFECTIVE_DYNAMIC_IMPORT] (AC-16(b)). The dynamic shape was strictly\n // a notation mismatch: rhi-webgpu was always eager-loaded in practice.\n // Channel 3 (rhi-wgpu) retains its dynamic import — that one IS effective.\n //\n const nav: { gpu?: unknown } | undefined =\n typeof globalThis !== 'undefined'\n ? (globalThis as { navigator?: { gpu?: unknown } }).navigator\n : undefined;\n if (nav !== undefined && 'gpu' in nav && nav.gpu !== undefined && nav.gpu !== null) {\n // Channel 2 — rhi-webgpu D-VD2 Round 2: the namespace carries rhi +\n // createShaderModule + translateErrorEventToRhiError + _internal_getRawDevice.\n // loadRhiPack probes all optional fields uniformly.\n return ok(loadRhiPack(rhiWebgpu as unknown as Record<string, unknown>));\n }\n\n // Channel 3 — navigator.gpu absent → rhi-wgpu lazy load (R-04 + R-05).\n try {\n const mod = (await import('@forgeax/engine-rhi-wgpu')) as Record<string, unknown>;\n const ensureReady = mod.ensureReady as () => Promise<unknown>;\n await ensureReady();\n // loadRhiPack probes rhi + optional fields (createShaderModule /\n // translateErrorEventToRhiError / _internal_getRawDevice) uniformly.\n return ok(loadRhiPack(mod));\n } catch (loadError) {\n const detail = loadError instanceof Error ? loadError.message : String(loadError);\n // Bundle size literal stays anchored to the M5 metrics baseline\n // (0.51 MB = 536512 bytes gzip per report/rhi-wgpu/bundle-size.json +\n // AGENTS.md ## RHI / WebGPU dual-impl stance line 130 SSOT). w54 round 2\n // fix-up F-1 closure aligned this literal with packages/rhi-wgpu/src/\n // errors.ts so AI consumers of err.hint see one bundle-size figure\n // regardless of which fault site triggers the rhi-not-available code\n // (charter proposition 3 machine-readable SSOT).\n return err(\n new RhiError({\n code: 'rhi-not-available',\n expected: 'either navigator.gpu available OR @forgeax/engine-rhi-wgpu wasm bundle loadable',\n hint: `failed to load @forgeax/engine-rhi-wgpu wasm bundle (0.51 MB gzip per M5 bundle-size baseline); check network connectivity or use createRenderer(canvas, { rhi: explicitInstance }) escape hatch (cause: ${detail})`,\n }),\n );\n }\n}\n\n// The concrete construction path above is now owned by assembly/backend.ts.\n// Keep this private body temporarily for source-level rollback comparison; it\n// is not exported and cannot become a second public authority.\nvoid legacyLoadBackendPack;\n\n// ─── Public API ─────────────────────────────────────────────────────────────\n\n/**\n * Async factory: probes WebGPU (channel 2: rhi-webgpu, channel 3: rhi-wgpu);\n * returns a fully-initialized Renderer or throws `EngineEnvironmentError`.\n *\n * Channel priority (bug-20260526-channel2-adapter-fail-no-channel3-fallback):\n * 1. `options.rhi` → escape hatch (D-R5), verbatim use.\n * 2. `navigator.gpu` present → static `rhiWebgpu` namespace.\n * If adapter/device/context fails → falls back to channel 3.\n * 3. Dynamic `import('@forgeax/engine-rhi-wgpu')` + wasm load.\n * 4. All fail → throw `EngineEnvironmentError` with `detail.webgpuError`\n * + `detail.wgpuError`.\n *\n * @param canvas HTMLCanvasElement | OffscreenCanvas — render surface.\n * @param options RendererOptions — clear color / shader manifest URL /\n * D-S1 raw-device single-point exemption / M3 `rhi` escape hatch.\n *\n * **Error propagation — three channels (D-P4 RK-04):**\n * (a) Construction-time: this Promise rejects with `EngineEnvironmentError`\n * whose `detail.webgpuError` is the Channel 2 `RhiError` and\n * `detail.wgpuError` is the Channel 3 failure (when both fail).\n * (b) Run-time pipeline build: `renderer.ready` rejects with a\n * structured `RhiError` once the dynamic-import path is past.\n * (c) Fan-out observability: `renderer.onError(listener)` captures the\n * same errors as a fallback channel.\n *\n * @throws {EngineEnvironmentError} when no backend is usable.\n */\n\n/**\n * Per-variant PipelineLayout selector (M4.5 / D-10 option A).\n *\n * The HDRP variant (`CLUSTER_FORWARD_AVAILABLE=true` or canonical `''`\n * all-true when the shader declares the cluster axis) needs the 7-slot\n * group(2) BGL chain (`hdrpPbrPipelineLayout`); URP variants\n * (`CLUSTER_FORWARD_AVAILABLE=false` / undefined / no axis) keep the\n * 1-slot mesh-array BGL chain (`pbrPipelineLayout`).\n *\n * Returns `null` only when the URP fallback layout itself is null\n * (Camera-only / empty-manifest path). When the HDRP layout is null but\n * URP exists, the HDRP variant gracefully falls back to URP — the WGSL\n * resolved upstream by `findVariantByKey` is the URP variant in that\n * case (manifest entry with all-true definesKey === '' was registered\n * with isHdrpActive=false at boot when storage-buffer caps are absent).\n *\n * Pure function — exported for unit-test access (M4.5 / w35).\n */\n/**\n * Closed enum of pipeline-layout kinds the selector can dispatch to.\n *\n * `pbr` — standard PBR (1-entry mesh-array BGL).\n * `pbr-skin` — bug-20260611-skin-pipeline-layout: 3-entry mesh-array BGL\n * (binding 0 meshes + bindings 1/2 current/previous palettes) for the `forgeax::pbr-skin`\n * material shader.\n * `hdrp-pbr` — feat-20260609 HDRP cluster-forward variant (7-slot group(2)\n * BGL substituted at slot 2).\n * `sprite-urp` — bug-20260708 M2 (c): sprite / sprite-lit shaders reuse\n * the URP 1-slot mesh-array BGL (they don't declare\n * CLUSTER_FORWARD_AVAILABLE) but their canonical all-true variant key\n * `''` (`SPRITE_PASS_PER_INSTANCE_REGION_VARIANT_SET`) MUST NOT trigger\n * the `variantSet===''` → HDRP branch of the selector. Callers\n * (`buildPipelineContext`) resolve `sprite-urp` from the sprite\n * `materialShaderId` and pass it through; the selector short-circuits\n * to `pbrPipelineLayout` before the HDRP check.\n *\n * AC-09 grep gate: the selector body (`selectPipelineLayoutForVariant`)\n * **MUST NOT** contain literal `'forgeax::pbr-skin'` (or any other\n * shader-id literal). The caller resolves `LayoutKind` upstream and passes\n * the structured value through (charter P4 consistent abstraction). New\n * material-shader layouts add a `LayoutKind` member + a PipelineState slot\n * + a switch arm here in one cut (charter P3 extensibility).\n */\nexport type LayoutKind = 'pbr' | 'pbr-skin' | 'hdrp-pbr' | 'sprite-urp' | 'unlit-urp';\n\n/**\n * Return every device-capability HDRP PBR variant that needs a lazy module\n * label seeded during renderer boot. Color availability is intentionally not\n * filtered: colored and no-color meshes use distinct composed WGSL modules.\n */\nexport function selectHdrpPbrPrewarmVariants(\n manifestEntry: MaterialShaderManifestEntry | undefined,\n storageBufferCapable: boolean,\n): readonly MaterialShaderManifestVariant[] {\n return (\n manifestEntry?.variants.filter(\n (variant) =>\n variant.defines.STORAGE_BUFFER_AVAILABLE === storageBufferCapable &&\n variant.defines.CLUSTER_FORWARD_AVAILABLE === true,\n ) ?? []\n );\n}\n\nexport type MaterialShaderBindingContract =\n | 'group-0'\n | 'group-0-resource'\n | 'view-only'\n | 'view-with-resource'\n | 'render-material';\nexport type MaterialShaderVertexInputContract = 'none' | 'render-material';\n\nexport function resolveMaterialShaderBindingContract(\n source: string,\n): MaterialShaderBindingContract {\n const withoutComments = source.replace(/\\/\\*[\\s\\S]*?\\*\\//gu, '').replace(/\\/\\/.*$/gmu, '');\n const groups = [...withoutComments.matchAll(/@group\\s*\\(\\s*(\\d+)\\s*\\)/gu)].map((match) =>\n Number(match[1]),\n );\n if (groups.length === 0) return 'group-0';\n const declaresView =\n /@group\\s*\\(\\s*0\\s*\\)\\s*@binding\\s*\\(\\s*0\\s*\\)\\s*var\\s*<\\s*uniform\\s*>\\s*view(?:X_naga_oil_mod_[A-Z0-9]+)?\\b/u.test(\n withoutComments,\n );\n const declaresViewResource =\n declaresView &&\n /@group\\s*\\(\\s*0\\s*\\)\\s*@binding\\s*\\(\\s*1\\s*\\)[^;]*texture_depth_2d/u.test(withoutComments);\n if (declaresViewResource && groups.every((group) => group === 0)) return 'view-with-resource';\n if (declaresView && groups.every((group) => group === 0)) return 'view-only';\n return groups.every((group) => group === 0) ? 'group-0-resource' : 'render-material';\n}\n\nexport function resolveMaterialShaderVertexInputContract(\n source: string,\n): MaterialShaderVertexInputContract {\n const withoutComments = source.replace(/\\/\\*[\\s\\S]*?\\*\\//gu, '').replace(/\\/\\/.*$/gmu, '');\n const inputStructs = [...withoutComments.matchAll(/struct\\s+([A-Za-z_]\\w*)\\s*\\{([^}]*)\\}/gu)]\n .filter((match) => /@location\\s*\\(/u.test(match[2] ?? ''))\n .map((match) => match[1]);\n // WGSL vertex inputs are commonly declared in a named struct before the\n // `@vertex` function (the engine uses `VsIn`, while package shaders often\n // use `VertexInput`). Match the type actually passed as the first vertex\n // parameter so fragment/output structs do not accidentally enable a\n // vertex buffer layout for fullscreen shaders.\n for (const inputStruct of inputStructs) {\n if (inputStruct === undefined) continue;\n const firstParameter = new RegExp(\n `@vertex\\\\s*fn\\\\s+\\\\w+\\\\s*\\\\(\\\\s*\\\\w+\\\\s*:\\\\s*${inputStruct}\\\\b`,\n 'u',\n );\n if (firstParameter.test(withoutComments)) return 'render-material';\n }\n // A shader may declare a location directly on a vertex parameter rather\n // than through a struct. Keep that contract explicit as well.\n return /@vertex\\s*fn[^{]*\\([^)]*@location\\s*\\(/u.test(withoutComments)\n ? 'render-material'\n : 'none';\n}\n\nfunction allowsUnlitPreparedFallback(\n depthFormatOverride: GPUTextureFormat | null | undefined,\n vertexLayout: string | undefined,\n materialShaderId?: string,\n): boolean {\n return (\n depthFormatOverride === null &&\n (vertexLayout === undefined || !materialShaderId?.startsWith('forgeax::'))\n );\n}\n\nexport function selectPipelineLayoutForVariant(\n state: {\n readonly pbrPipelineLayout: PipelineLayout | null;\n readonly hdrpPbrPipelineLayout: PipelineLayout | null;\n readonly pbrSkinPipelineLayout: PipelineLayout | null;\n } | null,\n variantSet: string | undefined,\n layoutKind?: LayoutKind,\n): PipelineLayout | null {\n if (state === null) return null;\n // bug-20260611: skin layout selection takes precedence over HDRP variant\n // resolution. HDRP × skin is OOS-1 (plan-strategy R-2 — left for a\n // dedicated feat); when an HDRP-variant skin call ever lands, we fail\n // fast with `null` rather than silently returning the URP layout\n // (charter P3 explicit failure, mirrors memory anchor\n // `hdrp-active-must-not-fallback-to-urp-pipeline`).\n if (layoutKind === 'pbr-skin') {\n return state.pbrSkinPipelineLayout;\n }\n // bug-20260708 M2 (c): sprite / sprite-lit shaders reuse the URP 1-slot\n // mesh-array pipeline layout but their canonical all-true variant key\n // `''` (SPRITE_PASS_PER_INSTANCE_REGION_VARIANT_SET) must NOT trigger\n // the `variantSet===''` → HDRP branch below. Caller-side\n // (`buildPipelineContext`) resolves LayoutKind='sprite-urp' from the\n // sprite `materialShaderId`; the selector short-circuits here before\n // the HDRP variant check reads `variantSet`. Prevents R-1'\n // device-lost when a SpriteInstances batch requests the PIR=true\n // canonical variant.\n if (layoutKind === 'sprite-urp') {\n return state.pbrPipelineLayout;\n }\n if (layoutKind === 'unlit-urp') {\n return state.pbrPipelineLayout;\n }\n // HDRP variant matches when:\n // - layoutKind === 'hdrp-pbr' (caller-driven, future-proof), OR\n // - variantSet is the canonical all-true key '' (boot-time HDRP\n // registration produces '' when both axes resolve to true), OR\n // - variantSet contains `CLUSTER_FORWARD_AVAILABLE=true` substring\n // (record-stage caller emits the expanded form).\n // URP variants have CLUSTER_FORWARD_AVAILABLE=false explicitly, or omit\n // the axis altogether, or pass undefined (no variant routing).\n // G-14 (D-11): empty-string is the canonical all-true HDRP key, so we\n // explicitly distinguish '' vs undefined rather than using an optional-chain\n // (charter P3: explicit failure / no implicit empty-vs-missing collapse).\n const isHdrpVariant =\n layoutKind === 'hdrp-pbr' ||\n variantSet === '' ||\n // biome-ignore lint/complexity/useOptionalChain: G-14 grep gate forbids the optional-chain falsy collapse on variantSet.\n (variantSet !== undefined && variantSet.includes('CLUSTER_FORWARD_AVAILABLE=true'));\n if (isHdrpVariant && state.hdrpPbrPipelineLayout !== null) {\n return state.hdrpPbrPipelineLayout;\n }\n return state.pbrPipelineLayout;\n}\n\n/**\n * Resolve a requested material variant against the actual backend capabilities.\n * Record callers use the native-capability request; the backend-owned axes\n * must be rewritten before the request reaches shader lookup and PSO layout\n * selection.\n */\nexport function resolveMaterialShaderVariantSet(\n requestedVariantSet: string | undefined,\n variants: ReadonlyArray<{\n readonly defines: Readonly<Record<string, boolean>>;\n }>,\n backendKind: RhiDevice['caps']['backendKind'],\n storageBuffer: boolean,\n): string | undefined {\n const declaredAxes = new Set(variants.flatMap((variant) => Object.keys(variant.defines)));\n const declaresCapabilityVariants =\n declaredAxes.has('WEBGL2_COMPAT') || declaredAxes.has('STORAGE_BUFFER_AVAILABLE');\n if (!declaresCapabilityVariants) return requestedVariantSet;\n\n const requested: Record<string, boolean> = {};\n for (const part of requestedVariantSet?.split('+') ?? []) {\n const separator = part.indexOf('=');\n if (separator > 0) requested[part.slice(0, separator)] = part.slice(separator + 1) === 'true';\n }\n const filtered: Record<string, boolean> = {};\n for (const axis of declaredAxes) {\n filtered[axis] =\n axis === 'WEBGL2_COMPAT'\n ? backendKind === 'wgpu-webgl2'\n : axis === 'STORAGE_BUFFER_AVAILABLE'\n ? backendKind !== 'wgpu-webgl2' && storageBuffer\n : (requested[axis] ?? true);\n }\n const sorted = Object.entries(filtered).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));\n return sorted.every(([, value]) => value)\n ? requestedVariantSet === ''\n ? ''\n : undefined\n : sorted.map(([name, value]) => `${name}=${value}`).join('+');\n}\n\nexport async function createRenderer(\n canvas: unknown,\n options?: RendererOptions,\n // feat-20260608-create-app-param-surface-trim / M2 / D-3: the third arg is\n // now BundlerOptions -- the build-tool injection channel that aggregates\n // (a) shaderManifestUrl (vite-plugin-shader emit URL) and (b) importTransport\n // (dev-only AssetRegistry transport from feat-20260604). Both fields\n // optional so {} is a valid call shape. Absent => both shipped-form\n // fallbacks fire: shaderManifestUrl falls back to '/shaders/manifest.json'\n // (D-2 q5-A, ~30 lines below); importTransport stays undefined (AssetRegistry\n // shipped form, DDC miss fails fast with `asset-not-imported`, AC-08).\n //\n // The interface lives in @forgeax/engine-app to keep host-injection types\n // colocated with createApp; createRenderer accepts a structurally-compatible\n // local minimal shape so packages/runtime does NOT depend on packages/app\n // (charter P4 layering, R-4 reverse-coupling deny-list).\n bundler?: BundlerOptions,\n): Promise<Renderer> {\n // D-P4 auto-select — backend selection happens BEFORE context acquisition\n // (w19 / M4). `loadBackendPack` reads navigator.gpu and returns either the\n // rhi-webgpu static pack (Channel 2) or the rhi-wgpu dynamic-import pack\n // (Channel 3). `tryCreateWebGPURenderer` then calls\n // `pack.rhi.acquireCanvasContext(canvas)` which polymorphically routes to:\n // Channel 2: rhi-webgpu internally calls canvas.getContext('webgpu')\n // Channel 3: rhi-wgpu internally calls wasm createSurface(canvas)\n // Neither getContext nor wasm surface is invoked until after the pack is\n // selected (charter P4 consistent abstraction).\n const packResult = await loadAssemblyBackendPack(options).catch((e: unknown) => {\n const errMsg = e instanceof Error ? e.message : String(e);\n return err(\n new RhiError({\n code: 'rhi-not-available',\n expected:\n 'rhi-webgpu static namespace OR dynamic import of @forgeax/engine-rhi-wgpu succeeds',\n hint: `unexpected exception during backend-pack load: ${errMsg}`,\n }),\n );\n });\n if (!packResult.ok) {\n throw new EngineEnvironmentError('rhi backend pack load failed', {\n webgpuError: packResult.error,\n });\n }\n const pack = packResult.value;\n const webgpuOutcome = await tryCreateWebGPURenderer(\n canvas as HTMLCanvasElement | OffscreenCanvas,\n options,\n pack,\n bundler,\n ).catch((e: unknown) => {\n return { kind: 'throw' as const, error: toError(e) };\n });\n if (webgpuOutcome.kind === 'ok') {\n return webgpuOutcome.renderer;\n }\n\n // Collect the structured error for the EngineEnvironmentError detail.\n // D-1: on the context-null path, webgpuError is undefined (no synthetic\n // RhiError wrapping — context-null is upstream of rhi-wgpu).\n let webgpuError: RhiError | Error | undefined;\n if (webgpuOutcome.kind === 'rhi-err') {\n webgpuError = webgpuOutcome.error;\n } else if (webgpuOutcome.kind === 'throw') {\n webgpuError = webgpuOutcome.error;\n }\n\n // Channel 2 to Channel 3 fallback (bug-20260526):\n // `navigator.gpu` present does not guarantee adapter availability;\n // `requestAdapter()` may return null in headless Chrome, remote\n // servers, or iframe sandboxes. When Channel 2 fails AND the pack was\n // NOT from the escape-hatch (`options.rhi`), dynamically import\n // `@forgeax/engine-rhi-wgpu` and retry renderer creation.\n const isEscapeHatch = options?.rhi !== undefined && options?.rhi !== null;\n if (!isEscapeHatch) {\n try {\n const mod = (await import('@forgeax/engine-rhi-wgpu')) as Record<string, unknown>;\n const ensureReady = mod.ensureReady as () => Promise<unknown>;\n await ensureReady();\n const wgpuPack = loadRhiPack(mod);\n const wgpuOutcome = await tryCreateWebGPURenderer(\n canvas as HTMLCanvasElement | OffscreenCanvas,\n options,\n wgpuPack,\n bundler,\n ).catch((e: unknown) => {\n return { kind: 'throw' as const, error: toError(e) };\n });\n if (wgpuOutcome.kind === 'ok') {\n return wgpuOutcome.renderer;\n }\n // Channel 3 also failed — compound error with both failure details.\n let wgpuError: RhiError | Error | undefined;\n if (wgpuOutcome.kind === 'rhi-err') {\n wgpuError = wgpuOutcome.error;\n } else if (wgpuOutcome.kind === 'throw') {\n wgpuError = wgpuOutcome.error;\n }\n // bug-20260610: when both channels fail with environmental codes\n // (adapter-unavailable / rhi-not-available), append browser-config guidance\n // so AI users do not chase non-existent GPU bugs (Edge with WebGPU flag\n // disabled is the canonical case — see composeEnvErrorHint JSDoc).\n const envHint = composeEnvErrorHint(webgpuError, wgpuError);\n const baseReason = classifyEnvErrorReason(\n 'no usable rendering backend',\n webgpuError ?? wgpuError,\n );\n throw new EngineEnvironmentError(\n envHint !== undefined ? `${baseReason}; ${envHint}` : baseReason,\n {\n ...(webgpuError !== undefined ? { webgpuError } : {}),\n ...(wgpuError !== undefined ? { wgpuError } : {}),\n },\n );\n } catch (channel3Error) {\n // Channel 3 dynamic import / ensureReady threw — compound error.\n if (channel3Error instanceof EngineEnvironmentError) {\n throw channel3Error;\n }\n const wgpuError =\n channel3Error instanceof Error ? channel3Error : new Error(String(channel3Error));\n const envHint = composeEnvErrorHint(webgpuError, wgpuError);\n const baseReason = classifyEnvErrorReason(\n 'no usable rendering backend (Channel 3 fallback failed)',\n webgpuError ?? wgpuError,\n );\n throw new EngineEnvironmentError(\n envHint !== undefined ? `${baseReason}; ${envHint}` : baseReason,\n {\n ...(webgpuError !== undefined ? { webgpuError } : {}),\n wgpuError,\n },\n );\n }\n }\n\n throw new EngineEnvironmentError(\n classifyEnvErrorReason('no usable rendering backend', webgpuError),\n {\n ...(webgpuError !== undefined ? { webgpuError } : {}),\n },\n );\n}\n\n// ─── WebGPU branch ──────────────────────────────────────────────────────────\n\n/**\n * Wire the spec `device.lost` Promise into the lost / error / health channels\n * (research §F-4 / R2). A genuine device loss fans out through `errorRegistry`\n * so `renderer.onError(err => switch err.code { 'device-lost' })` triggers, and\n * through `healthRegistry` so `health().reason` flips to `'device-lost'`\n * (feat-20260622-s5 M1/M2). Explicit renderer teardown is observable through\n * `onLost`, but is not a runtime error and must not manufacture an RhiError.\n *\n * Extracted to a single helper (SSOT) so the createRenderer assembly path AND\n * the recover() rebuild path attach byte-identical fan-out to whichever device\n * is current — recover() mints a fresh device whose own `lost` Promise must be\n * re-wired to the SAME registries the host already subscribed to.\n */\nfunction attachDeviceLostFanout(\n device: RhiDevice,\n pack: RhiBackendPack,\n registries: {\n lostRegistry: LostListenerRegistry;\n errorRegistry: RhiErrorListenerRegistry;\n healthRegistry: HealthListenerRegistry;\n onDeviceLost?: (detail: string) => void;\n },\n): () => void {\n const { lostRegistry, errorRegistry, healthRegistry, onDeviceLost } = registries;\n let active = true;\n device.lost\n .then((info) => {\n if (!active) return;\n const safe = {\n reason: info?.reason ?? 'unknown',\n message: info?.message ?? '',\n };\n onDeviceLost?.(`device.lost: ${safe.reason}; ${safe.message || '<empty>'}`);\n pack.instrumentation?.onDeviceLost?.();\n lostRegistry.fire(safe);\n // Health channel fan-out: safe.reason is 'unknown' | 'destroyed' per\n // RhiDevice.lost return type, matching HealthDetailDeviceLost.lostReason\n // with no narrowing cast needed (plan-decisions D-6 / OOS-1).\n //\n // requirements A constraint (W3C spec assumption): `reason ===\n // 'destroyed'` is INTENTIONAL teardown (host/driver called\n // device.destroy() -- e.g. renderer.dispose(), browser tab recycle,\n // or test-isolation device pooling), NOT a recoverable fault. It must\n // NOT flip health to 'device-lost' (which would make draw() refuse via\n // the M2 guard and invite a spurious recover()). The lost channel still\n // fires so AI users observe the teardown; the health and error channels\n // are gated because this is an expected lifecycle event, not a renderer\n // failure. Genuine unrecoverable loss surfaces as reason 'unknown'.\n if (safe.reason !== 'destroyed') {\n healthRegistry.fire({\n reason: 'device-lost',\n detail: { lostReason: safe.reason, message: safe.message },\n recoverable: true,\n });\n // Translate only genuine device loss to RhiError. When the backend\n // translator is unavailable (e.g. an explicit escape-hatch instance),\n // build a minimal error so the real lost path remains fail-loud.\n if (pack.translateErrorEventToRhiError) {\n const translated = pack.translateErrorEventToRhiError(safe);\n errorRegistry.fire(translated.error);\n } else {\n errorRegistry.fire(\n new RhiError({\n code: 'device-lost',\n expected:\n 'device must remain alive (driver / browser must not destroy the GPUDevice)',\n hint: `device-lost reason: ${safe.reason}; message: ${safe.message || '<empty>'}`,\n }),\n );\n }\n }\n })\n .catch((err: unknown) => {\n if (!active) return;\n onDeviceLost?.(`device.lost rejected: ${String(err)}`);\n pack.instrumentation?.onDeviceLost?.();\n lostRegistry.fire({ reason: 'unknown', message: String(err) });\n healthRegistry.fire({\n reason: 'device-lost',\n detail: { lostReason: 'unknown', message: String(err) },\n recoverable: true,\n });\n errorRegistry.fire(\n new RhiError({\n code: 'device-lost',\n expected: 'device.lost Promise resolves with GPUDeviceLostInfo',\n hint: `device.lost Promise rejected unexpectedly: ${String(err)}`,\n }),\n );\n });\n return () => {\n active = false;\n };\n}\n\nfunction attachDeviceUncapturedErrorFanout(\n device: RhiDevice,\n pack: RhiBackendPack,\n errorRegistry: RhiErrorListenerRegistry,\n): () => void {\n const translate = pack.translateErrorEventToRhiError;\n const _internal_getRawDevice = pack._internal_getRawDevice;\n if (translate === undefined || _internal_getRawDevice === undefined) return () => undefined;\n const rawDevice = _internal_getRawDevice(device);\n if (rawDevice === undefined || rawDevice === null || typeof rawDevice !== 'object') {\n return () => undefined;\n }\n const target = rawDevice as {\n onuncapturederror?: ((event: unknown) => void) | null;\n };\n let active = true;\n const handler = (event: unknown): void => {\n if (!active) return;\n const translated = translate(event);\n if (!translated.ok) errorRegistry.fire(translated.error);\n };\n target.onuncapturederror = handler;\n return () => {\n active = false;\n if (target.onuncapturederror === handler) target.onuncapturederror = null;\n };\n}\n\n/**\n * tryCreateWebGPURenderer returns three kinds of outcome (fix-f1 / w16):\n * - `ok` → Renderer created successfully\n * - `rhi-err` → RHI Result.err path (preserves the original RhiError\n * for AI consumers to read; now includes context acquisition\n * failures via pack.rhi.acquireCanvasContext)\n * - `throw` → exception path (caught and wrapped by the caller as\n * an Error)\n */\ntype WebGPUOutcome =\n | { kind: 'ok'; renderer: Renderer }\n | { kind: 'rhi-err'; error: RhiError }\n | { kind: 'throw'; error: Error };\n\n// Optional compression is exposed on a device only when it is requested from\n// the adapter. Keep this capability projection shared by initial construction\n// and device-loss recovery; otherwise recovery silently drops BC/ETC2/ASTC\n// and already-catalogued compressed textures fail on the first new frame.\nconst COMPRESSION_FEATURES: GPUFeatureName[] = [\n 'texture-compression-bc',\n 'texture-compression-etc2',\n 'texture-compression-astc',\n];\n\nfunction deviceOptionsForAdapter(\n adapter: Pick<RhiAdapter, 'features'>,\n membershipTiming?: RendererOptions['membershipTiming'],\n): { requiredFeatures: GPUFeatureName[] } | undefined {\n const requiredFeatures = COMPRESSION_FEATURES.filter((feature) => adapter.features.has(feature));\n if (membershipTiming?.mode === 'gpu' && adapter.features.has('timestamp-query')) {\n requiredFeatures.push('timestamp-query');\n }\n return requiredFeatures.length > 0 ? { requiredFeatures } : undefined;\n}\n\n/**\n * Goes through the strict two-step path injected by `@forgeax/engine-rhi-webgpu`:\n * `rhi.requestAdapter()` -> `adapter.requestDevice()`\n * (M6 fix-up [w51] retires the legacy single-step factory per plan-strategy\n * §6 M3 break-point #2 + AGENTS.md break-point list 2026-05-10 #2). Returns\n * `Result<RhiAdapter, RhiError>` then `Result<RhiDevice, RhiError>`; any\n * failure / failure to acquire the canvas WebGPU context returns a\n * structured outcome so the caller can decide on fallback and error-\n * preservation strategy (plan-strategy §7.3).\n *\n * fix-f1: on either Result.err path the original `RhiError` is preserved\n * via the `rhi-err` outcome — when fallback also fails, AI consumers read\n * it via `EngineEnvironmentError.detail.webgpuError.code`.\n *\n * w19 / M4: context acquisition goes through `pack.rhi.acquireCanvasContext(canvas)`\n * — a polymorphic entry that routes to canvas.getContext('webgpu') in\n * rhi-webgpu (Channel 2) or wasm createSurface in rhi-wgpu (Channel 3).\n * The backend pack is selected BEFORE this call (in `loadBackendPack` /\n * the Channel 2→3 fallback in `createRenderer`), so the canvas context\n * is never type-locked by a wrong backend's acquisition attempt.\n */\nasync function tryCreateWebGPURenderer(\n canvas: HTMLCanvasElement | OffscreenCanvas,\n options: RendererOptions | undefined,\n pack: RhiBackendPack,\n // feat-20260608 M2 / D-3: BundlerOptions threaded verbatim. Carries\n // shaderManifestUrl (consumed in getShader fallback ~30 lines below) and\n // importTransport (forwarded to the AssetRegistry third ctor slot;\n // undefined keeps the shipped form, AC-08).\n bundler: BundlerOptions | undefined,\n): Promise<WebGPUOutcome> {\n const importTransport = bundler?.importTransport;\n // M6 fix-up [w51]: spec-aligned two-step path. Step 1 - requestAdapter()\n // surfaces adapter.features / adapter.limits (capability pre-screen,\n // charter proposition 4 forward-reachable). Step 2 - adapter.requestDevice()\n // requests the actual device. M3 D-P4: `pack.rhi` is the auto-selected\n // backend singleton (rhi-webgpu / rhi-wgpu / explicit escape hatch).\n // w19: thread canvas as compatibleSurface so the wgpu GL backend can\n // enumerate adapters against it (escape hatch, capability-gated).\n const adapterResult = await pack.rhi.requestAdapter(undefined, canvas);\n if (!adapterResult.ok) {\n return { kind: 'rhi-err', error: adapterResult.error };\n }\n const adapter = adapterResult.value;\n // M4 w28: filter compression features from adapter.features (AC-07). The\n // same helper is used by recover() below so both paths share one profile.\n const deviceOpts = deviceOptionsForAdapter(adapter, options?.membershipTiming);\n const result = await adapter.requestDevice(deviceOpts);\n if (!result.ok) {\n return { kind: 'rhi-err', error: result.error };\n }\n const device: RhiDevice = result.value;\n\n // Acquire the canvas context through the backend pack (M3 / w16).\n // rhi-webgpu: internally calls canvas.getContext('webgpu') + branded wrap.\n // rhi-wgpu: internally calls wasm createSurface(canvas) + configure.\n // When context acquisition fails (null from canvas.getContext or wasm\n // createSurface throws), the pack returns Result.err(RhiError).\n const ctxResult = pack.rhi.acquireCanvasContext(canvas);\n if (!ctxResult.ok) {\n return { kind: 'rhi-err', error: ctxResult.error };\n }\n const context: RhiCanvasContext = ctxResult.value;\n\n const lostRegistry = new LostListenerRegistry();\n const errorRegistry = new RhiErrorListenerRegistry();\n const healthRegistry = new HealthListenerRegistry();\n const membershipTiming =\n options?.membershipTiming === undefined\n ? undefined\n : createMembershipTiming(device, options.membershipTiming);\n // D-S1 single-point exemption threading: forward rawDevice from\n // RendererOptions into internals so webgpu-backend.ts can use the\n // GPUCanvasContext.configure({device}) path. Accepts either a direct\n // value or a thunk - the thunk form lets callers wrap the\n // rhi.requestAdapter -> adapter.requestDevice two-step (so the raw\n // device is captured during this function's awaits above) and still get\n // the captured value at draw time. Evaluated lazily here, after both\n // requestAdapter and requestDevice have settled.\n const rawDeviceCandidate = options?.rawDeviceForContextConfigure;\n const rawDevice =\n typeof rawDeviceCandidate === 'function'\n ? (rawDeviceCandidate as () => unknown | undefined)()\n : rawDeviceCandidate;\n return {\n kind: 'ok',\n renderer: await makeWebGPURenderer({\n canvas,\n device,\n context,\n options,\n bundler,\n lostRegistry,\n errorRegistry,\n healthRegistry,\n ...(membershipTiming === undefined ? {} : { membershipTiming }),\n pack,\n importTransport,\n ...(rawDevice !== undefined ? { rawDevice } : {}),\n }),\n };\n}\n\ninterface WebGPURendererInternals {\n canvas: HTMLCanvasElement | OffscreenCanvas;\n device: RhiDevice;\n // M6 / w41 (feat-20260510-rhi-resource-creation): forgeax RhiCanvasContext\n // brand; RenderSystem + ensureContextConfigured both go through the RHI\n // surface (charter proposition 5 consistent abstraction red line).\n context: RhiCanvasContext;\n options: RendererOptions | undefined;\n /**\n * feat-20260608-create-app-param-surface-trim / M2 / D-3: BundlerOptions\n * forwarded verbatim from createRenderer's third arg. Carries\n * shaderManifestUrl (host-injected vite-plugin-shader emit URL; absent =>\n * createRenderer falls back to '/shaders/manifest.json') and the\n * importTransport that previously rode a dedicated internal slot.\n */\n bundler: BundlerOptions | undefined;\n lostRegistry: LostListenerRegistry;\n errorRegistry: RhiErrorListenerRegistry;\n healthRegistry: HealthListenerRegistry;\n membershipTiming?: MembershipTimingController;\n /** M3 D-P4 auto-select pack — carries the dynamic-imported rhi-webgpu / rhi-wgpu singleton + optional async shader factory. */\n pack: RhiBackendPack;\n /**\n * Legacy D-S1 single-point exemption channel (feat-20260508-rhi-surface-completion\n * / w9). After M6 the canvas-context configure path goes through\n * `RhiCanvasContext.configure({ device: RhiDevice, ... })` (the shim\n * resolves to the underlying raw GPUDevice via RAW_DEVICE_MAP), so this\n * field is retained only for backwards compatibility with callers that\n * still pass `RendererOptions.rawDeviceForContextConfigure` (now\n * effectively a no-op on the RHI path).\n */\n rawDevice?: unknown;\n /**\n * feat-20260604-hdr-equirect-cube-importer-loader M4 / w16 (D-3): the\n * dev-only ImportTransport, forwarded verbatim from createRenderer to the\n * AssetRegistry third ctor slot. `undefined` keeps the shipped form (DDC\n * miss fails fast with `asset-not-imported`, AC-08).\n */\n importTransport?: ImportTransport | undefined;\n /**\n * feat-20260608-mesh-ssbo-dynamic-grow-l1-lift-1024-entity-cap M2 / T-M2-05:\n * mesh-SSBO grow hook surfaced by `makeWebGPURenderer` after the controller\n * is constructed. Undefined before `makeWebGPURenderer` runs; populated by\n * the time the renderer is returned to the caller. M3's record stage reads\n * this field via the runtime path that bridges into render-system-record.ts\n * (the bridging plumbing is in M3's targetFiles).\n *\n * Returns `{ ok: true }` when the grow completed (or short-circuited\n * idempotently); `{ ok: false, code }` with a fired structured error\n * (`MeshSsboCeilingReachedError` or `MeshSsboCapacityExceededError`) when\n * the request cannot be satisfied. Never throws (D-5).\n */\n growMeshSsbo?: (neededSlots: number) => MeshSsboGrowResult;\n /**\n * feat-20260608-mesh-ssbo-dynamic-grow-l1-lift-1024-entity-cap M3 / T-M3-04:\n * read-only handle to the grow controller's state (slotCount + wrapper\n * refs), surfaced alongside `growMeshSsbo` so `ensureMeshSsboCapacity`\n * (record-stage wiring) can short-circuit when slotCount already covers the\n * frame's renderable count and so the dev-mode info log can report the\n * before/after slot count transition. Undefined until buildReadyWebGPU\n * has wired the controller; identity stable across grow events.\n */\n meshSsboState?: MeshSsboState;\n /** Host-owned producer features; created before device-bound assembly starts. */\n featureHost?: RenderFeatureHost;\n}\n\nasync function makeWebGPURenderer(internals: WebGPURendererInternals): Promise<Renderer> {\n let disposed = false;\n const membershipTiming =\n internals.membershipTiming ??\n (internals.options?.membershipTiming === undefined\n ? undefined\n : createMembershipTiming(internals.device, internals.options.membershipTiming));\n // device.lost dual-track (research §F-4 / R2 countermeasure): keep the\n // detach fence in the same closure as dispose() and recover() so a stale\n // Promise from a replaced device cannot mutate current renderer health.\n let detachDeviceLostFanout = attachDeviceLostFanout(internals.device, internals.pack, {\n lostRegistry: internals.lostRegistry,\n errorRegistry: internals.errorRegistry,\n healthRegistry: internals.healthRegistry,\n onDeviceLost: (detail) => membershipTiming?.markDeviceLost(detail),\n });\n let detachDeviceUncapturedErrorFanout = attachDeviceUncapturedErrorFanout(\n internals.device,\n internals.pack,\n internals.errorRegistry,\n );\n const featureHostResult = createRenderFeatureHost(internals.options?.features ?? []);\n if (!featureHostResult.ok) throw featureHostResult.error;\n internals.featureHost = featureHostResult.value;\n let recoverInFlight: Promise<Result<void, RecoverError>> | undefined;\n // Keep producer-declared shader identities live across the renderer\n // lifetime. Features can be installed after boot (the public late-install\n // seam used by asset-driven hosts), so a recovery rebuild must include their\n // modules in the same prewarm set as boot. A boot-only snapshot would let the\n // first recovered frame observe a cold async shader adapter and emit a\n // spurious prepared-pipeline failure before the next-frame retry succeeds.\n const requiredMaterialShaderSet = new Set(\n featureHostResult.value.features.flatMap((feature) => feature.requiredMaterialShaders ?? []),\n );\n let requiredMaterialShaders = Object.freeze([...requiredMaterialShaderSet]);\n // Lazy ShaderRegistry instance (plan-strategy section S-10 / D-R10 / OQ-5\n // close): constructed on first access; subsequent accesses return the\n // same instance.\n let shaderInstance: ShaderRegistry | null = null;\n // feat-20260523-shader-template-instance-split M9-T03 (D-PipelineBuilder):\n // the ShaderRegistryDevice adapter is created once and shared between the\n // ShaderRegistry instance (manifest hash -> ShaderModule) AND the M9\n // per-MaterialShader pipeline cache (materialShaderId -> RenderPipeline).\n // Sharing the adapter reuses the underlying async module-compile cache\n // (moduleCache + errorCache + pending Set inside makeShaderDeviceAdapter),\n // so a user shader registered at app boot incurs exactly one async\n // compile across both paths (charter P4 consistent abstraction +\n // architecture-principles #6 idempotency).\n let sharedShaderModuleAdapter: ShaderDeviceAdapterInternal | null = null;\n const getShaderModuleAdapter = (): ShaderDeviceAdapterInternal => {\n if (sharedShaderModuleAdapter === null) {\n sharedShaderModuleAdapter = makeShaderDeviceAdapter(\n internals.device,\n internals.errorRegistry,\n internals.pack.createShaderModule,\n );\n }\n return sharedShaderModuleAdapter;\n };\n const getShader = (): ShaderRegistry => {\n if (shaderInstance === null) {\n // feat-20260608-create-app-param-surface-trim / M2 / D-2 q5-A:\n // shaderManifestUrl moved to BundlerOptions (third arg). The fallback\n // literal '/shaders/manifest.json' stays here so the LO 1.1\n // hello-window zero-config takeoff path keeps working without any\n // bundler injection. The 'shaderManifestUrl' in (...) check preserves\n // the zero-entry opt-in: explicitly passing\n // `bundler: { shaderManifestUrl: undefined }` retains the\n // old \"no manifest fetched\" mode used by tests / camera-only worlds.\n const bundler = internals.bundler;\n const explicitUrl = bundler?.shaderManifestUrl;\n shaderInstance = new ShaderRegistry({\n device: getShaderModuleAdapter(),\n manifestUrl:\n bundler !== undefined && 'shaderManifestUrl' in bundler\n ? explicitUrl\n : '/shaders/manifest.json',\n });\n }\n return shaderInstance;\n };\n // The render asset port carries catalogued payload dependencies. MeshFilter\n // payloads stay World-local and become GPU-resident on first record access.\n //\n // The ShaderRegistryDevice adapter (shared between the registry and the\n // per-MaterialShader pipeline cache) is already available at this point.\n const shaderRegistry = getShader();\n\n // feat-20260528-material-shader-registration-unification M3 / w14:\n // placeholder hardcoded installMaterialArtifact calls deleted.\n //\n // bug-20260601-hello-tonemap-material-register M1 (plan-strategy D-1):\n // All material-shader entries are now registered from the manifest\n // BEFORE the renderer is returned, so `register<MaterialAsset>` referencing\n // an engine shader succeeds without waiting for `renderer.ready`.\n\n // The App assembles the single AssetRegistry and passes its resolver through\n // the renderer bundler seam. Render owns only this device-neutral projection;\n // scene-instantiation hooks are installed by renderComponentsPlugin so the\n // App/World plugin graph and renderer stay on one lifecycle.\n const assets = createRenderAssetPort(shaderRegistry, internals.bundler?.assetResolver);\n // feat-20260601-gpu-resource-store-extraction M1: the GPU residency layer\n // lives in a standalone store; `assets` keeps the CPU POD registry only.\n const gpuStore = new GpuResourceStore();\n // feat-20260623-world-space-video-asset M4 / w16 (D-3): transient per-frame\n // video texture store, fully independent of gpuStore (AC-08). Configured with\n // the device alongside gpuStore below; threaded into the record stage via the\n // RenderSystemRuntime so a `videoTextureFields` material field uploads its\n // frame here instead of entering the static ensureResident cache.\n const dynamicTextureStore = new DynamicTextureStore();\n // feat-20260527-sprite-nineslice M4 / w16 (D-5): per-Renderer EngineMetrics\n // counter. Surfaced through `renderer.metrics` and threaded to the record\n // stage via `RenderSystemRuntime.metrics` so soft-warns\n // (`nineslice.scale-too-small`, `nineslice.tile-needs-repeat-sampler`) bump\n // counters AI users read with `renderer.metrics.snapshot()` (charter P3\n // machine-readable signals over a per-frame console.warn flood). Each\n // Renderer instance owns its own counter Map (D-5 candidate 1 isolation).\n const metrics = createEngineMetrics();\n const paramSchemaProjectionCensus = createParamSchemaProjectionCensus(\n metrics,\n internals.options?.debugShadowObservation === true,\n );\n // feat-20260629 M4: per-material-shader UV set count from naga vertex\n // @location reflection. Populated during prepareMaterialShaders from\n // MaterialShaderManifestEntry.uvSetCount. Read by getMaterialShaderPipeline\n // to auto-fill shaderUvSetCount for clamp-to-last alias.\n const materialShaderUvSetCounts = new Map<string, number>();\n // feat-20260527-sprite-nineslice M4 / w18 prep (D-9): the same\n // EngineMetrics instance is threaded through RenderSystem so render-owned\n // soft-warns (sliceMode=1 + sampler.addressMode !== 'repeat') remain visible\n // on the public renderer metrics surface.\n // feat-20260707 M5 / w33 (D-11 + D-8): RhiCaps remain a Render DeviceScope\n // concern. The asset registry receives no device or transcode capability;\n // render residency owns any future device-specific compression target.\n\n // M1 (bug-20260601-hello-tonemap-material-register D-1/D-2): prepare\n // engine-shipped material shaders (cap gate + manifest load + registration)\n // so they are available in ShaderRegistry before `register<MaterialAsset>`.\n // Failures throw structured RhiError / ShaderError through `createRenderer`.\n await prepareMaterialShaders(internals.device, getShader, materialShaderUvSetCounts);\n // MaterialAsset per-slot texCoord: the built-in standard PBR + skin shaders\n // unconditionally declare all eight supported UV sets so they can honor\n // per-slot coordinate selection. Their vertex layout must therefore always\n // carry the declared UV slots or CreateRenderPipeline rejects the module.\n // in VertexState\"). `materialShaderUvSetCounts` is the SSOT both PSO paths read\n // (buildPipelineContext + getMaterialShaderPipeline) to drive the clamp-to-last\n // alias; naga reflection can be stale for engine-shipped modules, so the\n // count is asserted explicitly. Missing mesh sets are clamp-to-last aliases.\n materialShaderUvSetCounts.set('forgeax::default-standard-pbr', 8);\n materialShaderUvSetCounts.set(SKIN_MATERIAL_SHADER_ID, 8);\n // M5 wiring (feat-20260517-vite-plugin-image-build-time-cook w14b): configure\n // the Render-owned GPU residency store so the record path can materialise\n // loaded device-neutral payloads. The AssetRegistry remains CPU-only.\n // bug-20260518 D-1: configureGpuDevice gains a 2nd parameter --\n // `pack.createShaderModule`, the top-level async shader-module factory\n // (rhi-webgpu / rhi-wgpu both expose it). The runtime mipmap utility uses\n // this factory inside `generateMipmaps` instead of the (now-deleted)\n // synchronous `device.createShaderModule` member. The parameter is\n // structurally optional at this call-site so the explicit-rhi escape\n // hatch (D-R5) without a top-level factory still routes through the\n // existing `invokeDeviceCreateShaderModule` fallback in\n // buildReadyWebGPU; the store's mipmap branch surfaces the missing-factory\n // case as a structured `rhi-not-available` error\n // (charter P3 explicit failure) rather than throwing here.\n //\n // The factory's pack signature accepts a fully-typed `RhiDevice`, while\n // `MipmapShaderModuleFactory` declares its `device` parameter as the\n // narrower `MipmapDevice` subset. At runtime the value handed in IS a\n // real `RhiDevice` (same `internals.device` cast on the line below), so\n // the structural cast is sound; TS rejects only because function-param\n // contravariance is strict. No new cast lands on `internals.device`.\n const packShaderFactory = internals.pack.createShaderModule;\n // The RhiDevice surface satisfies `MipmapBlitDevice` (createTexture +\n // createTextureView + createCommandEncoder + createBindGroup +\n // queue.submit + queue.writeTexture all live on RhiDevice).\n // feat-20260601-gpu-resource-store-extraction M1 (D-3 / D-8): device +\n // shader-module factory + cube-POD register relay are wired onto the store\n // together. feat-20260614 M8 (D-15 / D-17): `registerCube` is the wire-layer\n // closure `(world, pod) => world.allocSharedRef('EquirectAsset', pod)` --\n // the runtime-minted cube POD lands in the draw-time world's\n // SharedRefStore (the AssetRegistry owns no handles). feat-20260630 M2 / w11:\n // the retired cube-texture asset kind is gone; the relay mints an EquirectAsset\n // shared ref as the cubemap GPU residency's identity token.\n gpuStore.configureGpuDevice(\n // biome-ignore lint/suspicious/noExplicitAny: MipmapBlitDevice descriptors are typed `any`; RhiDevice satisfies the shape\n internals.device as any,\n packShaderFactory as unknown as MipmapShaderModuleFactory | undefined,\n (world, pod) => {\n const handle = world.allocSharedRef('EquirectAsset', pod);\n return ok(handle);\n },\n internals.device.caps,\n );\n // feat-20260623-world-space-video-asset M4 / w16 (D-3): wire the same device\n // into the transient video texture store (createTexture / createTextureView /\n // destroyTexture / queue.copyExternalImageToTexture all live on RhiDevice).\n dynamicTextureStore.configureGpuDevice(\n // biome-ignore lint/suspicious/noExplicitAny: DynamicTextureDevice is a structural subset of RhiDevice\n internals.device as any,\n );\n // D-S3: Renderer.ready three-step strict-serial Promise. Kicked off\n // synchronously here so `await renderer.ready` is the AI-user-facing\n // barrier; failure is structured and goes through Promise reject (no\n // throw, no silent skip — charter proposition 4 explicit failure).\n let pipelineState: PipelineState | null = null;\n let readySettled = false;\n // w24 — Renderer.ready returns Promise<Result<void, RhiError>>: resolve\n // ok(undefined) on success / resolve err(RhiError) on failure. The legacy\n // reject path is converted by a `.then() / .catch()` wrap so the inner\n // factory (`buildReadyWebGPU`) keeps its reject-on-error shape (research\n // F-3 internal contract preserved) while the public surface settles\n // strictly resolve-only (charter proposition 4 explicit failure - AI\n // users branch on `.ok` instead of try/catch).\n // feat-20260523-shader-template-instance-split M9-T03 (D-PipelineBuilder):\n // per-MaterialShader pipeline cache (LDR + HDR variants keyed by\n // `${materialShaderId}:${ldr|hdr}`). Map is owned by the renderer (lifetime\n // = Renderer) so cache hits persist across draw calls but reset between\n // renderers. Map.get / .set are sync; the underlying shader-module compile\n // is async-cached inside `makeShaderDeviceAdapter` (1-frame warmup -- first\n // miss returns Result.err('rhi-not-available'); after the async build\n // resolves the adapter caches the module, the next miss-then-build returns\n // Ok and lands in this Map).\n //\n // M6 fix-up: declared BEFORE `buildReadyWebGPU` so the boot-time SPEC_CONST\n // prewarm step inside that promise can seed URP-variant entries directly\n // (the seeding closure captures this Map by reference; ordering is safe\n // because the prewarm step runs strictly before the first frame's\n // `getMaterialShaderPipeline` lookup that would consume it).\n const materialShaderPipelineCache = new Map<string, RenderPipeline>();\n const materialShaderManifestEntryCache = new Map<string, MaterialShaderManifestEntry>();\n const reportedMissingMaterialShaders = new Set<string>();\n // Variant resolution only depends on the requested axes, device capability\n // axes, and the manifest entry that owns the declarations. Cache it by the\n // manifest's variants-array identity so hot replacement naturally gets a\n // fresh result without adding a global strong reference to shader metadata.\n const materialShaderVariantResolutionCache = new WeakMap<\n object,\n Map<string, string | undefined>\n >();\n let group0MaterialLayout: {\n materialBgl: BindGroupLayout;\n pipelineLayout: PipelineLayout;\n } | null = null;\n let viewOnlyMaterialPipelineLayout: PipelineLayout | null = null;\n const viewWithResourceLayouts = new Map<\n string,\n { materialBgl: BindGroupLayout; pipelineLayout: PipelineLayout }\n >();\n const group0ResourceLayouts = new Map<\n string,\n { materialBgl: BindGroupLayout; pipelineLayout: PipelineLayout }\n >();\n const preparedMaterialPipelineLayoutCache = new Map<string, PipelineLayout>();\n // feat-20260621-learn-render-5-5-parallax M2 / w6 (D-1): per-shader material\n // BGL + pipeline layout cache. A custom material shader declaring >3\n // user-region textures (e.g. parallax `heightTexture`) needs a material BGL\n // whose user-region + injection start differ from the shared built-in\n // derived shared layout, plus a pipeline layout [view, perShaderMaterialBgl,\n // meshArray, instances] that the PSO builds against. Built lazily on first\n // request and cached by shaderId; 4-or-fewer-texture shaders never enter the cache\n // (they reuse the shared layout, byte-for-byte the built-in shape — D-2).\n type PerShaderMaterialLayout = {\n materialBgl: BindGroupLayout;\n pipelineLayout: PipelineLayout;\n };\n type PerShaderMaterialLayoutCacheEntry = {\n readonly source: string;\n readonly paramSchema: readonly ParamSchemaEntry[];\n readonly layout: PerShaderMaterialLayout | null;\n };\n const perShaderMaterialLayoutCache = new Map<string, PerShaderMaterialLayoutCacheEntry>();\n let bootMaterialLayoutInputs: {\n readonly viewBgl: BindGroupLayout;\n readonly meshArrayBgl: BindGroupLayout;\n readonly instancesBgl: BindGroupLayout;\n } | null = null;\n // Material binding contracts are derived from WGSL source, but the lookup\n // is also used by the per-submesh bind-group path. Cache the derived value\n // per renderer so a frame does not re-run the comment stripping and regex\n // scan for every visible submesh. Keep the source alongside the result so\n // shader hot-replacement invalidates the entry naturally.\n const materialShaderBindingContractCache = new Map<\n string,\n { source: string; contract: MaterialShaderBindingContract }\n >();\n const getCachedMaterialShaderBindingContract = (\n materialShaderId: string,\n ): MaterialShaderBindingContract => {\n const lookup = getShader().findMaterialArtifact(materialShaderId);\n if (!lookup.ok) return 'render-material';\n const cached = materialShaderBindingContractCache.get(materialShaderId);\n if (cached?.source === lookup.value.source) return cached.contract;\n const contract = resolveMaterialShaderBindingContract(lookup.value.source);\n materialShaderBindingContractCache.set(materialShaderId, {\n source: lookup.value.source,\n contract,\n });\n return contract;\n };\n const getMaterialLayoutInputs = (): {\n readonly viewBgl: BindGroupLayout;\n readonly meshArrayBgl: BindGroupLayout;\n readonly instancesBgl: BindGroupLayout;\n } | null => {\n if (pipelineState !== null) {\n return {\n viewBgl: pipelineState.viewBindGroupLayout,\n meshArrayBgl: pipelineState.meshBindGroupLayout,\n instancesBgl: pipelineState.instancesBindGroupLayout,\n };\n }\n return bootMaterialLayoutInputs;\n };\n const getOrBuildGroup0MaterialLayout = (): {\n materialBgl: BindGroupLayout;\n pipelineLayout: PipelineLayout;\n } | null => {\n if (group0MaterialLayout !== null) return group0MaterialLayout;\n const layoutInputs = getMaterialLayoutInputs();\n if (layoutInputs === null) return null;\n const bglRes = internals.device.createBindGroupLayout({ entries: [] });\n if (!bglRes.ok) {\n internals.errorRegistry.fire(bglRes.error);\n return null;\n }\n const plRes = internals.device.createPipelineLayout({\n label: 'material-group-0-pipeline-layout',\n bindGroupLayouts: [bglRes.value],\n });\n if (!plRes.ok) {\n internals.errorRegistry.fire(plRes.error);\n return null;\n }\n group0MaterialLayout = { materialBgl: bglRes.value, pipelineLayout: plRes.value };\n return group0MaterialLayout;\n };\n const getOrBuildViewOnlyMaterialPipelineLayout = (): PipelineLayout | null => {\n if (viewOnlyMaterialPipelineLayout !== null) return viewOnlyMaterialPipelineLayout;\n if (pipelineState === null) return null;\n const plRes = internals.device.createPipelineLayout({\n label: 'material-view-only-pipeline-layout',\n bindGroupLayouts: [pipelineState.viewBindGroupLayout],\n });\n if (!plRes.ok) {\n internals.errorRegistry.fire(plRes.error);\n return null;\n }\n viewOnlyMaterialPipelineLayout = plRes.value;\n return viewOnlyMaterialPipelineLayout;\n };\n const getOrBuildGroup0ResourceLayout = (\n materialShaderId: string,\n ): { materialBgl: BindGroupLayout; pipelineLayout: PipelineLayout } | null => {\n const cached = group0ResourceLayouts.get(materialShaderId);\n if (cached !== undefined) return cached;\n const lookup = getShader().findMaterialArtifact(materialShaderId);\n if (\n !lookup.ok ||\n !/@group\\s*\\(\\s*0\\s*\\)\\s*@binding\\s*\\(\\s*0\\s*\\)[^;]*texture_depth_2d/u.test(\n lookup.value.source,\n )\n ) {\n return null;\n }\n const bgl = internals.device.createBindGroupLayout({\n label: `material-group-0-resource-${materialShaderId}`,\n entries: [\n {\n binding: 0,\n visibility: 2,\n texture: { sampleType: 'depth', viewDimension: '2d', multisampled: false },\n },\n ],\n });\n if (!bgl.ok) return null;\n const pipelineLayout = internals.device.createPipelineLayout({\n label: `material-group-0-resource-pl-${materialShaderId}`,\n bindGroupLayouts: [bgl.value],\n });\n if (!pipelineLayout.ok) return null;\n const built = { materialBgl: bgl.value, pipelineLayout: pipelineLayout.value };\n group0ResourceLayouts.set(materialShaderId, built);\n return built;\n };\n const getOrBuildViewWithResourceLayout = (\n materialShaderId: string,\n ): { materialBgl: BindGroupLayout; pipelineLayout: PipelineLayout } | null => {\n const cached = viewWithResourceLayouts.get(materialShaderId);\n if (cached !== undefined) return cached;\n const lookup = getShader().findMaterialArtifact(materialShaderId);\n if (\n !lookup.ok ||\n !/@group\\s*\\(\\s*0\\s*\\)\\s*@binding\\s*\\(\\s*0\\s*\\)\\s*var\\s*<\\s*uniform\\s*>\\s*view(?:X_naga_oil_mod_[A-Z0-9]+)?\\b/u.test(\n lookup.value.source,\n ) ||\n !/@group\\s*\\(\\s*0\\s*\\)\\s*@binding\\s*\\(\\s*1\\s*\\)[^;]*texture_depth_2d/u.test(\n lookup.value.source,\n )\n ) {\n return null;\n }\n const bgl = internals.device.createBindGroupLayout({\n label: `material-view-with-resource-${materialShaderId}`,\n entries: [\n { binding: 0, visibility: 3, buffer: { type: 'uniform' } },\n {\n binding: 1,\n visibility: 2,\n texture: { sampleType: 'depth', viewDimension: '2d', multisampled: false },\n },\n ],\n });\n if (!bgl.ok) return null;\n const pipelineLayout = internals.device.createPipelineLayout({\n label: `material-view-with-resource-pl-${materialShaderId}`,\n bindGroupLayouts: [bgl.value],\n });\n if (!pipelineLayout.ok) return null;\n const built = { materialBgl: bgl.value, pipelineLayout: pipelineLayout.value };\n viewWithResourceLayouts.set(materialShaderId, built);\n return built;\n };\n const getOrBuildPreparedMaterialPipelineLayout = (\n materialShaderId: string,\n ): PipelineLayout | null => {\n const cached = preparedMaterialPipelineLayoutCache.get(materialShaderId);\n if (cached !== undefined) return cached;\n if (pipelineState === null) return null;\n const materialBgl =\n getOrBuildPerShaderMaterialLayout(materialShaderId)?.materialBgl ??\n pipelineState.materialBindGroupLayout;\n const result = internals.device.createPipelineLayout({\n label: `prepared-material-pl-${materialShaderId}`,\n bindGroupLayouts: [pipelineState.viewBindGroupLayout, materialBgl],\n });\n if (!result.ok) {\n internals.errorRegistry.fire(result.error);\n return null;\n }\n preparedMaterialPipelineLayoutCache.set(materialShaderId, result.value);\n return result.value;\n };\n // Returns the per-shader { materialBgl, pipelineLayout } for every registered\n // render-material shader. Its BGL is derived from the shader's paramSchema;\n // the shared PBR layout remains only as the bootstrap layout. Pure-ish:\n // builds + caches on miss via the same buildBindGroupLayoutDescriptor SSOT\n // (kind 'pbr-material-merged' + materialParamSchema) used by\n // buildPbrPipelineLayouts.\n const getOrBuildPerShaderMaterialLayout = (\n materialShaderId: string,\n ): PerShaderMaterialLayout | null => {\n const lookup = getShader().findMaterialArtifact(materialShaderId);\n if (!lookup.ok) return null;\n const cached = perShaderMaterialLayoutCache.get(materialShaderId);\n if (cached?.source === lookup.value.source && cached.paramSchema === lookup.value.paramSchema) {\n return cached.layout;\n }\n if (!/@group\\s*\\(\\s*1\\s*\\)/u.test(lookup.value.source)) {\n perShaderMaterialLayoutCache.set(materialShaderId, {\n source: lookup.value.source,\n paramSchema: lookup.value.paramSchema,\n layout: null,\n });\n return null;\n }\n const layoutInputs = getMaterialLayoutInputs();\n if (layoutInputs === null) return null;\n const spec: PipelineSpec = {\n shader: { id: materialShaderId, passKind: 'forward', variantSet: undefined },\n attachments: { colorFormats: [], depthFormat: undefined, sampleCount: 1 },\n geometry: { topology: 'triangle-list', vertexLayout: {} },\n renderState: undefined,\n };\n const desc = buildBindGroupLayoutDescriptor(spec, {\n kind: 'pbr-material-merged',\n registry: getShader(),\n });\n const bglRes = internals.device.createBindGroupLayout(\n // biome-ignore lint/suspicious/noExplicitAny: BGL desc 'entries' is mutable per @webgpu/types; rhiDevice accepts it\n desc as any,\n );\n if (!bglRes.ok) {\n internals.errorRegistry.fire(bglRes.error);\n return null;\n }\n const plRes = internals.device.createPipelineLayout({\n label: `pbr-pl-${materialShaderId}`,\n bindGroupLayouts: [\n layoutInputs.viewBgl,\n bglRes.value,\n layoutInputs.meshArrayBgl,\n layoutInputs.instancesBgl,\n ],\n });\n if (!plRes.ok) {\n internals.errorRegistry.fire(plRes.error);\n return null;\n }\n const built = { materialBgl: bglRes.value, pipelineLayout: plRes.value };\n perShaderMaterialLayoutCache.set(materialShaderId, {\n source: lookup.value.source,\n paramSchema: lookup.value.paramSchema,\n layout: built,\n });\n return built;\n };\n const resolveCachedMaterialShaderVariantSet = (\n requestedVariantSet: string | undefined,\n manifestEntry: import('@forgeax/engine-shader').MaterialShaderManifestEntry | undefined,\n ): string | undefined => {\n if (manifestEntry === undefined) {\n return resolveMaterialShaderVariantSet(\n requestedVariantSet,\n [],\n internals.device.caps.backendKind,\n internals.device.caps.storageBuffer,\n );\n }\n const variants = manifestEntry.variants;\n let byRequest = materialShaderVariantResolutionCache.get(variants);\n if (byRequest === undefined) {\n byRequest = new Map();\n materialShaderVariantResolutionCache.set(variants, byRequest);\n }\n const cacheKey = `${requestedVariantSet ?? '\\u0000'}|${internals.device.caps.backendKind}|${internals.device.caps.storageBuffer ? '1' : '0'}`;\n if (byRequest.has(cacheKey)) return byRequest.get(cacheKey);\n const resolved = resolveMaterialShaderVariantSet(\n requestedVariantSet,\n variants,\n internals.device.caps.backendKind,\n internals.device.caps.storageBuffer,\n );\n byRequest.set(cacheKey, resolved);\n return resolved;\n };\n const findMaterialShaderManifestEntry = (\n materialShaderId: string,\n ): MaterialShaderManifestEntry | undefined => {\n const cached = materialShaderManifestEntryCache.get(materialShaderId);\n if (cached !== undefined) return cached;\n for (const candidate of getShader().materialShaderManifestEntries()) {\n if (candidate.identifier === materialShaderId) {\n materialShaderManifestEntryCache.set(materialShaderId, candidate);\n return candidate;\n }\n }\n return undefined;\n };\n // feat-20260622-s5 M3 / w17: the pipeline build is factored into a closure so\n // the recover() rebuild can re-run the SAME three-step assembly against the\n // freshly-acquired device (SSOT — one build path, one set of seed callbacks).\n // All captured references (getShader / gpuStore / getShaderModuleAdapter /\n // materialShaderPipelineCache / renderSystem) are stable across recover; only\n // `internals.device` / `internals.pack` are read live, so a rebuild after a\n // device swap compiles against the new device.\n let tonemapRegistered = false;\n let deferredLightingRegistered = false;\n const buildPipeline = (): Promise<PipelineState> =>\n buildReadyWebGPU(\n internals.device,\n getShader,\n gpuStore,\n internals.pack.createShaderModule,\n internals.errorRegistry,\n requiredMaterialShaders,\n // feat-20260608-mesh-ssbo-dynamic-grow-l1-lift-1024-entity-cap M2 /\n // T-M2-05 + M3 / T-M3-04: callback set by buildReadyWebGPU once\n // meshSsboController is wired. Both the grow hook AND the read-only\n // state ref land on `internals` so the record stage (M3\n // ensureMeshSsboCapacity) can read slotCount + call grow through\n // RenderSystemInternals.\n (hook, state) => {\n internals.growMeshSsbo = hook;\n internals.meshSsboState = state;\n },\n // feat-20260609 R3-fixup: seed the lazy adapter cache with the\n // eagerly-compiled shadow_caster module.\n (label, module) => {\n getShaderModuleAdapter().seedModule(label, module);\n },\n // M6 fix-up: seed `materialShaderPipelineCache` from the boot-time\n // SPEC_CONST prewarm. Closure captures the Map declared just above so\n // the URP-variant prewarmed PSOs become visible to the URP record path\n // immediately (no 1-frame async-compile skip-draw window).\n (key, pso) => {\n if (!materialShaderPipelineCache.has(key)) {\n materialShaderPipelineCache.set(key, pso);\n }\n },\n // feat-20260621 M-A3 (D-5): register the built-in tonemap on the unified\n // post-process channel once buildReadyWebGPU resolves the tonemap manifest\n // entry's composed WGSL. Fires after the manifest-load await, by which point\n // `renderSystem` (declared synchronously below) is defined. The 16 B params\n // schema mirrors the prior dedicated UBO: [exposure(f32), whitePoint(f32),\n // mode(u32), pad(f32)]; the extract stage bridges Camera.exposure/whitePoint/\n // tonemap into this channel each frame (render-system-extract.ts w13).\n (source: string) => {\n if (tonemapRegistered) return;\n renderSystem.postProcess.register(TONEMAP_POST_PROCESS_ID, {\n source,\n params: { byteSize: 16, defaultValue: new Uint8Array(16) },\n reads: ['hdrColor'],\n });\n tonemapRegistered = true;\n },\n (source: string) => {\n if (deferredLightingRegistered) return;\n renderSystem.postProcess.register(HDRP_DEFERRED_LIGHTING_POST_PROCESS_ID, {\n source,\n params: { byteSize: 16, defaultValue: new Uint8Array(16) },\n reads: [\n 'gbuffer-albedo-metallic',\n 'gbuffer-normal-roughness',\n 'gbuffer-emissive-ao',\n { key: 'depth', sampleType: 'depth' },\n ],\n });\n deferredLightingRegistered = true;\n },\n (layouts) => {\n bootMaterialLayoutInputs = layouts;\n },\n );\n const ready: Promise<Result<void, RhiError>> = buildPipeline().then(\n (state): Result<void, RhiError> => {\n pipelineState = state;\n readySettled = true;\n return ok(undefined);\n },\n (e: unknown): Result<void, RhiError> => {\n readySettled = true;\n if (e instanceof RhiError) return err(e);\n const message = e instanceof Error ? e.message : String(e);\n return err(\n new RhiError({\n code: 'webgpu-runtime-error',\n expected: 'Renderer.ready three-step strict-serial succeeds',\n hint: `pipeline build raised: ${message}`,\n }),\n );\n },\n );\n /** Legacy feature-only pipeline source; authored MaterialReady never uses it. */\n const findStandardPbrEntry = (): import('@forgeax/engine-types').ManifestEntry | undefined => {\n for (const entry of getShader().entries()) {\n if (entry.wgsl.includes('f_schlick')) return entry;\n }\n return undefined;\n };\n // Shared builder context for the per-MaterialShader pipeline cache.\n // Built once for registered material shader IDs. Null when the manifest is\n // empty (Camera-only path).\n //\n // feat-20260609-hdrp-cluster-fragment-ggx M4.5 / w37 (D-10 option A):\n // `variantSet` parameter selects between URP `pbrPipelineLayout` (1-slot\n // group(2) BGL) and HDRP `hdrpPbrPipelineLayout` (7-slot group(2) BGL)\n // via `selectPipelineLayoutForVariant`. When undefined, the URP layout is\n // used for callers that do not request a variant.\n const buildPipelineContext = (\n variantSet?: string,\n materialShaderId?: string,\n // feat-20260611-fox-skinning-vertex-attribute-chain M4 / w16 (D-4):\n // when layoutKind === 'pbr-skin' the SSOT for the vertex buffer layout\n // is `deriveVertexBufferLayout` (vertex-attribute-layout.ts) — the same\n // function that the WGSL @location(N) declarations / naga reflect tests\n // consume. A caller passing a real `MeshAsset.attributes` produces the\n // exact 6-attribute / 72-byte layout the skin shader expects; passing\n // undefined falls into the synthetic 6-key sentinel below (the skin\n // path is fully determined by layoutKind, so key-presence is the only\n // signal `deriveVertexBufferLayout` reads — values never matter).\n meshAttributes?: VertexAttributeMap,\n vertexLayout?: string,\n vertexLayoutProjection?: VertexLayoutProjection,\n ) => {\n // bug-20260611: derive LayoutKind from materialShaderId (caller-driven)\n // so the selector body stays free of literal shader-id strings (AC-09).\n // Skin shader gets its own 4-slot layout chain with 3-entry mesh-array\n // BGL; everything else routes through the URP/HDRP variantSet logic.\n // bug-20260708 M2 (c): sprite / sprite-lit map to 'sprite-urp' so the\n // canonical all-true variant key `''` (used by SpriteInstances batches\n // via SPRITE_PASS_PER_INSTANCE_REGION_VARIANT_SET) does NOT route\n // through the HDRP layout branch of the selector — sprite shaders have\n // no HDRP variant, plan-strategy R-1' guard.\n const layoutKind: LayoutKind | undefined =\n materialShaderId === SKIN_MATERIAL_SHADER_ID\n ? 'pbr-skin'\n : materialShaderId === 'forgeax::sprite' || materialShaderId === 'forgeax::sprite-lit'\n ? 'sprite-urp'\n : materialShaderId === 'forgeax::default-unlit'\n ? 'unlit-urp'\n : undefined;\n const usesSharedBootMaterialLayout =\n materialShaderId === 'forgeax::default-standard-pbr' ||\n materialShaderId === 'forgeax::default-unlit' ||\n materialShaderId === SKIN_MATERIAL_SHADER_ID;\n // Every non-skin render-material shader owns a per-shader material layout.\n // Skin keeps its dedicated mesh-array pipeline because its group(2) shape\n // differs; all material BGL entries still come from the schema-derived\n // merged contract.\n const perShaderLayout =\n !usesSharedBootMaterialLayout && layoutKind !== 'pbr-skin' && materialShaderId !== undefined\n ? getOrBuildPerShaderMaterialLayout(materialShaderId)\n : null;\n const bindingContract =\n materialShaderId === undefined\n ? 'render-material'\n : getCachedMaterialShaderBindingContract(materialShaderId);\n const group0Layout = bindingContract === 'group-0' ? getOrBuildGroup0MaterialLayout() : null;\n const group0ResourceLayout =\n bindingContract === 'group-0-resource' && materialShaderId !== undefined\n ? getOrBuildGroup0ResourceLayout(materialShaderId)\n : null;\n const viewOnlyLayout =\n bindingContract === 'view-only' ? getOrBuildViewOnlyMaterialPipelineLayout() : null;\n const viewWithResourceLayout =\n bindingContract === 'view-with-resource' && materialShaderId !== undefined\n ? getOrBuildViewWithResourceLayout(materialShaderId)\n : null;\n const preparedMaterialLayout =\n bindingContract === 'render-material' &&\n materialShaderId !== undefined &&\n (vertexLayout === RENDER_FEATURE_VERTEX_LAYOUTS.billboardMaterialInstance ||\n vertexLayout === RENDER_FEATURE_VERTEX_LAYOUTS.meshGeometryMaterialInstance)\n ? getOrBuildPreparedMaterialPipelineLayout(materialShaderId)\n : null;\n const vertexInputContract =\n materialShaderId === undefined\n ? 'render-material'\n : (() => {\n const lookup = getShader().findMaterialArtifact(materialShaderId);\n return lookup.ok\n ? resolveMaterialShaderVertexInputContract(lookup.value.source)\n : 'render-material';\n })();\n const pipelineLayout =\n group0Layout !== null\n ? group0Layout.pipelineLayout\n : group0ResourceLayout !== null\n ? group0ResourceLayout.pipelineLayout\n : viewOnlyLayout !== null\n ? viewOnlyLayout\n : viewWithResourceLayout !== null\n ? viewWithResourceLayout.pipelineLayout\n : preparedMaterialLayout !== null\n ? preparedMaterialLayout\n : perShaderLayout !== null\n ? perShaderLayout.pipelineLayout\n : selectPipelineLayoutForVariant(pipelineState, variantSet, layoutKind);\n if (pipelineLayout === null) return null;\n // feat-20260611-fox-skinning-vertex-attribute-chain M4 / w16 (D-4):\n // pbr-skin -> deriveVertexBufferLayout (single SSOT for skin/non-skin\n // attribute layout). Caller may pass a real `MeshAsset.attributes`;\n // otherwise we synthesize a 6-key sentinel because deriveVertexBufferLayout\n // only reads key presence (value identity is irrelevant). Non-skin\n // layoutKinds keep the hardcoded 4-attribute / 48-byte layout for\n // backward-compat (`undefined` / `'pbr'` / `'hdrp-pbr'` -- the URP/HDRP\n // path has no skin attributes, AC-04 zero-regression).\n // The non-skin PBR fallback keeps the hardcoded 4-attribute / 48-byte\n // source layout (pos@0/normal@1/uv@2/tangent@3) for zero-regression\n // geometry. The shader-declared UV0-UV7 inputs are supplied by\n // deriveVertexBufferLayout's clamp-to-last aliases without changing the\n // interleaved stride.\n //\n // The derive path is taken in exactly the two cases where it is required:\n // 1. meshAttributes !== undefined -- a real per-mesh VertexAttributeMap\n // was forwarded (the record stage hands one through whenever a mesh\n // carries extra UV sets, e.g. uv1; honouring its key set is what emits\n // the @location(6+) attributes a custom multi-UV shader samples). A\n // custom shader registered via installMaterialArtifact is absent from\n // the naga-reflection map, so resolvedUvSetCount is undefined here --\n // the layout must come from the mesh keys, not the (missing) count.\n // 2. resolvedUvSetCount > 1 -- a manifest-reflected custom shader declares\n // multiple UV sets, so clamp-to-last aliases the missing mesh sets.\n // Built-in PBR (meshAttributes undefined + the explicit reflected count 8)\n // still uses the source layout plus the derived aliases. The pbr-skin\n // branch follows the same rule with its six-attribute source layout.\n const resolvedUvSetCount =\n materialShaderId !== undefined ? materialShaderUvSetCounts.get(materialShaderId) : undefined;\n const vertexBuffers: readonly GPUVertexBufferLayout[] =\n vertexInputContract === 'none'\n ? []\n : vertexLayout === RENDER_FEATURE_VERTEX_LAYOUTS.positionSizeColorInstance\n ? POSITION_SIZE_COLOR_INSTANCE_VERTEX_BUFFERS\n : vertexLayout === RENDER_FEATURE_VERTEX_LAYOUTS.billboardMaterialInstance\n ? BILLBOARD_MATERIAL_INSTANCE_VERTEX_BUFFERS\n : vertexLayout === RENDER_FEATURE_VERTEX_LAYOUTS.topologySegmentInstance\n ? TOPOLOGY_SEGMENT_INSTANCE_VERTEX_BUFFERS\n : vertexLayout === RENDER_FEATURE_VERTEX_LAYOUTS.meshGeometryMaterialInstance\n ? MESH_GEOMETRY_MATERIAL_INSTANCE_VERTEX_BUFFERS\n : vertexLayoutProjection !== undefined\n ? (deriveVertexBufferLayoutFromProjection(\n vertexLayoutProjection,\n resolvedUvSetCount !== undefined\n ? { shaderUvSetCount: resolvedUvSetCount }\n : undefined,\n ) as unknown as readonly GPUVertexBufferLayout[])\n : layoutKind === 'pbr-skin'\n ? (deriveVertexBufferLayout(\n meshAttributes ??\n ({\n position: PBR_SKIN_SENTINEL_ATTR_BUFFER,\n normal: PBR_SKIN_SENTINEL_ATTR_BUFFER,\n uv: PBR_SKIN_SENTINEL_ATTR_BUFFER,\n tangent: PBR_SKIN_SENTINEL_ATTR_BUFFER,\n skinIndex: PBR_SKIN_SENTINEL_ATTR_BUFFER,\n skinWeight: PBR_SKIN_SENTINEL_ATTR_BUFFER,\n } satisfies VertexAttributeMap),\n resolvedUvSetCount !== undefined\n ? { shaderUvSetCount: resolvedUvSetCount }\n : undefined,\n ) as unknown as readonly GPUVertexBufferLayout[])\n : meshAttributes !== undefined ||\n (resolvedUvSetCount !== undefined && resolvedUvSetCount > 1)\n ? (deriveVertexBufferLayout(\n meshAttributes ?? DEFAULT_VERTEX_ATTRS,\n resolvedUvSetCount !== undefined && resolvedUvSetCount > 1\n ? { shaderUvSetCount: resolvedUvSetCount }\n : undefined,\n ) as unknown as readonly GPUVertexBufferLayout[])\n : ([\n {\n arrayStride: 12 * 4,\n attributes: [\n { shaderLocation: 0, offset: 0, format: 'float32x3' as const },\n { shaderLocation: 1, offset: 3 * 4, format: 'float32x3' as const },\n { shaderLocation: 2, offset: 6 * 4, format: 'float32x2' as const },\n { shaderLocation: 3, offset: 8 * 4, format: 'float32x4' as const },\n ],\n },\n ] as unknown as readonly GPUVertexBufferLayout[]);\n return {\n device: internals.device,\n shaderModuleFactory: getShaderModuleAdapter(),\n pipelineLayout,\n vertexBuffers,\n };\n };\n /**\n * Builds a pipeline for the given entry, caches it keyed by cacheKey,\n * and returns it. Returns null on build failure (firing errorRegistry\n * for non-transient errors).\n */\n const buildAndCachePipeline = (\n cacheKey: string,\n entry: {\n readonly source: string;\n readonly paramSchema: readonly unknown[];\n },\n label: string,\n moduleLabel: string,\n isHdr: boolean,\n renderState: MaterialRenderState | undefined,\n topology: PrimitiveTopology | undefined,\n stripIndexFormat: 'uint16' | 'uint32' | undefined,\n // feat-20260609 M4.5 / w37 (D-10): thread variantSet to the layout selector\n // so HDRP-variant PSOs build with `hdrpPbrPipelineLayout` (7-slot group(2))\n // and URP-variant PSOs build with `pbrPipelineLayout` (1-slot group(2)).\n variantSet?: string,\n passKind: PassKind = 'forward',\n // bug-20260611-skin-pipeline-layout: thread materialShaderId so\n // buildPipelineContext can derive `LayoutKind === 'pbr-skin'` and pick\n // the 3-entry mesh-array BGL chain.\n materialShaderId?: string,\n // feat-20260611-fox-skinning-vertex-attribute-chain M4 / w16 (D-4):\n // pass the per-mesh `VertexAttributeMap` so the pbr-skin path's\n // vertex buffer layout flows from the SSOT `deriveVertexBufferLayout`\n // (vertex-attribute-layout.ts) instead of a parallel hardcoded copy.\n // Undefined falls into the synthetic 6-key sentinel inside\n // `buildPipelineContext` (key-presence-only); non-skin layoutKinds\n // ignore this parameter entirely.\n meshAttributes?: VertexAttributeMap,\n // bug-20260615 M2 / m2-1: sampleCount drives the multisample descriptor\n // field in buildPipelineForMaterialShader — it is a CAMERA fact (per-frame\n // antialias setting), not a material renderState value. Default 1 preserves\n // byte-identity of every existing pre-M2 cache slot + descriptor.\n sampleCount: number = 1,\n // feat-20260625-refactor-sprite-as-transparent-mesh R2 fix-up: LDR-color\n // override for sub-passes that write to a non-default attachment view.\n // Pre-feat the dedicated `forgeax::default-sprite` SPEC_CONST entries\n // (SPRITE_ATTACHMENTS_LDR_S1/S4) targeted the swap-chain STORAGE format\n // (non-sRGB) directly. Post-w14 sprite falls into the generic lazy build\n // path which defaults to `pipelineState.colorAttachmentFormat` (the sRGB\n // VIEW format used by the geometry pass) — incompatible with the sprite\n // sub-pass's non-sRGB attachment view (bgra8unorm / rgba8unorm), firing\n // a per-frame \"Attachment state ... not compatible\" validation error.\n // The sprite sub-pass call site passes `pipelineState.format` (storage,\n // non-sRGB) here so the resulting PSO matches the encoder's attachment\n // state. Undefined preserves the default (sRGB view) path used by every\n // pre-fix-up caller. Ignored when `isHdr=true` or `passKind='shadow-caster'`.\n colorFormatOverride?: GPUTextureFormat,\n // Prepared graphics passes use `null` to request an explicit color-only\n // pipeline; omitted preserves the material forward depth default.\n depthFormatOverride?: GPUTextureFormat | null,\n vertexLayout?: string,\n fragmentEntry?: string,\n vertexLayoutProjection?: VertexLayoutProjection,\n ): RenderPipeline | null => {\n const ctx = buildPipelineContext(\n variantSet,\n materialShaderId,\n meshAttributes,\n vertexLayout,\n vertexLayoutProjection,\n );\n if (ctx === null) return null;\n // bug-20260612: route the LDR color format through pipelineState so the\n // backend-aware swap-chain format chosen at buildReadyWebGPU flows here.\n // Callers gate on pipelineState !== null before reaching this lambda\n // (search \"buildAndCachePipeline\" call sites — every one is preceded by\n // the explicit null check).\n if (pipelineState === null) return null;\n const ldrColorFormat =\n colorFormatOverride ?? (pipelineState.colorAttachmentFormat as unknown as GPUTextureFormat);\n const built = buildPipelineForMaterialShader(\n cacheKey,\n // biome-ignore lint/suspicious/noExplicitAny: cast through any to satisfy MaterialShaderEntry shape\n entry as any,\n {\n ...ctx,\n colorFormat: isHdr ? HDR_COLOR_ATTACHMENT_FORMAT : ldrColorFormat,\n depthFormat:\n depthFormatOverride === null ? undefined : (depthFormatOverride ?? DEPTH_TEXTURE_FORMAT),\n label,\n // feat-20260604 w16-b: the shader-MODULE cache identity. Stable across\n // topology / renderState / isHdr / indexFormat (all baked into the PSO,\n // not the module), so every pipeline variant of the same shader source\n // reuses one compiled module instead of forcing a fresh async compile\n // per variant. See PipelineBuilderContext.moduleLabel.\n moduleLabel,\n },\n renderState,\n // w8/w15: pack topology (+ stripIndexFormat) into the builder's geometry\n // param. Strip topologies bake stripIndexFormat into the immutable PSO\n // (WebGPU spec: only valid for line-strip / triangle-strip). The record\n // stage (w9 + w15) threads each mesh's topology + indexFormat here; when\n // the caller omits stripIndexFormat we fall back to 'uint32' (the engine\n // procedural index width: createBoxGeometry etc. emit Uint32 indices).\n topology !== undefined\n ? {\n topology,\n ...(topology === 'line-strip' || topology === 'triangle-strip'\n ? { stripIndexFormat: stripIndexFormat ?? ('uint32' as const) }\n : {}),\n }\n : undefined,\n undefined, // vertexEntry — default vs_main\n fragmentEntry,\n undefined, // defines — none\n passKind,\n sampleCount,\n );\n if (!built.ok) {\n if (built.error.code !== 'rhi-not-available') {\n internals.errorRegistry.fire(built.error);\n }\n return null;\n }\n materialShaderPipelineCache.set(cacheKey, built.value);\n return built.value;\n };\n const getMaterialShaderPipeline = (\n materialShaderId: string,\n isHdr: boolean,\n renderState?: MaterialRenderState,\n topology?: PrimitiveTopology,\n indexFormat?: 'uint16' | 'uint32',\n variantSet?: string,\n passKind: PassKind = 'forward',\n // feat-20260611-fox-skinning-vertex-attribute-chain M4 / w16 (D-4):\n // forwarded to `buildAndCachePipeline -> buildPipelineContext` so the\n // pbr-skin layout chain reads from the `deriveVertexBufferLayout` SSOT.\n // Optional: existing callers (URP / HDRP / shadow-depth) pass undefined\n // and the hardcoded 4-attribute layout is preserved (AC-04 zero-regression).\n meshAttributes?: VertexAttributeMap,\n // bug-20260615 M2 / m2-1: sampleCount is threaded through to the cache key,\n // buildAndCachePipeline, and ultimately buildPipelineForMaterialShader which\n // sets the multisample descriptor field. Default 1 preserves byte-identity\n // of every pre-M2 caller.\n sampleCount: number = 1,\n // feat-20260625-refactor-sprite-as-transparent-mesh R2 fix-up: LDR-color\n // override for sub-passes that write to a non-default attachment view.\n // The LDR sprite split sub-pass writes through the storage (non-sRGB)\n // view of the swap-chain texture; the encoder's beginRenderPass\n // colorFormats uses `pipelineState.format` (storage), so the PSO must\n // build with the same non-sRGB format or WebGPU rejects SetPipeline\n // with \"Attachment state ... not compatible\". Pre-w14 the dedicated\n // `forgeax::default-sprite` SPEC_CONST entries (deleted) baked this\n // mapping into SPRITE_ATTACHMENTS_LDR_S1/S4; the generic lazy build\n // path that replaced them defaults to `colorAttachmentFormat` (the\n // sRGB view used by the geometry pass), so transparent-split callers\n // must override. Threaded into both the cache key (via the spec's\n // `attachments.colorFormats`) and the actual PSO descriptor. Ignored\n // for `isHdr=true` (HDR sub-pass uses rgba16float) and\n // `passKind='shadow-caster'` (depth-only, no color attachment).\n colorFormatOverride?: GPUTextureFormat,\n // feat-20260629-multi-uv-set-support m3-w5: shader-declared UV set count,\n // forwarded to PipelineSpec.geometry.shaderUvSetCount for clamp-to-last\n // alias. Undefined = fallback to mesh-provided count (no clamping).\n // m4-w3: auto-filled from naga reflection when caller passes undefined.\n shaderUvSetCount?: number,\n // Prepared graphics passes use `null` to request an explicit color-only\n // pipeline; omitted preserves the material forward depth default.\n depthFormatOverride?: GPUTextureFormat | null,\n vertexLayout?: string,\n materialGuid?: string,\n fragmentEntry?: string,\n vertexLayoutProjection?: VertexLayoutProjection,\n ): RenderPipeline | null => {\n // WebGL2 is a downlevel backend even when the record stage asks for the\n // native-capability variant string. Resolve the variant axes at this\n // shared PSO seam so the shader source, BGL layout, and cache key agree on\n // the actual device capabilities. Without this, WebGL2 can build a\n // storage-buffer PSO around a uniform-buffer shader and only reject it at\n // queue submit as an invalid RenderPipeline.\n const ldrColorFormat: GPUTextureFormat =\n colorFormatOverride ??\n (pipelineState !== null\n ? (pipelineState.colorAttachmentFormat as unknown as GPUTextureFormat)\n : ('bgra8unorm-srgb' as unknown as GPUTextureFormat));\n // feat-20260629 M4: auto-fill shaderUvSetCount from naga reflection\n // (stored in materialShaderUvSetCounts during prepareMaterialShaders).\n const resolvedUvSetCount = shaderUvSetCount ?? materialShaderUvSetCounts.get(materialShaderId);\n const manifestEntry = findMaterialShaderManifestEntry(materialShaderId);\n const resolvedVariantSet = resolveCachedMaterialShaderVariantSet(variantSet, manifestEntry);\n // The record stage also composes engine capability axes for user shaders.\n // Keep only manifest-declared axes for non-engine material IDs: a plain\n // custom shader must not collapse that request to '' because '' is the\n // canonical HDRP variant key and would pair an HDRP PSO with the URP mesh\n // bind group. Builtin forgeax:: shaders keep the compatibility request\n // when a reduced test/legacy manifest omits variant metadata.\n let effectiveVariantSet = resolvedVariantSet;\n if (\n vertexLayoutProjection === undefined &&\n manifestEntry?.variants.some((variant) => 'VERTEX_COLOR_AVAILABLE' in variant.defines)\n ) {\n if (effectiveVariantSet === '') {\n // Empty is the canonical all-true key. A legacy/implicit mesh has no\n // projection, so resolve the same capability variant with only the\n // geometry-owned color axis disabled; otherwise the shader reads\n // @location(13) while the default VertexState has no color input.\n const noColorVariant = manifestEntry.variants.find(\n (variant) =>\n variant.defines.VERTEX_COLOR_AVAILABLE === false &&\n Object.entries(variant.defines).every(\n ([axis, value]) => axis === 'VERTEX_COLOR_AVAILABLE' || value === true,\n ),\n );\n effectiveVariantSet = noColorVariant?.definesKey ?? 'VERTEX_COLOR_AVAILABLE=false';\n } else {\n effectiveVariantSet = effectiveVariantSet?.replace(\n 'VERTEX_COLOR_AVAILABLE=true',\n 'VERTEX_COLOR_AVAILABLE=false',\n );\n }\n }\n if (\n manifestEntry !== undefined &&\n !materialShaderId.startsWith('forgeax::') &&\n effectiveVariantSet !== undefined &&\n effectiveVariantSet !== ''\n ) {\n const declaredAxes = new Set<string>();\n for (const variant of manifestEntry.variants) {\n for (const axis of Object.keys(variant.defines)) declaredAxes.add(axis);\n }\n const filteredVariantParts = effectiveVariantSet\n .split('+')\n .filter((part) => declaredAxes.has(part.slice(0, part.indexOf('='))))\n .sort();\n effectiveVariantSet =\n filteredVariantParts.length === 0 ? undefined : filteredVariantParts.join('+');\n }\n // feat-20260615-pipeline-spec-ssot M2-T2: cache key derived from PipelineSpec\n // 4-axis SSOT via cacheKeyOf(spec). The spec carries all 4 axes (shader /\n // attachments / geometry / renderState), replacing the legacy 8-segment string\n // construction. vertexLayout is now included in the cache key (was previously\n // threaded but not hashed — research F1 R-VertexLayout-Cache). sampleCount is\n // cast to 1 | 4 for the closed spec axis.\n // M2-fixup follow-up: LDR color format SSOT is `pipelineState.colorAttachmentFormat`\n // (set in buildReadyWebGPU from selectSwapChainFormat). Hardcoding 'bgra8unorm-srgb'\n // here let the cache key drift from the prewarm key on backends where\n // getPreferredCanvasFormat returns rgba8unorm (dawn-node, lavapipe, wgpu-wasm GLES),\n // forcing a redundant second PSO build on first-frame URP record path.\n const colorFormat: GPUTextureFormat =\n passKind === 'shadow-caster'\n ? (undefined as unknown as GPUTextureFormat)\n : isHdr\n ? ('rgba16float' as unknown as GPUTextureFormat)\n : ldrColorFormat;\n const spec: PipelineSpec = {\n shader: {\n id: materialShaderId,\n passKind,\n variantSet: effectiveVariantSet,\n ...(fragmentEntry === undefined ? {} : { fragmentEntry }),\n },\n attachments: {\n colorFormats: colorFormatsForPassKind(passKind, colorFormat),\n depthFormat:\n passKind === 'shadow-caster'\n ? ('depth32float' as unknown as GPUTextureFormat)\n : depthFormatOverride === null\n ? undefined\n : (depthFormatOverride ?? ('depth24plus-stencil8' as unknown as GPUTextureFormat)),\n sampleCount: (sampleCount === 4 ? 4 : 1) as 1 | 4,\n },\n geometry: {\n topology: topology ?? 'triangle-list',\n stripIndexFormat: indexFormat,\n vertexLayout:\n meshAttributes ??\n (vertexLayout === RENDER_FEATURE_VERTEX_LAYOUTS.positionSizeColorInstance\n ? PREPARED_INSTANCE_VERTEX_ATTRS\n : vertexLayout === RENDER_FEATURE_VERTEX_LAYOUTS.billboardMaterialInstance ||\n vertexLayout === RENDER_FEATURE_VERTEX_LAYOUTS.topologySegmentInstance ||\n vertexLayout === RENDER_FEATURE_VERTEX_LAYOUTS.meshGeometryMaterialInstance\n ? PREPARED_MATERIAL_INSTANCE_VERTEX_ATTRS\n : DEFAULT_VERTEX_ATTRS),\n // Thread the shader-declared count whenever it is greater than one.\n // Built-in PBR reserves all eight supported UV inputs; single-UV meshes\n // remain byte-stable because missing sets are clamp-to-last aliases.\n ...(resolvedUvSetCount !== undefined && resolvedUvSetCount > 1\n ? { shaderUvSetCount: resolvedUvSetCount }\n : {}),\n ...(vertexLayoutProjection === undefined ? {} : { vertexLayoutProjection }),\n },\n renderState,\n };\n const cacheKey = cacheKeyOf(spec);\n const cached = materialShaderPipelineCache.get(cacheKey);\n if (cached !== undefined) return cached;\n if (pipelineState === null) return null;\n const lookup = getShader().findMaterialArtifact(materialShaderId);\n if (!lookup.ok) {\n if (materialGuid !== undefined && !reportedMissingMaterialShaders.has(materialShaderId)) {\n reportedMissingMaterialShaders.add(materialShaderId);\n // A missing material shader is an authored/runtime contract failure.\n // Forward the ShaderRegistry-owned structured error once and skip the\n // affected draw; never substitute an engine shader with a different\n // binding or parameter contract.\n internals.errorRegistry.fire(lookup.error);\n }\n if (materialGuid !== undefined) return null;\n // Feature-only prepared graphics and legacy test fixtures do not carry\n // an authored MaterialAsset GUID. Keep their existing engine pipeline\n // compatibility path; it is not a fallback for a published material.\n if (\n renderState === undefined &&\n !allowsUnlitPreparedFallback(depthFormatOverride, vertexLayout, materialShaderId)\n ) {\n return null;\n }\n if (renderState === undefined) {\n const unlitLookup = getShader().findMaterialArtifact('forgeax::default-unlit');\n if (!unlitLookup.ok) return null;\n return buildAndCachePipeline(\n cacheKey,\n unlitLookup.value,\n `pbr-pipeline-prepared-${materialShaderId}`,\n 'unlit',\n isHdr,\n undefined,\n topology,\n indexFormat,\n effectiveVariantSet,\n passKind,\n 'forgeax::default-unlit',\n meshAttributes,\n sampleCount,\n colorFormatOverride,\n depthFormatOverride,\n vertexLayout,\n fragmentEntry,\n vertexLayoutProjection,\n );\n }\n const pbrEntry = findStandardPbrEntry();\n if (pbrEntry === undefined) return null;\n return buildAndCachePipeline(\n cacheKey,\n { source: pbrEntry.wgsl, paramSchema: [] },\n `pbr-pipeline-fallback-${materialShaderId}${isHdr ? '-hdr' : ''}`,\n 'module-fallback-pbr',\n isHdr,\n renderState,\n topology,\n indexFormat,\n effectiveVariantSet,\n passKind,\n 'forgeax::default-standard-pbr',\n meshAttributes,\n sampleCount,\n colorFormatOverride,\n depthFormatOverride,\n vertexLayout,\n fragmentEntry,\n vertexLayoutProjection,\n );\n }\n // feat-20260609 M4 / w31: resolve variant WGSL from manifest when\n // variantSet is non-empty. The boot-time registered shader (from\n // `installMaterialArtifact` at line ~2473) carries the default (all-true)\n // variant's WGSL. For URP callers that want a different variant\n // (e.g. STORAGE_BUFFER_AVAILABLE=true without CLUSTER_FORWARD_AVAILABLE),\n // we look up the manifest entry, find the matching variant, and\n // substitute its composedWgsl into the PSO build path. The pipeline\n // layout itself is built by buildPbrPipelineLayouts (M3 / w12).\n // When variantSet is empty/undefined, the boot-time registered entry\n // (which is the all-true default) is used verbatim — backward compat.\n let shaderEntry = lookup.value;\n // M4.5 / w38 (D-11): `variantSet === ''` is canonical all-true (HDRP\n // path) and MUST hit the manifest variant lookup -- treat it as a\n // first-class variant request, not a falsy \"no variant\" signal.\n // Use `!== undefined` so the empty-string case enters the lookup.\n if (effectiveVariantSet !== undefined) {\n const registry = getShader();\n for (const msEntry of registry.materialShaderManifestEntries()) {\n if (msEntry.identifier === materialShaderId) {\n const variant = findVariantByKey(msEntry, effectiveVariantSet);\n if (variant) {\n // M3 / w12-w13: variant substitution carries the same source +\n // paramSchema as the boot-registered entry; the binding layout\n // is no longer carried on MaterialShaderEntry (deleted in\n // w13) — buildPbrPipelineLayouts is the BGL SSOT and reads\n // derive(paramSchema).bglEntries on demand.\n shaderEntry = {\n ...lookup.value,\n source: variant.composedWgsl,\n };\n }\n break;\n }\n }\n }\n // feat-20260609 M4 / R3-fixup: append `-${passKind}` to the PSO label so\n // GPU debug captures (and the shadow-caster branch in the builder)\n // make the cache variant visible. The fallback path above keeps the\n // pre-existing fallback-* label shape (no shadow-caster fallback\n // exists today; the only shadow caller registers shadowCaster directly).\n const passKindLabelSegment = passKind === 'forward' ? '' : `-${passKind}`;\n return buildAndCachePipeline(\n cacheKey,\n shaderEntry,\n `pbr-pipeline-${materialShaderId}${isHdr ? '-hdr' : ''}${passKindLabelSegment}`,\n // feat-20260609 M4 / w31: when variantSet is non-empty, the module identity\n // includes the variant key so URP (STORAGE_BUFFER_AVAILABLE=true) and HDRP\n // (CLUSTER_FORWARD_AVAILABLE=true+STORAGE_BUFFER_AVAILABLE=true) variants\n // compile as separate shader modules (they have different WGSL sources).\n // When variantSet is empty/undefined, the module identity stays pre-M4\n // backward-compatible for all PSOs of the default variant.\n // M4.5 / w38 (D-11): same `!== undefined` discipline as the cache\n // key -- `''` (canonical all-true) gets its own module-label slot,\n // distinct from the no-variant path. Trailing `#` for the empty\n // case is intentional (parallel to the cache key's `:variant:`\n // empty-tail segment); module identity stays a function of the\n // exact variantSet string.\n effectiveVariantSet !== undefined\n ? `module-${materialShaderId}#${effectiveVariantSet}`\n : `module-${materialShaderId}`,\n isHdr,\n renderState,\n topology,\n indexFormat,\n // M4.5 / w37 (D-10): main path threads variantSet so HDRP-variant PSO\n // builds against `hdrpPbrPipelineLayout` (7-slot group(2) BGL) and URP\n // builds against `pbrPipelineLayout` (1-slot group(2) BGL).\n effectiveVariantSet,\n // feat-20260609 / T-002: passKind selects createRenderPipeline\n // attachment shape (forward color+DS vs shadow-caster depth32float\n // no-color). Orthogonal to variantSet (which selects the BGL chain).\n passKind,\n // bug-20260611-skin-pipeline-layout: thread the registered materialShaderId\n // so buildPipelineContext can resolve LayoutKind='pbr-skin' for the skin\n // shader (3-entry mesh-array BGL).\n materialShaderId,\n // feat-20260611-fox-skinning-vertex-attribute-chain M4 / w16 (D-4):\n // forward meshAttributes so the pbr-skin path's vertex buffer layout\n // is derived via the SSOT (deriveVertexBufferLayout). For URP/HDRP\n // callers (and for any caller passing undefined) the synthetic 6-key\n // sentinel inside buildPipelineContext keeps the layout deterministic.\n meshAttributes,\n sampleCount,\n colorFormatOverride,\n depthFormatOverride,\n vertexLayout,\n fragmentEntry,\n vertexLayoutProjection,\n );\n };\n const getParamSchema = (materialShaderId: string) => {\n const lookup = getShader().findMaterialArtifact(materialShaderId);\n return lookup.ok ? lookup.value.paramSchema : undefined;\n };\n const getParamSchemaProjection = (\n materialShaderId: string,\n ): ImmutableParamSchemaProjection | undefined => {\n const lookup = getShader().findMaterialArtifact(materialShaderId);\n return lookup.ok ? lookup.value.paramSchemaProjection : undefined;\n };\n // feat-20260621-learn-render-5-5-parallax M2 / w6 (D-1): expose the per-shader\n // material BGL so the record stage creates the material bind group against\n // the matching layout (empty for group-0 shaders, wider for >3-texture\n // custom shaders). Returns undefined for the ordinary 3-texture path so the\n // record stage falls back to the shared built-in materialBindGroupLayout.\n const getMaterialBindGroupLayout = (materialShaderId: string): BindGroupLayout | undefined => {\n if (\n materialShaderId === 'forgeax::default-standard-pbr' ||\n materialShaderId === 'forgeax::default-unlit' ||\n materialShaderId === SKIN_MATERIAL_SHADER_ID\n ) {\n return undefined;\n }\n const contract = getCachedMaterialShaderBindingContract(materialShaderId);\n if (contract === 'group-0') {\n return getOrBuildGroup0MaterialLayout()?.materialBgl;\n }\n if (contract === 'group-0-resource') {\n return getOrBuildGroup0ResourceLayout(materialShaderId)?.materialBgl;\n }\n if (contract === 'view-with-resource') {\n return getOrBuildViewWithResourceLayout(materialShaderId)?.materialBgl;\n }\n return getOrBuildPerShaderMaterialLayout(materialShaderId)?.materialBgl ?? undefined;\n };\n // feat-20260609 M4 / T-10-a: post-process pipeline factory backing\n // RenderSystemRuntime.getPostProcessPipeline. Solves M1 CONCERN-1: previously\n // the dispatcher in render-graph-primitives.ts passed `pipeline=null` to\n // built.createHandle because per-frame execute closures cannot await\n // device.createShaderModule (async). This factory uses the same shared\n // makeShaderDeviceAdapter the material-shader pipeline cache uses (sync\n // wrapper + 1-frame warmup); first-call returns null while the async compile\n // is in flight; second frame onward returns the built pipeline.\n //\n // The pipeline layout is fixed:\n // group(0) = empty BGL (reserved per render-graph-primitives.ts convention\n // for view bind groups; populated by future post-process passes\n // that need view UBOs)\n // group(1) = the input-texture BGL the dispatcher already composed via\n // buildFullscreenPostProcessPass (texture + sampler)\n // Vertex stage: vs_main (no vertex buffers); fragment stage: fs_main targeting\n // `colorFormat`. Topology: triangle-list with cullMode='none' (3-vertex\n // fullscreen draw via the canonical fullscreen_triangle pattern).\n let emptyPostProcessBgl: BindGroupLayout | null = null;\n const buildPostProcessPipeline = (\n entry: PostProcessShaderEntry,\n bgl: BindGroupLayout,\n colorFormat: GPUTextureFormat,\n label: string,\n ): RenderPipeline | null => {\n const moduleFactory = getShaderModuleAdapter();\n const moduleResult = moduleFactory.createShaderModule({\n code: entry.source,\n label: `${label}-module`,\n });\n if (!moduleResult.ok) {\n // 'rhi-not-available' = async compile in flight: caller falls back one frame.\n // Other codes are real failures: surface through the error registry so AI\n // users see a structured RhiError instead of a silent black screen (charter P3).\n if (moduleResult.error.code !== 'rhi-not-available') {\n internals.errorRegistry.fire(moduleResult.error);\n }\n return null;\n }\n if (emptyPostProcessBgl === null) {\n const bglRes = internals.device.createBindGroupLayout({ entries: [] });\n if (!bglRes.ok) {\n internals.errorRegistry.fire(bglRes.error);\n return null;\n }\n emptyPostProcessBgl = bglRes.value;\n }\n const needsView = /@group\\(0\\)\\s*@binding\\(0\\)\\s*var<uniform>\\s+view\\b/.test(entry.source);\n const viewBgl = needsView ? pipelineState?.viewBindGroupLayout : null;\n if (needsView && viewBgl === undefined) return null;\n const layoutRes = internals.device.createPipelineLayout({\n label: `${label}-layout`,\n bindGroupLayouts: [viewBgl ?? emptyPostProcessBgl, bgl],\n });\n if (!layoutRes.ok) {\n internals.errorRegistry.fire(layoutRes.error);\n return null;\n }\n const pipelineRes = internals.device.createRenderPipeline({\n label,\n layout: layoutRes.value as unknown as GPUPipelineLayout,\n vertex: {\n module: moduleResult.value as unknown as GPUShaderModule,\n entryPoint: 'vs_main',\n buffers: [],\n } as unknown as GPUVertexState,\n fragment: {\n module: moduleResult.value as unknown as GPUShaderModule,\n entryPoint: entry.source.includes('fn fs_lighting') ? 'fs_lighting' : 'fs_main',\n targets: [{ format: colorFormat }],\n } as unknown as GPUFragmentState,\n primitive: { topology: 'triangle-list', cullMode: 'none', frontFace: 'ccw' },\n depthStencil: undefined,\n multisample: undefined,\n });\n if (!pipelineRes.ok) {\n internals.errorRegistry.fire(pipelineRes.error);\n return null;\n }\n return pipelineRes.value;\n };\n const renderSystem: RenderSystem = createRenderSystem({\n canvas: internals.canvas,\n featureHost: internals.featureHost,\n // Keep the feature-facing factory stable while resolving the adapter at\n // call time. Renderer recovery swaps the device and invalidates the\n // per-device adapter; a boot-time snapshot would feed recovered VFX\n // programs shader modules owned by the lost device.\n shaderModuleFactory: {\n createShaderModule: (descriptor) => getShaderModuleAdapter().createShaderModule(descriptor),\n },\n profiler: internals.options?.profiler,\n shadowDebugObservation: internals.options?.debugShadowObservation === true,\n paramSchemaProjectionCensus,\n // feat-20260622-s5 M3 / w17: device + context read live off `internals` via\n // getters so the recover() rebuild (which swaps internals.device /\n // internals.context for a freshly-acquired pair) is observed by the record\n // stage without reconstructing the RenderSystem (RenderSystemRuntime.device\n // / RenderSystemInternals.context are read at frame time, not cached).\n get device() {\n return internals.device;\n },\n get context() {\n return internals.context;\n },\n // feat-20260608-create-app-param-surface-trim / M1 / AC-02: clearColor\n // is no longer threaded through createRenderSystem; the record stage\n // reads `camera.clearColor` straight from the Camera SoA column\n // (array<f32,4>, feat-20260709 M3).\n getPipelineState: () => pipelineState,\n assets,\n gpuStore,\n dynamicTextureStore,\n membershipTiming,\n errorRegistry: internals.errorRegistry,\n healthRegistry: internals.healthRegistry,\n getMaterialShaderPipeline,\n getMaterialShaderBindingContract: getCachedMaterialShaderBindingContract,\n getParamSchema,\n getParamSchemaProjection,\n getMaterialBindGroupLayout,\n metrics,\n // feat-20260609 M4 / T-10-a: post-process pipeline factory (CONCERN-1 fix).\n // createRenderSystem wraps this in a per-RenderSystem cache + the public\n // getPostProcessPipeline lookup the dispatcher reads at frame time.\n buildPostProcessPipeline,\n // feat-20260608-mesh-ssbo-dynamic-grow-l1-lift-1024-entity-cap M3 / T-M3-04:\n // forward the grow hook + state via getter closures — buildReadyWebGPU\n // sets `internals.growMeshSsbo` / `internals.meshSsboState` after this\n // factory call, so the record stage reads them through the closures\n // (read at frame time, when ready has already settled).\n get growMeshSsbo() {\n return internals.growMeshSsbo;\n },\n get meshSsboState() {\n return internals.meshSsboState;\n },\n });\n // feat-20260601-customizable-render-pipeline-seam M1 / w8 (D-19): DOGFOOD. The default\n // frame is driven through the SAME public channel an AI user would use - registerPipeline\n // the built-in forward logic, then installPipeline a default RenderPipelineAsset POD\n // (built inline, no AssetRegistry round-trip; D-19: installPipeline takes the payload,\n // there is no World at boot to allocate a shared ref against). install cannot fail here\n // (the id was just registered), so it throws -- a failure would be an engine-boot\n // invariant break, not part of the RhiError onError fan-out (PipelineError is a distinct\n // union).\n renderSystem.registerPipeline(URP_PIPELINE_ID, urpPipeline);\n // feat-20260608-cluster-lighting M2 / w10: HDRP cluster-forward registered (not installed).\n // installPipeline(hdrpAsset) is the explicit AI-user opt-in.\n renderSystem.registerPipeline(HDRP_PIPELINE_ID, hdrpPipeline);\n const defaultInstall = renderSystem.installPipeline({\n kind: 'render-pipeline',\n pipelineId: URP_PIPELINE_ID,\n });\n if (!defaultInstall.ok) throw defaultInstall.error;\n // One producer-owned completion signal for diagnostics, FPS reporting, and\n // RHI capture. It fires only after the record stage reaches queue submission.\n const frameEndListeners = new Set<() => void>();\n const attachedWorlds = new Map<World, () => void>();\n let surfaceReleased = false;\n\n const renderer: Renderer = {\n backend: 'webgpu',\n get device(): RhiDevice {\n return internals.device;\n },\n // Keep engine-owned shader consumers on the exact backend pack selected\n // for this renderer. Importing @forgeax/engine-rhi-webgpu again from a\n // feature glue module can produce a second bundled module instance whose\n // RAW_DEVICE_MAP does not contain this opaque RhiDevice handle.\n _internal_createShaderModule:\n internals.pack.createShaderModule ??\n ((device, desc) => invokeDeviceCreateShaderModule(device, desc)),\n get shader(): ShaderRegistry {\n return getShader();\n },\n assets,\n metrics,\n store: gpuStore,\n updateMesh(handle, vertices, indices, worldId = 0, submeshes) {\n return gpuStore.updateMesh(handle, vertices, indices, worldId, submeshes);\n },\n updateMeshVertexRange(handle, vertices, firstVertex, vertexCount, worldId = 0) {\n return gpuStore.updateMeshVertexRange(handle, vertices, firstVertex, vertexCount, worldId);\n },\n input: RENDERER_INPUT_FACADE,\n ready,\n ...(membershipTiming === undefined ? {} : { membershipTiming }),\n attachWorld(world: World): Result<void, RhiError> {\n if (disposed) {\n return err(\n new RhiError({\n code: 'rhi-not-available',\n expected: 'renderer not disposed before attaching a World',\n hint: 'rebuild the renderer before attaching another World',\n }),\n );\n }\n if (attachedWorlds.has(world)) return ok(undefined);\n try {\n const releaseTransforms = registerPropagateTransforms(world);\n attachedWorlds.set(world, releaseTransforms);\n return ok(undefined);\n } catch (cause) {\n const error = new RhiError({\n code: 'webgpu-runtime-error',\n expected: 'renderer.attachWorld(world) installs derived-state systems once',\n hint: 'inspect the World schedule registration or derived-state system failure',\n detail: {\n error: {\n code: 'unknown',\n message: cause instanceof Error ? cause.message : String(cause),\n ...(cause instanceof Error ? { name: cause.name } : {}),\n },\n },\n });\n internals.errorRegistry.fire(error);\n return err(error);\n }\n },\n detachWorld(world: World): void {\n const releaseTransforms = attachedWorlds.get(world);\n if (releaseTransforms === undefined) return;\n attachedWorlds.delete(world);\n releaseTransforms();\n renderSystem.detachWorld(world);\n },\n observeCurrentFrame(options) {\n return renderSystem.observeCurrentFrame(options);\n },\n get frustumStats() {\n return renderSystem.frustumStats;\n },\n get visibilityStats() {\n return renderSystem.visibilityStats;\n },\n get renderScene() {\n return renderSystem.renderScene;\n },\n get meshMaterialBindings() {\n return renderSystem.meshMaterialBindings;\n },\n get perFramePassNames() {\n return renderSystem.perFramePassNames;\n },\n get bindGroupCounts() {\n return renderSystem.bindGroupCounts;\n },\n renderFeatureDiagnostics() {\n return internals.featureHost?.diagnostics() ?? [];\n },\n subscribeRenderFeatureDiagnostics(listener) {\n return internals.featureHost?.subscribeDiagnostics(listener) ?? (() => undefined);\n },\n subscribeFrameEnd(listener) {\n frameEndListeners.add(listener);\n return () => {\n frameEndListeners.delete(listener);\n };\n },\n async installRenderFeature(\n feature: RenderFeature<unknown>,\n ): Promise<RenderResult<void, RenderError>> {\n if (disposed) {\n return err(\n new RenderFeatureStageFailedError(feature.identity, -1, 'extract', 'registration'),\n );\n }\n const host = internals.featureHost;\n if (host === undefined) {\n return err(\n new RenderFeatureStageFailedError(feature.identity, -1, 'extract', 'registration'),\n );\n }\n const missingCapability = feature.requiredCapabilities?.find(\n (capability) => internals.device.caps[capability] !== true,\n );\n if (missingCapability !== undefined) {\n return err(\n new RenderFeatureCapabilityMissingError(feature.identity, host.size, missingCapability),\n );\n }\n for (const materialShaderId of feature.requiredMaterialShaders ?? []) {\n const lookup = getShader().findMaterialArtifact(materialShaderId);\n if (!lookup.ok) {\n const error = new RhiError({\n code: 'shader-compile-failed',\n expected: `declared render feature material shader '${materialShaderId}' is present in the loaded manifest`,\n hint: `add material shader '${materialShaderId}' to the shader manifest or remove it from the feature declaration`,\n });\n internals.errorRegistry.fire(error);\n return err(\n new RenderFeatureStageFailedError(feature.identity, -1, 'prepare', 'registration'),\n );\n }\n const label = `module-${materialShaderId}`;\n const moduleResult = internals.pack.createShaderModule\n ? await internals.pack.createShaderModule(internals.device, {\n code: lookup.value.source,\n label,\n })\n : await invokeDeviceCreateShaderModule(internals.device, {\n code: lookup.value.source,\n label,\n });\n if (!moduleResult.ok) {\n internals.errorRegistry.fire(moduleResult.error);\n return err(\n new RenderFeatureStageFailedError(feature.identity, -1, 'prepare', 'registration'),\n );\n }\n getShaderModuleAdapter().seedModule(label, moduleResult.value);\n }\n const installed = host.install(feature);\n if (installed.ok) {\n for (const materialShaderId of feature.requiredMaterialShaders ?? []) {\n requiredMaterialShaderSet.add(materialShaderId);\n }\n requiredMaterialShaders = Object.freeze([...requiredMaterialShaderSet]);\n }\n return installed;\n },\n async uninstallRenderFeature(\n feature: RenderFeature<unknown>,\n ): Promise<RenderResult<void, RenderError>> {\n const host = internals.featureHost;\n if (disposed || host === undefined) {\n return err(\n new RenderFeatureStageFailedError(feature.identity, -1, 'dispose', 'registration'),\n );\n }\n try {\n await internals.device.queue.onSubmittedWorkDone();\n } catch {\n return err(\n new RenderFeatureStageFailedError(feature.identity, -1, 'dispose', 'registration'),\n );\n }\n const removed = host.uninstall(feature);\n if (removed.ok) {\n requiredMaterialShaderSet.clear();\n for (const remaining of host.features) {\n for (const materialShaderId of remaining.requiredMaterialShaders ?? []) {\n requiredMaterialShaderSet.add(materialShaderId);\n }\n }\n requiredMaterialShaders = Object.freeze([...requiredMaterialShaderSet]);\n }\n return removed;\n },\n draw(worlds: readonly World[], options: DrawOwnerOptions): Result<void, RhiError> {\n // feat-20260612-rhi-destroy-renderer-dispose-gpu-lifecycle / M5 / w21\n // (plan-strategy D-1, D-8): post-dispose the renderer is dead. AI\n // users observing `result.ok === false && err.code === 'rhi-not-\n // available'` know to rebuild the renderer (mirrors the \"ready not\n // settled\" + \"pipelineState null\" fail-fast paths below; reuses the\n // existing closed-union member, no new ErrorCode introduced).\n if (disposed) {\n const e = new RhiError({\n code: 'rhi-not-available',\n expected:\n 'renderer not disposed before calling renderer.draw(worlds, { cameraOwner, resourceOwner })',\n hint: 'renderer.dispose() flipped the lifecycle latch; rebuild via createRenderer / Engine.create',\n });\n internals.errorRegistry.fire(e);\n return err(e);\n }\n if (surfaceReleased) {\n return err(\n new RhiError({\n code: 'rhi-not-available',\n expected: 'renderer surface restored before drawing',\n hint: 'call renderer.restoreSurface() after the temporary surface owner stops',\n }),\n );\n }\n // M2 / w9 (A-IN-5): device-lost guard — draw() silently returns err\n // without firing onError each frame. The device-lost channel fires once\n // through the dual-channel fan-out (:750-797); draw() does not repeat it\n // (canvas holds previous frame). Host observes health().reason ===\n // 'device-lost' and calls recover() when ready.\n if (internals.healthRegistry.getLastSnapshot().reason === 'device-lost') {\n return err(\n new RhiError({\n code: 'rhi-not-available',\n expected: 'GPUDevice is lost; recover() to rebuild and resume rendering',\n hint: 'call renderer.recover() after a host-chosen delay; camera holds previous frame',\n }),\n );\n }\n // D-S4: ready not settled => fire onError + skip frame. Uses\n // 'rhi-not-available' (closed union placeholder semantics; charter\n // proposition 4 explicit failure - AI users observe through onError\n // and decide whether to retry).\n if (!readySettled) {\n const e = new RhiError({\n code: 'rhi-not-available',\n expected:\n 'await renderer.ready before calling renderer.draw(worlds, { cameraOwner, resourceOwner })',\n hint: 'await renderer.ready resolves once the manifest / pipeline / asset upload chain completes',\n });\n internals.errorRegistry.fire(e);\n return err(e);\n }\n // pipeline build rejected: ready Promise has already surfaced the\n // structured error to AI users through `await renderer.ready`. Skip\n // to keep draw(world) idempotent; a transient retry next frame is\n // the responsibility of the AI user (charter proposition 9).\n if (pipelineState === null) {\n const e = new RhiError({\n code: 'rhi-not-available',\n expected: 'pipelineState built during Renderer.ready',\n hint: 'await renderer.ready resolved successfully; rebuild renderer or fix the upstream RhiError',\n });\n internals.errorRegistry.fire(e);\n return err(e);\n }\n // feat-20260708-composited-multi-world-rendering M3 / D-5: draw-args\n // entry validation runs before any extract or context configuration.\n // Empty worlds / owner out of range returns a structured Result.err\n // (never silent, charter P3) without touching GPU state. The two codes\n // are non-exclusive: an empty array short-circuits to empty-worlds. The\n // check is defensive against JS callers passing a non-array despite the\n // compile-time World[] type (red-window migration safety).\n const worldCount = Array.isArray(worlds) ? worlds.length : 0;\n if (worldCount === 0 && internals.device.caps.backendKind === 'null') {\n return ok(undefined);\n }\n // Validate both owner indices (cameraOwner before resourceOwner, first\n // offender wins). The empty object only protects the JS boundary; it is\n // rejected by the same validation and never becomes another draw shape.\n const drawOwners = options ?? ({} as DrawOwnerOptions);\n const argsCheck = validateDrawArgs(worldCount, drawOwners);\n if (!argsCheck.ok) {\n internals.errorRegistry.fire(argsCheck.error);\n return argsCheck;\n }\n const unattachedWorld = worlds.findIndex((world) => !attachedWorlds.has(world));\n if (unattachedWorld >= 0) {\n const e = new RhiError({\n code: 'webgpu-runtime-error',\n expected: 'each World passed to draw is attached to this Renderer',\n hint: `call renderer.attachWorld(world) before draw; World index ${unattachedWorld} is not attached`,\n });\n internals.errorRegistry.fire(e);\n return err(e);\n }\n // Host publication boundary: successful World.update has completed all\n // user schedules; renderer-owned scene projections are derived exactly\n // once immediately before extraction and recording.\n for (const world of worlds) {\n tilemapChunkExtractSystem(world, (guid) => assets.lookup(guid));\n const glyphResult = glyphTextLayoutSystem(world, gpuStore);\n if (!glyphResult.ok) {\n (\n world as World & { _routeError(error: unknown, context: { systemName: string }): void }\n )._routeError(glyphResult.error, { systemName: 'glyphTextLayoutSystem' });\n }\n }\n // Configure context lazily on first draw (D-S1 single-point\n // exemption): GPUCanvasContext.configure({device}) needs a raw\n // GPUDevice; main.ts passes it via RendererOptions.rawDeviceForContextConfigure.\n ensureContextConfigured(internals, pipelineState, internals.errorRegistry);\n // w24 — facade-level try/catch produces Result.err on unexpected throw\n // (D-P6 dual-channel preserved: per-stage RhiError continues to fan out\n // through onError separately; the facade Result is the synchronous\n // summary AI users can ignore or branch on).\n try {\n const submitted = renderSystem.draw(worlds, options);\n if (submitted) {\n for (const fn of frameEndListeners) {\n fn();\n }\n internals.pack.instrumentation?.onFrameBoundary?.();\n }\n return ok(undefined);\n } catch (cause) {\n const error =\n cause instanceof Error\n ? { code: 'unknown' as const, message: cause.message, name: cause.name }\n : { code: 'unknown' as const, message: String(cause) };\n const e = new RhiError({\n code: 'webgpu-runtime-error',\n expected:\n 'renderSystem.draw(worlds, { cameraOwner, resourceOwner }) completes without throwing',\n hint: `RenderSystem internal error: ${error.message}`,\n detail: { error },\n });\n internals.errorRegistry.fire(e);\n return err(e);\n }\n },\n async readPixels(): Promise<Result<Uint8Array, RhiError>> {\n // Read the canvas's current pixel contents back into an RGBA Uint8Array\n // via the lowest-common-denominator browser path: createImageBitmap ->\n // OffscreenCanvas 2D drawImage -> getImageData. The WebGPU canvas's\n // GPUTexture is not directly readable via getImageData, so this 2D\n // bounce is the canonical browser path. Returns top-left origin RGBA\n // (the natural getImageData convention); apps that need bottom-left\n // origin (parity with gl.readPixels) Y-flip on top of the result.\n const target = internals.canvas;\n try {\n const bmp = await createImageBitmap(target);\n const off = new OffscreenCanvas(target.width, target.height);\n const ctx2d = off.getContext('2d', { willReadFrequently: true });\n if (ctx2d === null) {\n bmp.close();\n return err(\n new RhiError({\n code: 'webgpu-runtime-error',\n expected: 'OffscreenCanvas 2D context available',\n hint: 'browser does not expose a 2D context on OffscreenCanvas; readPixels requires the OffscreenCanvas + 2D ctx + getImageData browser combo',\n detail: {\n error: {\n code: 'unknown',\n message: 'OffscreenCanvas.getContext(\"2d\") returned null',\n },\n },\n }),\n );\n }\n ctx2d.drawImage(bmp, 0, 0);\n const imgData = ctx2d.getImageData(0, 0, target.width, target.height);\n bmp.close();\n return ok(\n new Uint8Array(imgData.data.buffer, imgData.data.byteOffset, imgData.data.byteLength),\n );\n } catch (caught: unknown) {\n const message = caught instanceof Error ? caught.message : String(caught);\n return err(\n new RhiError({\n code: 'webgpu-runtime-error',\n expected: 'createImageBitmap + OffscreenCanvas 2D pipeline succeeds',\n hint: 'pixel readback failed; verify the canvas has been drawn to and the browser supports OffscreenCanvas + createImageBitmap',\n detail: { error: { code: 'unknown', message } },\n }),\n );\n }\n },\n releaseSurface(): Result<void, RhiError> {\n if (surfaceReleased) return ok(undefined);\n if (disposed) {\n return err(\n new RhiError({\n code: 'rhi-not-available',\n expected: 'live renderer before releasing its surface',\n hint: 'create a new Renderer; disposed renderers are terminal',\n }),\n );\n }\n try {\n internals.context.unconfigure();\n if (pipelineState !== null) pipelineState.perPassResources.configured = false;\n surfaceReleased = true;\n return ok(undefined);\n } catch (cause) {\n return err(wrapDisposeError(cause, 'context.unconfigure'));\n }\n },\n restoreSurface(): Result<void, RhiError> {\n if (!surfaceReleased) return ok(undefined);\n if (disposed) {\n return err(\n new RhiError({\n code: 'rhi-not-available',\n expected: 'live renderer before restoring its surface',\n hint: 'create a new Renderer; disposed renderers are terminal',\n }),\n );\n }\n surfaceReleased = false;\n return ok(undefined);\n },\n /**\n * Release every GPU resource the renderer owns + detach the listener\n * registries; flip the `disposed` latch so subsequent `draw(world)`\n * calls fail-fast with `'rhi-not-available'`.\n *\n * feat-20260612-rhi-destroy-renderer-dispose-gpu-lifecycle / M5 / w21\n * 6-step cascade (plan-strategy D-2 ordering):\n * 1. `context.unconfigure()` -- release the current surface image\n * 2. `gpuStore.destroyAll()` -- texture / cubemap / mesh maps\n * 3. `renderSystem.disposeFrameState()` -- graph.drain() + instanceBuffers\n * 4. `featureHost.dispose()` -- feature resources + lifecycle\n * 5. `clearIblCacheForDevice(device)` -- per-device IBL pipeline cache\n * 6. `lostRegistry.clear() / errorRegistry.clear()`\n *\n * Each step runs inside its own try/catch (D-3 method A): a sub-step\n * failure DOES NOT halt the cascade; the structured RhiError (or wrapped\n * runtime exception) fans out through `errorRegistry.fire` so AI users\n * observing `renderer.onError` see every dispose-time fault. The\n * `disposed` latch flips up-front so a re-entrant dispose (or a draw\n * that races with the cascade) short-circuits.\n *\n * NOT calling `device.destroy()` on the raw GPUDevice (w25 lesson from\n * feat-20260517-vite-plugin-image-build-time-cook CI-fix v4): w23\n * attempted to evict stale devices from the chromium WebGPU adapter\n * pool via `_internal_getRawDevice`, but the explicit destroy\n * accelerated pool poisoning -- after the first `dispose()` the\n * chromium adapter pool started recycling the just-destroyed device\n * into the next `requestDevice` so the NEXT test's `Engine.create`\n * resolved with `ready.error.code: 'device-lost'`. Cross-test isolation\n * moved to the vitest infra layer (`browser.isolate: true`) instead of\n * test code self-managing device lifecycle.\n *\n * Stays in sync with the `Renderer.dispose` row of the README \"API index\".\n */\n dispose(): void {\n if (disposed) return;\n disposed = true;\n detachDeviceLostFanout();\n detachDeviceUncapturedErrorFanout();\n membershipTiming?.dispose();\n for (const releaseTransforms of attachedWorlds.values()) releaseTransforms();\n attachedWorlds.clear();\n // Release the current swap-chain image before destroying any resource\n // wrappers that may share its underlying device allocation. The wgpu\n // WebGL2 surface owns an explicit SurfaceTexture; leaving this until\n // after the resource sweep lets wasm drop it against a dead Surface.\n if (!surfaceReleased) {\n try {\n internals.context.unconfigure();\n } catch (cause) {\n internals.errorRegistry.fire(wrapDisposeError(cause, 'context.unconfigure'));\n }\n }\n // Step 2: release every Buffer / Texture handle owned by the runtime\n // GPU residency layer (feat-20260601-gpu-resource-store-extraction).\n try {\n gpuStore.destroyAll();\n } catch (cause) {\n internals.errorRegistry.fire(wrapDisposeError(cause, 'gpuStore.destroyAll'));\n }\n // Step 3: drain the per-frame render-graph pool + the per-entity\n // instanceBuffers GPU storage cache. Both walks live on the\n // RenderSystem closure (frameState is closure-private).\n try {\n renderSystem.disposeFrameState();\n } catch (cause) {\n internals.errorRegistry.fire(wrapDisposeError(cause, 'renderSystem.disposeFrameState'));\n }\n try {\n renderSystem.releaseProfilerCatalog();\n } catch (cause) {\n internals.errorRegistry.fire(\n wrapDisposeError(cause, 'renderSystem.releaseProfilerCatalog'),\n );\n }\n // Step 4: release feature-owned resources and invoke feature disposal\n // hooks after render-graph state has been drained. The host is already\n // idempotent, and its structured cleanup detail is preserved by the\n // error registry when a feature cleanup fails.\n try {\n const featureDispose = internals.featureHost?.dispose();\n if (featureDispose !== undefined && !featureDispose.ok) {\n internals.errorRegistry.fire(featureDispose.error);\n }\n } catch (cause) {\n internals.errorRegistry.fire(wrapDisposeError(cause, 'featureHost.dispose'));\n }\n // Step 5: drop the per-device IBL pipeline cache entry. The GPU\n // pipeline / texture handles inside the entry are released\n // implicitly when the device tears down (spec contract); clearing\n // the WeakMap entry lets GC reclaim the JS-side cache record.\n try {\n clearIblCacheForDevice(internals.device);\n } catch (cause) {\n internals.errorRegistry.fire(wrapDisposeError(cause, 'clearIblCacheForDevice'));\n }\n // Step 6: detach the listener registries so any post-dispose error\n // event (race with the spec layer) does not fan out to user-supplied\n // listeners (charter P3 explicit failure: post-dispose the renderer\n // is dead, no observable side-effects). Performed last so steps 1-5\n // can still surface failures through `errorRegistry.fire`.\n try {\n internals.lostRegistry.clear();\n internals.errorRegistry.clear();\n } catch {\n // listener-registry clear() is best-effort cleanup at the very end\n // of dispose; no further fan-out channel survives.\n }\n },\n onError(listener: RendererErrorListener): () => void {\n return internals.errorRegistry.add(listener);\n },\n onLost(listener: RendererLostListener): () => void {\n return internals.lostRegistry.add(listener);\n },\n health(): HealthSnapshot {\n return internals.healthRegistry.getLastSnapshot();\n },\n recover(): Promise<Result<void, RecoverError>> {\n if (recoverInFlight !== undefined) return recoverInFlight;\n recoverInFlight = (async () => {\n // feat-20260622-s5 M3 / w17 (A-IN-3 / D-1): single idempotent device\n // rebuild. One attempt only — no loop, no backoff, no timer, no extra\n // in-flight health state (A-OOS-1); the host owns the cadence of calling\n // this again. Fail-Fast entry guards (architecture-principles #5):\n // disposed renderer or non-device-lost state short-circuits before any\n // GPU work.\n if (disposed) {\n // A-IN-6: disposed latch wins; recover() never rebuilds a dead\n // renderer. `recover-not-needed` is the sentinel (no degraded state to\n // recover from on a disposed renderer).\n return err(new RecoverError('recover-not-needed'));\n }\n const snapshot = internals.healthRegistry.getLastSnapshot();\n // A-AC-08: `alive` (including the alive state after a prior successful\n // recover) is a no-op signal — idempotent second call.\n if (snapshot.reason !== 'device-lost') {\n return err(new RecoverError('recover-not-needed'));\n }\n\n // Step (a): release every GPU resource owned by the lost device. The CPU\n // POD caches (AssetRegistry catalog/payload, pack cache) are NOT touched\n // (A-AC-12) — only the GpuResourceStore + canvas context are torn down.\n gpuStore.destroyAll();\n // The shader adapter owns a per-device module cache. Reusing it after a\n // loss would hand PSO construction opaque ShaderModule handles minted by\n // the dead device, which can invalidate the first post-recovery command\n // buffer (or crash the browser GPU process). Keep the ShaderRegistry's\n // CPU material/source catalogue, but rebuild this device-bound adapter.\n clearIblCacheForDevice(internals.device);\n sharedShaderModuleAdapter = null;\n // The fullscreen post-process builder keeps one empty group-0 layout\n // outside RenderSystem's frame cache. It is also device-bound, so retain\n // the source/registration but force the next post-process pass to derive\n // a layout from the replacement device.\n emptyPostProcessBgl = null;\n internals.context.unconfigure();\n\n // Step (b) / B-2 / B-AC-02: shed device-bound RenderSystem state minted by\n // the lost device — the render-graph pendingDestroy queue (its PooledTextures\n // belong to the lost device; the clear skips device.destroyTexture, mirroring\n // the null-device fast path) plus device-bound post-process resources.\n // RenderSystem snapshots the CPU declarations, clears old UBOs, and\n // replays them after the replacement device is live.\n renderSystem.resetForRecover();\n\n // Step (c): re-acquire device through the SAME backend pack (the\n // idempotent factory primitives tryCreateWebGPURenderer uses). On the\n // adapter / device failure paths, health stays `device-lost` (A-AC-07):\n // recover() never fakes the renderer back to `alive`.\n const adapterResult = await internals.pack.rhi.requestAdapter(undefined, internals.canvas);\n if (!adapterResult.ok) {\n return err(new RecoverError('recover-adapter-unavailable'));\n }\n let device: RhiDevice;\n try {\n const deviceResult = await adapterResult.value.requestDevice(\n deviceOptionsForAdapter(adapterResult.value, internals.options?.membershipTiming),\n );\n if (!deviceResult.ok) {\n return err(new RecoverError('recover-device-unavailable'));\n }\n device = deviceResult.value;\n } catch {\n return err(new RecoverError('recover-device-unavailable'));\n }\n if (disposed) return err(new RecoverError('recover-not-needed'));\n const ctxResult = internals.pack.rhi.acquireCanvasContext(internals.canvas);\n if (!ctxResult.ok) {\n return err(new RecoverError('recover-device-unavailable'));\n }\n\n // Fence every callback owned by the old device at the swap boundary.\n // Both device.lost and GPUUncapturedErrorEvent can arrive after the\n // replacement is alive; neither is allowed to poison current health.\n detachDeviceLostFanout();\n detachDeviceUncapturedErrorFanout();\n\n // Step (d): swap in the new device + context. Downstream reads device via\n // getters off `internals` (RenderSystem, ensureContextConfigured), so the\n // swap is observed without reconstructing the RenderSystem.\n internals.device = device;\n internals.context = ctxResult.value;\n membershipTiming?.bindDevice(device);\n renderSystem.restoreGpuDrivenForRecover();\n\n // Re-attach the device.lost fan-out to the new device's lost Promise,\n // reusing the SAME registries the host already subscribed to (SSOT\n // helper). When this device is lost again, health() flips to\n // `device-lost` and the host can call recover() once more.\n detachDeviceLostFanout = attachDeviceLostFanout(device, internals.pack, {\n lostRegistry: internals.lostRegistry,\n errorRegistry: internals.errorRegistry,\n healthRegistry: internals.healthRegistry,\n onDeviceLost: (detail) => membershipTiming?.markDeviceLost(detail),\n });\n detachDeviceUncapturedErrorFanout = attachDeviceUncapturedErrorFanout(\n device,\n internals.pack,\n internals.errorRegistry,\n );\n\n // Step (e): rebuild GPU-bound state against the new device. The per-shader\n // PSO + layout caches hold handles minted by the lost device; drop them so\n // the rebuild compiles fresh PSOs. configureGpuDevice + prepareMaterialShaders\n // + buildPipeline reuse the exact boot-time assembly (the closures capture\n // stable references; only `internals.device` changed).\n materialShaderPipelineCache.clear();\n perShaderMaterialLayoutCache.clear();\n group0ResourceLayouts.clear();\n viewWithResourceLayouts.clear();\n preparedMaterialPipelineLayoutCache.clear();\n group0MaterialLayout = null;\n viewOnlyMaterialPipelineLayout = null;\n bootMaterialLayoutInputs = null;\n gpuStore.configureGpuDevice(\n // biome-ignore lint/suspicious/noExplicitAny: MipmapBlitDevice descriptors are typed `any`; RhiDevice satisfies the shape\n internals.device as any,\n internals.pack.createShaderModule as unknown as MipmapShaderModuleFactory | undefined,\n (world, pod) => {\n const handle = world.allocSharedRef('EquirectAsset', pod);\n return ok(handle);\n },\n internals.device.caps,\n );\n // A device loss invalidates the transient video textures too. Rebind\n // through the store owner so its cached textures are destroyed before\n // the first post-recovery upload; unlike CPU asset payloads, these\n // handles cannot survive a device replacement.\n dynamicTextureStore.configureGpuDevice(\n // biome-ignore lint/suspicious/noExplicitAny: DynamicTextureDevice is a structural subset of RhiDevice\n internals.device as any,\n );\n const abortDisposedRecovery = (): Result<void, RecoverError> | undefined => {\n if (!disposed) return undefined;\n gpuStore.destroyAll();\n renderSystem.disposeFrameState();\n clearIblCacheForDevice(internals.device);\n materialShaderPipelineCache.clear();\n perShaderMaterialLayoutCache.clear();\n group0ResourceLayouts.clear();\n viewWithResourceLayouts.clear();\n preparedMaterialPipelineLayoutCache.clear();\n group0MaterialLayout = null;\n viewOnlyMaterialPipelineLayout = null;\n bootMaterialLayoutInputs = null;\n pipelineState = null;\n return err(new RecoverError('recover-not-needed'));\n };\n try {\n await prepareMaterialShaders(internals.device, getShader, materialShaderUvSetCounts);\n const abortedAfterShaders = abortDisposedRecovery();\n if (abortedAfterShaders !== undefined) return abortedAfterShaders;\n pipelineState = await buildPipeline();\n const abortedAfterPipeline = abortDisposedRecovery();\n if (abortedAfterPipeline !== undefined) return abortedAfterPipeline;\n renderSystem.restorePostProcessResources();\n } catch {\n // Pipeline rebuild failed against the new device. Treat as a device\n // unavailability (the device was acquired but is not usable); health\n // stays `device-lost` so the host can retry.\n const aborted = abortDisposedRecovery();\n if (aborted !== undefined) return aborted;\n return err(new RecoverError('recover-device-unavailable'));\n }\n const abortedAfterPostProcess = abortDisposedRecovery();\n if (abortedAfterPostProcess !== undefined) return abortedAfterPostProcess;\n\n // Re-evaluate feature capability gates against the replacement device.\n // Feature recovery is isolated from renderer recovery: a feature that is\n // still unsupported or fails its hook remains diagnosed as disabled or\n // failed while the zero-feature renderer can become alive.\n const featureRecover = internals.featureHost?.recover({\n caps: internals.device.caps,\n frameNumber: 0,\n });\n if (featureRecover !== undefined && !featureRecover.ok) {\n internals.errorRegistry.fire(featureRecover.error);\n }\n\n // Chromium retains a transparent canvas backing store after the GPU\n // process/device is replaced, even when the logical drawing-buffer\n // size is unchanged. Reassert the same dimensions so the next draw\n // creates a live swap-chain image on both HTMLCanvasElement and\n // OffscreenCanvas without making the host invent a recovery-only\n // resize operation.\n const recoveredWidth = internals.canvas.width;\n const recoveredHeight = internals.canvas.height;\n internals.canvas.width = recoveredWidth;\n internals.canvas.height = recoveredHeight;\n\n // Step (f): the renderer is alive again. The next draw() lazily\n // re-configures the canvas context (ensureContextConfigured keys off the\n // fresh pipelineState's `configured` flag) and re-uploads GPU resources\n // via ensureResident from the preserved CPU POD caches (A-AC-12).\n internals.healthRegistry.fire({ reason: 'alive', recoverable: false });\n return ok(undefined);\n })().finally(() => {\n recoverInFlight = undefined;\n });\n return recoverInFlight;\n },\n onHealthChange(cb: HealthChangeListener): () => void {\n return internals.healthRegistry.add(cb);\n },\n async debugReadback() {\n if (pipelineState === null) return null;\n return debugReadbackShadowDepth(internals, pipelineState);\n },\n // feat-20260520-directional-light-shadow-mapping M3 / w16 (D-6 + AC-13):\n // debugSampleShadowFactor renders one pixel per probe through the\n // shadow-probe pipeline (constructed in createPipelineState) and reads\n // back the resulting rgba32float values. The probe shader uses the same\n // atlas UV remap, dynamic PCF kernel, comparison sampler, and bias formula\n // as pbr.wgsl::evalDirectional(). The per-probe input w lane carries the\n // exact production bias computed from the supplied surface normal. The\n // four output lanes are shadow factor, center atlas depth, selected\n // cascade index, and receiver depth. Caps at PROBE_MAX_COUNT (64); excess\n // inputs are dropped with no error.\n //\n // Separate command encoder per the M1c lesson (see feat-20260520\n // commit ceff773b): binding the shadow RT as both depth-attachment\n // (write) and texture-binding (read) inside the same encoder triggers\n // WebGPU \"usage scope\" validation and silently drops one side.\n async debugSampleShadowFactor(\n worldPositions: ReadonlyArray<readonly [number, number, number]>,\n options?: {\n readonly surfaceNormals?: ReadonlyArray<readonly [number, number, number]>;\n },\n ): Promise<ReadonlyArray<{\n readonly shadowFactor: number;\n readonly sampledDepth: number;\n readonly cascadeIndex: number;\n readonly receiverDepth: number;\n readonly bias: number;\n }> | null> {\n if (pipelineState === null) return null;\n const state = pipelineState;\n if (\n state.shadowProbePipeline === null ||\n state.shadowProbeBindGroupLayout === null ||\n state.shadowProbeLsmUbo === null ||\n state.shadowProbeInputBuf === null ||\n state.shadowProbeOutputView === null ||\n state.shadowProbeOutputTex === null ||\n state.shadowProbeStagingBuf === null\n ) {\n return null;\n }\n // feat-20260613-csm-cascaded-shadow-maps M5 / w28: probe consumes\n // the 4-cascade lightViewProj pack + cascadeCount; falls through to\n // single-cascade when the CSM pack hasn't been populated (e.g.\n // pre-extract first frame).\n const csmPack = state.perPassResources.shadowCsmLightViewProj;\n const cascadeCount = state.perPassResources.shadowCascadeCount;\n const lsm = state.perPassResources.shadowLightSpaceMatrix;\n const csmSelection = state.perPassResources.shadowCsmSelection;\n const outgoingLightDirection = state.perPassResources.shadowLightDirection;\n const depthBias = state.perPassResources.shadowDepthBias;\n const normalBias = state.perPassResources.shadowNormalBias;\n const pcfKernelSize = state.perPassResources.shadowPcfKernelSize;\n // No shadow caster → all points are fully lit (1.0). Return identity\n // values so callers (e.g. shadow-quality-metrics falsify probe) can\n // distinguish \"no shadow\" from \"probe not compiled\".\n if (csmPack === null && lsm === null) {\n return worldPositions.slice(0, PROBE_MAX_COUNT).map(() => ({\n shadowFactor: 1,\n sampledDepth: 1,\n cascadeIndex: -1,\n receiverDepth: 1,\n bias: SHADOW_PROBE_BIAS,\n }));\n }\n // M5-T2: shadow texture view resolved via render-graph getter\n // (`renderSystem.getCurrentShadowView()` -> graph\n // `addColorTarget('shadowDepth', ...)`); the ECS-managed\n // perPassResources slot was deleted in this milestone (D-2\n // SSOT). Falls back to the 1x1 fallback view when the graph\n // has not allocated the target (castShadow:false or\n // shadowMapSize=0).\n const graphShadowView = renderSystem.getCurrentShadowView();\n const probeShadowView =\n graphShadowView !== null ? graphShadowView : state.shadowFallbackTextureView;\n\n const requested = worldPositions.length;\n const probeCount = Math.min(requested, PROBE_MAX_COUNT);\n const defaultNormal: readonly [number, number, number] = [0, 1, 0];\n const normalAt = (index: number): readonly [number, number, number] => {\n const normal = options?.surfaceNormals?.[index];\n return normal ?? defaultNormal;\n };\n const biasAt = (index: number): number =>\n shadowProbeBias(\n normalAt(index),\n outgoingLightDirection ?? undefined,\n depthBias,\n normalBias,\n );\n\n // Pack worldPositions into vec4<f32>[64] (16 B per slot; w carries the\n // producer-equivalent receiver bias).\n // Slots beyond probeCount are zero-padded — fs_main never reads them\n // because instanceCount = probeCount.\n const inputData = new Float32Array(PROBE_MAX_COUNT * 4);\n for (let i = 0; i < probeCount; i++) {\n const p = worldPositions[i];\n if (p === undefined) continue;\n const base = i * 4;\n inputData[base] = p[0];\n inputData[base + 1] = p[1];\n inputData[base + 2] = p[2];\n inputData[base + 3] = biasAt(i);\n }\n\n const inputUploadResult = internals.device.queue.writeBuffer(\n state.shadowProbeInputBuf,\n 0,\n inputData.buffer,\n inputData.byteOffset,\n inputData.byteLength,\n );\n if (!inputUploadResult.ok) {\n internals.errorRegistry.fire(inputUploadResult.error);\n return null;\n }\n\n // LSM UBO write: PROBE_LSM_UBO_BYTES bytes. Layout mirrors the\n // SHADOW_PROBE_WGSL `CsmLsm` struct and carries the producer-owned\n // view-space selector facts alongside the cascade matrices.\n // When only the legacy single-mat4 lsm is available (CSM pack null),\n // duplicate it across all 4 cascade slots so the probe still works\n // pre-extract or in single-cascade legacy paths.\n const lsmBytes = new Float32Array(PROBE_LSM_UBO_BYTES / 4);\n const baseMat = csmPack ?? null;\n if (baseMat !== null) {\n for (let i = 0; i < 64; i++) lsmBytes[i] = baseMat[i] ?? 0;\n } else if (lsm !== null) {\n for (let c = 0; c < 4; c++) {\n for (let i = 0; i < 16; i++) lsmBytes[c * 16 + i] = lsm[i] ?? 0;\n }\n }\n if (csmSelection !== null) {\n for (let i = 0; i < 16; i++) lsmBytes[64 + i] = csmSelection.viewMatrix[i] ?? 0;\n for (let i = 0; i < 4; i++) lsmBytes[80 + i] = csmSelection.splitPlanes[i] ?? 0;\n lsmBytes[86] = csmSelection.cascadeBlend;\n }\n // cascadeCount (u32) at byte 336 -> float index 84. Use a Uint32 view\n // sharing the underlying buffer so the value stays a u32 word.\n const lsmU32 = new Uint32Array(lsmBytes.buffer);\n lsmU32[84] = Math.max(1, cascadeCount) >>> 0;\n lsmU32[85] = Math.max(1, pcfKernelSize) >>> 0;\n const lsmUploadResult = internals.device.queue.writeBuffer(\n state.shadowProbeLsmUbo,\n 0,\n lsmBytes.buffer,\n lsmBytes.byteOffset,\n PROBE_LSM_UBO_BYTES,\n );\n if (!lsmUploadResult.ok) {\n internals.errorRegistry.fire(lsmUploadResult.error);\n return null;\n }\n\n // Transient probe BindGroup: binds the **active** shadow texture view\n // (not the 1x1 fallback when a real shadow map exists) + the **same**\n // comparison sampler the main pass viewBindGroup binding(4) uses, so\n // probe + geometry pass cannot drift on sampler config.\n const probeBgResult = internals.device.createBindGroup({\n label: 'shadow-probe-bg',\n layout: state.shadowProbeBindGroupLayout,\n entries: [\n {\n binding: 0,\n resource: { kind: 'buffer', value: { buffer: state.shadowProbeLsmUbo } },\n },\n {\n binding: 1,\n resource: { kind: 'buffer', value: { buffer: state.shadowProbeInputBuf } },\n },\n {\n binding: 2,\n resource: { kind: 'textureView', value: probeShadowView },\n },\n {\n binding: 3,\n resource: { kind: 'sampler', value: state.perPassResources.shadowSampler },\n },\n ],\n });\n if (!probeBgResult.ok) {\n internals.errorRegistry.fire(probeBgResult.error);\n return null;\n }\n const probeBg = probeBgResult.value;\n\n // Separate command encoder per M1c lesson — must not share with any\n // in-flight encoder that binds the shadow RT as RenderAttachment.\n const encResult = internals.device.createCommandEncoder({\n label: 'shadow-probe-encoder',\n });\n if (!encResult.ok) {\n internals.errorRegistry.fire(encResult.error);\n return null;\n }\n const enc = encResult.value;\n\n // Clear value: r=1.0 means \"fully lit\"; g=1.0 is the empty-atlas\n // depth sentinel; b=-1.0 marks no selected cascade; a=1.0 is the\n // receiver-depth sentinel. Slots beyond probeCount land here, and any\n // fragments outside the rasterised columns (none, since we cover the\n // full RT row exactly) would also default to these sentinels.\n const probePass = enc.beginRenderPass({\n label: 'shadow-probe-pass',\n colorAttachments: [\n {\n view: state.shadowProbeOutputView,\n loadOp: 'clear',\n storeOp: 'store',\n clearValue: { r: 1, g: 1, b: -1, a: 1 },\n },\n ],\n } as never);\n probePass.setPipeline(state.shadowProbePipeline);\n probePass.setBindGroup(0, probeBg);\n probePass.draw(6, probeCount, 0, 0);\n probePass.end();\n\n enc.copyTextureToBuffer(\n { texture: state.shadowProbeOutputTex as never, aspect: 'all' },\n {\n buffer: state.shadowProbeStagingBuf as never,\n bytesPerRow: PROBE_READBACK_ROW_BYTES,\n rowsPerImage: 1,\n },\n { width: PROBE_MAX_COUNT, height: 1, depthOrArrayLayers: 1 },\n );\n\n const finishResult = enc.finish();\n if (!finishResult.ok) {\n internals.errorRegistry.fire(finishResult.error);\n return null;\n }\n const submitResult = internals.device.queue.submit([finishResult.value]);\n if (!submitResult.ok) {\n internals.errorRegistry.fire(submitResult.error);\n return null;\n }\n\n const mapResult = await state.shadowProbeStagingBuf.mapAsync(1);\n if (!mapResult.ok) {\n internals.errorRegistry.fire(mapResult.error);\n return null;\n }\n const mappedBuf = mapResult.value;\n const rangeResult = mappedBuf.getMappedRange();\n if (!rangeResult.ok) {\n internals.errorRegistry.fire(rangeResult.error);\n return null;\n }\n const data = new Float32Array(rangeResult.value);\n const results: {\n shadowFactor: number;\n sampledDepth: number;\n cascadeIndex: number;\n receiverDepth: number;\n bias: number;\n }[] = [];\n for (let i = 0; i < requested; i++) {\n if (i < probeCount) {\n const base = i * 4;\n results.push({\n shadowFactor: data[base] ?? 1,\n sampledDepth: data[base + 1] ?? 1,\n cascadeIndex: Math.round(data[base + 2] ?? -1),\n receiverDepth: data[base + 3] ?? 1,\n bias: biasAt(i),\n });\n } else {\n // Caller asked for more than PROBE_MAX_COUNT; surface a sentinel\n // result so length matches the request without inventing a new\n // error code (charter F2 minimal surface).\n results.push({\n shadowFactor: 1,\n sampledDepth: 1,\n cascadeIndex: -1,\n receiverDepth: 1,\n bias: biasAt(i),\n });\n }\n }\n mappedBuf.unmap();\n\n return results;\n },\n get directionalShadow() {\n if (pipelineState === null) return null;\n return directionalShadowSnapshot(pipelineState);\n },\n // feat-20260601-customizable-render-pipeline-seam M1 / w8: 1:1 forwards to the\n // RenderSystem layer (plan-strategy D-D: all real logic lives there; the facade is a\n // zero-processing pass-through, same pattern as the perFramePassNames getter above).\n registerPipeline(id, impl) {\n renderSystem.registerPipeline(id, impl);\n },\n installPipeline(asset) {\n return renderSystem.installPipeline(asset);\n },\n // F-2 fix-up: 1:1 forward to RenderSystem.postProcess.register (D-D zero\n // processing — the registry + dedup live on the RenderSystem closure).\n postProcess: {\n register(id, entry) {\n return renderSystem.postProcess.register(id, entry);\n },\n },\n // feat-20260612-skin-palette-per-frame-upload M1 / m1-1: @internal test\n // hatch — returns the closure-held `pipelineState` (or `null` before\n // `await renderer.ready` settles). Same shape as `getPipelineState`\n // already passed into `createRenderSystem` above, exposed on the public\n // Renderer object for unit tests asserting PipelineState field presence\n // (e.g. `skinPaletteAllocator` after stub retirement). Returns `unknown`\n // so the public surface stays opaque; callers cast at the test boundary.\n _internal_getPipelineState() {\n return pipelineState;\n },\n };\n return renderer;\n}\n\n// ─── feat-20260520-directional-light-shadow-mapping M1c / w8 helpers ────────\n\n/**\n * debugReadbackShadowDepth: reads 5 depth pixels from the shadow RT via\n * copyTextureToBuffer + mapAsync + Float32Array direct read.\n *\n * D-2 round-3: format = depth32float -> Float32Array direct read;\n * no 24-in-32 unorm decode. D-5: 5 pixel integer coordinates\n * (center + 4 corners), whole-image copy with 256B-aligned row stride,\n * JS-side strided read of the 5 target pixels.\n */\nasync function debugReadbackShadowDepth(\n internals: WebGPURendererInternals,\n state: PipelineState,\n): Promise<{\n readonly center: number;\n readonly corners: {\n readonly tl: number;\n readonly tr: number;\n readonly bl: number;\n readonly br: number;\n };\n readonly mapSize: number;\n} | null> {\n const tex = state.perPassResources.shadowTexture;\n if (tex === null) return null;\n const mapSize = state.perPassResources.shadowMapSize;\n if (mapSize <= 0) return null;\n\n // feat-20260613-csm-cascaded-shadow-maps M5 / w28: shadow texture is now\n // the exact atlas produced by directionalCascadeAtlasSize. In particular,\n // two cascades occupy 2*mapSize by mapSize, not a square 2*mapSize atlas.\n // depth32float copyTextureToBuffer requires copying the entire\n // subresource, so we read the full atlas and slice the cascade-0\n // quadrant for the legacy center / corners API contract.\n const cascadeCount = Math.max(1, state.perPassResources.shadowCascadeCount);\n const fallbackAtlasSize = directionalCascadeAtlasSize(cascadeCount, mapSize);\n const atlasSize = {\n width:\n state.perPassResources.shadowAtlasWidth > 0\n ? state.perPassResources.shadowAtlasWidth\n : fallbackAtlasSize.width,\n height:\n state.perPassResources.shadowAtlasHeight > 0\n ? state.perPassResources.shadowAtlasHeight\n : fallbackAtlasSize.height,\n };\n\n const bytesPerPixel = 4; // depth32float\n const rowBytes = atlasSize.width * bytesPerPixel;\n // 256B alignment per WebGPU spec copyTextureToBuffer bytesPerRow requirement\n const alignedRowBytes = ((rowBytes + 255) >> 8) << 8;\n const totalBytes = alignedRowBytes * atlasSize.height;\n\n const bufResult = internals.device.createBuffer({\n label: 'shadow-readback-staging',\n size: totalBytes,\n usage: GPU_BUFFER_USAGE_COPY_DST | GPU_BUFFER_USAGE_MAP_READ,\n mappedAtCreation: false,\n });\n if (!bufResult.ok) {\n internals.errorRegistry.fire(bufResult.error);\n return null;\n }\n const stagingBuf = bufResult.value;\n\n const encResult = internals.device.createCommandEncoder({ label: 'shadow-readback-encoder' });\n if (!encResult.ok) {\n internals.errorRegistry.fire(encResult.error);\n return null;\n }\n const enc = encResult.value;\n\n enc.copyTextureToBuffer(\n { texture: tex as never, aspect: 'depth-only' },\n {\n buffer: stagingBuf as never,\n bytesPerRow: alignedRowBytes,\n rowsPerImage: atlasSize.height,\n },\n { width: atlasSize.width, height: atlasSize.height, depthOrArrayLayers: 1 },\n );\n\n const finishResult = enc.finish();\n if (!finishResult.ok) {\n internals.errorRegistry.fire(finishResult.error);\n return null;\n }\n const submitResult = internals.device.queue.submit([finishResult.value]);\n if (!submitResult.ok) {\n internals.errorRegistry.fire(submitResult.error);\n return null;\n }\n\n const mapResult = await stagingBuf.mapAsync(1);\n if (!mapResult.ok) {\n internals.errorRegistry.fire(mapResult.error);\n return null;\n }\n const mappedBuf = mapResult.value;\n const rangeResult = mappedBuf.getMappedRange();\n if (!rangeResult.ok) {\n internals.errorRegistry.fire(rangeResult.error);\n return null;\n }\n const data = new Float32Array(rangeResult.value);\n // D-5: 5 pixel integer coordinates\n const cx = mapSize >> 1;\n const cy = mapSize >> 1;\n const readPixel = (x: number, y: number): number => {\n const offset = y * alignedRowBytes + x * bytesPerPixel;\n // Float32Array indices are in f32 units (bytesPerPixel = 4, so offset/4)\n return data[offset >> 2] ?? 0;\n };\n\n const center = readPixel(cx, cy);\n const corners = {\n tl: readPixel(0, 0),\n tr: readPixel(mapSize - 1, 0),\n bl: readPixel(0, mapSize - 1),\n br: readPixel(mapSize - 1, mapSize - 1),\n };\n const fixedSamples = [center, corners.tl, corners.tr, corners.bl, corners.br];\n let representativeCenter = center;\n if (fixedSamples.every((value) => value >= 0.99)) {\n // CSM owns a receiver-fitted atlas, so a caster is not required to land\n // on the legacy center/corner sentinel pixels. Keep those coordinates as\n // the first diagnostic contract, but make an all-clear result prove the\n // same depth owner by surfacing its nearest written cascade-0 texel.\n let nearestWrittenDepth = 1;\n for (let y = 0; y < mapSize; y += 1) {\n for (let x = 0; x < mapSize; x += 1) {\n const value = readPixel(x, y);\n if (Number.isFinite(value) && value >= 0 && value < nearestWrittenDepth) {\n nearestWrittenDepth = value;\n }\n }\n }\n if (nearestWrittenDepth < 0.99) representativeCenter = nearestWrittenDepth;\n }\n\n const result = {\n center: representativeCenter,\n corners,\n mapSize,\n };\n\n mappedBuf.unmap();\n // forgeax Buffer wrapper does not expose destroy(); the underlying\n // GPUBuffer is reclaimed when the JS wrapper is garbage-collected.\n\n return result;\n}\n\n/**\n * directionalShadowSnapshot: reads the current shadow configuration\n * (mapSize, lightSpaceMatrix) from PipelineState. Returns null when no\n * shadow RT exists (shader manifest empty or castShadow:false).\n */\nfunction directionalShadowSnapshot(state: PipelineState): {\n readonly mapSize: number;\n readonly lightSpaceMatrix: readonly number[] | null;\n} | null {\n if (state.perPassResources.shadowTexture === null) return null;\n return {\n mapSize: state.perPassResources.shadowMapSize,\n lightSpaceMatrix: state.perPassResources.shadowLightSpaceMatrix\n ? Array.from(state.perPassResources.shadowLightSpaceMatrix)\n : null,\n };\n}\n\n// ─── Helpers ────────────────────────────────────────────────────────────────\n\nfunction toError(value: unknown): Error {\n if (value instanceof Error) return value;\n return new Error(String(value));\n}\n\n/**\n * V-2 first-class input shim (plan-strategy D-2 + AC-09 — feat-20260519).\n *\n * Curried `input.snapshot(world)` reader (charter P4 consistent abstraction).\n * Holds no World reference (P5 producer/consumer split); reads via\n * `world.getResource<InputSnapshot>(INPUT_SNAPSHOT_RESOURCE_KEY)` per call.\n */\nconst RENDERER_INPUT_FACADE: {\n snapshot(world: World): InputSnapshot | undefined;\n} = {\n snapshot(world: World): InputSnapshot | undefined {\n // World.getResource throws on missing key; charter P3 demands the\n // empty signal be the signal here (callers check `=== undefined`),\n // so guard with hasResource first.\n if (!world.hasResource(INPUT_SNAPSHOT_RESOURCE_KEY)) return undefined;\n return world.getResource<InputSnapshot>(INPUT_SNAPSHOT_RESOURCE_KEY);\n },\n};\n\n/**\n * Sync-shaped `ShaderRegistryDevice` adapter wrapping `@forgeax/engine-rhi-webgpu`'s\n * async `createShaderModule(rhiDevice, desc)`.\n *\n * Shape: fire-and-forget pre-bake — the first call for hash X returns\n * `Result.err(RhiError)` (a pending signal) while kicking off the async\n * createShaderModule + cache write; subsequent calls for the same hash hit\n * the cache and return `Result.ok(ShaderModule)` (charter proposition 9\n * graceful degradation).\n *\n * @placeholder M3 scope limit: the full async pre-bake wiring is delivered\n * by the ECS-driven render pipeline (later closure). The current shape is\n * already enough to support MVP-2.2 instance-per-engine + AI consumer\n * onboarding (charter proposition 1 progressive disclosure / proposition 4\n * explicit failure with retry guidance in the error hint).\n */\n/**\n * Extended ShaderRegistryDevice contract for engine internals: adds a\n * `seedModule(label, module)` to populate the lazy adapter cache from an\n * already-compiled module, so eager-built modules (PBR / unlit / shadow\n * caster) and the lazy MaterialShader pipeline cache share one cache and\n * the lazy path is hit-on-first-call (no 1-frame warmup) for engine-shipped\n * shaders. Externally still typed as ShaderRegistryDevice (see callers in\n * ShaderRegistry).\n */\ninterface ShaderDeviceAdapterInternal extends ShaderRegistryDevice {\n /**\n * feat-20260609 R3-fixup: seed the adapter's moduleCache with an\n * already-compiled ShaderModule under `label`. Used by the eager\n * shadow_caster pre-bake so the lazy PSO build hit on\n * `module-forgeax::default-shadow-caster` returns OK on frame 1.\n */\n seedModule(label: string, module: ShaderModule): void;\n}\n\nfunction makeShaderDeviceAdapter(\n rhiDevice: RhiDevice,\n _errorRegistry: RhiErrorListenerRegistry,\n asyncCreateShaderModule:\n | ((\n device: RhiDevice,\n desc: { code: string; label?: string | undefined },\n ) => Promise<Result<ShaderModule, RhiError>>)\n | undefined,\n): ShaderDeviceAdapterInternal {\n const moduleCache = new Map<string, ShaderModule>();\n const errorCache = new Map<string, RhiError>();\n const pending = new Set<string>();\n\n return {\n createShaderModule(desc): Result<ShaderModule, RhiError> {\n const key = desc.label ?? desc.code;\n const cachedModule = moduleCache.get(key);\n if (cachedModule !== undefined) return ok(cachedModule);\n const cachedError = errorCache.get(key);\n if (cachedError !== undefined) return err(cachedError);\n\n // Fire async creation; first sync call returns pending error (the AI consumer retry pattern).\n // M3 D-P4: rhi-webgpu supplies the async factory; rhi-wgpu (no top-level\n // async factory) falls back to the synchronous device.createShaderModule\n // entry which already returns Result<ShaderModule, RhiError>.\n if (!pending.has(key)) {\n pending.add(key);\n const desc2: { code: string; label?: string | undefined } = { code: desc.code };\n if (desc.label !== undefined) desc2.label = desc.label;\n const asyncResult: Promise<Result<ShaderModule, RhiError>> = asyncCreateShaderModule\n ? asyncCreateShaderModule(rhiDevice, desc2)\n : invokeDeviceCreateShaderModule(rhiDevice, desc2);\n void asyncResult.then((result) => {\n if (result.ok) {\n moduleCache.set(key, result.value);\n } else {\n errorCache.set(key, result.error);\n }\n pending.delete(key);\n });\n }\n\n return err(makeRhiNotAvailableError());\n },\n seedModule(label: string, module: ShaderModule): void {\n moduleCache.set(label, module);\n },\n };\n}\n\n/**\n * Fallback path for the M3 D-P4 auto-select facade when the backend pack\n * does not supply a top-level async `createShaderModule` (e.g. the rhi-wgpu\n * path which routes through the synchronous `device.createShaderModule`\n * entry, or an explicit escape-hatch instance that omits the async\n * factory). The forgeax `RhiDevice` interface intentionally does not expose\n * a sync `createShaderModule` (fix-f3; see packages/rhi/src/index.ts line\n * 1164), so this helper performs a structural probe + returns a structured\n * error when neither the async factory nor a structural sync entry exists\n * (charter proposition 4 explicit failure baseline).\n */\nfunction invokeDeviceCreateShaderModule(\n rhiDevice: RhiDevice,\n desc: { code: string; label?: string | undefined },\n): Promise<Result<ShaderModule, RhiError>> {\n const candidate = (\n rhiDevice as unknown as {\n createShaderModule?: (d: {\n code: string;\n label?: string | undefined;\n }) => Result<ShaderModule, RhiError>;\n }\n ).createShaderModule;\n if (typeof candidate === 'function') {\n try {\n return Promise.resolve(candidate.call(rhiDevice, desc));\n } catch (caught) {\n const message = caught instanceof Error ? caught.message : String(caught);\n return Promise.resolve(\n err(\n new RhiError({\n code: 'shader-compile-failed',\n expected: 'device.createShaderModule returns Result<ShaderModule, RhiError>',\n hint: `synchronous fallback threw: ${message}`,\n }),\n ),\n );\n }\n }\n return Promise.resolve(\n err(\n new RhiError({\n code: 'rhi-not-available',\n expected:\n 'either RhiBackendPack.createShaderModule (async) or device.createShaderModule (sync) available',\n hint: 'the explicit RhiInstance escape hatch must expose a top-level createShaderModule(device, desc) or RhiDevice.createShaderModule(desc) entry',\n }),\n ),\n );\n}\n\n/**\n * Synthesizes a `RhiError` with code 'rhi-not-available' for the\n * sync-adapter pending path. AI-consumer onboarding: consume\n * `.code === 'rhi-not-available'` → after `await loadManifest` retry\n * `registry.get` (charter proposition 4 explicit failure + proposition 9).\n *\n * 'rhi-not-available' is the placeholder member of the 5-member closed\n * union (plan-decisions OQ-P2).\n */\nfunction makeRhiNotAvailableError(): RhiError {\n return new RhiError({\n code: 'rhi-not-available',\n expected: 'shader module pre-bake to complete asynchronously',\n hint: 'await registry.loadManifest() finished; retry registry.get(hash) on next frame',\n });\n}\n\n// ─── D-S3 Renderer.ready three-step serial pipeline ─────────────────────────\n\n// feat-20260518-pbr-direct-lighting-mvp M5 / w22.9 (AC-05 + plan-strategy\n// D-3 + D-4): the legacy inline fallback PBR-shaped WGSL source has been\n// deleted in favor of the manifest-driven path. The build-time\n// `@forgeax/engine-vite-plugin-shader` plugin eagerly compiles\n// `@forgeax/engine-shader/src/{pbr,unlit}.wgsl` (with common.wgsl + brdf.wgsl\n// as naga_oil `#import` peers) at `buildStart`; the runtime path consumes\n// the resulting manifest entries via `getShader().get(<hash>)`. The two\n// distinct shader modules are wired into the three render pipelines\n// (`unlitBuiltinPipeline` + `unlitPipeline` for unlit at the 6F\n// vs 12F vertex strides; `standardPipeline` for PBR at 12F stride) so the\n// triple-pipeline contract (M5 / w22.10 + w22.11) hands distinct\n// `unlitBuiltinPipeline.module === unlitPipeline.module !==\n// standardPipeline.module` GPU handles back to `RenderSystem` per-frame\n// dispatch (D-P4 + AGENTS.md `MeshRenderer` shader-identity discriminant).\n\n// Per-pipeline buffer sizes consumed by the manifest-shipped pbr / unlit\n// shaders (D-S2 + plan-strategy; w22.9 retired the inline fallback shader\n// constant in favor of the @forgeax/engine-vite-plugin-shader manifest path):\n// View UBO : worldViewProj mat4x4<f32> = 64 bytes (frame-shared)\n// Material UBO : { vec3 baseColor, f32 metallic, f32 roughness } padded to 32\n// Mesh SSBO : runtime-sized `array<Mesh>` where Mesh = mat4x4<f32> =\n// 64 bytes (indexed via @builtin(instance_index), bound\n// with size = instanceCount * 64 B per draw; D-P9)\n//\n// feat-20260513-instanced-mesh M5 (T-M5-1 + T-M5-3): legacy\n// per-frame entity-count cap removed.\n// feat-20260514-ecs-children-instances-managed-buffer-array M3 / w15: the\n// `'limit-exceeded'` emit point migrated from the now-deleted\n// `AssetRegistry.createInstancedBuffer` factory to the RenderSystem record\n// stage's per-entity instance buffer upload path\n// (`packages/runtime/src/render-system-record.ts`); the cap-check still\n// runs against `device.limits.maxStorageBufferBindingSize`, but the\n// `requestedBytes` now reflects the ECS-managed `Instances.transforms`\n// snapshot size per frame. The shared `meshStorageBuffer` and\n// `materialUniformBuffer` are owned by `meshSsboController` (M2 / T-M2-05):\n// the initial allocation lands at `INITIAL_MESH_SSBO_SLOT_COUNT = 1024`\n// slots and grows on demand via `growMeshSsbo(neededSlots)` (pow2 doubling,\n// ceiling = `device.limits.maxStorageBufferBindingSize` per plan-strategy\n// §2.D-1; spec floor of 128 MiB / 256 B stride = 524288 slots theoretical\n// max).\n//\n// `MATERIAL_PER_ENTITY_STRIDE` is the larger stride required by the material\n// UBO and is used for the shared mesh/material capacity allocation. Mesh\n// payload offsets remain independently owned by `MESH_PER_ENTITY_STRIDE` in\n// the record path; the shared buffer simply reserves the material-sized slot\n// for each renderable. The mesh path writes the leading `instanceCount * 64 B`\n// (tight-packed) payload into each reserved slot.\n// feat-20260518-pbr-direct-lighting-mvp M3 / w13 + AC-07 std140 layout:\n// View UBO : worldViewProj (64 B mat4) + lightDir (16 B vec3+pad) +\n// lightColor (16 B vec3+pad) + cameraPos (16 B vec3+pad)\n// = 112 B (frame-shared). Field order matches common.wgsl\n// `View` struct byte-for-byte (single SSOT, charter P5).\n// Naming: cameraPos (not viewPos) -> mirrors pbr.wgsl\n// `view.cameraPos` literal.\n//\n// feat-20260520-directional-light-shadow-mapping M1b / w7: extended to 176 B.\n// feat-20260531-skybox-env-background M2 / w3: extended to 240 B.\n// inverseViewProj mat4x4<f32> (64 B) appended at tail (offset 176, align 16,\n// total 176 + 64 = 240 B). Field added to common.wgsl View struct; host\n// writes the tail via queue.writeBuffer in render-system-record.\n// feat-20260613-csm-cascaded-shadow-maps M4 / w16: extended to 592 B.\n// lightSpaceMatrix replaced by lightViewProj_A at offset 112; inverseViewProj\n// stays at offset 176; lightViewProj_B..D + splitPlanes[4] + cascadeCount +\n// cascadeBlend + tail padding appended after inverseViewProj. Total 148 f32\n// = 592 B, fixed independent of cascadeCount (AC-08).\n// feat-20260621-merge-directionallightshadow-into-directionallight M3 / m3-t3:\n// depthBias / normalBias / pcfKernelSize from the merged DirectionalLight\n// append at the formerly-free tail pad (bytes 504/508/512, floats 126/127/128).\n// VIEW_UBO_BYTES stays 592 (the host tail pad shrinks 88 B -> 64 B); the WGSL\n// View struct in common.wgsl carries the matching 3 f32 (SSOT comment synced).\n// feat-20260625-spot-light-shadow-mapping w25 (scope-amend webkit-fallback):\n// grew 592 -> 784. The per-spot fragment-read perspective lightViewProj matrices\n// (`array<mat4x4<f32>, 4>` = 256 B) fold from a standalone @group(0) binding 9\n// uniform buffer into the View UBO tail (bytes 528..784, 16 B-aligned after\n// pcfKernelSize at byte 512). This removes the 12th fragment-stage uniform\n// buffer that overflowed GLES 3.0's max_uniform_buffers_per_shader_stage = 11 on\n// the WebGL2 fallback path. render-system-record writes the full 196 f32 payload;\n// common.wgsl `View.spotLightViewProj` is the matching SSOT.\nconst VIEW_UBO_BYTES = VIEW_UNIFORM_BUFFER_SIZE;\n\n// ── feat-20260520-directional-light-shadow-mapping M2 / w15 (AC-12 numeric flip)\n//\n// debugSampleShadowFactor probe pipeline. Renders one pixel per probe into a\n// 1xN rgba32float color attachment using the same cascade selector, local tile\n// guard, comparison sampler, slope-scaled bias, dynamic PCF, shadowDistance\n// early-out, and cascade-blend path as pbr.wgsl::evalDirectional(). The input\n// w lane carries the producer-equivalent receiver bias. The other lanes expose\n// the center depth, selected cascade index, and projected receiver depth.\n//\n// Probe count cap: 64. AI users wanting more should batch. Four f32 lanes per\n// probe keep the readback staging buffer at 1024 B (single 256B-aligned row).\nconst PROBE_MAX_COUNT = 64;\nconst SHADOW_PROBE_BIAS = 0.005;\nconst PROBE_INPUT_BYTES = PROBE_MAX_COUNT * 16; // array<vec4<f32>, 64>; w=bias\n\nfunction shadowProbeBias(\n normal: ArrayLike<number>,\n outgoingLightDirection: ArrayLike<number> | undefined,\n depthBias: number,\n normalBias: number,\n): number {\n const normalX = normal[0] ?? 0;\n const normalY = normal[1] ?? 1;\n const normalZ = normal[2] ?? 0;\n const normalLength = Math.hypot(normalX, normalY, normalZ);\n const nx = normalLength > 0 ? normalX / normalLength : 0;\n const ny = normalLength > 0 ? normalY / normalLength : 1;\n const nz = normalLength > 0 ? normalZ / normalLength : 0;\n const direction = outgoingLightDirection ?? [0, -1, 0];\n const directionX = direction[0] ?? 0;\n const directionY = direction[1] ?? -1;\n const directionZ = direction[2] ?? 0;\n const directionLength = Math.hypot(directionX, directionY, directionZ);\n const lx = directionLength > 0 ? -directionX / directionLength : 0;\n const ly = directionLength > 0 ? -directionY / directionLength : 1;\n const lz = directionLength > 0 ? -directionZ / directionLength : 0;\n return Math.max(normalBias * (1 - (nx * lx + ny * ly + nz * lz)), depthBias);\n}\n\n// feat-20260613-csm-cascaded-shadow-maps M5 / w28: probe LSM UBO carries\n// 4 cascade lightViewProj matrices (4 × 64 B = 256 B), then the producer's\n// receiver-selection view matrix (64 B), split planes (16 B), and\n// cascadeCount + pcfKernelSize + cascadeBlend + 4 B pad (16 B). The probe therefore shares the main\n// viewZ + splitPlanes selector instead of approximating it with geometric\n// containment, which can disagree at split boundaries.\nconst PROBE_LSM_UBO_BYTES = 352;\nconst PROBE_OUTPUT_TEXTURE_FORMAT: GPUTextureFormat = 'rgba32float';\nconst PROBE_READBACK_ROW_BYTES = 1024; // 256B-aligned per WebGPU spec; 64*16=1024 B\n\n/** @internal Exact producer-owned probe shader, exported for Dawn falsifiers. */\nexport const SHADOW_PROBE_WGSL = `\nstruct CsmLsm {\n m0 : mat4x4<f32>,\n m1 : mat4x4<f32>,\n m2 : mat4x4<f32>,\n m3 : mat4x4<f32>,\n view : mat4x4<f32>,\n splitPlanes : vec4<f32>,\n cascadeCount : u32,\n pcfKernelSize : u32,\n cascadeBlend : f32,\n probePadC : u32,\n};\nstruct WorldPositions { p : array<vec4<f32>, ${PROBE_MAX_COUNT}> };\n\n@group(0) @binding(0) var<uniform> lsm : CsmLsm;\n@group(0) @binding(1) var<storage, read> worldPositions : WorldPositions;\n@group(0) @binding(2) var shadowMap : texture_depth_2d;\n@group(0) @binding(3) var shadowSampler : sampler_comparison;\n\nstruct VsOut {\n @builtin(position) clip : vec4<f32>,\n @location(0) @interpolate(flat) probeIdx : u32,\n};\n\n@vertex fn vs_main(@builtin(vertex_index) v : u32, @builtin(instance_index) i : u32) -> VsOut {\n let n = f32(${PROBE_MAX_COUNT});\n let xL = (f32(i) / n) * 2.0 - 1.0;\n let xR = (f32(i + 1u) / n) * 2.0 - 1.0;\n var x : f32 = xL;\n var y : f32 = -1.0;\n switch (v) {\n case 0u: { x = xL; y = -1.0; }\n case 1u: { x = xR; y = -1.0; }\n case 2u: { x = xR; y = 1.0; }\n case 3u: { x = xL; y = -1.0; }\n case 4u: { x = xR; y = 1.0; }\n default: { x = xL; y = 1.0; }\n }\n var out : VsOut;\n out.clip = vec4<f32>(x, y, 0.0, 1.0);\n out.probeIdx = i;\n return out;\n}\n\nfn _probeCascadeMatrix(layer : u32) -> mat4x4<f32> {\n switch (layer) {\n case 0u: { return lsm.m0; }\n case 1u: { return lsm.m1; }\n case 2u: { return lsm.m2; }\n default: { return lsm.m3; }\n }\n}\n\nfn _pickCascadeLayer(viewDepth : f32, count : u32) -> u32 {\n var layer : u32 = count - 1u;\n for (var i : u32 = 0u; i < count - 1u; i = i + 1u) {\n if (viewDepth < lsm.splitPlanes[i]) {\n layer = i;\n break;\n }\n }\n return layer;\n}\n\nfn _sampleProbeCascade(\n worldPosition : vec3<f32>,\n layer : u32,\n count : u32,\n bias : f32,\n) -> vec3<f32> {\n let columns : u32 = select(2u, 1u, count <= 1u);\n let rows : u32 = (count + columns - 1u) / columns;\n let grid = vec2<u32>(columns, rows);\n let tileScale = vec2<f32>(1.0) / vec2<f32>(grid);\n let m = _probeCascadeMatrix(layer);\n let lightClip = m * vec4<f32>(worldPosition, 1.0);\n let projCoords = lightClip.xyz / lightClip.w;\n let tileUv = vec2<f32>(projCoords.x * 0.5 + 0.5, -projCoords.y * 0.5 + 0.5);\n let tile = vec2<u32>(layer % grid.x, layer / grid.x);\n let tileOrigin = vec2<f32>(tile) / vec2<f32>(grid);\n let uv = tileUv * tileScale + tileOrigin;\n let currentDepth = projCoords.z;\n var sampledDepth : f32 = 1.0;\n var shadow : f32 = 1.0;\n // The host computes max(normalBias * (1 - N.L), depthBias) from the same\n // DirectionalLight snapshot and puts it in the input w lane. This keeps\n // the probe's receiver comparison tied to the exact surface normal used by\n // the evidence caller instead of inventing a fixed floor bias.\n let adjustedDepth : f32 = currentDepth - bias;\n // Keep this check in cascade-local coordinates. An atlas-space check would\n // accept an out-of-cascade receiver that still lands inside the atlas,\n // clamp it to a tile edge, and report a false shadow. The production\n // receiver uses the same local tileUv contract.\n if (tileUv.x >= 0.0 && tileUv.x <= 1.0 && tileUv.y >= 0.0 && tileUv.y <= 1.0 && currentDepth <= 1.0) {\n let texelDims = vec2<f32>(textureDimensions(shadowMap, 0));\n let texel = vec2<f32>(1.0 / texelDims.x, 1.0 / texelDims.y);\n let tileLo = tileOrigin + texel;\n let tileHi = tileOrigin + tileScale - texel;\n let baseCoord = vec2<i32>(uv * texelDims);\n let maxCoord = vec2<i32>(texelDims) - vec2<i32>(1, 1);\n let centerCoord = clamp(baseCoord, vec2<i32>(0, 0), maxCoord);\n sampledDepth = textureLoad(shadowMap, centerCoord, 0);\n let requestedKernel = clamp(lsm.pcfKernelSize, 1u, 5u);\n let kernel = select(select(5u, 3u, requestedKernel <= 4u), 1u, requestedKernel == 1u);\n if (kernel == 1u) {\n shadow = textureSampleCompareLevel(shadowMap, shadowSampler, clamp(uv, tileLo, tileHi), adjustedDepth);\n } else if (kernel == 3u) {\n // Keep the same bilinear 3x3 optimization as lighting-directional.wgsl.\n // The edge path deliberately falls back to clamped nine-tap comparisons.\n let interior = all(uv >= tileLo + texel) && all(uv <= tileHi - texel);\n if (interior) {\n let pcfFraction = fract(uv / texel - vec2<f32>(0.5));\n let loWeight = vec2<f32>(2.0) - pcfFraction;\n let hiWeight = vec2<f32>(1.0) + pcfFraction;\n let loOffset = vec2<f32>(-1.0) - pcfFraction + vec2<f32>(1.0) / loWeight;\n let hiOffset = vec2<f32>(1.0) - pcfFraction + pcfFraction / hiWeight;\n let litLoLo = textureSampleCompareLevel(\n shadowMap, shadowSampler, uv + vec2<f32>(loOffset.x, loOffset.y) * texel, adjustedDepth,\n );\n let litHiLo = textureSampleCompareLevel(\n shadowMap, shadowSampler, uv + vec2<f32>(hiOffset.x, loOffset.y) * texel, adjustedDepth,\n );\n let litLoHi = textureSampleCompareLevel(\n shadowMap, shadowSampler, uv + vec2<f32>(loOffset.x, hiOffset.y) * texel, adjustedDepth,\n );\n let litHiHi = textureSampleCompareLevel(\n shadowMap, shadowSampler, uv + vec2<f32>(hiOffset.x, hiOffset.y) * texel, adjustedDepth,\n );\n shadow = (\n litLoLo * loWeight.x * loWeight.y +\n litHiLo * hiWeight.x * loWeight.y +\n litLoHi * loWeight.x * hiWeight.y +\n litHiHi * hiWeight.x * hiWeight.y\n ) / 9.0;\n } else {\n var blocked : f32 = 0.0;\n for (var x = -1; x <= 1; x++) {\n for (var y = -1; y <= 1; y++) {\n let offsetUv = clamp(uv + vec2<f32>(f32(x), f32(y)) * texel, tileLo, tileHi);\n let lit = textureSampleCompareLevel(shadowMap, shadowSampler, offsetUv, adjustedDepth);\n blocked = blocked + (1.0 - lit);\n }\n }\n shadow = 1.0 - blocked / 9.0;\n }\n } else {\n var blocked : f32 = 0.0;\n for (var x = -2; x <= 2; x++) {\n for (var y = -2; y <= 2; y++) {\n let offsetUv = clamp(uv + vec2<f32>(f32(x), f32(y)) * texel, tileLo, tileHi);\n let lit = textureSampleCompareLevel(shadowMap, shadowSampler, offsetUv, adjustedDepth);\n blocked = blocked + (1.0 - lit);\n }\n }\n shadow = 1.0 - blocked / 25.0;\n }\n }\n return vec3<f32>(shadow, sampledDepth, currentDepth);\n}\n\n@fragment fn fs_main(in : VsOut) -> @location(0) vec4<f32> {\n let p4 = worldPositions.p[in.probeIdx];\n let count = max(lsm.cascadeCount, 1u);\n let viewPosition = lsm.view * vec4<f32>(p4.xyz, 1.0);\n let viewDepth = -viewPosition.z;\n // Match the production shadowDistance early-out. A receiver past the last\n // split is fully lit instead of being assigned to the last atlas tile.\n if (viewDepth > lsm.splitPlanes[count - 1u]) {\n return vec4<f32>(1.0, 1.0, -1.0, 1.0);\n }\n let selectedLayer = _pickCascadeLayer(viewDepth, count);\n let current = _sampleProbeCascade(p4.xyz, selectedLayer, count, p4.w);\n var shadow = current.x;\n if (lsm.cascadeBlend > 0.0 && selectedLayer + 1u < count) {\n let split = lsm.splitPlanes[selectedLayer];\n let blendWidth = split * lsm.cascadeBlend;\n if (blendWidth > 0.0) {\n let distanceToSplit = split - viewDepth;\n let t = clamp(1.0 - distanceToSplit / blendWidth, 0.0, 1.0);\n if (t > 0.0) {\n let next = _sampleProbeCascade(p4.xyz, selectedLayer + 1u, count, p4.w);\n shadow = mix(current.x, next.x, t);\n }\n }\n }\n return vec4<f32>(shadow, current.y, f32(selectedLayer), current.z);\n}\n`;\n\n// Canvas swap-chain storage + view formats.\n//\n// `bug-20260519` — wood-container looked black on screen because pipelines\n// authored linear values (sampler decoded `rgba8unorm-srgb` -> linear) into\n// a `bgra8unorm` (linear) canvas; the display interpreted the linear bytes\n// as sRGB-encoded and crushed them near zero.\n//\n// Fix: configure canvas storage as `bgra8unorm` and provide\n// `bgra8unorm-srgb` in `viewFormats` so the per-frame `createTextureView`\n// can yield the sRGB *view*. Pipelines target the sRGB view -> the GPU\n// encodes linear -> sRGB on store; the display decodes sRGB back to\n// linear, so colours land correctly.\n//\n// Spec anchor: W3C WebGPU §3.3 GPUCanvasConfiguration disallows\n// `format: '<...>-srgb'` directly; the srgb-via-viewFormats path is the\n// canonical recipe.\n// bug-20260610: switched from `bgra8unorm` to `rgba8unorm` so the same\n// constant works on both backends. WebGPU spec allows both as a canvas\n// storage format on browser-native WebGPU (D3D / Metal), and wgpu's GLES\n// backend only supports Rgba (Bgra is hardware-illegal on OpenGL ES 3.0).\n// RGBA-on-Metal/D3D pays at most a tiny driver-side swizzle which is\n// invisible to AI users; the alternative — branching the format per\n// backend — would split every demo's pipeline-target list and viewFormats\n// declarations into two parallel chains for no measurable gain.\n//\n// bug-20260612: superseded — the trade-off above (one tiny swizzle hidden\n// from AI users) ignored the per-frame Chromium \"configured with a\n// different format than is preferred\" warning that pollutes hello-* demo\n// console capture. The module-level `SWAP_CHAIN_STORAGE_FORMAT` /\n// `SWAP_CHAIN_VIEW_FORMAT` constants were deleted; both formats now flow\n// from `selectSwapChainFormat(storageBufferCapable)` (defined below) into\n// `PipelineState.format` / `.colorAttachmentFormat` and from there into\n// every pipeline target / configure() call. Channel 2 follows\n// `navigator.gpu.getPreferredCanvasFormat()`; Channel 3 keeps `rgba8unorm`\n// (GLES hardware constraint). The historical comment block above is\n// retained as the OOS-5 evolution record.\n\n// bug-20260612: backend-aware swap-chain format selection. bug-20260610's\n// hard-coded `rgba8unorm` triggers Chromium's \"configured with a different\n// format than is preferred ... extra copy ... may impact performance\"\n// warning every time the canvas is configured on Channel 2 (D3D / Metal /\n// Vulkan all prefer `bgra8unorm` via the WebGPU-spec `getPreferredCanvasFormat`\n// entry point). The console noise pollutes hello-* demo capture and misleads\n// AI users debugging unrelated issues (charter F1 + P3).\n//\n// Branching by `storageBufferCapable` (Channel 2 native WebGPU = true /\n// Channel 3 wgpu-wasm GLES = false) preserves the GLES hardware constraint\n// (Bgra-on-OpenGL-ES is illegal — wgpu rejects it) while letting the\n// browser-native path follow UA preference. The `view` format is the\n// `${storage}-srgb` partner; WebGPU spec §3.3 allows both\n// `bgra8unorm` / `bgra8unorm-srgb` and `rgba8unorm` / `rgba8unorm-srgb`\n// pairs through the `viewFormats` srgb route.\n//\n// Three-step protection inside `selectSwapChainFormat`:\n// 1. `storageBufferCapable === false` → hard `rgba8unorm` (Channel 3 GLES\n// hardware constraint; `navigator.gpu` is irrelevant in this branch).\n// 2. `storageBufferCapable === true` + `navigator.gpu.getPreferredCanvasFormat`\n// callable → use the spec-preferred format from the UA (typically\n// `bgra8unorm` on Chrome / Edge / Safari).\n// 3. `storageBufferCapable === true` but `navigator.gpu` missing or\n// `getPreferredCanvasFormat` not a function (very old UA, or test\n// shim) → fall back to `rgba8unorm` and surface a structured\n// `RhiError { code: 'rhi-not-available' }` through the renderer's\n// error registry so AI users can subscribe via `Renderer.onError(cb)`\n// and react. Charter P3: explicit failure > silent fallback.\n//\n// Exported (module-private to runtime; **not** re-exported through the\n// `@forgeax/engine-runtime` barrel) so the unit test can import it\n// without spinning up a renderer. Consumers outside this module must\n// not depend on it — public swap-chain-format negotiation is **not**\n// part of the engine surface.\ninterface SwapChainFormatPair {\n readonly storage: GPUTextureFormat;\n readonly view: GPUTextureFormat;\n /**\n * Set when step ③ above fired. Caller (buildReadyWebGPU) inspects this\n * field to fire a structured RhiError through the registry. `undefined`\n * on the happy paths (steps ① and ②).\n */\n readonly fallbackReason?: 'preferred-canvas-format-missing';\n}\n\n/** @internal */\nfunction selectSwapChainFormat(storageBufferCapable: boolean): SwapChainFormatPair {\n if (storageBufferCapable === false) {\n // Step ①: Channel 3 wgpu-wasm WebGL2 — Bgra is hardware-illegal on\n // OpenGL ES 3.0 (wgpu's GLES backend rejects it via downlevel flags).\n return { storage: 'rgba8unorm', view: 'rgba8unorm-srgb' };\n }\n // Step ②: Channel 2 native WebGPU — follow UA preference.\n const nav = (\n globalThis as { navigator?: { gpu?: { getPreferredCanvasFormat?: () => GPUTextureFormat } } }\n ).navigator;\n const gpu = nav?.gpu;\n const getPreferred = gpu?.getPreferredCanvasFormat;\n if (gpu !== undefined && typeof getPreferred === 'function') {\n const storage = getPreferred.call(gpu);\n return { storage, view: `${storage}-srgb` as unknown as GPUTextureFormat };\n }\n // Step ③: navigator.gpu absent or getPreferredCanvasFormat not a function.\n // Fall back to rgba8unorm + flag the diagnostic; caller fires RhiError.\n return {\n storage: 'rgba8unorm',\n view: 'rgba8unorm-srgb',\n fallbackReason: 'preferred-canvas-format-missing',\n };\n}\n\n// feat-20260519-tonemap-reinhard-mvp / M2 / T-M2.5: HDR offscreen colour\n// attachment format. `rgba16float` is the WebGPU spec's filterable HDR\n// format (no `float32-filterable` feature gate required) and carries enough\n// dynamic range for the Reinhard-extended luminance compression to land\n// physically-meaningful values (research F1 + Constraints C1-C2 +\n// plan-strategy D-2 / AC-03(d)). The post-process tonemap pass samples this\n// attachment and writes the LDR result into the swap-chain's\n// `bgra8unorm-srgb` view.\nconst HDR_COLOR_ATTACHMENT_FORMAT: GPUTextureFormat = 'rgba16float';\n\n/**\n * Six fullscreen triangles tagged with their cube-face index. The atmosphere\n * producer renders one 2D face at a time; unlike the IBL capture mesh, these\n * vertices are clip-space coordinates, so every face covers its attachment.\n */\nconst ATMOSPHERE_FACE_VERTICES = (() => {\n const corners = [\n [-1, -1],\n [1, -1],\n [1, 1],\n [-1, -1],\n [1, 1],\n [-1, 1],\n ] as const;\n const vertices = new Float32Array(6 * corners.length * 3);\n let offset = 0;\n for (let face = 0; face < 6; face += 1) {\n for (const [x, y] of corners) {\n vertices[offset] = x;\n vertices[offset + 1] = y;\n vertices[offset + 2] = face + 1;\n offset += 3;\n }\n }\n return vertices;\n})();\n\n// feat-20260601-gpu-resource-store-extraction M1 (D-9 sub-contract 1): texture\n// formats prewarmed into the mipmap pipeline cache at `renderer.ready` so the\n// record-stage `gpuStore.ensureResident` texture arm runs a pure-synchronous\n// mipmap blit (no lazy async build inside the sync draw frame). Covers every\n// `mipmap:true` 2D texture format the smoke set uploads: `rgba8unorm-srgb`\n// (sRGB color / sprite / wood) + `rgba8unorm` (linear normal / metallic-rough /\n// occlusion maps). HDR equirect (`rgba16float` / `rgba32float`) is uploaded via\n// the internal equirect-to-cubemap projection path, NOT the sync texture arm,\n// so it is intentionally absent here. A `mipmap:true` texture in an\n// un-prewarmed format surfaces a structured RhiError at record (never an\n// async stall) -- the falsifiable anchor for an incomplete prewarm list.\nconst MIPMAP_PREWARM_FORMATS: readonly GPUTextureFormat[] = ['rgba8unorm-srgb', 'rgba8unorm'];\n\n// feat-20260531-bloom-first-declarative-render-graph-pass / w13:\n// UBO sizes for bloom params (std140 layout).\n// BRIGHT: threshold (f32) + 12 B pad = 16 B\n// BLUR: texelSize.xy (vec2f) + radius (f32) + pad = 16 B\n// COMPOSITE: intensity (f32) + 12 B pad = 16 B\nconst BRIGHT_PARAMS_BYTES = 16;\nconst BLUR_PARAMS_BYTES = 16;\nconst COMPOSITE_PARAMS_BYTES = 16;\n\n// Depth-stencil format for the per-frame depth attachment. `depth24plus-stencil8`\n// is the WebGPU-mandated format on every adapter (core required format);\n// pipelines and the per-frame `createTexture(...)` call agree on this single\n// literal so the renderpass attachment + pipeline format match. bug-20260519:\n// without a depth attachment + back-face cull every cube triangle painted in\n// submission order — the back face overdrew the front face and the side\n// faces showed as a wood-coloured rim outside the front-face footprint.\nconst DEPTH_TEXTURE_FORMAT: GPUTextureFormat = 'depth24plus-stencil8';\n\n// feat-20260608-mesh-ssbo-dynamic-grow-l1-lift-1024-entity-cap M2 / T-M2-05:\n// the legacy MESH_SSBO_SLOT_COUNT / MATERIAL_UBO_TOTAL_BYTES /\n// MESH_SSBO_TOTAL_BYTES literal-1024 module constants are gone. The\n// renderer now starts at INITIAL_MESH_SSBO_SLOT_COUNT and grows on demand\n// via `createMeshSsboGrowController` (pow2 doubling, ceiling =\n// device.limits.maxStorageBufferBindingSize / MATERIAL_PER_ENTITY_STRIDE per\n// plan-strategy §2.D-1). The shared allocation stride remains the material\n// owner; only slotCount grows.\nconst INITIAL_MESH_SSBO_SLOT_COUNT = 1024;\n\n// ── createMeshSsboGrowController ───────────────────────────────────────────\n//\n// feat-20260608-mesh-ssbo-dynamic-grow-l1-lift-1024-entity-cap M2 / T-M2-05:\n// pure factory that owns the mesh-SSBO + material-UBO grow state. State is\n// closure-local (plan-strategy §2.D-4: no separate allocator class — state\n// stays beside its createBuffer producer). Outer wrapper-object identity is\n// stable across grow so PipelineState.meshStorageBuffer / materialUniformBuffer\n// references never dangle (research §F8 / §3.1 R1); inner `.buffer` is\n// replaced by a fresh createBuffer return value when the grow path runs.\n//\n// Grow algorithm (AC-05 / AC-06):\n// 1. If `slotCount >= needed` → idempotent guard short-circuits with `{ ok: true }`.\n// 2. Compute `targetSlots = nextPow2 doubling from slotCount until >= needed`.\n// 3. If `targetSlots * stride > device.limits.maxStorageBufferBindingSize`\n// → fire `MeshSsboCeilingReachedError` and return `{ ok: false, code: 'mesh-ssbo-ceiling-reached' }`.\n// No createBuffer is called; recordFrame is expected to skip the frame.\n// 4. createBuffer × 2 (mesh + material) sized at `targetSlots * stride`,\n// using the usage flags captured at construction (mesh = STORAGE|COPY_DST,\n// material = UNIFORM|COPY_DST — both unchanged from initialBuild).\n// 5. Replace `state.mesh.buffer` and `state.material.buffer` in-place;\n// update `state.mesh.sizeInBytes` and `state.material.sizeInBytes`;\n// bump `state.slotCount = targetSlots`.\n// 6. Defensive belt-and-suspenders: if the grow somehow lands with\n// `state.slotCount < needed` (shouldn't happen given the pow2 invariant)\n// → fire `MeshSsboCapacityExceededError` and return capacity-exceeded.\n//\n// Errors flow through `errorRegistry.fire` only (D-5: never throw — keeps the\n// grow surface compatible with the recordFrame outer try/catch without\n// dual-firing through 'webgpu-runtime-error').\n\n/** Pow2 round-up — smallest power of 2 >= n (n>=1). */\nfunction nextPow2(n: number): number {\n if (n <= 1) return 1;\n let v = 1;\n while (v < n) v <<= 1;\n return v;\n}\n\n/**\n * WebGPU spec floor for `maxStorageBufferBindingSize` (128 MiB).\n * @see {@link https://www.w3.org/TR/webgpu/#dom-supported-limits-maxstoragebufferbindingsize}\n */\nconst WEBGPU_SPEC_FLOOR_MAX_STORAGE_BUFFER_BINDING_SIZE = 134217728;\n\n/**\n * Derive a usable storage-buffer ceiling from device limits.\n *\n * Mirrors the `SKIN_PALETTE_MAX_BINDING_BYTES` 0/undefined floor pattern\n * (createRenderer.ts:4070-4073): when `maxStorageBufferBindingSize` is 0 or\n * undefined (WebKit `downlevel_webgl2_defaults`), climb the fallback chain —\n * `maxBufferSize` → `maxUniformBufferBindingSize` → WebGPU spec floor\n * 134217728 (128 MiB).\n *\n * Pure helper — no device dependency, directly testable in node.\n */\nexport function deriveStorageBufferCeiling(\n limits: Readonly<{\n maxStorageBufferBindingSize?: number;\n maxBufferSize?: number;\n maxUniformBufferBindingSize?: number;\n }>,\n): number {\n // Preferred: the device-reported storage-buffer binding size (when > 0).\n if (\n typeof limits.maxStorageBufferBindingSize === 'number' &&\n limits.maxStorageBufferBindingSize > 0\n ) {\n return limits.maxStorageBufferBindingSize;\n }\n // Fallback 1: maxBufferSize (device-level buffer allocation limit).\n if (typeof limits.maxBufferSize === 'number' && limits.maxBufferSize > 0) {\n return limits.maxBufferSize;\n }\n // Fallback 2: maxUniformBufferBindingSize (uniform binding limit, lower\n // but still a real device capacity signal).\n if (\n typeof limits.maxUniformBufferBindingSize === 'number' &&\n limits.maxUniformBufferBindingSize > 0\n ) {\n return limits.maxUniformBufferBindingSize;\n }\n // Fallback 3: WebGPU spec floor — always non-zero, safe as last resort.\n return WEBGPU_SPEC_FLOOR_MAX_STORAGE_BUFFER_BINDING_SIZE;\n}\n\n/**\n * Mesh + material buffer wrapper carrying the inner `Buffer` handle plus\n * the byte-size at the time of allocation. The wrapper-object identity is\n * stable across grow events — only `.buffer` and `.sizeInBytes` are mutated\n * in place — so `PipelineState.meshStorageBuffer` / `materialUniformBuffer`\n * fields capture the wrapper once and survive grow events without a re-bind\n * cycle through the public Renderer surface (research §F8 R1).\n */\nexport interface MeshSsboBufferWrapper {\n buffer: Buffer;\n sizeInBytes: number;\n}\n\n/** Closure-local grow state surfaced for spy assertions in unit tests. */\nexport interface MeshSsboState {\n slotCount: number;\n mesh: MeshSsboBufferWrapper;\n material: MeshSsboBufferWrapper;\n}\n\n/** `growMeshSsbo` return shape (D-5: Result-like, never throws). */\nexport type MeshSsboGrowResult =\n | { readonly ok: true }\n | {\n readonly ok: false;\n readonly code: 'mesh-ssbo-ceiling-reached' | 'mesh-ssbo-capacity-exceeded';\n /** Pre-grow slotCount — the caller can render up to this many slots (degraded subset). */\n readonly degradedToSlotCount: number;\n };\n\n/** Minimal device surface the grow controller needs (mocked in unit tests). */\nexport interface MeshSsboGrowDevice {\n readonly limits: { readonly maxStorageBufferBindingSize: number };\n readonly createBuffer: (descriptor: {\n readonly label?: string;\n readonly size: number;\n readonly usage: number;\n readonly mappedAtCreation?: boolean;\n }) => Buffer;\n}\n\n/** Minimal error-registry surface (just `fire` — `RhiErrorListenerRegistry` matches). */\nexport interface MeshSsboGrowErrorRegistry {\n fire: (e: MeshSsboCeilingReachedError | MeshSsboCapacityExceededError) => void;\n}\n\nexport interface MeshSsboGrowControllerInit {\n readonly device: MeshSsboGrowDevice;\n readonly errorRegistry: MeshSsboGrowErrorRegistry;\n readonly initialSlotCount: number;\n readonly perEntityStride: number;\n readonly meshUsage: number;\n readonly materialUsage: number;\n}\n\nexport interface MeshSsboGrowController {\n readonly state: MeshSsboState;\n /** Allocate the initial mesh + material buffer pair at `initialSlotCount`. */\n readonly initialBuild: () => void;\n /** Grow to satisfy `neededSlots`; idempotent + ceiling-aware. */\n readonly growMeshSsbo: (neededSlots: number) => MeshSsboGrowResult;\n}\n\n/**\n * Build a closure-scoped mesh-SSBO grow controller. Module-scope so unit\n * tests (`__tests__/mesh-ssbo-grow.test.ts`) can construct it with a fake\n * device + spy errorRegistry without spinning up the full WebGPU renderer\n * (charter F2 minimal surface — the controller is the testable seam).\n */\nexport function createMeshSsboGrowController(\n init: MeshSsboGrowControllerInit,\n): MeshSsboGrowController {\n const { device, errorRegistry, initialSlotCount, perEntityStride, meshUsage, materialUsage } =\n init;\n // Wrapper-object identity is set once and shared with PipelineState.\n // Inner buffer + sizeInBytes are mutated in place during grow.\n const meshWrapper: MeshSsboBufferWrapper = {\n buffer: undefined as unknown as Buffer,\n sizeInBytes: 0,\n };\n const materialWrapper: MeshSsboBufferWrapper = {\n buffer: undefined as unknown as Buffer,\n sizeInBytes: 0,\n };\n const state: MeshSsboState = {\n slotCount: 0,\n mesh: meshWrapper,\n material: materialWrapper,\n };\n let initialised = false;\n\n const allocBufferPair = (slots: number): void => {\n const sizeInBytes = slots * perEntityStride;\n const meshBuf = device.createBuffer({\n label: 'pbr-mesh-ssbo',\n size: sizeInBytes,\n usage: meshUsage,\n mappedAtCreation: false,\n });\n const materialBuf = device.createBuffer({\n label: 'pbr-material-ubo',\n size: sizeInBytes,\n usage: materialUsage,\n mappedAtCreation: false,\n });\n meshWrapper.buffer = meshBuf;\n meshWrapper.sizeInBytes = sizeInBytes;\n materialWrapper.buffer = materialBuf;\n materialWrapper.sizeInBytes = sizeInBytes;\n state.slotCount = slots;\n };\n\n const initialBuild = (): void => {\n if (initialised) return;\n initialised = true;\n allocBufferPair(initialSlotCount);\n };\n\n const growMeshSsbo = (neededSlots: number): MeshSsboGrowResult => {\n // (1) idempotent guard — already large enough.\n if (state.slotCount >= neededSlots) {\n return { ok: true };\n }\n // (2) pow2 double until >= needed.\n let target = state.slotCount > 0 ? state.slotCount : 1;\n while (target < neededSlots) target = target * 2;\n // Round up to nextPow2 of needed in case slotCount is 0 / not pow2.\n target = Math.max(target, nextPow2(neededSlots));\n const ceilingBytes = deriveStorageBufferCeiling(device.limits);\n const targetBytes = target * perEntityStride;\n // (3) ceiling check — refuse + fire structured error.\n if (targetBytes > ceilingBytes) {\n errorRegistry.fire(\n new MeshSsboCeilingReachedError(neededSlots, state.slotCount, ceilingBytes),\n );\n return {\n ok: false,\n code: 'mesh-ssbo-ceiling-reached',\n degradedToSlotCount: state.slotCount,\n };\n }\n // (4) + (5) allocate fresh buffers + replace inner refs.\n allocBufferPair(target);\n // (6) defensive belt-and-suspenders.\n if (state.slotCount < neededSlots) {\n errorRegistry.fire(\n new MeshSsboCapacityExceededError(neededSlots, state.slotCount, ceilingBytes),\n );\n return {\n ok: false,\n code: 'mesh-ssbo-capacity-exceeded',\n degradedToSlotCount: state.slotCount,\n };\n }\n return { ok: true };\n };\n\n return { state, initialBuild, growMeshSsbo };\n}\n\n// feat-20260613 fix-issue-1 (D-8 channelMap split, AC-07 std140 layout):\n// per-entity material slice carries the post-split sidecar paramSchema for\n// default-standard-pbr (14 numeric entries packed std140 across 96 B):\n// baseColor : vec4<f32> 16 B (offset 0)\n// metallic + roughness + 4 channel selectors 4*f32 numeric run (offset 16..40)\n// (implicit pad to 48 -- vec3 align=16)\n// emissive : vec3<f32> 12 B (offset 48)\n// emissiveIntensity : f32 +4 B (offset 60)\n// occlusionStrength : f32 +4 B (offset 64)\n// = 96 B (alignUp 16)\n// The material dynamic-offset stride is `MATERIAL_PER_ENTITY_STRIDE = 512`;\n// the mesh dynamic-offset stride remains `MESH_PER_ENTITY_STRIDE = 256` in the\n// record path. The material BindGroup entry's `size` matches the 128 B bind\n// window, so the trailing 512 - 128 = 384 B of the reserved material slot is\n// unread by the shader. The material SSOT lives in `./render-system.ts` so\n// record consumers can import it without a createRenderer cycle (charter P5).\n\n/**\n * Build the `Renderer.ready` Promise (D-S3 three-step strict-serial chain).\n *\n * Steps run in order; any rejection short-circuits the chain and the\n * resulting Promise rejects with a structured `RhiError` / `ShaderError`.\n * AI users `await renderer.ready` once before the first `draw(world)` call;\n * subsequent frames may skip the await (the Promise stays resolved).\n *\n * Step 1 (manifest load): `shader.loadManifest()` populates the runtime\n * registry. Failure = `ShaderError 'manifest-malformed'` /\n * `'shader-not-found'`.\n *\n * Step 2 (pipeline compile): synthesises the PBR pipeline (3 BindGroupLayout\n * + 1 PipelineLayout + 1 ShaderModule + 1 RenderPipeline). Failure =\n * `RhiError 'shader-compile-failed'` / `'feature-not-enabled'` /\n * `'limit-exceeded'`.\n *\n * Mesh GPU buffers are intentionally absent here. Record resolves each mesh\n * from its owning World and lazily establishes device residency.\n */\n/**\n * bug-20260601-hello-tonemap-material-register M1: prepare engine-shipped\n * material shaders (cap gate + manifest load + registration) before the\n * renderer is returned so that `register<MaterialAsset>` referencing an\n * engine shader (e.g. `forgeax::default-standard-pbr`) succeeds without\n * waiting for `renderer.ready` (plan-strategy D-1/D-2/D-5).\n *\n * Failures (cap-gate insufficient, manifest-malformed, shader-not-found)\n * throw structured `RhiError` / `ShaderError` which propagate through\n * `createRenderer`'s synchronous reject path (D-2 structured reject).\n */\nasync function prepareMaterialShaders(\n rhiDevice: RhiDevice,\n getShader: () => ShaderRegistry,\n // feat-20260629 M4: populated with uvSetCount from naga reflection JSON\n // keyed by materialShaderId; consumed by getMaterialShaderPipeline for\n // auto-fill of shaderUvSetCount clamp-to-last alias parameter.\n materialShaderUvSetCounts: Map<string, number>,\n): Promise<void> {\n // ── Step 0: storage-buffer cap gate ───────────────────────────────────────\n const capValue = (rhiDevice.limits as Readonly<Record<string, number>>)\n .maxStorageBuffersPerShaderStage;\n const webgl2Downlevel = rhiDevice.caps.backendKind === 'wgpu-webgl2';\n let storageBufferCapable = !webgl2Downlevel;\n if (typeof capValue === 'number') {\n const capCheck = assertStorageBufferCap(capValue);\n if (!capCheck.ok) throw capCheck.error;\n storageBufferCapable = !webgl2Downlevel && capCheck.value;\n }\n\n // ── Step 1: manifest load ─────────────────────────────────────────────────\n const registry = getShader();\n const loaded = await registry.loadManifest();\n if (!loaded.ok) {\n throw loaded.error;\n }\n\n // ── Step 1b: material shader variant resolution + registration ───────────\n // feat-20260609-hdrp-cluster-fragment-ggx M1 / w7: dual-axis variant\n // resolution. At boot time isHdrpActive is always false (URP default),\n // so CLUSTER_FORWARD_AVAILABLE=false variant is selected. HDRP variant\n // (CLUSTER_FORWARD_AVAILABLE=true) is resolved later when\n // installPipeline(hdrpAsset) activates HDRP.\n const isHdrpActive = false; // M4: wire to actual renderSystem.frameState.isHdrpActive\n for (const msEntry of registry.materialShaderManifestEntries()) {\n // bug-20260610: skip synthetic non-material engine entries piggy-backing\n // on the materialShaders channel for variant surfacing (shadow_caster).\n // They use the `forgeax::engine-` prefix and are consumed by Step 2's\n // engine-entry compile path, NOT by installMaterialArtifact.\n if (msEntry.identifier.startsWith('forgeax::engine-')) continue;\n // buildVariantKey logic: sorted key=value pairs joined with +; all-true = ''.\n const variantDefines: Record<string, boolean> = {\n STORAGE_BUFFER_AVAILABLE: storageBufferCapable,\n };\n // Only include CLUSTER_FORWARD_AVAILABLE when the material shader declares\n // the axis (has a variant with this key), preserving backward compat for\n // entries without the pragma.\n if (msEntry.variants.some((v) => 'CLUSTER_FORWARD_AVAILABLE' in v.defines)) {\n variantDefines.CLUSTER_FORWARD_AVAILABLE = isHdrpActive;\n }\n if (msEntry.variants.some((v) => 'VERTEX_COLOR_AVAILABLE' in v.defines)) {\n variantDefines.VERTEX_COLOR_AVAILABLE = false;\n }\n // bug-20260708 M2 (a): PER_INSTANCE_REGION axis default = false at boot.\n // Per-entity spritePH path (`main-pass-sprite-draws.ts:511-513`) expects\n // `variantSet=undefined` to resolve to the PIR=false shader source (64B\n // InstanceData) via `lookup.value.source` fallback in\n // `getMaterialShaderPipeline`. The PIR=true canonical variant (80B) is\n // reserved for SpriteInstances batches which explicitly request it via\n // `SPRITE_PASS_PER_INSTANCE_REGION_VARIANT_SET === ''` (canonical all-\n // true) — resolved through `findVariantByKey(msEntry, '')` in the same\n // `getMaterialShaderPipeline` substitution branch. Mirrors the\n // CLUSTER_FORWARD_AVAILABLE pattern above: axis default false unless\n // explicitly requested by a caller variantSet.\n if (msEntry.variants.some((v) => 'PER_INSTANCE_REGION' in v.defines)) {\n variantDefines.PER_INSTANCE_REGION = false;\n }\n const sortedEntries = Object.entries(variantDefines).sort(([a], [b]) =>\n a < b ? -1 : a > b ? 1 : 0,\n );\n const definesKey = sortedEntries.every(([, v]) => v === true)\n ? ''\n : sortedEntries.map(([k, v]) => `${k}=${v}`).join('+');\n const chosen = findVariantByKey(msEntry, definesKey);\n const wgsl = chosen?.composedWgsl ?? msEntry.composedWgsl;\n if (wgsl.length > 0) {\n const existing = registry.findMaterialArtifact(msEntry.identifier);\n if (existing.ok) continue;\n const paramSchema = JSON.parse(\n msEntry.paramSchema,\n ) as readonly import('@forgeax/engine-types').ParamSchemaEntry[];\n // feat-20260613-material-paramschema-driven-binding M3 / w12-w13:\n // paramSchema is the SSOT; the BGL is derived on demand via\n // `derive(paramSchema).bglEntries` and consumed by\n // buildPbrPipelineLayouts at pipeline-build time. The historical\n // separate bind-layout sidecar field has been deleted from\n // MaterialShaderEntry / MaterialRuntimeInfo (D-1 / D-2).\n registry.installMaterialArtifact(msEntry.identifier, {\n source: wgsl,\n paramSchema,\n });\n // feat-20260629 M4: store uvSetCount from naga reflection for\n // auto-fill in getMaterialShaderPipeline clamp-to-last alias.\n if (msEntry.uvSetCount !== undefined) {\n materialShaderUvSetCounts.set(msEntry.identifier, msEntry.uvSetCount);\n }\n // Sanity check the schema parses through derive — a malformed sidecar\n // schema (e.g. unknown type literal) should fail loud at register time\n // (charter P3 explicit failure). The derived output is discarded; the\n // SSOT consumer is buildPbrPipelineLayouts later.\n derive(paramSchema);\n }\n }\n\n // ── Step 1c: register forgeax::default-shadow-caster from its manifest identity ──\n // feat-20260609-pipeline-driven-pass-selector-shadowcaster-via-mat M3 / T-007:\n // The reserved material-shader identifier is the SSOT. Content heuristics are\n // invalid here: a game-authored vertex-only shader can legitimately expose\n // position without normal (billboards and procedural VFX commonly do), and\n // must never be mistaken for the engine shadow caster merely because it is\n // encountered first in the flat manifest.\n const shadowCasterIdentifier = 'forgeax::default-shadow-caster';\n if (!registry.findMaterialArtifact(shadowCasterIdentifier).ok) {\n const manifestEntry = Array.from(registry.materialShaderManifestEntries()).find(\n (candidate) => candidate.identifier === shadowCasterIdentifier,\n );\n if (manifestEntry !== undefined) {\n // shadow_caster has no authored material parameters. M3 / w12-w13\n // (D-2 / D-12): derive([]) is the graceful empty-schema path.\n registry.installMaterialArtifact(shadowCasterIdentifier, {\n source: manifestEntry.composedWgsl,\n paramSchema: [],\n });\n }\n }\n}\n\nasync function buildReadyWebGPU(\n rhiDevice: RhiDevice,\n getShader: () => ShaderRegistry,\n gpuStore: GpuResourceStore,\n asyncCreateShaderModule:\n | ((\n device: RhiDevice,\n desc: { code: string; label?: string | undefined },\n ) => Promise<Result<ShaderModule, RhiError>>)\n | undefined,\n errorRegistry: RhiErrorListenerRegistry,\n /**\n * Material shader modules declared by producer features. These are compiled\n * during Renderer.ready so prepared graphics do not fail on their first\n * frame while the shared async shader adapter is still warming up.\n */\n requiredMaterialShaders: readonly string[],\n // feat-20260608-mesh-ssbo-dynamic-grow-l1-lift-1024-entity-cap M2 /\n // T-M2-05 + M3 / T-M3-04: surface for setting `internals.growMeshSsbo`\n // + `internals.meshSsboState` so the record stage's\n // `ensureMeshSsboCapacity` hook can reach both. The mesh-SSBO grow\n // controller is owned in this function's scope, so the cleanest expose\n // path is a callback that buildReadyWebGPU invokes once after\n // `meshSsboController` is wired (the alternative — returning the\n // function + state alongside the PipelineState — bloats every\n // successful call site for two optional hooks).\n setGrowMeshSsboHook: (\n hook: (neededSlots: number) => MeshSsboGrowResult,\n state: MeshSsboState,\n ) => void,\n // feat-20260609 R3-fixup: seed-shader-module hook the lazy\n // MaterialShader pipeline cache adapter exposes (see\n // makeShaderDeviceAdapter / ShaderDeviceAdapterInternal). Used to seed\n // the shadow_caster module under\n // `module-forgeax::default-shadow-caster` so the lazy PSO build hits\n // OK on frame 1 (no 1-frame warmup for the engine-shipped shadow\n // caster).\n seedShaderModule: (label: string, module: ShaderModule) => void,\n // M6 fix-up (feat-20260615-pipeline-spec-ssot): seed-pipeline hook the\n // outer `makeWebGPURenderer` exposes for `materialShaderPipelineCache`.\n // Invoked once per URP-variant SPEC_CONST entry after the boot-time\n // prewarm completes, so the URP record path's first-frame\n // `getMaterialShaderPipeline` lookup hits a live PSO instead of falling\n // into a 1-frame async-compile skip-draw window. Idempotent: caller\n // guards against re-seeding when a key already exists.\n seedMaterialShaderPipelineCache: (key: string, pso: RenderPipeline) => void,\n // feat-20260621 M-A3 (D-5): register the engine built-in tonemap onto the\n // unified post-process channel once the tonemap manifest entry's composed\n // WGSL is resolved. Invoked with the tonemap WGSL source string; the outer\n // `makeWebGPURenderer` closure forwards it to\n // `renderSystem.postProcess.register('forgeax::tonemap', { source, params })`.\n // Scope bridge mirrors `setGrowMeshSsboHook` / `seedShaderModule`: the\n // tonemap source resolves inside this async function (after the manifest-load\n // await), by which point the synchronous `renderSystem` const is defined.\n registerBuiltinTonemap: (source: string) => void,\n registerBuiltinDeferredLighting: (source: string) => void,\n setBootMaterialLayoutInputs: (layouts: {\n readonly viewBgl: BindGroupLayout;\n readonly meshArrayBgl: BindGroupLayout;\n readonly instancesBgl: BindGroupLayout;\n }) => void,\n): Promise<PipelineState> {\n // bug-20260610: WebGL2 fallback path — read storage-buffer capability up\n // front so both Step 2 (shader-module compile, where we patch engine\n // entries to the STORAGE_BUFFER_AVAILABLE=false variant) and Step 3\n // (buildPbrPipelineLayouts, which switches between read-only-storage\n // and uniform BGL entries) walk the same axis. Step 0 already ran in\n // `prepareMaterialShaders`; this is an idempotent re-read driven by\n // `device.limits.maxStorageBuffersPerShaderStage`, which is 0 on the\n // wgpu-wasm WebGL2 backend (downlevel_webgl2_defaults).\n const capValue = (rhiDevice.limits as Readonly<Record<string, number>>)\n .maxStorageBuffersPerShaderStage;\n const webgl2Downlevel = rhiDevice.caps.backendKind === 'wgpu-webgl2';\n let storageBufferCapable = !webgl2Downlevel;\n if (typeof capValue === 'number') {\n const capCheck = assertStorageBufferCap(capValue);\n storageBufferCapable = capCheck.ok ? !webgl2Downlevel && capCheck.value : !webgl2Downlevel;\n }\n\n // bug-20260612: choose swap-chain storage / view formats by backend.\n // Channel 2 (native WebGPU) follows navigator.gpu.getPreferredCanvasFormat();\n // Channel 3 (wgpu-wasm GLES, storageBufferCapable=false) hard-codes\n // rgba8unorm. The pair flows into PipelineState.format /\n // .colorAttachmentFormat below and through it into every downstream\n // pipeline target, configure() call, and color-attachment format —\n // single SSOT, no scattered branches. See selectSwapChainFormat\n // (above the SWAP_CHAIN_*_FORMAT historical constants).\n const swapChainFormats = selectSwapChainFormat(storageBufferCapable);\n // The 'null' (headless RhiNull) backend has no UA preferred-canvas-format by\n // design; the rgba8unorm fallback is its intended steady state, not a\n // degraded one — firing 'rhi-not-available' there is territorially wrong\n // (the backend IS available) and only pollutes Renderer.onError in headless\n // CI. Skip the diagnostic for it; Channel 2/3 still report a missing\n // getPreferredCanvasFormat as before.\n if (swapChainFormats.fallbackReason !== undefined && rhiDevice.caps.backendKind !== 'null') {\n // Step ③ in selectSwapChainFormat fired — surface a structured\n // diagnostic through the RhiError channel so AI users subscribed via\n // Renderer.onError(cb) can detect \"extremely-old UA / missing\n // navigator.gpu.getPreferredCanvasFormat\" and react. The renderer\n // continues with the rgba8unorm fallback (charter §9 graceful\n // degradation; charter P3 explicit failure — no silent fallback).\n errorRegistry.fire(\n new RhiError({\n code: 'rhi-not-available',\n expected: 'navigator.gpu.getPreferredCanvasFormat is callable on Channel 2',\n hint: 'browser is too old or WebGPU implementation incomplete; falling back to rgba8unorm swap-chain format. Update the UA or use a Channel-3-compatible canvas configuration.',\n }),\n );\n }\n\n // ── Step 2: PBR + unlit pipeline compile ───────────────────────────────────\n // bug-20260519 D-1 + D-3: gate the entire PBR / unlit shader-compile block\n // behind `manifestEntries.length > 0`. The Camera-only / clear-pass-only\n // path (LO 1.1 hello-window equivalent) ships an empty manifest -- no\n // PBR/unlit entry to find, no shader module to compile. When the gate is\n // skipped both `unlitModule` and `pbrModule` stay `null` and the later\n // unlit / standard `createRenderPipeline` calls are skipped in turn so\n // the returned `PipelineState.{unlitPipeline,standardPipeline}` fields\n // are written `null` (D-3 nullable). The render-time access point in\n // `render-system-record.ts` narrows on `=== null` and fires a structured\n // `RhiError shader-compile-failed` (charter P3 explicit failure;\n // AC-03). Other PipelineState fields (BindGroupLayout chain / shared\n // buffers / defaultSampler / fallbackTextureView / depthTexture* /\n // identityInstanceBuffer / mesh handles) keep their existing\n // construction so the clear-pass path remains fully wired (D-3\n // explicit scope).\n const registry = getShader();\n //\n // feat-20260518-pbr-direct-lighting-mvp M5 / w22.9 (AC-05 + plan-strategy\n // D-3 + D-4 + dual-pipeline contract w12): the manifest now ships the\n // pbr.wgsl + unlit.wgsl entries written by `@forgeax/engine-vite-plugin-shader`'s\n // `buildStart` hook (engine-entries eager compile via naga_oil). Identify\n // them by content marker (charter P3 explicit failure: silent fallback to\n // a wrong entry would produce mis-shaded pixels indistinguishable from\n // success). pbr.wgsl is the only entry whose composed body contains the\n // `f_schlick(` BRDF helper call; the other engine entry is unlit.\n // M3 D-P4: rhi-webgpu supplies the async factory; rhi-wgpu and the\n // explicit escape hatch fall back to the synchronous device entry.\n const manifestEntries: ManifestEntry[] = [];\n for (const entry of registry.entries()) {\n manifestEntries.push(entry);\n }\n let pbrModule: ShaderModule | null = null;\n let unlitModule: ShaderModule | null = null;\n let spriteModule: ShaderModule | null = null;\n let spriteLitModule: ShaderModule | null = null;\n let fxaaModule: ShaderModule | null = null;\n let taaResolveModule: ShaderModule | null = null;\n let taaResolveResources: TaaResolvePipelineResources | null = null;\n let skyboxModule: ShaderModule | null = null;\n let bloomBrightModule: ShaderModule | null = null;\n let bloomBlurModule: ShaderModule | null = null;\n let bloomCompositeModule: ShaderModule | null = null;\n let ssaoModule: ShaderModule | null = null;\n let atmosphereCubemapModule: ShaderModule | null = null;\n let atmosphereIblModule: ShaderModule | null = null;\n let atmosphereBackgroundModule: ShaderModule | null = null;\n let atmosphereCubemapPipelineHandle: RenderPipeline | null = null;\n let atmosphereCubemapBglHandle: BindGroupLayout | null = null;\n let atmosphereIrradiancePipelineHandle: RenderPipeline | null = null;\n let atmospherePrefilterPipelineHandle: RenderPipeline | null = null;\n let atmosphereIblParamsBglHandle: BindGroupLayout | null = null;\n let atmosphereIblSkyBglHandle: BindGroupLayout | null = null;\n let atmosphereBackgroundPipelineHandle: RenderPipeline | null = null;\n let atmosphereBackgroundBglHandle: BindGroupLayout | null = null;\n let atmosphereParamsBufferHandle: Buffer | null = null;\n let atmosphereCubeVertexBufferHandle: Buffer | null = null;\n const findEngineManifestEntry = (identifier: string): ManifestEntry | undefined => {\n const materialEntry = Array.from(registry.materialShaderManifestEntries()).find(\n (candidate) => candidate.identifier === identifier,\n );\n if (materialEntry === undefined) return undefined;\n return (\n manifestEntries.find((entry) => entry.wgsl === materialEntry.composedWgsl) ?? {\n hash: `engine:${identifier}`,\n wgsl: materialEntry.composedWgsl,\n glsl: undefined,\n bindings: '',\n }\n );\n };\n if (manifestEntries.length > 0) {\n // Merge of bug-20260519 D-1 + D-3 (manifest-zero gate, this branch's\n // outer `if (manifestEntries.length > 0)`) + main feat-20260519-tonemap\n // T-M2.5 (engine SSOT triple — pbr + unlit + tonemap) +\n // feat-20260520-directional-light-shadow-mapping M1c / w9 (shadow_caster\n // as additional engine entry) + feat-20260520-2d-sprite-layer-mvp M-3 / w24\n // (sprite as additional engine entry) + feat-20260520-skylight-ibl-cubemap\n // M5-amend Gap A (4 IBL precompute entries).\n //\n // Manifest non-empty: require pbr + unlit + tonemap; shadow_caster +\n // sprite + IBL entries are optional — absent ones leave their module\n // null and the dependent pipeline stays null (callers fail-fast at\n // dispatch if they relied on a missing entry).\n //\n // Marker triage (charter P3 explicit failure):\n // - tonemap.wgsl: declares `struct TonemapParams`\n // - sprite.wgsl: declares `pivotAndSize` Material field\n // - pbr.wgsl: composes `f_schlick`\n // - shadow_caster.wgsl: only position input (no normal/uv/tangent)\n // - IBL entries: identified by their fragment entry-point markers\n // (equirectToCube_fs / irradianceConvolve_fs / prefilterEnv_fs /\n // brdfLutBake_fs) which survive naga_oil composition unchanged.\n // - unlit.wgsl: none of the above markers → falls into the unlit slot.\n let pbrEntry = findEngineManifestEntry('forgeax::default-standard-pbr');\n let unlitEntry = findEngineManifestEntry('forgeax::default-unlit');\n let tonemapEntry: ManifestEntry | undefined;\n let deferredLightingEntry: ManifestEntry | undefined;\n let spriteEntry: ManifestEntry | undefined;\n // sprite-lit identification marker is the `spriteLitShadeAccum`\n // helper (defined in sprite-lit.wgsl, absent from sprite.wgsl). The\n // outer shading accumulator name is stable across shading-formula\n // changes and unique to sprite-lit. Identified BEFORE sprite so the\n // `pivotAndSize` marker (shared between sprite + sprite-lit since\n // their paramSchema mirror) does not mis-classify sprite-lit as\n // sprite.\n let spriteLitEntry: ManifestEntry | undefined;\n let iblEquirectEntry: ManifestEntry | undefined;\n let iblIrradianceEntry: ManifestEntry | undefined;\n let iblPrefilterEntry: ManifestEntry | undefined;\n let iblBrdfLutEntry: ManifestEntry | undefined;\n let fxaaEntry: ManifestEntry | undefined;\n let taaResolveEntry: ManifestEntry | undefined;\n let skyboxEntry: ManifestEntry | undefined;\n let bloomBrightEntry: ManifestEntry | undefined;\n let bloomBlurEntry: ManifestEntry | undefined;\n let bloomCompositeEntry: ManifestEntry | undefined;\n let ssaoEntry: ManifestEntry | undefined;\n let atmosphereCubemapEntry: ManifestEntry | undefined;\n let atmosphereIblEntry: ManifestEntry | undefined;\n let atmosphereBackgroundEntry: ManifestEntry | undefined;\n // feat-20260609 R3-fixup: shadow_caster module pre-bake. T-009 deleted\n // the hardcoded shadowCasterPipeline; the lazy\n // getMaterialShaderPipeline path (passKind='shadow-caster') uses\n // the shared adapter cache, which is unwarmed for shadow_caster on\n // frame 1. We eagerly compile + seed the adapter cache so the lazy\n // build hit on `module-forgeax::default-shadow-caster` returns OK\n // without a 1-frame warmup. Resolve it by its reserved manifest identity;\n // game shaders are free to use any vertex-input subset.\n let shadowCasterEntry = findEngineManifestEntry('forgeax::default-shadow-caster');\n for (const entry of manifestEntries) {\n if (entry.wgsl.includes('fn fs_lighting')) {\n deferredLightingEntry ??= entry;\n continue;\n }\n if (entry.wgsl.includes('TonemapParams')) {\n tonemapEntry ??= entry;\n continue;\n }\n if (entry.wgsl.includes('spriteLitShadeAccum')) {\n // sprite-lit identification — must precede the `pivotAndSize`\n // marker since sprite-lit also carries that field (paramSchema\n // mirror with sprite.wgsl).\n spriteLitEntry ??= entry;\n continue;\n }\n if (entry.wgsl.includes('pivotAndSize')) {\n spriteEntry ??= entry;\n continue;\n }\n if (entry.wgsl.includes('equirectToCube_fs')) {\n iblEquirectEntry ??= entry;\n continue;\n }\n if (entry.wgsl.includes('irradianceConvolve_fs')) {\n iblIrradianceEntry ??= entry;\n continue;\n }\n if (entry.wgsl.includes('prefilterEnv_fs')) {\n iblPrefilterEntry ??= entry;\n continue;\n }\n if (entry.wgsl.includes('brdfLutBake_fs')) {\n iblBrdfLutEntry ??= entry;\n continue;\n }\n if (entry.wgsl.includes('f_schlick')) {\n pbrEntry ??= entry;\n continue;\n }\n // feat-20260528-fxaa-post-processing: fxaa marker — the composed\n // WGSL contains the rgb2luma helper unique to the FXAA algorithm\n // (plan-strategy D-5). Identified before shadow_caster / unlit\n // fallback so the marker takes priority over generic position-only\n // heuristics.\n if (entry.wgsl.includes('rgb2luma')) {\n fxaaEntry ??= entry;\n continue;\n }\n if (entry.wgsl.includes('TaaResolveParams') && entry.wgsl.includes('fs_taa_resolve')) {\n taaResolveEntry ??= entry;\n continue;\n }\n // feat-20260531-skybox-env-background M3 / w15: skybox marker --\n // the composed WGSL contains the skybox_fs fragment entry point\n // unique to skybox.wgsl (plan-strategy D-7).\n if (entry.wgsl.includes('skybox_fs')) {\n skyboxEntry ??= entry;\n continue;\n }\n if (entry.wgsl.includes('atmosphere_cubemap_fs')) {\n atmosphereCubemapEntry ??= entry;\n continue;\n }\n if (entry.wgsl.includes('atmosphere_irradiance_fs')) {\n atmosphereIblEntry ??= entry;\n continue;\n }\n if (entry.wgsl.includes('atmosphere_background_fs')) {\n atmosphereBackgroundEntry ??= entry;\n continue;\n }\n // feat-20260531-bloom-first-declarative-render-graph-pass / w13:\n // bloom marker triage (D-7). Identify the 3 bloom WGSL modules by their\n // unique uniform-struct names ('BloomBrightParams' in bloom-bright.wgsl,\n // 'BloomBlurParams' in bloom-blur.wgsl shared by H/V pipelines,\n // 'BloomCompositeParams' in bloom-composite.wgsl). Struct names are naga\n // IR and survive naga_oil composition unchanged -- unlike the original\n // `// bloomBrightExtract` content-marker COMMENTS, which naga's WGSL\n // writeback drops (comments are not part of the IR), leaving the markers\n // absent from the composed `entry.wgsl` so the triage never matched and\n // bloom silently never initialised (bug-20260625). Same survives-naga\n // rationale as the SSAO `fs_ssao_calc` entry-point marker below.\n if (entry.wgsl.includes('BloomBrightParams')) {\n bloomBrightEntry ??= entry;\n continue;\n }\n if (entry.wgsl.includes('BloomBlurParams')) {\n bloomBlurEntry ??= entry;\n continue;\n }\n if (entry.wgsl.includes('BloomCompositeParams')) {\n bloomCompositeEntry ??= entry;\n continue;\n }\n // feat-20260612-hdrp-ssao M6 / w27: SSAO marker triage (D-E).\n // The composed WGSL contains 'fs_ssao_calc' fragment entry point\n // which survives naga_oil composition unchanged. Same pattern as\n // the bloom struct-name markers above.\n if (entry.wgsl.includes('fs_ssao_calc')) {\n ssaoEntry ??= entry;\n continue;\n }\n unlitEntry ??= entry;\n }\n // The null backend is intentionally headless: its shader module and\n // pipeline handles are structural, so a minimal manifest is sufficient\n // for lifecycle/assembly tests. Real GPU backends retain the strict\n // shipped-manifest contract below.\n if (\n rhiDevice.caps.backendKind === 'null' &&\n (pbrEntry === undefined || unlitEntry === undefined || tonemapEntry === undefined)\n ) {\n const fallback = (hash: string) =>\n ({ hash, wgsl: '', glsl: '', bindings: '' }) as ManifestEntry;\n pbrEntry ??= fallback('null-pbr');\n unlitEntry ??= fallback('null-unlit');\n tonemapEntry ??= fallback('null-tonemap');\n }\n if (pbrEntry === undefined || unlitEntry === undefined || tonemapEntry === undefined) {\n throw new RhiError({\n code: 'shader-compile-failed',\n expected:\n 'manifest entries include pbr.wgsl + unlit.wgsl + tonemap.wgsl (engine SSOT triple)',\n hint: 'verify @forgeax/engine-vite-plugin-shader emits manifest.json with the 3 engine entries; check vite plugin engineEntries option',\n });\n }\n // The flat `registry.entries()` map carries the canonical composed source,\n // while the runtime layout is selected from the actual device capability\n // and the URP/HDRP owner. Select the same runtime variant for every eager\n // engine module before creating its shader module. This is required for\n // native WebGPU too: the canonical PBR source enables the HDRP cluster\n // bindings, but the boot layout is the URP one until HDRP is activated.\n // A missing variant is intentionally a no-op for older manifests.\n const idToRuntimeVariantWgsl = new Map<string, string>();\n for (const ms of registry.materialShaderManifestEntries()) {\n const exact = ms.variants.find(\n (v) =>\n v.defines.STORAGE_BUFFER_AVAILABLE === storageBufferCapable &&\n (!('CLUSTER_FORWARD_AVAILABLE' in v.defines) ||\n v.defines.CLUSTER_FORWARD_AVAILABLE === false) &&\n (!('VERTEX_COLOR_AVAILABLE' in v.defines) || v.defines.VERTEX_COLOR_AVAILABLE === false),\n );\n const v =\n exact ??\n ms.variants.find(\n (candidate) => candidate.defines.STORAGE_BUFFER_AVAILABLE === storageBufferCapable,\n );\n if (v !== undefined) idToRuntimeVariantWgsl.set(ms.identifier, v.composedWgsl);\n }\n const patchRuntimeVariant = (entry: ManifestEntry, identifier: string): ManifestEntry => {\n const wgsl = idToRuntimeVariantWgsl.get(identifier);\n return wgsl !== undefined ? { ...entry, wgsl } : entry;\n };\n pbrEntry = patchRuntimeVariant(pbrEntry, 'forgeax::default-standard-pbr');\n unlitEntry = patchRuntimeVariant(unlitEntry, 'forgeax::default-unlit');\n if (shadowCasterEntry !== undefined) {\n shadowCasterEntry = patchRuntimeVariant(shadowCasterEntry, 'forgeax::default-shadow-caster');\n }\n if (spriteEntry !== undefined) {\n spriteEntry = patchRuntimeVariant(spriteEntry, 'forgeax::sprite');\n }\n if (spriteLitEntry !== undefined) {\n spriteLitEntry = patchRuntimeVariant(spriteLitEntry, 'forgeax::sprite-lit');\n }\n // bug-20260708 M2 (a): sprite entry WGSL patch — always substitute the\n // PIR=false variant so the eager compile at line ~4272 (which produces\n // `spriteModule`, seeded under `module-forgeax::sprite` at line ~4297 and\n // exposed via `shaderModuleMap.set('forgeax::sprite', ...)` at line\n // ~5438) yields the 5575B PIR=false shader module. The character /\n // sprite-atlas per-entity path (`main-pass-sprite-draws.ts:511-513`)\n // routes `variantSet=undefined` through `getMaterialShaderPipeline`\n // with `moduleLabel='module-forgeax::sprite'` — hitting this seeded\n // module. SpriteInstances batches request `variantSet=''` →\n // `moduleLabel='module-forgeax::sprite#'` (distinct label) → compile\n // fresh from `findVariantByKey(msEntry, '')` returning the PIR=true\n // 5653B variant. The upstream `manifestEntries` populated\n // `spriteEntry.wgsl` with the plugin default (all-true canonical =\n // PIR=true+SBA=true); we substitute the matching-SBA PIR=false variant\n // here. Runs regardless of `storageBufferCapable` — the WebGL2 fallback\n // patch above (bug-20260610) already substitutes SBA=false; we now\n // substitute PIR=false on top so the boot-time seeded module for\n // sprite is aligned with the boot-registered material-shader source\n // (patched at line ~3710 via the PER_INSTANCE_REGION extension above).\n if (spriteEntry !== undefined) {\n for (const msEntry of registry.materialShaderManifestEntries()) {\n if (msEntry.identifier === 'forgeax::sprite') {\n const pirFalseVariant = msEntry.variants.find(\n (v) =>\n v.defines.PER_INSTANCE_REGION === false &&\n v.defines.STORAGE_BUFFER_AVAILABLE === storageBufferCapable,\n );\n if (pirFalseVariant !== undefined) {\n spriteEntry = { ...spriteEntry, wgsl: pirFalseVariant.composedWgsl };\n }\n break;\n }\n }\n }\n // Wire composed IBL shaders into IblPipelineCache before the cache's\n // createIblPipelines runs (called downstream by the internal\n // GpuResourceStore equirect-to-cubemap projection during the first Skylight\n // dispatch). When all 4 are present, register them; otherwise leave\n // the cache untouched (charter F1: tests / non-IBL hosts that ship\n // empty / 3-entry manifests still boot, and the IBL pipeline cache's\n // own error surfacing covers the \"missing\" case downstream).\n if (\n iblEquirectEntry !== undefined &&\n iblIrradianceEntry !== undefined &&\n iblPrefilterEntry !== undefined &&\n iblBrdfLutEntry !== undefined\n ) {\n setIblComposedShaders({\n equirectToCube: iblEquirectEntry.wgsl,\n irradiance: iblIrradianceEntry.wgsl,\n prefilter: iblPrefilterEntry.wgsl,\n brdfLut: iblBrdfLutEntry.wgsl,\n });\n }\n // Producer-declared material shader modules use the same source and module\n // label as getMaterialShaderPipeline. Prewarming them here keeps the\n // renderer.ready barrier meaningful for prepared graphics: the first draw\n // resolves a pipeline instead of publishing a transient preparation error.\n for (const materialShaderId of requiredMaterialShaders) {\n const lookup = registry.findMaterialArtifact(materialShaderId);\n if (!lookup.ok) {\n throw new RhiError({\n code: 'shader-compile-failed',\n expected: `declared render feature material shader '${materialShaderId}' is present in the loaded manifest`,\n hint: `add material shader '${materialShaderId}' to the shader manifest or remove it from the feature declaration`,\n });\n }\n const label = `module-${materialShaderId}`;\n const shaderResult = await runShimStep(\n () =>\n asyncCreateShaderModule\n ? asyncCreateShaderModule(rhiDevice, { code: lookup.value.source, label })\n : invokeDeviceCreateShaderModule(rhiDevice, { code: lookup.value.source, label }),\n 'shader-compile-failed',\n `declared render feature material shader '${materialShaderId}' compiled`,\n `inspect the composed WGSL for '${materialShaderId}' and check device.features`,\n );\n if (!shaderResult.ok) throw shaderResult.error;\n seedShaderModule(label, shaderResult.value);\n }\n\n const pbrShaderResult = await runShimStep(\n () =>\n asyncCreateShaderModule\n ? asyncCreateShaderModule(rhiDevice, { code: pbrEntry.wgsl, label: 'pbr' })\n : invokeDeviceCreateShaderModule(rhiDevice, { code: pbrEntry.wgsl, label: 'pbr' }),\n 'shader-compile-failed',\n 'PBR shader module compiled',\n 'inspect manifest pbr entry composed wgsl; check device.features',\n );\n if (!pbrShaderResult.ok) throw pbrShaderResult.error;\n pbrModule = pbrShaderResult.value;\n // feat-20260629-multi-uv-set-support: a real extra-UV mesh creates a\n // layout-specific material PSO after the boot-time standard-layout PSO\n // has been pre-warmed. Seed the shared shader-module adapter under the\n // exact lazy-build labels so that this first-touch PSO can reuse the\n // already compiled PBR variant instead of returning the transient\n // `rhi-not-available` pending signal in a tight draw loop.\n seedShaderModule('module-forgeax::default-standard-pbr', pbrModule);\n const pbrManifestEntry = [...registry.materialShaderManifestEntries()].find(\n (entry) => entry.identifier === 'forgeax::default-standard-pbr',\n );\n const pbrVariant = pbrManifestEntry?.variants.find(\n (variant) => variant.composedWgsl === pbrEntry.wgsl,\n );\n if (pbrVariant !== undefined) {\n seedShaderModule(`module-forgeax::default-standard-pbr#${pbrVariant.definesKey}`, pbrModule);\n }\n\n // HDRP uses the canonical all-true variant key (`''`) and the lazy\n // material pipeline adapter therefore requests the distinct module label\n // `module-forgeax::default-standard-pbr#`. The boot path intentionally\n // seeds the URP capability variant above, but without this matching HDRP\n // seed the first deferred/forward HDRP PSO reports `rhi-not-available`\n // and skips its draw while the async module adapter warms up. Compile the\n // device-capability-matched HDRP variants through the same shader owner\n // and seed each exact label consumed by getMaterialShaderPipeline.\n const prewarmedHdrpModules = new Map<string, ShaderModule>([[pbrEntry.wgsl, pbrModule]]);\n for (const hdrpVariant of selectHdrpPbrPrewarmVariants(\n pbrManifestEntry,\n storageBufferCapable,\n )) {\n const moduleLabel = `module-forgeax::default-standard-pbr#${hdrpVariant.definesKey}`;\n let hdrpModule = prewarmedHdrpModules.get(hdrpVariant.composedWgsl);\n if (hdrpModule === undefined) {\n const hdrpModuleResult = await runShimStep(\n () =>\n asyncCreateShaderModule\n ? asyncCreateShaderModule(rhiDevice, {\n code: hdrpVariant.composedWgsl,\n label: moduleLabel,\n })\n : invokeDeviceCreateShaderModule(rhiDevice, {\n code: hdrpVariant.composedWgsl,\n label: moduleLabel,\n }),\n 'shader-compile-failed',\n 'HDRP PBR shader module compiled',\n 'inspect the composed HDRP PBR variant WGSL and check device.features',\n );\n if (!hdrpModuleResult.ok) throw hdrpModuleResult.error;\n hdrpModule = hdrpModuleResult.value;\n prewarmedHdrpModules.set(hdrpVariant.composedWgsl, hdrpModule);\n }\n seedShaderModule(moduleLabel, hdrpModule);\n }\n\n // M2-07-c: Materials.standard with an explicit renderState reaches the\n // lazy material pipeline path, whose module label includes the requested\n // variant set. Reuse the boot-compiled PBR module only for manifest\n // variants with byte-identical composed WGSL; HDRP and WebGL2 variants\n // keep their own module identities and are never aliased here.\n for (const materialEntry of registry.materialShaderManifestEntries()) {\n for (const variant of materialEntry.variants) {\n if (variant.composedWgsl === pbrEntry.wgsl) {\n seedShaderModule(`module-${materialEntry.identifier}#${variant.definesKey}`, pbrModule);\n }\n }\n }\n\n const unlitShaderResult = await runShimStep(\n () =>\n asyncCreateShaderModule\n ? asyncCreateShaderModule(rhiDevice, { code: unlitEntry.wgsl, label: 'unlit' })\n : invokeDeviceCreateShaderModule(rhiDevice, { code: unlitEntry.wgsl, label: 'unlit' }),\n 'shader-compile-failed',\n 'unlit shader module compiled',\n 'inspect manifest unlit entry composed wgsl; check device.features',\n );\n if (!unlitShaderResult.ok) throw unlitShaderResult.error;\n unlitModule = unlitShaderResult.value;\n // Seed the shared lazy adapter with the eagerly compiled module so\n // prepared color-only PSOs build synchronously on their first frame.\n seedShaderModule('unlit', unlitModule);\n // Material render-state variants use the canonical material id as their\n // module-cache label. Seed that alias too so a first-frame stencil,\n // blend, or cull variant does not skip its draw while the adapter warms.\n seedShaderModule('module-forgeax::default-unlit', unlitModule);\n // The canonical colored unlit variant uses the empty defines key. Its\n // WGSL differs from the boot-time no-color module, so seed the exact lazy\n // label used by `getMaterialShaderPipeline` instead of letting the first\n // colored draw fall back to the no-color PSO while shader compilation\n // catches up.\n const unlitManifestEntry = [...registry.materialShaderManifestEntries()].find(\n (entry) => entry.identifier === 'forgeax::default-unlit',\n );\n const coloredUnlitVariant = unlitManifestEntry?.variants.find(\n (variant) =>\n variant.defines.VERTEX_COLOR_AVAILABLE === true &&\n variant.defines.STORAGE_BUFFER_AVAILABLE === storageBufferCapable,\n );\n if (coloredUnlitVariant !== undefined && coloredUnlitVariant.composedWgsl !== unlitEntry.wgsl) {\n const coloredUnlitShaderResult = await runShimStep(\n () =>\n asyncCreateShaderModule\n ? asyncCreateShaderModule(rhiDevice, {\n code: coloredUnlitVariant.composedWgsl,\n label: 'unlit-vertex-color',\n })\n : invokeDeviceCreateShaderModule(rhiDevice, {\n code: coloredUnlitVariant.composedWgsl,\n label: 'unlit-vertex-color',\n }),\n 'shader-compile-failed',\n 'colored unlit shader module compiled',\n 'inspect the VERTEX_COLOR_AVAILABLE=true unlit variant and device.features',\n );\n if (!coloredUnlitShaderResult.ok) throw coloredUnlitShaderResult.error;\n seedShaderModule(\n `module-forgeax::default-unlit#${coloredUnlitVariant.definesKey}`,\n coloredUnlitShaderResult.value,\n );\n }\n // The default-unlit record path requests the explicit URP no-color key\n // for meshes without COLOR_0. Seed that exact lazy module label too;\n // otherwise Browser's first synchronous frame can skip the no-color PSO\n // while the async shader adapter warms, leaving a black primitive even\n // though the same projection succeeds on Dawn.\n const uncoloredUnlitVariant = unlitManifestEntry?.variants.find(\n (variant) =>\n variant.defines.VERTEX_COLOR_AVAILABLE === false &&\n variant.defines.STORAGE_BUFFER_AVAILABLE === storageBufferCapable,\n );\n if (uncoloredUnlitVariant !== undefined) {\n const uncoloredUnlitLabel = `module-forgeax::default-unlit#${uncoloredUnlitVariant.definesKey}`;\n seedShaderModule(uncoloredUnlitLabel, unlitModule);\n }\n\n // feat-20260609 R3-fixup: eagerly compile shadow_caster module + seed\n // the lazy MaterialShader pipeline cache adapter so the first frame's\n // shadow PSO build (passKind='shadow-caster') hits OK without a\n // 1-frame warmup. T-009 deleted the hardcoded shadowCasterPipeline;\n // the lazy path replaces it but the adapter cache key\n // ('module-forgeax::default-shadow-caster') was previously unwarmed,\n // causing the first frame's createShaderModule to return\n // 'rhi-not-available' and the shadow PSO build to fail (which left\n // the shadow depth attachment unwritten). Optional: when the manifest\n // omits shadow_caster (legacy hosts), the lazy path simply falls\n // through to the existing 1-frame retry; no regression.\n if (shadowCasterEntry !== undefined) {\n const shadowCasterShaderResult = await runShimStep(\n () =>\n asyncCreateShaderModule\n ? asyncCreateShaderModule(rhiDevice, {\n code: shadowCasterEntry.wgsl,\n label: 'shadow_caster',\n })\n : invokeDeviceCreateShaderModule(rhiDevice, {\n code: shadowCasterEntry.wgsl,\n label: 'shadow_caster',\n }),\n 'shader-compile-failed',\n 'shadow_caster shader module compiled',\n 'inspect manifest shadow_caster entry composed wgsl; check device.features',\n );\n if (!shadowCasterShaderResult.ok) throw shadowCasterShaderResult.error;\n // Seed the adapter cache under the same label\n // (`module-${materialShaderId}`) that getMaterialShaderPipeline\n // uses so the lazy build's createShaderModule call hits OK on\n // frame 1.\n seedShaderModule('module-forgeax::default-shadow-caster', shadowCasterShaderResult.value);\n }\n\n // feat-20260621 M-A3 (D-5): register the built-in tonemap onto the unified\n // post-process channel instead of building a dedicated pipeline. The composed\n // tonemap WGSL (`tonemapEntry.wgsl`, @group(1) bindings after w16) becomes the\n // registered `entry.source`; `postProcess.register` eager-creates the 16 B\n // params UBO (fail-fast). The empty-manifest path never reaches here (the\n // manifest triple guard above throws when tonemapEntry is undefined), so\n // registration is unconditional within this gate.\n //\n // Eager pre-warm (zero-regression): the dedicated tonemap pipeline used to be\n // built during `ready`, so tonemap rendered correctly on frame 1 with NO\n // event-loop yield. The unified `getPostProcessPipeline` lazy path otherwise\n // returns `rhi-not-available` until the async shader-compile promise resolves\n // -- a consumer driving `draw()` in a tight loop without an `await` between\n // frames (e.g. the hello-tonemap dawn smoke) would stall on a black frame\n // forever. Mirror the shadow_caster prewarm: await-compile the tonemap module\n // here and `seedShaderModule` it under the exact label\n // `buildPostProcessPipeline` requests (`post-process-${id}-module`), so the\n // first `getPostProcessPipeline('forgeax::tonemap', …)` hits the module cache\n // synchronously and builds the pipeline on frame 1.\n const tonemapPrewarm = await runShimStep(\n () =>\n asyncCreateShaderModule\n ? asyncCreateShaderModule(rhiDevice, {\n code: tonemapEntry.wgsl,\n label: `post-process-${TONEMAP_POST_PROCESS_ID}-module`,\n })\n : invokeDeviceCreateShaderModule(rhiDevice, {\n code: tonemapEntry.wgsl,\n label: `post-process-${TONEMAP_POST_PROCESS_ID}-module`,\n }),\n 'shader-compile-failed',\n 'tonemap shader module compiled (unified post-process prewarm)',\n 'inspect manifest tonemap entry composed wgsl; check device.features',\n );\n if (!tonemapPrewarm.ok) throw tonemapPrewarm.error;\n seedShaderModule(`post-process-${TONEMAP_POST_PROCESS_ID}-module`, tonemapPrewarm.value);\n registerBuiltinTonemap(tonemapEntry.wgsl);\n\n if (deferredLightingEntry !== undefined) {\n const deferredLightingPrewarm = await runShimStep(\n () =>\n asyncCreateShaderModule\n ? asyncCreateShaderModule(rhiDevice, {\n code: deferredLightingEntry.wgsl,\n label: `post-process-${HDRP_DEFERRED_LIGHTING_POST_PROCESS_ID}-module`,\n })\n : invokeDeviceCreateShaderModule(rhiDevice, {\n code: deferredLightingEntry.wgsl,\n label: `post-process-${HDRP_DEFERRED_LIGHTING_POST_PROCESS_ID}-module`,\n }),\n 'shader-compile-failed',\n 'HDRP deferred lighting shader module compiled',\n 'inspect manifest hdrp-deferred-lighting entry composed wgsl',\n );\n if (!deferredLightingPrewarm.ok) throw deferredLightingPrewarm.error;\n seedShaderModule(\n `post-process-${HDRP_DEFERRED_LIGHTING_POST_PROCESS_ID}-module`,\n deferredLightingPrewarm.value,\n );\n registerBuiltinDeferredLighting(deferredLightingEntry.wgsl);\n }\n\n // feat-20260520-2d-sprite-layer-mvp M-3 / w24: sprite shader module\n // is optional in the 3-tuple legacy manifest (back-compat for apps\n // that locked their manifest URL before this feat). With the\n // vite-plugin-shader 4-entry surface (M-3 / w20), spriteEntry is\n // present and we build both LDR + HDR sprite pipeline variants.\n if (spriteEntry !== undefined) {\n const spriteShaderResult = await runShimStep(\n () =>\n asyncCreateShaderModule\n ? asyncCreateShaderModule(rhiDevice, { code: spriteEntry.wgsl, label: 'sprite' })\n : invokeDeviceCreateShaderModule(rhiDevice, {\n code: spriteEntry.wgsl,\n label: 'sprite',\n }),\n 'shader-compile-failed',\n 'sprite shader module compiled',\n 'inspect manifest sprite entry composed wgsl; check device.features',\n );\n if (!spriteShaderResult.ok) throw spriteShaderResult.error;\n spriteModule = spriteShaderResult.value;\n // feat-20260625-refactor-sprite-as-transparent-mesh CI-fix: seed the\n // lazy adapter cache under the same label (`module-forgeax::sprite`)\n // that `getMaterialShaderPipeline -> buildAndCachePipeline ->\n // buildPipelineForMaterialShader` uses, so the first lazy build of\n // the sprite PSO at LDR transparent-split time hits the module cache\n // on frame 1 and does NOT trip the 1-frame `rhi-not-available` skip\n // (which surfaces as `shader-compile-failed` \"manifest entries\n // include sprite.wgsl\" at the spritePH===null branch in\n // render-system-record.ts §spritePass). Mirrors the\n // `module-forgeax::default-shadow-caster` prewarm above; the pre-\n // feat-20260625 dedicated `spritePipeline` baked the module into a\n // boot-time PSO so this seed step was implicit. Post-w14 the sprite\n // shares the generic per-MaterialShader lazy build path, which now\n // needs the explicit seed to preserve frame-1 readiness.\n seedShaderModule('module-forgeax::sprite', spriteShaderResult.value);\n }\n\n // feat-20260624-sprite-lit-shading-model-pure-2d-lighting M1' / t7:\n // sprite-lit shader module — mirrors sprite registration shape (same\n // lazy-build seed under `module-forgeax::sprite-lit`). Optional in the\n // manifest (back-compat for apps locked to a pre-sprite-lit manifest URL).\n if (spriteLitEntry !== undefined) {\n const spriteLitEntryConst = spriteLitEntry;\n const spriteLitShaderResult = await runShimStep(\n () =>\n asyncCreateShaderModule\n ? asyncCreateShaderModule(rhiDevice, {\n code: spriteLitEntryConst.wgsl,\n label: 'sprite-lit',\n })\n : invokeDeviceCreateShaderModule(rhiDevice, {\n code: spriteLitEntryConst.wgsl,\n label: 'sprite-lit',\n }),\n 'shader-compile-failed',\n 'sprite-lit shader module compiled',\n 'inspect manifest sprite-lit entry composed wgsl; check device.features',\n );\n if (!spriteLitShaderResult.ok) throw spriteLitShaderResult.error;\n spriteLitModule = spriteLitShaderResult.value;\n seedShaderModule('module-forgeax::sprite-lit', spriteLitShaderResult.value);\n }\n\n // feat-20260528-fxaa-post-processing: fxaa shader module is optional\n // (apps with legacy manifests without fxaa.wgsl continue to boot).\n // Identified by rgb2luma content marker (plan-strategy D-5). When\n // present, the module is compiled here; pipeline construction happens\n // alongside the tonemap pipeline below (step 2 prebuild).\n if (fxaaEntry !== undefined) {\n const fxaaShaderResult = await runShimStep(\n () =>\n asyncCreateShaderModule\n ? asyncCreateShaderModule(rhiDevice, { code: fxaaEntry.wgsl, label: 'fxaa' })\n : invokeDeviceCreateShaderModule(rhiDevice, {\n code: fxaaEntry.wgsl,\n label: 'fxaa',\n }),\n 'shader-compile-failed',\n 'fxaa shader module compiled',\n 'inspect manifest fxaa entry composed wgsl; check device.features',\n );\n if (!fxaaShaderResult.ok) throw fxaaShaderResult.error;\n fxaaModule = fxaaShaderResult.value;\n }\n\n if (taaResolveEntry !== undefined) {\n const taaResolveShaderResult = await runShimStep(\n () =>\n asyncCreateShaderModule\n ? asyncCreateShaderModule(rhiDevice, {\n code: taaResolveEntry.wgsl,\n label: 'taa-resolve',\n })\n : invokeDeviceCreateShaderModule(rhiDevice, {\n code: taaResolveEntry.wgsl,\n label: 'taa-resolve',\n }),\n 'shader-compile-failed',\n 'TAA resolve shader module compiled',\n 'inspect the taa-resolve manifest entry and packed temporal ABI',\n );\n if (!taaResolveShaderResult.ok) throw taaResolveShaderResult.error;\n taaResolveModule = taaResolveShaderResult.value;\n const created = createTaaResolvePipelineResources(rhiDevice, taaResolveModule);\n if (!created.ok) throw created.error;\n taaResolveResources = created.value;\n }\n\n // feat-20260531-skybox-env-background M3 / w15: skybox shader module.\n // Optional (apps with legacy manifests without skybox.wgsl continue to\n // boot). Identified by skybox_fs content marker (plan-strategy D-7).\n // Compiled here; pipeline construction happens alongside tonemap/fxaa\n // in step 2 prebuild below.\n if (skyboxEntry !== undefined) {\n const skyboxShaderResult = await runShimStep(\n () =>\n asyncCreateShaderModule\n ? asyncCreateShaderModule(rhiDevice, { code: skyboxEntry.wgsl, label: 'skybox' })\n : invokeDeviceCreateShaderModule(rhiDevice, {\n code: skyboxEntry.wgsl,\n label: 'skybox',\n }),\n 'shader-compile-failed',\n 'skybox shader module compiled',\n 'inspect manifest skybox entry composed wgsl; check device.features',\n );\n if (!skyboxShaderResult.ok) throw skyboxShaderResult.error;\n skyboxModule = skyboxShaderResult.value;\n }\n\n if (atmosphereCubemapEntry !== undefined) {\n const atmosphereCubemapShaderResult = await runShimStep(\n () =>\n asyncCreateShaderModule\n ? asyncCreateShaderModule(rhiDevice, {\n code: atmosphereCubemapEntry.wgsl,\n label: 'atmosphere-cubemap',\n })\n : invokeDeviceCreateShaderModule(rhiDevice, {\n code: atmosphereCubemapEntry.wgsl,\n label: 'atmosphere-cubemap',\n }),\n 'shader-compile-failed',\n 'atmosphere cubemap shader module compiled',\n 'inspect manifest atmosphere-cubemap entry and preetham imports',\n );\n if (!atmosphereCubemapShaderResult.ok) throw atmosphereCubemapShaderResult.error;\n atmosphereCubemapModule = atmosphereCubemapShaderResult.value;\n }\n\n if (atmosphereIblEntry !== undefined) {\n const atmosphereIblShaderResult = await runShimStep(\n () =>\n asyncCreateShaderModule\n ? asyncCreateShaderModule(rhiDevice, {\n code: atmosphereIblEntry.wgsl,\n label: 'atmosphere-ibl',\n })\n : invokeDeviceCreateShaderModule(rhiDevice, {\n code: atmosphereIblEntry.wgsl,\n label: 'atmosphere-ibl',\n }),\n 'shader-compile-failed',\n 'atmosphere IBL shader module compiled',\n 'inspect manifest atmosphere-ibl entry and sky-cube sampling imports',\n );\n if (!atmosphereIblShaderResult.ok) throw atmosphereIblShaderResult.error;\n atmosphereIblModule = atmosphereIblShaderResult.value;\n }\n\n if (atmosphereBackgroundEntry !== undefined) {\n const atmosphereBackgroundShaderResult = await runShimStep(\n () =>\n asyncCreateShaderModule\n ? asyncCreateShaderModule(rhiDevice, {\n code: atmosphereBackgroundEntry.wgsl,\n label: 'atmosphere-background',\n })\n : invokeDeviceCreateShaderModule(rhiDevice, {\n code: atmosphereBackgroundEntry.wgsl,\n label: 'atmosphere-background',\n }),\n 'shader-compile-failed',\n 'atmosphere background shader module compiled',\n 'inspect manifest atmosphere-background entry and View imports',\n );\n if (!atmosphereBackgroundShaderResult.ok) throw atmosphereBackgroundShaderResult.error;\n atmosphereBackgroundModule = atmosphereBackgroundShaderResult.value;\n }\n\n // Analytic atmosphere uses one executable producer for every cube face and\n // one fullscreen consumer for the background plus the independent Sun\n // disc. Both pipelines share the renderer's View UBO and a single params\n // buffer, so the graph owns no second camera or Sun contract.\n if (\n atmosphereCubemapModule !== null &&\n atmosphereIblModule !== null &&\n atmosphereBackgroundModule !== null\n ) {\n const cubemapModule = atmosphereCubemapModule;\n const iblModule = atmosphereIblModule;\n const backgroundModule = atmosphereBackgroundModule;\n const atmosphereCubemapBglResult = runShimSyncStep(\n () =>\n rhiDevice.createBindGroupLayout({\n label: 'atmosphere-cubemap-bgl',\n entries: [\n {\n binding: 0,\n visibility: GPU_SHADER_STAGE_VERTEX | GPU_SHADER_STAGE_FRAGMENT,\n buffer: { type: 'uniform' },\n },\n ],\n }),\n 'webgpu-runtime-error',\n 'createBindGroupLayout(atmosphere cubemap) succeeded',\n 'verify atmosphere-cubemap.wgsl uniform binding',\n );\n if (!atmosphereCubemapBglResult.ok) throw atmosphereCubemapBglResult.error;\n atmosphereCubemapBglHandle = atmosphereCubemapBglResult.value;\n const atmosphereBackgroundBglResult = runShimSyncStep(\n () =>\n rhiDevice.createBindGroupLayout({\n label: 'atmosphere-background-bgl',\n entries: [\n {\n binding: 0,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n texture: { sampleType: 'float', viewDimension: 'cube' },\n },\n {\n binding: 1,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n sampler: { type: 'filtering' },\n },\n {\n binding: 2,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n buffer: { type: 'uniform' },\n },\n {\n binding: 3,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n buffer: { type: 'uniform' },\n },\n ],\n }),\n 'webgpu-runtime-error',\n 'createBindGroupLayout(atmosphere background) succeeded',\n 'verify atmosphere-background.wgsl texture, View, and params bindings',\n );\n if (!atmosphereBackgroundBglResult.ok) throw atmosphereBackgroundBglResult.error;\n atmosphereBackgroundBglHandle = atmosphereBackgroundBglResult.value;\n const atmosphereIblParamsBglResult = runShimSyncStep(\n () =>\n rhiDevice.createBindGroupLayout({\n label: 'atmosphere-ibl-params-bgl',\n entries: [\n {\n binding: 0,\n visibility: GPU_SHADER_STAGE_VERTEX | GPU_SHADER_STAGE_FRAGMENT,\n buffer: { type: 'uniform' },\n },\n ],\n }),\n 'webgpu-runtime-error',\n 'createBindGroupLayout(atmosphere IBL params) succeeded',\n 'verify atmosphere-ibl.wgsl params binding',\n );\n if (!atmosphereIblParamsBglResult.ok) throw atmosphereIblParamsBglResult.error;\n atmosphereIblParamsBglHandle = atmosphereIblParamsBglResult.value;\n const atmosphereIblSkyBglResult = runShimSyncStep(\n () =>\n rhiDevice.createBindGroupLayout({\n label: 'atmosphere-ibl-sky-bgl',\n entries: [\n {\n binding: 0,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n texture: { sampleType: 'float', viewDimension: 'cube' },\n },\n {\n binding: 1,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n sampler: { type: 'filtering' },\n },\n ],\n }),\n 'webgpu-runtime-error',\n 'createBindGroupLayout(atmosphere IBL sky) succeeded',\n 'verify atmosphere-ibl.wgsl sky cube bindings',\n );\n if (!atmosphereIblSkyBglResult.ok) throw atmosphereIblSkyBglResult.error;\n atmosphereIblSkyBglHandle = atmosphereIblSkyBglResult.value;\n\n const cubemapLayoutResult = runShimSyncStep(\n () =>\n rhiDevice.createPipelineLayout({\n label: 'atmosphere-cubemap-pl',\n bindGroupLayouts: [atmosphereCubemapBglResult.value],\n }),\n 'webgpu-runtime-error',\n 'createPipelineLayout(atmosphere cubemap) succeeded',\n 'verify atmosphere cubemap BGL',\n );\n if (!cubemapLayoutResult.ok) throw cubemapLayoutResult.error;\n const backgroundLayoutResult = runShimSyncStep(\n () =>\n rhiDevice.createPipelineLayout({\n label: 'atmosphere-background-pl',\n bindGroupLayouts: [atmosphereBackgroundBglResult.value],\n }),\n 'webgpu-runtime-error',\n 'createPipelineLayout(atmosphere background) succeeded',\n 'verify atmosphere background BGL',\n );\n if (!backgroundLayoutResult.ok) throw backgroundLayoutResult.error;\n const atmosphereIblLayoutResult = runShimSyncStep(\n () =>\n rhiDevice.createPipelineLayout({\n label: 'atmosphere-ibl-pl',\n bindGroupLayouts: [atmosphereIblParamsBglResult.value, atmosphereIblSkyBglResult.value],\n }),\n 'webgpu-runtime-error',\n 'createPipelineLayout(atmosphere IBL) succeeded',\n 'verify atmosphere IBL params and sky BGLs',\n );\n if (!atmosphereIblLayoutResult.ok) throw atmosphereIblLayoutResult.error;\n\n const vertexLayout = {\n arrayStride: 12,\n attributes: [{ shaderLocation: 0, offset: 0, format: 'float32x3' as const }],\n };\n const cubemapPipelineResult = runShimSyncStep(\n () =>\n rhiDevice.createRenderPipeline({\n label: 'atmosphere-cubemap-pipeline',\n layout: cubemapLayoutResult.value,\n vertex: {\n module: cubemapModule,\n entryPoint: 'atmosphere_cubemap_vs',\n buffers: [vertexLayout],\n },\n fragment: {\n module: cubemapModule,\n entryPoint: 'atmosphere_cubemap_fs',\n targets: [{ format: HDR_COLOR_ATTACHMENT_FORMAT }],\n },\n primitive: { topology: 'triangle-list', cullMode: 'none' },\n } as unknown as Parameters<typeof rhiDevice.createRenderPipeline>[0]),\n 'webgpu-runtime-error',\n 'createRenderPipeline(atmosphere cubemap) succeeded',\n 'inspect atmosphere cubemap entry points and HDR attachment format',\n );\n if (!cubemapPipelineResult.ok) throw cubemapPipelineResult.error;\n atmosphereCubemapPipelineHandle = cubemapPipelineResult.value;\n const atmosphereIrradiancePipelineResult = runShimSyncStep(\n () =>\n rhiDevice.createRenderPipeline({\n label: 'atmosphere-irradiance-pipeline',\n layout: atmosphereIblLayoutResult.value,\n vertex: {\n module: iblModule,\n entryPoint: 'atmosphere_ibl_vs',\n buffers: [vertexLayout],\n },\n fragment: {\n module: iblModule,\n entryPoint: 'atmosphere_irradiance_fs',\n targets: [{ format: HDR_COLOR_ATTACHMENT_FORMAT }],\n },\n primitive: { topology: 'triangle-list', cullMode: 'none' },\n } as unknown as Parameters<typeof rhiDevice.createRenderPipeline>[0]),\n 'webgpu-runtime-error',\n 'createRenderPipeline(atmosphere irradiance) succeeded',\n 'inspect atmosphere IBL irradiance entry point and HDR attachment format',\n );\n if (!atmosphereIrradiancePipelineResult.ok) throw atmosphereIrradiancePipelineResult.error;\n atmosphereIrradiancePipelineHandle = atmosphereIrradiancePipelineResult.value;\n const atmospherePrefilterPipelineResult = runShimSyncStep(\n () =>\n rhiDevice.createRenderPipeline({\n label: 'atmosphere-prefilter-pipeline',\n layout: atmosphereIblLayoutResult.value,\n vertex: {\n module: iblModule,\n entryPoint: 'atmosphere_ibl_vs',\n buffers: [vertexLayout],\n },\n fragment: {\n module: iblModule,\n entryPoint: 'atmosphere_prefilter_fs',\n targets: [{ format: HDR_COLOR_ATTACHMENT_FORMAT }],\n },\n primitive: { topology: 'triangle-list', cullMode: 'none' },\n } as unknown as Parameters<typeof rhiDevice.createRenderPipeline>[0]),\n 'webgpu-runtime-error',\n 'createRenderPipeline(atmosphere prefilter) succeeded',\n 'inspect atmosphere IBL prefilter entry point and HDR attachment format',\n );\n if (!atmospherePrefilterPipelineResult.ok) throw atmospherePrefilterPipelineResult.error;\n atmospherePrefilterPipelineHandle = atmospherePrefilterPipelineResult.value;\n const backgroundPipelineResult = runShimSyncStep(\n () =>\n rhiDevice.createRenderPipeline({\n label: 'atmosphere-background-pipeline',\n layout: backgroundLayoutResult.value,\n vertex: {\n module: backgroundModule,\n entryPoint: 'atmosphere_background_vs',\n buffers: [],\n },\n fragment: {\n module: backgroundModule,\n entryPoint: 'atmosphere_background_fs',\n targets: [{ format: HDR_COLOR_ATTACHMENT_FORMAT }],\n },\n primitive: { topology: 'triangle-list', cullMode: 'none' },\n depthStencil: {\n format: 'depth24plus-stencil8',\n depthWriteEnabled: false,\n depthCompare: 'less-equal',\n },\n } as unknown as Parameters<typeof rhiDevice.createRenderPipeline>[0]),\n 'webgpu-runtime-error',\n 'createRenderPipeline(atmosphere background) succeeded',\n 'inspect atmosphere background entry points and HDR attachment format',\n );\n if (!backgroundPipelineResult.ok) throw backgroundPipelineResult.error;\n atmosphereBackgroundPipelineHandle = backgroundPipelineResult.value;\n\n const atmosphereParamsResult = runShimSyncStep(\n () =>\n rhiDevice.createBuffer({\n label: 'atmosphere-params-ubo',\n size: ATMOSPHERE_PARAMS_SLOT_BYTES * ATMOSPHERE_PARAMS_SLOT_COUNT,\n usage: GPU_BUFFER_USAGE_UNIFORM | GPU_BUFFER_USAGE_COPY_DST,\n mappedAtCreation: false,\n }),\n 'webgpu-runtime-error',\n 'createBuffer(atmosphere params) succeeded',\n `check uniform-buffer limits for analytic atmosphere (${ATMOSPHERE_PARAMS_BYTES} B per slot)`,\n );\n if (!atmosphereParamsResult.ok) throw atmosphereParamsResult.error;\n atmosphereParamsBufferHandle = atmosphereParamsResult.value;\n const atmosphereCubeVertexResult = runShimSyncStep(\n () =>\n rhiDevice.createBuffer({\n label: 'atmosphere-cube-vertices',\n size: ATMOSPHERE_FACE_VERTICES.byteLength,\n usage: GPU_BUFFER_USAGE_VERTEX | GPU_BUFFER_USAGE_COPY_DST,\n mappedAtCreation: false,\n }),\n 'webgpu-runtime-error',\n 'createBuffer(atmosphere cube vertices) succeeded',\n 'check vertex-buffer allocation for analytic atmosphere',\n );\n if (!atmosphereCubeVertexResult.ok) throw atmosphereCubeVertexResult.error;\n atmosphereCubeVertexBufferHandle = atmosphereCubeVertexResult.value;\n const vertexWrite = rhiDevice.queue.writeBuffer(\n atmosphereCubeVertexBufferHandle,\n 0,\n ATMOSPHERE_FACE_VERTICES,\n );\n if (!vertexWrite.ok) throw vertexWrite.error;\n }\n\n // feat-20260531-bloom-first-declarative-render-graph-pass / w13:\n // bloom shader modules are optional (apps with legacy manifests without\n // bloom.wgsl continue to boot). Identified by the uniform-struct-name\n // markers 'BloomBrightParams' / 'BloomBlurParams' / 'BloomCompositeParams'\n // (see triage above; struct names survive naga_oil composition). When\n // present, each module is compiled here; pipeline construction happens\n // alongside the FXAA / tonemap pipelines below.\n if (bloomBrightEntry !== undefined) {\n const brightShaderResult = await runShimStep(\n () =>\n asyncCreateShaderModule\n ? asyncCreateShaderModule(rhiDevice, {\n code: bloomBrightEntry.wgsl,\n label: 'bloom-bright',\n })\n : invokeDeviceCreateShaderModule(rhiDevice, {\n code: bloomBrightEntry.wgsl,\n label: 'bloom-bright',\n }),\n 'shader-compile-failed',\n 'bloom-bright shader module compiled',\n 'inspect manifest bloom-bright entry composed wgsl; check device.features',\n );\n if (!brightShaderResult.ok) throw brightShaderResult.error;\n bloomBrightModule = brightShaderResult.value;\n }\n if (bloomBlurEntry !== undefined) {\n const blurShaderResult = await runShimStep(\n () =>\n asyncCreateShaderModule\n ? asyncCreateShaderModule(rhiDevice, {\n code: bloomBlurEntry.wgsl,\n label: 'bloom-blur',\n })\n : invokeDeviceCreateShaderModule(rhiDevice, {\n code: bloomBlurEntry.wgsl,\n label: 'bloom-blur',\n }),\n 'shader-compile-failed',\n 'bloom-blur shader module compiled',\n 'inspect manifest bloom-blur entry composed wgsl; check device.features',\n );\n if (!blurShaderResult.ok) throw blurShaderResult.error;\n bloomBlurModule = blurShaderResult.value;\n }\n if (bloomCompositeEntry !== undefined) {\n const compositeShaderResult = await runShimStep(\n () =>\n asyncCreateShaderModule\n ? asyncCreateShaderModule(rhiDevice, {\n code: bloomCompositeEntry.wgsl,\n label: 'bloom-composite',\n })\n : invokeDeviceCreateShaderModule(rhiDevice, {\n code: bloomCompositeEntry.wgsl,\n label: 'bloom-composite',\n }),\n 'shader-compile-failed',\n 'bloom-composite shader module compiled',\n 'inspect manifest bloom-composite entry composed wgsl; check device.features',\n );\n if (!compositeShaderResult.ok) throw compositeShaderResult.error;\n bloomCompositeModule = compositeShaderResult.value;\n }\n // feat-20260612-hdrp-ssao M6 / w27: SSAO shader module compilation.\n // Optional manifest entry — absent on legacy manifests (zero-overhead\n // opt-out, same as bloom). Identified by 'fs_ssao_calc' content marker.\n if (ssaoEntry !== undefined) {\n const entry = ssaoEntry;\n const ssaoShaderResult = await runShimStep(\n () =>\n asyncCreateShaderModule\n ? asyncCreateShaderModule(rhiDevice, {\n code: entry.wgsl,\n label: 'hdrp-ssao',\n })\n : invokeDeviceCreateShaderModule(rhiDevice, {\n code: entry.wgsl,\n label: 'hdrp-ssao',\n }),\n 'shader-compile-failed',\n 'hdrp-ssao shader module compiled',\n 'inspect manifest hdrp-ssao entry composed wgsl; check device.features',\n );\n if (!ssaoShaderResult.ok) throw ssaoShaderResult.error;\n ssaoModule = ssaoShaderResult.value;\n }\n }\n\n // feat-20260520-skylight-ibl-cubemap M4 round-4 / t59: the PBR pipeline\n // layout construction migrated to `pbr-pipeline.ts buildPbrPipelineLayouts`.\n // The factory builds 4 BindGroupLayouts (view + material + mesh-array +\n // instances) and the 4-slot pipeline layout in one call, throwing on any\n // device.createBindGroupLayout / device.createPipelineLayout failure.\n // material BGL now carries 14 entries (material 0..6 + Skylight 7..13 via\n // mergeSkylightIntoMaterialBgl) -- pipeline layout itself stays at 4 slots,\n // no @group(4) allocated (D-5 round-4 fix for the round-2 maxBindGroups=4\n // BLOCKER). The unlit pipeline currently shares this 14-entry layout\n // (carrying fallback identity at binding 7..13 from the record stage);\n // future split via `buildUnlitMaterialBgl` is exposed for tests.\n //\n // feat-20260520-directional-light-shadow-mapping merge: view BGL entries\n // include binding(3) shadowMap + binding(4) comparison sampler (extended\n // in `buildPbrViewBglEntries`); the shadow caster pipeline + shadow RT\n // remain owned by createRenderer below, but the layout is shared.\n // bug-20260610: storageBufferCapable is hoisted to the top of\n // buildReadyWebGPU (above) so Step 2 (variant patch) and this layout\n // build read the same value.\n const pbrLayouts = runShimSyncStep(\n // biome-ignore lint/suspicious/noExplicitAny: rhiDevice BGL desc 'entries' is mutable per @webgpu/types; PbrPipelineDevice narrows on readonly\n () => ok(buildPbrPipelineLayouts(rhiDevice as any, { storageBuffer: storageBufferCapable })),\n 'webgpu-runtime-error',\n 'buildPbrPipelineLayouts succeeded',\n 'check device.limits.maxBindingsPerBindGroup (need >=14) and maxBindGroupsPerPipelineLayout',\n );\n if (!pbrLayouts.ok) throw pbrLayouts.error;\n setBootMaterialLayoutInputs({\n viewBgl: pbrLayouts.value.viewBgl,\n meshArrayBgl: pbrLayouts.value.meshArrayBgl,\n instancesBgl: pbrLayouts.value.instancesBgl,\n });\n const viewBglResult = ok(pbrLayouts.value.viewBgl);\n const materialBglResult = ok(pbrLayouts.value.materialBgl);\n const meshArrayBglResult = ok(pbrLayouts.value.meshArrayBgl);\n const instancesBglResult = ok(pbrLayouts.value.instancesBgl);\n const pipelineLayoutResult = ok(pbrLayouts.value.pipelineLayout);\n\n // feat-20260609-hdrp-cluster-fragment-ggx M4.5 / w36 (D-10 option A):\n // boot-time build of the HDRP-variant PipelineLayout. The 4-BGL chain is\n // [view, material, hdrp-unified-7-slot, instances]; the HDRP unified BGL\n // (createHdrpBindGroupLayoutDescriptor) replaces the 1-slot pbr-mesh-array\n // BGL at group(2) so an HDRP-variant PSO validates against the 7-slot\n // group(2) bindGroup that the record stage sets via hdrpClusterBindGroup.\n // Stays null when createBindGroupLayout / createPipelineLayout fails;\n // selectPipelineLayoutForVariant gracefully falls back to pbrPipelineLayout\n // (URP layout) so the manifest entry's URP variant WGSL still builds a\n // valid PSO instead of hard-disabling the entire HDRP-variant build path.\n let hdrpPbrPipelineLayoutHandle: PipelineLayout | null = null;\n {\n const hdrpUnifiedBglDesc = createHdrpBindGroupLayoutDescriptor(storageBufferCapable);\n // biome-ignore lint/suspicious/noExplicitAny: rhiDevice BGL desc 'entries' mutable per @webgpu/types\n const hdrpUnifiedBglRes = rhiDevice.createBindGroupLayout(hdrpUnifiedBglDesc as any);\n if (hdrpUnifiedBglRes.ok) {\n const hdrpPlRes = rhiDevice.createPipelineLayout({\n label: 'hdrp-pbr-pl',\n bindGroupLayouts: [\n viewBglResult.value,\n materialBglResult.value,\n hdrpUnifiedBglRes.value,\n instancesBglResult.value,\n ],\n });\n if (hdrpPlRes.ok) {\n hdrpPbrPipelineLayoutHandle = hdrpPlRes.value;\n }\n }\n }\n\n // The storage path can move the repeated light/cluster membership materializer\n // into the same command buffer as the deferred lighting pass. This is an\n // optional producer: module or pipeline creation failure leaves the CPU\n // binner active, and non-storage backends never attempt the path.\n let hdrpClusterMembershipPipeline: ComputePipeline | null = null;\n let hdrpClusterMembershipBindGroupLayout: BindGroupLayout | null = null;\n if (\n storageBufferCapable &&\n rhiDevice.caps.compute &&\n pbrModule !== null &&\n unlitModule !== null\n ) {\n const producerBgl = rhiDevice.createBindGroupLayout(\n createHdrpClusterMembershipBindGroupLayoutDescriptor(),\n );\n if (producerBgl.ok) {\n hdrpClusterMembershipBindGroupLayout = producerBgl.value;\n }\n const membershipModule = asyncCreateShaderModule\n ? await asyncCreateShaderModule(rhiDevice, {\n code: HDRP_CLUSTER_MEMBERSHIP_WGSL,\n label: 'hdrp-cluster-membership',\n })\n : await invokeDeviceCreateShaderModule(rhiDevice, {\n code: HDRP_CLUSTER_MEMBERSHIP_WGSL,\n label: 'hdrp-cluster-membership',\n });\n if (membershipModule.ok && hdrpClusterMembershipBindGroupLayout !== null) {\n const producerLayout = rhiDevice.createPipelineLayout({\n label: 'hdrp-cluster-membership-pl',\n bindGroupLayouts: [hdrpClusterMembershipBindGroupLayout],\n });\n if (producerLayout.ok) {\n const membershipPipeline = rhiDevice.createComputePipeline({\n label: 'hdrp-cluster-membership',\n layout: producerLayout.value,\n compute: {\n module: membershipModule.value,\n entryPoint: 'cs_cluster_membership',\n },\n });\n if (membershipPipeline.ok) {\n hdrpClusterMembershipPipeline = membershipPipeline.value;\n }\n } else {\n hdrpClusterMembershipBindGroupLayout = null;\n }\n }\n }\n\n // bug-20260611-skin-pipeline-layout-mesh-array-bgl-2bindings: boot-time\n // build of the skin-variant PipelineLayout. Mirrors the HDRP block above\n // (D-2 / D-3 in plan-strategy): reuse view / material / instances BGLs\n // from `pbrLayouts` and only create a 3-entry mesh-array BGL (binding 0\n // meshes + bindings 1/2 current/previous palettes) so the `forgeax::pbr-skin` shader's\n // `@group(2) @binding(1) palette` declaration validates. Stays null when\n // createBindGroupLayout / createPipelineLayout fails;\n // selectPipelineLayoutForVariant returns null in that case (charter P3\n // explicit failure -- no silent fallback to URP layout, mirroring memory\n // anchor `hdrp-active-must-not-fallback-to-urp-pipeline`).\n let pbrSkinPipelineLayoutHandle: PipelineLayout | null = null;\n // feat-20260611 R2 / M8 / w28: capture the 3-binding skin mesh-array BGL\n // produced by `buildPbrSkinLayouts` so the record stage can build a BG\n // matching `pbr-skin-pl` (pipeline-layout BGL[2] is this 3-entry skin\n // BGL, NOT the 1-entry `pbr-mesh-array-bgl`). The BGL handle stays null\n // when the skin pipeline layout itself failed to build, keeping the skin\n // path explicitly disabled (charter P3 — record-stage falls back to URP\n // path which is correct for non-skin entries; skin entries hit the\n // explicit-failure branch).\n let pbrSkinMeshBindGroupLayoutHandle: BindGroupLayout | null = null;\n {\n const skinLayoutsResult = runShimSyncStep(\n () =>\n ok(\n buildPbrSkinLayouts(\n // biome-ignore lint/suspicious/noExplicitAny: PbrPipelineDevice shim aligns with rhiDevice interface\n rhiDevice as any,\n { storageBuffer: storageBufferCapable },\n pbrLayouts.value,\n ),\n ),\n 'webgpu-runtime-error',\n 'buildPbrSkinLayouts succeeded',\n 'check device.limits.maxBindingsPerBindGroup (need >=14) and maxBindGroupsPerPipelineLayout',\n );\n if (skinLayoutsResult.ok) {\n pbrSkinPipelineLayoutHandle = skinLayoutsResult.value.pipelineLayout;\n pbrSkinMeshBindGroupLayoutHandle = skinLayoutsResult.value.meshArrayBgl;\n }\n }\n\n // feat-20260612-skin-palette-per-frame-upload M1 / m1-2: skin palette\n // allocator. Replaces the prior 16320 B identity-seeded UBO stub (PR #353,\n // feat-20260611 R2 / M8 / w28 IS-14, retired identity-buffer field) with\n // the animator-ready `SkinPaletteAllocator` from\n // `./systems/skin-palette-allocator`. Per\n // plan-strategy D-1 candidate (b) the allocator is the single\n // authoritative carrier of the palette GPU resource -- no parallel\n // identity-fallback buffer; the boot code only constructs the allocator\n // and the per-frame extract / record stages drive `allocateSlice` +\n // `writeJointPalette` (M2 / M3) to land animated palette data. The\n // allocator's `buffer` is `null` until the first `allocateSlice` call\n // grows it, and the record stage gates skin entries on `pbrSkinPipelineLayout`\n // + `skinPaletteAllocator.buffer !== null` (charter P3 explicit failure).\n //\n // M6 fix: the cap is the device's max BUFFER binding size for the\n // selected usage path -- NOT 16320 B (that's the static BG @binding(1)\n // ENTRY size, a per-draw window slid by dynamic offset; the underlying\n // buffer must span every entity's window so `dynOffset + entry.size <=\n // buffer.size` holds for the last skinned draw). Pre-M6 conflated the\n // two and rejected the 2nd skin entity with SkinPaletteOverflowError.\n //\n // Storage path -> `maxStorageBufferBindingSize`; uniform fallback ->\n // `maxUniformBufferBindingSize` (WebGPU spec floor 64 KiB; 16320 still\n // fits 4 entities back-to-back even on the floor).\n const skinPaletteLimitKey = storageBufferCapable\n ? 'maxStorageBufferBindingSize'\n : 'maxUniformBufferBindingSize';\n const skinPaletteDeviceLimit = (rhiDevice.limits as Readonly<Record<string, number>>)[\n skinPaletteLimitKey\n ];\n const SKIN_PALETTE_MAX_BINDING_BYTES =\n typeof skinPaletteDeviceLimit === 'number' && skinPaletteDeviceLimit > 0\n ? skinPaletteDeviceLimit\n : 65536; // WebGPU spec floor for maxUniformBufferBindingSize\n const skinPaletteAllocatorHandle: SkinPaletteAllocator = createSkinPaletteAllocator(\n rhiDevice,\n SKIN_PALETTE_MAX_BINDING_BYTES,\n storageBufferCapable,\n );\n\n // bug-20260519: the legacy `pbr-pipeline-unlit-builtin` (6F-stride + a\n // 24-byte zero-fill dummy VBO that hard-coded uv=(0,0)) is gone. Procedural\n // geometry ships 12-floats per vertex (pos + normal + uv + tangent),\n // identical to procedural meshes, so a single (`unlit-procedural` /\n // `standard`) pipeline pair covers every renderable.\n\n const queue = rhiDevice.queue;\n\n // ── Step 3.b: per-pipeline shared UBO / SSBO buffers ──────────────────────\n // The 3 BindGroups (view / material / mesh) the pbr.wgsl pipeline expects\n // are built per draw(world) frame in render-system.ts; the underlying\n // buffers are pipeline-scoped (allocated once, queue.writeBuffer-updated\n // per frame). The mesh storage path uses a runtime-sized\n // array<Mesh> bound up to instanceCount * 64 B per draw\n // (feat-20260511-tetris-retro-followups M4 D-P9); the buffer is initially\n // sized for INITIAL_MESH_SSBO_SLOT_COUNT = 1024 slots and grows on demand\n // via `meshSsboController.growMeshSsbo(neededSlots)` (M2 / T-M2-05;\n // pow2 doubling, ceiling = device.limits.maxStorageBufferBindingSize).\n const viewUboResult = runShimSyncStep(\n () =>\n rhiDevice.createBuffer({\n label: 'pbr-view-ubo',\n size: VIEW_UBO_BYTES,\n usage: GPU_BUFFER_USAGE_UNIFORM | GPU_BUFFER_USAGE_COPY_DST,\n mappedAtCreation: false,\n }),\n 'webgpu-runtime-error',\n 'createBuffer (view ubo) succeeded',\n 'check device.limits.maxUniformBufferBindingSize',\n );\n if (!viewUboResult.ok) throw viewUboResult.error;\n\n // feat-20260613-csm-cascaded-shadow-maps M5 / w28: per-pass cascade-index\n // UBO consumed by shadow_caster.wgsl. Stable singleton; the record stage\n // queue.writeBuffer-overwrites the fields immediately before each pass's\n // command-encoder submit, and the per-pass submits serialize host writes\n // against GPU reads.\n //\n // feat-20260625-spot-light-shadow-mapping M2 / w10 + w11 (D-1): grew 16 -> 80\n // B. First 16 B carry `index` u32 + `isSpot` u32 + 2 pad u32 (keeps the\n // mat4 16 B-aligned for WebGL2); the trailing 64 B carry `spotLightViewProj`\n // mat4x4<f32>, written per spot tile pass by recordSpotShadowPass and read by\n // the shadow_caster spot branch. Directional cascade passes leave isSpot=0\n // and ignore the matrix lanes.\n const shadowCasterCascadeUboResult = runShimSyncStep(\n () =>\n rhiDevice.createBuffer({\n label: 'shadow-caster-cascade-ubo',\n size: SHADOW_CASTER_BUFFER_SIZE,\n usage: GPU_BUFFER_USAGE_UNIFORM | GPU_BUFFER_USAGE_COPY_DST,\n mappedAtCreation: false,\n }),\n 'webgpu-runtime-error',\n 'createBuffer (shadow-caster cascade ubo) succeeded',\n 'check device.limits.maxUniformBufferBindingSize',\n );\n if (!shadowCasterCascadeUboResult.ok) throw shadowCasterCascadeUboResult.error;\n // feat-20260608-mesh-ssbo-dynamic-grow-l1-lift-1024-entity-cap M2 / T-M2-05:\n // mesh + material buffer pair owned by `meshSsboController`; the\n // controller closes over `rhiDevice` + `internals.errorRegistry` so\n // `growMeshSsbo(neededSlots)` (called by record stage in M3) can rebuild\n // both buffers in lock-step (AC-06). Initial allocation lands at\n // `INITIAL_MESH_SSBO_SLOT_COUNT = 1024` slots (parity with the pre-feat\n // legacy literal); subsequent grow events pow2-double in one shot\n // (AC-05). MATERIAL_PER_ENTITY_STRIDE stays at 512 B for the shared\n // allocation — only slot count grows (OOS-10). Wrapper-object identity (`meshSsboState.mesh` /\n // `meshSsboState.material`) is stable across grow so PipelineState\n // fields below reference these wrappers once and survive grow events\n // (research §F8 R1).\n // M5 / T-M5-02 (P0 fix surfaced by GRID_SIZE=46 stress smoke):\n // `MeshSsboGrowDevice.createBuffer` returns a raw `Buffer`, but\n // `rhiDevice.createBuffer` returns `Result<Buffer, RhiError>` (RHI\n // explicit-failure contract). The previous direct cast\n // `rhiDevice as unknown as MeshSsboGrowDevice` smuggled a Result wrapper\n // into `meshWrapper.buffer`, which then surfaced at queue.submit as\n // \"no overload matched for writeBuffer: object is not of the correct\n // interface type\" once the 1024-slot grow path actually fired (any\n // workload >= 1024 entities; M5 culling stress is the first to land).\n // Unit tests at M2-02/03 mock createBuffer to return `Buffer` directly,\n // so they never caught the mismatch. Adapter unwraps the Result here\n // (errors bubble to the surrounding `runShimSyncStep` / record-stage\n // outer try/catch as `webgpu-runtime-error`).\n const meshSsboGrowDeviceAdapter: MeshSsboGrowDevice = {\n limits: rhiDevice.limits,\n createBuffer: (descriptor) => {\n const result = rhiDevice.createBuffer(descriptor);\n if (!result.ok) throw result.error;\n return result.value;\n },\n };\n const meshSsboController = createMeshSsboGrowController({\n device: meshSsboGrowDeviceAdapter,\n errorRegistry: {\n fire: (error) => errorRegistry.fire(error as unknown as RendererError),\n },\n initialSlotCount: INITIAL_MESH_SSBO_SLOT_COUNT,\n perEntityStride: MATERIAL_PER_ENTITY_STRIDE,\n // bug-20260610: WebGL2 fallback uses uniform-buffer for the mesh array\n // (matches the STORAGE_BUFFER_AVAILABLE=false shader variant which\n // declares `var<uniform> meshes : array<Mesh, 128>` instead of\n // `var<storage> meshes : array<Mesh>`).\n meshUsage: storageBufferCapable\n ? GPU_BUFFER_USAGE_STORAGE | GPU_BUFFER_USAGE_COPY_DST\n : GPU_BUFFER_USAGE_UNIFORM | GPU_BUFFER_USAGE_COPY_DST,\n materialUsage: GPU_BUFFER_USAGE_UNIFORM | GPU_BUFFER_USAGE_COPY_DST,\n });\n const initialBuildResult = runShimSyncStep<true>(\n () => {\n meshSsboController.initialBuild();\n return ok(true as const);\n },\n 'webgpu-runtime-error',\n 'createBuffer (mesh ssbo + material ubo initial build) succeeded',\n 'check device.limits.maxStorageBufferBindingSize / maxUniformBufferBindingSize',\n );\n if (!initialBuildResult.ok) throw initialBuildResult.error;\n const meshSsboState = meshSsboController.state;\n // Expose the grow hook + state on internals (via the setGrowMeshSsboHook\n // callback) so M3's record stage `ensureMeshSsboCapacity` can call it\n // (T-M2-05 acceptanceCheck #3 + T-M3-04 wiring: `growMeshSsbo` mention\n // count >= 2 in createRenderer.ts — definition + this exposure).\n setGrowMeshSsboHook(meshSsboController.growMeshSsbo, meshSsboController.state);\n\n // feat-20260519-light-casters-point-spot-pbr M3 / w20 (D-S1 + D-S2):\n // PointLight + SpotLight std430 storage buffers. Header 16 B (count u32 +\n // 12 B pad) + 4-slot first-slice cap (32 B / 48 B per slot). Sized\n // generously so that the buffer.size never changes once allocated; per-\n // frame writeBuffer overwrites the entire range (D-S6 full rewrite +\n // charter P3 explicit failure: stable buffer.size means no orphan slot\n // reuse).\n const POINT_LIGHTS_BUFFER_BYTES =\n LIGHT_ARRAY_HEADER_BYTES + POINT_LIGHT_STD430_BYTES * LIGHT_ARRAY_MAX_SLOTS;\n const SPOT_LIGHTS_BUFFER_BYTES =\n LIGHT_ARRAY_HEADER_BYTES + SPOT_LIGHT_STD430_BYTES * LIGHT_ARRAY_MAX_SLOTS;\n // bug-20260610: WebGL2 fallback — pointLights / spotLights buffers must\n // be UNIFORM-usage (the storage variant of the shader is gated by\n // STORAGE_BUFFER_AVAILABLE; the uniform-fallback path expects uniform\n // buffers). Without this swap, the buffer-creation succeeds (driver still\n // accepts STORAGE flag), but `createBindGroup` validation rejects the\n // mismatch: `Usage flags BufferUsages(COPY_DST | STORAGE) ... do not\n // contain required usage flags BufferUsages(UNIFORM)`.\n const LIGHTS_BUFFER_USAGE = storageBufferCapable\n ? GPU_BUFFER_USAGE_STORAGE | GPU_BUFFER_USAGE_COPY_DST\n : GPU_BUFFER_USAGE_UNIFORM | GPU_BUFFER_USAGE_COPY_DST;\n const pointLightsBufferResult = runShimSyncStep(\n () =>\n rhiDevice.createBuffer({\n label: 'pbr-point-lights-ssbo',\n size: POINT_LIGHTS_BUFFER_BYTES,\n usage: LIGHTS_BUFFER_USAGE,\n mappedAtCreation: false,\n }),\n 'webgpu-runtime-error',\n 'createBuffer (point-lights ssbo) succeeded',\n 'check device.limits.maxStorageBufferBindingSize',\n );\n if (!pointLightsBufferResult.ok) throw pointLightsBufferResult.error;\n const spotLightsBufferResult = runShimSyncStep(\n () =>\n rhiDevice.createBuffer({\n label: 'pbr-spot-lights-ssbo',\n size: SPOT_LIGHTS_BUFFER_BYTES,\n usage: LIGHTS_BUFFER_USAGE,\n mappedAtCreation: false,\n }),\n 'webgpu-runtime-error',\n 'createBuffer (spot-lights ssbo) succeeded',\n 'check device.limits.maxStorageBufferBindingSize',\n );\n if (!spotLightsBufferResult.ok) throw spotLightsBufferResult.error;\n\n // feat-20260513-instanced-mesh M3 (T-M3-2): identity-mat4 fallback\n // storage buffer. Single 64-byte storage buffer carrying one identity\n // mat4 column-major. Renderables without an `Instances` component bind\n // this buffer at @group(3) so the shader's\n // `instances_local[instance_index]` lookup at idx=0 returns I (no\n // additional transform), giving the consistent-abstraction single\n // branch (charter prop 5; plan D-7 fallback semantics). The buffer is\n // seeded once at pipeline creation; the record-stage never rewrites\n // it.\n // bug-20260610: WebGL2 fallback uses uniform-buffer for instances\n // (the shader's `STORAGE_BUFFER_AVAILABLE=false` variant declares\n // `var<uniform> instances : array<InstanceData, 128>`).\n //\n // fix: the shared identity instance buffer is bound at @group(3) for EVERY\n // pipeline variant that lacks per-entity Instances, including the sprite\n // `PER_INSTANCE_REGION=true` variant whose InstanceData is 80 bytes\n // (mat4 64B + region vec4 16B) rather than the base PBR 64B (mat4 only).\n // The transparent split pass reaches that 80B-min-binding pipeline as soon\n // as any transparent geometry exists (e.g. a glTF alphaMode=BLEND material),\n // and a 64B buffer fails WebGPU's min-binding-size validation\n // (\"requires a buffer binding which is at least 80 bytes\"), invalidating the\n // frame's command buffer. Size the shared identity buffer to the largest\n // InstanceData variant (80B) so it satisfies both the 64B PBR and 80B\n // sprite-region layouts; the extra 16 region bytes stay zeroed (a valid\n // empty UV region) and the PBR shader never reads past its mat4.\n const IDENTITY_INSTANCE_BYTES = storageBufferCapable ? 144 : 80 * 128; // uniform array<InstanceData, 128> is full-sized\n const identityInstanceResult = runShimSyncStep(\n () =>\n rhiDevice.createBuffer({\n label: 'pbr-identity-instance-ssbo',\n size: IDENTITY_INSTANCE_BYTES,\n usage: storageBufferCapable\n ? GPU_BUFFER_USAGE_STORAGE | GPU_BUFFER_USAGE_COPY_DST\n : GPU_BUFFER_USAGE_UNIFORM | GPU_BUFFER_USAGE_COPY_DST,\n mappedAtCreation: false,\n }),\n 'webgpu-runtime-error',\n 'createBuffer (identity instance ssbo) succeeded',\n 'check device.limits.maxStorageBufferBindingSize',\n );\n if (!identityInstanceResult.ok) throw identityInstanceResult.error;\n // Seed the identity-mat4 (column-major; diagonal 1s).\n const identityMat4 = new Float32Array(storageBufferCapable ? 32 : 16);\n identityMat4[0] = 1;\n identityMat4[5] = 1;\n identityMat4[10] = 1;\n identityMat4[15] = 1;\n if (storageBufferCapable) {\n identityMat4[16] = 1;\n identityMat4[21] = 1;\n identityMat4[26] = 1;\n identityMat4[31] = 1;\n }\n const identityWrite = runShimSyncStep(\n () => queue.writeBuffer(identityInstanceResult.value, 0, identityMat4),\n 'queue-write-buffer-out-of-bounds',\n 'queue.writeBuffer (identity instance ssbo) succeeded',\n 'verify offset alignment and bounds against buffer.size',\n );\n if (!identityWrite.ok) throw identityWrite.error;\n\n // feat-20260515 M3 / T-M3-05 (research F-6 fix): default sampler + fallback\n // 1x1 white texture seed the materialBindGroup sampler / textureView\n // entries when MaterialAsset.baseColorTexture is undefined. Default\n // sampler matches research F-5 SSOT three-source convergence (linear\n // min/mag/mipmap; repeat addressMode); the fallback texture is a 1x1\n // RGBA8 white pixel so unlit / standard materials with no texture\n // multiply by 1 in M5 once UV-driven sampling lands.\n const defaultSamplerResult = runShimSyncStep(\n () =>\n rhiDevice.createSampler({\n label: 'default-sampler',\n magFilter: 'linear',\n minFilter: 'linear',\n mipmapFilter: 'linear',\n addressModeU: 'repeat',\n addressModeV: 'repeat',\n }),\n 'webgpu-runtime-error',\n 'createSampler (default) succeeded',\n 'check device.limits.maxSamplersPerShaderStage',\n );\n if (!defaultSamplerResult.ok) throw defaultSamplerResult.error;\n\n const nearestSamplerResult = runShimSyncStep(\n () =>\n rhiDevice.createSampler({\n label: 'nearest-sampler',\n magFilter: 'nearest',\n minFilter: 'nearest',\n mipmapFilter: 'nearest',\n addressModeU: 'clamp-to-edge',\n addressModeV: 'clamp-to-edge',\n }),\n 'webgpu-runtime-error',\n 'createSampler (nearest) succeeded',\n 'check device.limits.maxSamplersPerShaderStage',\n );\n if (!nearestSamplerResult.ok) throw nearestSamplerResult.error;\n\n // feat-20260520-directional-light-shadow-mapping M1c / w8 + M2 / w14:\n // shadow comparison sampler — clamp-to-edge, linear filter, compare:'less'.\n // Used for shadow map sampling in M2/M3 and shadow depth pass. comparison\n // sampler enables textureSampleCompareLevel in pbr.wgsl's evalDirectional().\n // Created once at pipeline build time; reused across frames.\n const shadowSamplerResult = runShimSyncStep(\n () =>\n rhiDevice.createSampler({\n label: 'shadow-sampler',\n magFilter: 'linear',\n minFilter: 'linear',\n mipmapFilter: 'linear',\n addressModeU: 'clamp-to-edge',\n addressModeV: 'clamp-to-edge',\n compare: 'less',\n }),\n 'webgpu-runtime-error',\n 'createSampler (shadow) succeeded',\n 'check device.limits.maxSamplersPerShaderStage',\n );\n if (!shadowSamplerResult.ok) throw shadowSamplerResult.error;\n\n const fallbackTextureResult = runShimSyncStep(\n () =>\n rhiDevice.createTexture({\n label: 'fallback-white-1x1',\n size: { width: 1, height: 1, depthOrArrayLayers: 1 },\n mipLevelCount: 1,\n sampleCount: 1,\n dimension: '2d',\n format: 'rgba8unorm',\n usage: GPU_TEXTURE_USAGE_TEXTURE_BINDING | GPU_TEXTURE_USAGE_COPY_DST,\n viewFormats: [],\n textureBindingViewDimension: undefined,\n }),\n 'webgpu-runtime-error',\n 'createTexture (fallback white) succeeded',\n 'check device.limits.maxTextureDimension2D',\n );\n if (!fallbackTextureResult.ok) throw fallbackTextureResult.error;\n\n // The fallback white pixel is a 1x1 RGBA8 sample. The forgeax rhi shim\n // enforces `bytesPerRow % 256 === 0` regardless of row count (spec\n // normative for multi-row copies, but the shim is uniformly strict).\n // Pad the source buffer to a 256-byte row stride; the upload still\n // writes only 1x1 because the destination size is 1x1.\n const fallbackPixel = new Uint8Array(FALLBACK_BYTES_PER_ROW);\n fallbackPixel[0] = 255;\n fallbackPixel[1] = 255;\n fallbackPixel[2] = 255;\n fallbackPixel[3] = 255;\n const fallbackWriteResult = runShimSyncStep(\n () =>\n queue.writeTexture(\n {\n texture: fallbackTextureResult.value as unknown as GPUTexture,\n mipLevel: 0,\n origin: { x: 0, y: 0, z: 0 },\n },\n fallbackPixel,\n { offset: 0, bytesPerRow: FALLBACK_BYTES_PER_ROW, rowsPerImage: 1 },\n { width: 1, height: 1, depthOrArrayLayers: 1 },\n ),\n 'queue-write-buffer-out-of-bounds',\n 'queue.writeTexture (fallback white pixel) succeeded',\n 'verify bytesPerRow / rowsPerImage alignment',\n );\n if (!fallbackWriteResult.ok) throw fallbackWriteResult.error;\n\n const fallbackTextureViewResult = runShimSyncStep(\n () =>\n rhiDevice.createTextureView(fallbackTextureResult.value, {\n label: 'fallback-white-view',\n dimension: '2d',\n }),\n 'webgpu-runtime-error',\n 'createTextureView (fallback white) succeeded',\n 'check fallback texture format / usage',\n );\n if (!fallbackTextureViewResult.ok) throw fallbackTextureViewResult.error;\n\n // Normal-slot fallback: 1x1 RGBA8 (128, 128, 255, 255). pbr.wgsl decodes\n // sample.rg * 2 - 1 + z = sqrt(1 - x^2 - y^2), so RG=(128,128)=0.5 maps\n // to tangent (0, 0, 1) -- zero perturbation when normalTexture is absent.\n // Cannot share the white fallback (255,255,...) because RG=(255,255)=1.0\n // gives tangent.xy=(1,1) -> 1 - 2 = -1 under the sqrt -> NaN (saturate\n // clamps to 0 z=0, still wrong). White-on-missing semantics for baseColor\n // / metallicRoughness slots is preserved by keeping those bound to the\n // shared fallbackTextureView; only the normal slot uses this view.\n const fallbackNormalTextureResult = runShimSyncStep(\n () =>\n rhiDevice.createTexture({\n label: 'fallback-normal-1x1',\n size: { width: 1, height: 1, depthOrArrayLayers: 1 },\n mipLevelCount: 1,\n sampleCount: 1,\n dimension: '2d',\n format: 'rgba8unorm',\n usage: GPU_TEXTURE_USAGE_TEXTURE_BINDING | GPU_TEXTURE_USAGE_COPY_DST,\n viewFormats: [],\n textureBindingViewDimension: undefined,\n }),\n 'webgpu-runtime-error',\n 'createTexture (fallback normal) succeeded',\n 'check device.limits.maxTextureDimension2D',\n );\n if (!fallbackNormalTextureResult.ok) throw fallbackNormalTextureResult.error;\n\n const fallbackNormalPixel = new Uint8Array(FALLBACK_BYTES_PER_ROW);\n fallbackNormalPixel[0] = 128;\n fallbackNormalPixel[1] = 128;\n fallbackNormalPixel[2] = 255;\n fallbackNormalPixel[3] = 255;\n const fallbackNormalWriteResult = runShimSyncStep(\n () =>\n queue.writeTexture(\n {\n texture: fallbackNormalTextureResult.value as unknown as GPUTexture,\n mipLevel: 0,\n origin: { x: 0, y: 0, z: 0 },\n },\n fallbackNormalPixel,\n { offset: 0, bytesPerRow: FALLBACK_BYTES_PER_ROW, rowsPerImage: 1 },\n { width: 1, height: 1, depthOrArrayLayers: 1 },\n ),\n 'queue-write-buffer-out-of-bounds',\n 'queue.writeTexture (fallback normal pixel) succeeded',\n 'verify bytesPerRow / rowsPerImage alignment',\n );\n if (!fallbackNormalWriteResult.ok) throw fallbackNormalWriteResult.error;\n\n const fallbackNormalTextureViewResult = runShimSyncStep(\n () =>\n rhiDevice.createTextureView(fallbackNormalTextureResult.value, {\n label: 'fallback-normal-view',\n dimension: '2d',\n }),\n 'webgpu-runtime-error',\n 'createTextureView (fallback normal) succeeded',\n 'check fallback normal texture format / usage',\n );\n if (!fallbackNormalTextureViewResult.ok) throw fallbackNormalTextureViewResult.error;\n\n // feat-20260520-directional-light-shadow-mapping M2 / w14 (D-1):\n // shadowFallbackTextureView is a 1x1 depth32float fallback bound at\n // viewBindGroup entry 3 when no shadow RT exists (castShadow:false\n // or allocation failed). Cleared to 1.0 (far plane) via a minimal\n // render pass so textureSampleCompareLevel always returns 1.0 (fully lit).\n // Uses RENDER_ATTACHMENT for the clear pass + TEXTURE_BINDING for sampling.\n const shadowFallbackTexResult = runShimSyncStep(\n () =>\n rhiDevice.createTexture({\n label: 'shadow-fallback-depth-1x1',\n size: { width: 1, height: 1, depthOrArrayLayers: 1 },\n mipLevelCount: 1,\n sampleCount: 1,\n dimension: '2d',\n format: 'depth32float',\n usage: GPU_TEXTURE_USAGE_RENDER_ATTACHMENT_AND_TEXTURE_BINDING,\n viewFormats: [],\n textureBindingViewDimension: undefined,\n }),\n 'webgpu-runtime-error',\n 'createTexture (shadow fallback depth) succeeded',\n 'check device.limits.maxTextureDimension2D',\n );\n if (!shadowFallbackTexResult.ok) throw shadowFallbackTexResult.error;\n\n const shadowFallbackViewResult = runShimSyncStep(\n () =>\n rhiDevice.createTextureView(shadowFallbackTexResult.value, {\n label: 'shadow-fallback-depth-view',\n dimension: '2d',\n }),\n 'webgpu-runtime-error',\n 'createTextureView (shadow fallback depth) succeeded',\n 'check shadow fallback texture format / usage',\n );\n if (!shadowFallbackViewResult.ok) throw shadowFallbackViewResult.error;\n\n // Clear the 1x1 depth fallback to 1.0 (far plane) via a 1-pixel render pass.\n const shadowFallbackClearEncResult = rhiDevice.createCommandEncoder({\n label: 'shadow-fallback-clear-encoder',\n });\n if (!shadowFallbackClearEncResult.ok) throw shadowFallbackClearEncResult.error;\n const shadowFallbackPass = shadowFallbackClearEncResult.value.beginRenderPass({\n colorAttachments: [],\n depthStencilAttachment: {\n view: shadowFallbackViewResult.value,\n depthClearValue: 1,\n depthLoadOp: 'clear',\n depthStoreOp: 'store',\n },\n } as never);\n shadowFallbackPass.end();\n const shadowFallbackClearFinish = shadowFallbackClearEncResult.value.finish();\n if (!shadowFallbackClearFinish.ok) throw shadowFallbackClearFinish.error;\n const shadowFallbackClearSubmit = queue.submit([shadowFallbackClearFinish.value]);\n if (!shadowFallbackClearSubmit.ok) throw shadowFallbackClearSubmit.error;\n\n // feat-20260612-point-light-shadows-urp-hdrp Round-2 F-1: 1x1x6\n // depth32float cube_array fallback bound at viewBindGroup entry 5 when no\n // PointLightShadow snapshots are active. dimension: '2d' with\n // depthOrArrayLayers: 6 produces a 6-layer 2D array that\n // `dimension: 'cube-array'` views can target (one cube, layers=1). The\n // texture is cleared to depth=1.0 (far plane) so\n // textureSampleCompareLevel always returns 1.0 (fully lit) regardless of\n // the depthRef the shader passes. AC-09 zero-allocation invariant\n // preserved: the real cube_array atlas in ShadowAtlas is still\n // lazy-allocated (the fallback is always created, but it only takes 24\n // bytes of GPU memory).\n const shadowAtlasFallbackTexResult = runShimSyncStep(\n () =>\n rhiDevice.createTexture({\n label: 'shadow-atlas-fallback-cube-1x1',\n size: { width: 1, height: 1, depthOrArrayLayers: 6 },\n mipLevelCount: 1,\n sampleCount: 1,\n dimension: '2d',\n format: 'depth32float',\n usage: GPU_TEXTURE_USAGE_RENDER_ATTACHMENT_AND_TEXTURE_BINDING,\n viewFormats: [],\n textureBindingViewDimension: 'cube',\n }),\n 'webgpu-runtime-error',\n 'createTexture (shadow atlas fallback cube) succeeded',\n 'check device.limits.maxTextureDimension2D and cube-array support',\n );\n if (!shadowAtlasFallbackTexResult.ok) throw shadowAtlasFallbackTexResult.error;\n\n const shadowAtlasFallbackViewResult = runShimSyncStep(\n () =>\n rhiDevice.createTextureView(shadowAtlasFallbackTexResult.value, {\n label: 'shadow-atlas-fallback-cube-array-view',\n dimension: 'cube-array',\n aspect: 'depth-only',\n baseArrayLayer: 0,\n arrayLayerCount: 6,\n baseMipLevel: 0,\n mipLevelCount: 1,\n }),\n 'webgpu-runtime-error',\n 'createTextureView (shadow atlas fallback cube-array) succeeded',\n 'check shadow atlas fallback texture format / usage / dimension',\n );\n if (!shadowAtlasFallbackViewResult.ok) throw shadowAtlasFallbackViewResult.error;\n\n // Clear all 6 fallback faces to 1.0 (far plane). One pass per face\n // (WebGPU forbids cube views as render-pass attachments; per-face 2D view\n // is required).\n for (let face = 0; face < 6; face++) {\n const faceViewRes = runShimSyncStep(\n () =>\n rhiDevice.createTextureView(shadowAtlasFallbackTexResult.value, {\n label: `shadow-atlas-fallback-face-${face}`,\n dimension: '2d',\n aspect: 'depth-only',\n baseArrayLayer: face,\n arrayLayerCount: 1,\n baseMipLevel: 0,\n mipLevelCount: 1,\n }),\n 'webgpu-runtime-error',\n `createTextureView (shadow atlas fallback face ${face}) succeeded`,\n 'check shadow atlas fallback texture format / usage',\n );\n if (!faceViewRes.ok) throw faceViewRes.error;\n const encRes = rhiDevice.createCommandEncoder({\n label: `shadow-atlas-fallback-clear-encoder-face-${face}`,\n });\n if (!encRes.ok) throw encRes.error;\n const pass = encRes.value.beginRenderPass({\n colorAttachments: [],\n depthStencilAttachment: {\n view: faceViewRes.value,\n depthClearValue: 1,\n depthLoadOp: 'clear',\n depthStoreOp: 'store',\n },\n } as never);\n pass.end();\n const finRes = encRes.value.finish();\n if (!finRes.ok) throw finRes.error;\n const subRes = queue.submit([finRes.value]);\n if (!subRes.ok) throw subRes.error;\n }\n\n // feat-20260612-point-light-shadows-urp-hdrp Round-2 F-1: shadowParams\n // uniform buffer = `array<vec4<f32>, 4>` (4 lanes x 16 B = 64 B). One\n // lane per PointLightShadow slot (cap = 4). Each lane stores\n // `(near, far, 1/(far-near), 0)` for depth-ref reconstruction in\n // lighting-punctual.wgsl evalPointShadowed. Written per frame in the\n // record stage from `frameState.pointShadowSnapshots`. Initial contents\n // are zero (writeBuffer at create time is implicit per spec); zero lanes\n // are safe because the WGSL sample path is gated on\n // `PointLight.shadowAtlasLayer >= 0` -- a non-shadow-casting light\n // cannot read its lane.\n const SHADOW_PARAMS_BYTES = 4 * 16;\n const shadowParamsBufferResult = runShimSyncStep(\n () =>\n rhiDevice.createBuffer({\n label: 'shadow-params-ubo',\n size: SHADOW_PARAMS_BYTES,\n usage: GPU_BUFFER_USAGE_UNIFORM | GPU_BUFFER_USAGE_COPY_DST,\n mappedAtCreation: false,\n }),\n 'webgpu-runtime-error',\n 'createBuffer (shadow params UBO) succeeded',\n 'check device.limits.maxUniformBufferBindingSize (need >= 64)',\n );\n if (!shadowParamsBufferResult.ok) throw shadowParamsBufferResult.error;\n // Zero-initialize the buffer so the no-shadow path reads deterministic\n // zeros (writeBuffer with 64 B of zeros).\n const SHADOW_PARAMS_ZEROES = new Uint8Array(SHADOW_PARAMS_BYTES);\n const shadowParamsZeroWriteRes = queue.writeBuffer(\n shadowParamsBufferResult.value,\n 0,\n SHADOW_PARAMS_ZEROES,\n );\n if (!shadowParamsZeroWriteRes.ok) throw shadowParamsZeroWriteRes.error;\n\n // feat-20260625-spot-light-shadow-mapping w25 (scope-amend webkit-fallback):\n // the per-spot fragment-read perspective lightViewProj matrices no longer have\n // a standalone uniform buffer — they fold into the View UBO tail\n // (`view.spotLightViewProj`, bytes 528..784, allocated as part of\n // VIEW_UBO_BYTES = 784 above). The View UBO's createBuffer already zero-fills\n // on first writeBuffer; render-system-record writes the spot lanes inside the\n // per-frame viewPayload. Removing the dedicated buffer drops the WebGL2\n // fallback fragment uniform-buffer count from 12 back to 11.\n\n // feat-20260520-skylight-ibl-cubemap M2 round-4 / t40 amend\n // (plan-strategy D-5 round-4 REVISED): allocate the fallback Skylight\n // identity resource bundle -- 1x1 all-zero rgba16float texture_cube * 2\n // (irradiance + prefilter) + 1x1 approximate rg16float brdfLut +\n // intensity=0 uniform buffer + a single linear/clamp sampler reused\n // across the three texture slots. No stand-alone BindGroupLayout /\n // BindGroup is allocated -- those roles moved into the PBR material\n // BGL factory (entries 7..13 inside @group(1)). The M4 record-stage\n // material BG assembly site feeds these resources through\n // `assembleMaterialWithSkylightEntries` when `skylightCount === 0` so\n // `standardPipeline` / `standardPipelineHdr` dispatch with ambient = 0\n // -- physical convergence with D-4 (charter F1: AI users writing\n // demos do not need a \"is there a skylight?\" branch).\n //\n // SkylightDevice / SkylightQueue minimal subsets are structurally\n // compatible with RhiDevice / RhiQueue; the cast at the boundary is\n // safe by construction (the helper only touches createBindGroupLayout\n // / createSampler / createTexture / createTextureView / createBuffer /\n // createBindGroup on the device side and writeTexture / writeBuffer on\n // the queue side, all of which RhiDevice / RhiQueue declare).\n let skylightFallback: SkylightFallback | null = null;\n try {\n skylightFallback = createSkylightFallback(\n rhiDevice as unknown as Parameters<typeof createSkylightFallback>[0],\n queue as unknown as Parameters<typeof createSkylightFallback>[1],\n );\n } catch (caught) {\n if (caught instanceof RhiError) throw caught;\n throw new RhiError({\n code: 'webgpu-runtime-error',\n expected: 'createSkylightFallback succeeded',\n hint: `verify texture_cube + uniform allocation (cause: ${\n caught instanceof Error ? caught.message : String(caught)\n })`,\n });\n }\n\n // feat-20260615-pipeline-spec-ssot M2-T4: PipelineCache is the single PSO container\n // (SSOT axiom — plan D-12). Created once at boot; shared across all call sites.\n // The provider is a thin wrapper over rhiDevice that fills in vertex buffers +\n // pipeline layout on the descriptor produced by buildPipelineDescriptor.\n const pipelineCache: PipelineCache = new Map();\n\n // Shader module mapping — maps spec.shader.id to compiled shader modules +\n // optional per-pass metadata (layout, entry points). Material shaders fill\n // only vertex/fragment; fullscreen-post passes add layout + entry points\n // for the boot-time SPEC_CONST pre-warm and lazy-build getOrBuildPipeline.\n const shaderModuleMap = new Map<\n string,\n {\n vertex: unknown;\n fragment: unknown;\n vertexEntryPoint?: string;\n fragmentEntryPoint?: string;\n layout?: unknown;\n label?: string;\n }\n >();\n if (unlitModule !== null)\n shaderModuleMap.set('forgeax::default-unlit', {\n vertex: unlitModule,\n fragment: unlitModule,\n });\n if (pbrModule !== null)\n shaderModuleMap.set('forgeax::default-standard-pbr', {\n vertex: pbrModule,\n fragment: pbrModule,\n });\n if (spriteModule !== null)\n // feat-20260625-refactor-sprite-as-transparent-mesh M3 / w14 (D-7):\n // sprite shader registers under the single canonical id `forgeax::sprite`\n // (previously double-mapped via the engine-built default-sprite id for\n // the deleted boot-time pre-warm path). The generic per-MaterialShader\n // pipeline cache reads this entry when a sprite material lands a\n // transparent pass through the LDR split.\n shaderModuleMap.set('forgeax::sprite', {\n vertex: spriteModule,\n fragment: spriteModule,\n });\n // feat-20260624-sprite-lit-shading-model-pure-2d-lighting M1' / t7:\n // sprite-lit shader registers under canonical `forgeax::sprite-lit` —\n // mirror sprite, parallel cache slot (D-11 string isolation).\n if (spriteLitModule !== null)\n shaderModuleMap.set('forgeax::sprite-lit', {\n vertex: spriteLitModule,\n fragment: spriteLitModule,\n });\n // M2-T4: fullscreen-post shader modules (tonemap + skybox) are registered\n // in their respective blocks after pipeline layout creation — layout is\n // required for the boot-time SPEC_CONST pre-warm to succeed. The entries\n // in SPEC_CONST_TABLE will be pre-warmed per-block.\n\n // M2-T4: provider no longer overwrites vertex buffers — buildPipelineDescriptor\n // derives them from spec.geometry.vertexLayout (SSOT). Layout is only filled\n // when the descriptor doesn't already carry one (fullscreen-post passes set it\n // via modules.layout). Fullscreen-post module detection added for label generation.\n const pipelineDeviceProvider: PipelineDeviceProvider = {\n createRenderPipeline(descriptor: Record<string, unknown>):\n | {\n ok: true;\n value: unknown;\n }\n | { ok: false; error: unknown } {\n const d = { ...descriptor } as Record<string, unknown>;\n\n // Layout: only fill if buildPipelineDescriptor did not already set it.\n if (d.layout === undefined) {\n d.layout = pipelineLayoutResult.value;\n }\n\n // Sprite HDR uses fragment entry point 'fs_main_hdr'; all other\n // standard material pipelines (unlit/standard LDR/HDR, sprite LDR)\n // use 'fs_main'. The spec is business-agnostic (plan D-7) so the\n // provider resolves this by checking the fragment module reference\n // against the compiled sprite module + the attachment format.\n //\n // Also generates a label for each PSO so integration tests and GPU\n // debug captures can identify the pipeline variant. The label shape\n // is derived from the fragment module + color format (backward-\n // compatible with pre-M2 descriptor literals).\n let label = 'pbr-pipeline';\n if (d.fragment) {\n const f = { ...(d.fragment as Record<string, unknown>) } as Record<string, unknown>;\n const fragModule = f.module;\n const targets = f.targets as Array<Record<string, unknown>> | undefined;\n const isHdr = targets?.[0]?.format === HDR_COLOR_ATTACHMENT_FORMAT;\n\n if (fragModule === spriteModule) {\n label = isHdr ? 'sprite-pipeline-hdr' : 'sprite-pipeline';\n if (isHdr) {\n f.entryPoint = 'fs_main_hdr';\n }\n } else if (fragModule === spriteLitModule) {\n // feat-20260624 M1' / t7: sprite-lit mirrors sprite's HDR\n // entry swap — `fs_main` (LDR clamped) vs `fs_main_hdr`\n // (HDR pass-through). Labels keep the same shape.\n label = isHdr ? 'sprite-lit-pipeline-hdr' : 'sprite-lit-pipeline';\n if (isHdr) {\n f.entryPoint = 'fs_main_hdr';\n }\n } else if (fragModule === unlitModule || fragModule === pbrModule) {\n const prefix = fragModule === unlitModule ? 'unlit' : 'standard';\n label = isHdr ? `pbr-pipeline-${prefix}-hdr` : `pbr-pipeline-${prefix}`;\n } else if (fragModule === fxaaModule) {\n label = 'fxaa-pipeline';\n } else if (fragModule === skyboxModule) {\n const msaa = d.multisample as Record<string, unknown> | undefined;\n label = msaa !== undefined ? 'skybox-pipeline-msaa' : 'skybox-pipeline';\n } else if (fragModule === bloomBrightModule) {\n label = 'bloom-bright-pipeline';\n } else if (fragModule === bloomBlurModule) {\n label = (d.label as string) ?? 'bloom-blur-h-pipeline';\n } else if (fragModule === bloomCompositeModule) {\n label = 'bloom-composite-pipeline';\n } else if (fragModule === ssaoModule) {\n label = (d.label as string) ?? 'ssao-calc-pipeline';\n }\n\n d.fragment = f;\n }\n d.label = (d.label as string | undefined) ?? label;\n\n return rhiDevice.createRenderPipeline(\n d as unknown as Parameters<typeof rhiDevice.createRenderPipeline>[0],\n );\n },\n };\n\n // bug-20260615 fix-up: build the SPEC_CONST table with the runtime-resolved\n // LDR view format. Hard-coding `bgra8unorm-srgb` at module load made the\n // pre-warmed PSOs incompatible with the actual swap-chain format on\n // backends where `getPreferredCanvasFormat()` (or the wgpu-wasm GLES path)\n // returns `rgba8unorm` (Channel 3 + dawn-node) — every frame's whole\n // commandBuffer was being rejected. Calling `buildSpecConstTable` after\n // `selectSwapChainFormat` resolves keeps the pre-warmed key (`cacheKeyOf`)\n // and the runtime tonemap call site (uses the same `swapChainFormats.view`)\n // identical, so the cache lookup hits instead of double-building.\n // Pass both view (unlit / standard / tonemap LDR target) and storage\n // (sprite LDR target — pre-feat sprite PSO targeted swapChainFormats.storage\n // directly so the alpha-blend pass writes the raw, non-srgb view of the\n // swap-chain texture; see pipeline-spec.ts SPRITE_ATTACHMENTS jsdoc).\n const runtimeSpecConstTable = buildSpecConstTable(swapChainFormats.view);\n const runtimeLinearLdrMaterialSpecTable = buildLinearLdrMaterialSpecTable(swapChainFormats.view);\n const runtimeMaterialPrewarmTable = [\n ...runtimeSpecConstTable,\n ...runtimeLinearLdrMaterialSpecTable,\n ];\n\n // Boot-time pre-warm: build SPEC_CONST entries whose shader modules are\n // compiled. Entries referencing a missing module are silently skipped\n // (the empty-manifest path — D-3). Any build failure for an available\n // module throws PipelineSpecError (fail-fast, charter P3).\n if (\n unlitModule !== null ||\n pbrModule !== null ||\n spriteModule !== null ||\n spriteLitModule !== null\n ) {\n for (const spec of runtimeMaterialPrewarmTable) {\n const modules = shaderModuleMap.get(spec.shader.id);\n if (modules === undefined) {\n // Module not compiled (empty-manifest for this shader): skip.\n continue;\n }\n try {\n getOrBuildPipeline(spec, pipelineDeviceProvider, pipelineCache, modules);\n } catch (err) {\n if (err instanceof PipelineSpecError) throw err;\n throw new PipelineSpecError({\n code: 'pipeline-build-failed',\n detail: { cause: err },\n hint: `Boot-time SPEC_CONST pre-warm failed for shader '${spec.shader.id}'; inspect gpuMessage on the cause`,\n });\n }\n }\n\n // M6 fix-up: seed `materialShaderPipelineCache` (owned by the outer\n // `makeWebGPURenderer` scope) from the prewarmed `pipelineCache` for\n // SPEC_CONST entries whose `variantSet !== undefined`. The URP record\n // path queries `getMaterialShaderPipeline(...)` keyed off\n // `cacheKeyOf(spec)` with `variantSet=URP_PBR_VARIANT_SET`; both caches\n // generate keys via the same `cacheKeyOf` so the lookup hits the\n // boot-time prewarmed PSO instead of triggering a 1-frame async-compile\n // skip-draw. Seeding only variantSet-bearing entries keeps the\n // no-variant entries flowing through the original\n // `pipelineState.standardPipeline*` channel (consumed by sprite /\n // unlit-fallback paths), so URP-vs-no-variant cache identity stays\n // explicit instead of collapsing into one map (charter P3).\n for (const spec of runtimeSpecConstTable) {\n if (spec.shader.variantSet === undefined) continue;\n if (shaderModuleMap.get(spec.shader.id) === undefined) continue;\n const key = cacheKeyOf(spec);\n const built = pipelineCache.get(key);\n if (built !== undefined) {\n seedMaterialShaderPipelineCache(key, built as RenderPipeline);\n }\n }\n\n // The linear-LDR geometry target is intentionally separate from the\n // swap-chain view target. Seed every material entry, including no-variant\n // unlit, because tonemap=none reaches this cache directly on frame one.\n for (const spec of runtimeLinearLdrMaterialSpecTable) {\n if (shaderModuleMap.get(spec.shader.id) === undefined) continue;\n const key = cacheKeyOf(spec);\n const built = pipelineCache.get(key);\n if (built !== undefined) {\n seedMaterialShaderPipelineCache(key, built as RenderPipeline);\n }\n }\n }\n\n // helper: look up a pre-warmed PSO from cache by (shaderId, isHdr, sampleCount).\n // Resolves the matching runtimeSpecConstTable entry, computes cacheKeyOf,\n // and returns the cached handle. Returns null when the spec entry's module\n // was not compiled (empty-manifest path) or the cache is cold.\n const getCachedPipelineOrNull = (\n shaderId: string,\n isHdr: boolean,\n sampleCount: 1 | 4,\n ): RenderPipeline | null => {\n for (const entry of runtimeSpecConstTable) {\n if (entry.shader.id === shaderId && entry.attachments.sampleCount === sampleCount) {\n const color0 = entry.attachments.colorFormats[0];\n const entryIsHdr = color0 === HDR_COLOR_ATTACHMENT_FORMAT;\n if (entryIsHdr === isHdr) {\n const key = cacheKeyOf(entry);\n return (pipelineCache.get(key) ?? null) as RenderPipeline | null;\n }\n }\n }\n return null;\n };\n\n // ── feat-20260520-directional-light-shadow-mapping M2 / w15 (AC-12) ───────\n //\n // Shadow-factor probe pipeline. Compiled once at pipeline build time when\n // the shader manifest is non-empty (gated on `unlitModule !== null` as a\n // proxy for \"the device can compile shaders\"; see the empty-manifest D-3\n // pattern). The probe uses an inline WGSL constant (SHADOW_PROBE_WGSL,\n // declared near the top of this file) and its own 1-BGL pipeline layout —\n // intentionally orthogonal to the main pipeline's 4-BGL chain. Probe-only\n // resources (LSM UBO + storage input + 1xN rgba32float RT + 1024B staging\n // buffer) are allocated up-front; per-call cost in `debugSampleShadowFactor`\n // is two `queue.writeBuffer` + one transient BindGroup + one render pass +\n // one `copyTextureToBuffer` + one `mapAsync`.\n let shadowProbePipelineHandle: RenderPipeline | null = null;\n let shadowProbeBindGroupLayoutHandle: BindGroupLayout | null = null;\n let shadowProbeLsmUboHandle: Buffer | null = null;\n let shadowProbeInputBufHandle: Buffer | null = null;\n // biome-ignore lint/suspicious/noExplicitAny: opaque RHI handle (matches sibling shadowTexture field)\n let shadowProbeOutputTexHandle: any | null = null;\n let shadowProbeOutputViewHandle: TextureView | null = null;\n let shadowProbeStagingBufHandle: Buffer | null = null;\n // bug-20260610: WebGL2 (downlevel_webgl2_defaults) reports\n // `maxStorageBuffersPerShaderStage = 0`, which makes the shadow-probe\n // BindGroupLayout fail at creation (its binding 1 is a fragment-stage\n // storage buffer). The probe is a debug helper used by\n // `debugSampleShadowFactor`; without it the main render path is intact.\n // Skip the entire probe-pipeline construction when storage buffers are\n // unavailable; the probe handles stay null and the debug entry returns\n // a structured RhiError if invoked (charter P3 explicit failure).\n if (unlitModule !== null && storageBufferCapable) {\n const probeBglResult = runShimSyncStep(\n () =>\n rhiDevice.createBindGroupLayout({\n label: 'shadow-probe-bgl',\n entries: [\n {\n binding: 0,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n buffer: { type: 'uniform' },\n },\n {\n binding: 1,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n buffer: { type: 'read-only-storage' },\n },\n {\n binding: 2,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n texture: { sampleType: 'depth', viewDimension: '2d' },\n },\n {\n binding: 3,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n sampler: { type: 'comparison' },\n },\n ],\n }),\n 'webgpu-runtime-error',\n 'createBindGroupLayout(shadow-probe) succeeded',\n 'check device.limits.maxBindGroupsPerPipelineLayout',\n );\n if (!probeBglResult.ok) throw probeBglResult.error;\n shadowProbeBindGroupLayoutHandle = probeBglResult.value;\n\n const probePipelineLayoutResult = runShimSyncStep(\n () =>\n rhiDevice.createPipelineLayout({\n label: 'shadow-probe-pl',\n bindGroupLayouts: [probeBglResult.value],\n }),\n 'webgpu-runtime-error',\n 'createPipelineLayout(shadow-probe) succeeded',\n 'verify shadow-probe BindGroupLayout matches inline WGSL @group(0) bindings',\n );\n if (!probePipelineLayoutResult.ok) throw probePipelineLayoutResult.error;\n\n const probeShaderResult = await runShimStep(\n () =>\n asyncCreateShaderModule\n ? asyncCreateShaderModule(rhiDevice, {\n code: SHADOW_PROBE_WGSL,\n label: 'shadow-probe',\n })\n : invokeDeviceCreateShaderModule(rhiDevice, {\n code: SHADOW_PROBE_WGSL,\n label: 'shadow-probe',\n }),\n 'shader-compile-failed',\n 'shadow-probe shader module compiled',\n 'inspect SHADOW_PROBE_WGSL constant; verify textureLoad depth sampling + output lanes',\n );\n if (!probeShaderResult.ok) throw probeShaderResult.error;\n const probeModule = probeShaderResult.value;\n\n // M2-T4: shadow-probe pipeline via getOrBuildPipeline (lazy-build).\n // The probe is a fullscreen pass that samples the cascaded shadow map and\n // writes per-probe factor/depth/cascade evidence into an rgba32float color attachment\n // (PROBE_OUTPUT_TEXTURE_FORMAT) — `passKind: 'post-process'` is correct;\n // the prior `'shadow-caster'` value triggered `buildPipelineDescriptor`'s\n // depth-only branch (skip fragment stage), producing a PSO with no\n // attachment that Dawn rejects with \"No attachment was specified\" (bug\n // surfaced by the bug-20260615 hello-cube smoke once the BGRA/RGBA\n // attachment-mismatch error storm was cleared).\n {\n const probeSpec: PipelineSpec = {\n shader: { id: 'forgeax::shadow::probe', passKind: 'post-process', variantSet: undefined },\n attachments: {\n colorFormats: [PROBE_OUTPUT_TEXTURE_FORMAT],\n depthFormat: undefined,\n sampleCount: 1,\n },\n geometry: {\n topology: 'triangle-list',\n stripIndexFormat: undefined,\n vertexLayout: {},\n },\n renderState: { cullMode: 'none' },\n };\n const modules = {\n vertex: probeModule,\n fragment: probeModule,\n layout: probePipelineLayoutResult.value,\n };\n try {\n shadowProbePipelineHandle = getOrBuildPipeline(\n probeSpec,\n pipelineDeviceProvider,\n pipelineCache,\n modules,\n ) as RenderPipeline;\n } catch (err) {\n if (err instanceof PipelineSpecError) throw err;\n throw new PipelineSpecError({\n code: 'pipeline-build-failed',\n detail: { cause: err },\n hint: 'createRenderPipeline(shadow-probe) failed; inspect SHADOW_PROBE_WGSL',\n });\n }\n }\n\n const probeLsmUboResult = runShimSyncStep(\n () =>\n rhiDevice.createBuffer({\n label: 'shadow-probe-lsm-ubo',\n size: PROBE_LSM_UBO_BYTES,\n usage: GPU_BUFFER_USAGE_UNIFORM | GPU_BUFFER_USAGE_COPY_DST,\n mappedAtCreation: false,\n }),\n 'webgpu-runtime-error',\n 'createBuffer(shadow-probe LSM UBO) succeeded',\n 'check device.limits.maxUniformBufferBindingSize',\n );\n if (!probeLsmUboResult.ok) throw probeLsmUboResult.error;\n shadowProbeLsmUboHandle = probeLsmUboResult.value;\n\n const probeInputBufResult = runShimSyncStep(\n () =>\n rhiDevice.createBuffer({\n label: 'shadow-probe-input-storage',\n size: PROBE_INPUT_BYTES,\n usage: GPU_BUFFER_USAGE_STORAGE | GPU_BUFFER_USAGE_COPY_DST,\n mappedAtCreation: false,\n }),\n 'webgpu-runtime-error',\n 'createBuffer(shadow-probe input storage) succeeded',\n 'check device.limits.maxStorageBufferBindingSize',\n );\n if (!probeInputBufResult.ok) throw probeInputBufResult.error;\n shadowProbeInputBufHandle = probeInputBufResult.value;\n\n // GPUTextureUsage.COPY_SRC = 0x01 spec literal. The probe RT is\n // copyTextureToBuffer source; RENDER_ATTACHMENT for the probe pass\n // colour target; TEXTURE_BINDING is unused but cheap and keeps the\n // texture symmetric with the shadow RT for future debug taps.\n const PROBE_RT_USAGE =\n GPU_TEXTURE_USAGE_RENDER_ATTACHMENT_AND_TEXTURE_BINDING | GPU_TEXTURE_USAGE_COPY_SRC;\n const probeOutputTexResult = runShimSyncStep(\n () =>\n rhiDevice.createTexture({\n label: 'shadow-probe-output-1xN-rgba32float',\n size: { width: PROBE_MAX_COUNT, height: 1, depthOrArrayLayers: 1 },\n mipLevelCount: 1,\n sampleCount: 1,\n dimension: '2d',\n format: PROBE_OUTPUT_TEXTURE_FORMAT,\n usage: PROBE_RT_USAGE,\n viewFormats: [],\n textureBindingViewDimension: undefined,\n }),\n 'webgpu-runtime-error',\n 'createTexture(shadow-probe output) succeeded',\n 'check device.limits.maxTextureDimension2D and rgba32float RENDER_ATTACHMENT support',\n );\n if (!probeOutputTexResult.ok) throw probeOutputTexResult.error;\n shadowProbeOutputTexHandle = probeOutputTexResult.value;\n\n const probeOutputViewResult = runShimSyncStep(\n () =>\n rhiDevice.createTextureView(probeOutputTexResult.value, {\n label: 'shadow-probe-output-view',\n dimension: '2d',\n }),\n 'webgpu-runtime-error',\n 'createTextureView(shadow-probe output) succeeded',\n 'check shadow-probe output texture format / usage',\n );\n if (!probeOutputViewResult.ok) throw probeOutputViewResult.error;\n shadowProbeOutputViewHandle = probeOutputViewResult.value;\n\n const probeStagingBufResult = runShimSyncStep(\n () =>\n rhiDevice.createBuffer({\n label: 'shadow-probe-staging',\n size: PROBE_READBACK_ROW_BYTES,\n usage: GPU_BUFFER_USAGE_COPY_DST | GPU_BUFFER_USAGE_MAP_READ,\n mappedAtCreation: false,\n }),\n 'webgpu-runtime-error',\n 'createBuffer(shadow-probe staging) succeeded',\n 'check device.limits.maxBufferSize',\n );\n if (!probeStagingBufResult.ok) throw probeStagingBufResult.error;\n shadowProbeStagingBufHandle = probeStagingBufResult.value;\n }\n\n // ── feat-20260520-2d-sprite-layer-mvp / M-3 / w24 ────────────────────────\n //\n // Sprite alpha-blend pipeline pair — LDR (`bgra8unorm-srgb` swap-chain\n // view) + HDR (`rgba16float` offscreen view; routed when active camera\n // carries `tonemap !== 'none'`, same as unlit/standard HDR siblings).\n //\n // @new-surface sprite alpha-blend pipeline (4th + 5th GPU render-pipeline\n // handles on PipelineState; the engine grows 5 -> 9 distinct pipelines:\n // unlit + standard + tonemap each existed before; sprite adds LDR + HDR).\n // The blend op is premultiplied alpha (charter P5 consistent abstraction\n // with the OpenGL / WebGPU industry default; sprite.wgsl fragment outputs\n // premultiplied RGB so srcFactor='one' / dstFactor='one-minus-src-alpha'\n // composes correctly).\n //\n // @reuses pipelineLayoutResult (the 4-BindGroupLayout chain shared with\n // unlit / standard / pbr — view + material + meshArray + instances).\n // @reuses defaultSampler — sprite material BindGroup entries 3 + 5\n // (metallicRoughnessSampler / normalSampler placeholders bound to\n // `pipelineState.defaultSampler`; D-1 candidate b; zero new sampler\n // created).\n // @reuses defaultWhiteTextureView — sprite material BindGroup entries\n // 4 + 6 (metallicRoughnessTexture / normalTexture placeholders bound\n // to `pipelineState.defaultWhiteTextureView`; D-1 candidate b; the\n // 1x1 white view was already provisioned for unlit / standard fallback\n // so the sprite path adds 0 lines of new GPU resource code, only\n // binding references in render-system-record.ts w25).\n // Sprite material BindGroup populates entries 0..2 with sprite's own\n // uniform / sampler / texture, and entries 3..6 with\n // pipelineState.defaultSampler + pipelineState.defaultWhiteTextureView\n // (D-1 candidate b — zero new GPU resource; 4-line binding wiring lives\n // in render-system-record.ts w25). The unused entries are physically\n // bound to ensure WebGPU's BindGroupLayout congruence (declared in the\n // shader at @binding 3..6 even though the sprite fragment never reads\n // them; plan-strategy D-1 + sprite.wgsl JSDoc head).\n //\n // @derives unlit / standard LDR+HDR dual-pipeline structure (lines 2058-\n // 2147 above + 2174-2253 below). The sprite pair mirrors the unlit\n // pair byte-for-byte except for:\n // - module: spriteModule (vs unlitModule)\n // - fragment.targets[0].blend: premultiplied alpha (vs no blend)\n // - depthStencil.depthWriteEnabled: false (vs true)\n // - depthStencil.depthCompare: 'less-equal' (vs 'less')\n // The vertex stride stays 12F (the unit quad passes through the same\n // 12-float interleaved layout as procedural meshes), so no new vertex\n // pipeline branch is needed in the record stage (plan-strategy §3 RT4).\n //\n // Premultiplied alpha blend op (`{ srcFactor: 'one', dstFactor:\n // 'one-minus-src-alpha', operation: 'add' }`) is the industry-default for\n // sprite atlases; sprite.wgsl emits premultiplied RGB so the over-\n // composite math (`dst' = src + dst * (1 - src.a)`) is direct.\n // feat-20260615-pipeline-spec-ssot M2-T4: sprite pipelines are pre-warmed in\n // SPEC_CONST_TABLE (4 entries: LDR/HDR x S1/S4). Cache lookup replaces the\n // prior local-handle variables + createMsaaVariant closure.\n // The pre-existing sprite-build-failure defer-to-null semantics are now\n // handled by the boot-time SPEC_CONST pre-warm block above: if the sprite\n // module exists but the SPEC_CONST build fails, the fail-fast throw blocks\n // the engine from entering the first frame (charter P3: no silent fallback).\n // AI users who need sprite tolerance for lavapipe / dawn-vulkan validation\n // can skip SPEC_CONST entries at their own peril via a future M7 opt-out\n // gate; the current M2 contract is fail-fast.\n // feat-20260608-tilemap-object-layer-rendering M2 / m2-t6 (D-8): SPEC_CONST\n // sprite entries set cullMode='none' so H/V flip via negative scale x/y\n // (tilemap per-cell entity TRS form, D-1) does not get culled when winding\n // inverts. See pipeline-spec.ts sprite LDR S1/S4 + HDR S1/S4 entries.\n\n // ── feat-20260519-tonemap-reinhard-mvp / M2 / T-M2.5 ──────────────────────\n //\n // HDR variants of the unlit + standard pipelines (rgba16float colour\n // attachment instead of bgra8unorm-srgb) plus the post-process tonemap\n // pipeline + 3-entry BGL + sampler + 16 B params UBO. Routed by record-\n // stage when the active camera carries `tonemap !== 'none'` (AC-03(a) /\n // AC-11). Sharing the geometry shader modules across the sRGB + HDR\n // pipelines keeps the shader compile cost flat and the WGSL byte-for-byte\n // identical between the two routes — the only difference is the colour-\n // attachment format declaration in the fragment state target list (charter\n // P5 consistent abstraction; plan-strategy D-2 + D-3).\n //\n // bug-20260519 D-3 nullable extension: the HDR pipeline block is gated on\n // `pbrModule + unlitModule !== null` so the empty-manifest path skips every\n // device.create* call below and writes `null` into the corresponding\n // PipelineState fields. feat-20260621 M-A3 (D-5): the dedicated tonemap\n // pipeline / BGL / sampler / params-UBO handles are gone — the built-in\n // tonemap registers through the unified post-process channel (see the\n // `registerBuiltinTonemap` callback above; pipeline + BGL + sampler + UBO\n // are owned by dispatchFullscreenPass / postProcess.register).\n let fxaaPipelineHandle: RenderPipeline | null = null;\n let fxaaBglHandle: BindGroupLayout | null = null;\n let fxaaSamplerHandle: Sampler | null = null;\n let skyboxPipelineHandle: RenderPipeline | null = null;\n let skyboxBglHandle: BindGroupLayout | null = null;\n let skyboxSamplerHandle: Sampler | null = null;\n let skyboxRotationBufferHandle: Buffer | null = null;\n let skyboxPipelineMsaaHandle: RenderPipeline | null = null;\n // feat-20260531-bloom-first-declarative-render-graph-pass / w13:\n // bloom pipeline handles (D-1, D-4, D-6). Bright + 2x blur (H/V per-axis)\n // + 1x composite = 4 pipelines. Blur H/V share the same WGSL module but\n // are separate pipelines with per-axis texelSize baked at creation (D-1).\n // All 4 use rgba16float target format (D-6).\n let bloomBrightPipelineHandle: RenderPipeline | null = null;\n let bloomBlurHPipelineHandle: RenderPipeline | null = null;\n let bloomBlurVPipelineHandle: RenderPipeline | null = null;\n let bloomCompositePipelineHandle: RenderPipeline | null = null;\n let bloomBrightBglHandle: BindGroupLayout | null = null;\n let bloomBlurBglHandle: BindGroupLayout | null = null;\n let bloomCompositeBglHandle: BindGroupLayout | null = null;\n let bloomSamplerHandle: Sampler | null = null;\n let bloomBrightParamsBufferHandle: Buffer | null = null;\n // bug-20260625: separate H/V blur params UBOs (see PerPassResources comment).\n let bloomBlurHParamsBufferHandle: Buffer | null = null;\n let bloomBlurVParamsBufferHandle: Buffer | null = null;\n let bloomCompositeParamsBufferHandle: Buffer | null = null;\n // feat-20260612-hdrp-ssao M6 / w26 + w43: SSAO pipeline handles (D-A).\n // calc + blur RenderPipeline pair sharing a dedicated 6-entry BGL.\n // Optional — null when manifest lacks hdrp-ssao entry.\n let ssaoCalcPipelineHandle: RenderPipeline | null = null;\n let ssaoBlurPipelineHandle: RenderPipeline | null = null;\n let ssaoBglHandle: BindGroupLayout | null = null;\n if (unlitModule !== null && pbrModule !== null) {\n // feat-20260615-pipeline-spec-ssot M2-T4: unlit/standard HDR pipeline\n // variants are pre-warmed in SPEC_CONST_TABLE (4 entries: unlit/standard\n // HDR x S1/S4). Cache lookup replaces prior local-handle variables.\n // The fxaa / skybox / bloom / SSAO fullscreen pipelines below\n // are NOT in SPEC_CONST_TABLE and remain boot-time lazy-built here.\n // feat-20260621 M-A3 (D-5): tonemap is no longer built here — it registers\n // through the unified post-process channel (registerBuiltinTonemap).\n\n // feat-20260528-fxaa-post-processing M2 / w10: FXAA pipeline prebuilt.\n // When the manifest contains the fxaa entry (rgb2luma marker, D-5),\n // construct the 2-entry BGL (texture + sampler, no UBO per D-2),\n // pipeline layout, fullscreen render pipeline (vertex = fullscreen\n // triangle from fxaa.wgsl, fragment = FXAA 3.11 algorithm), and\n // linear clamp-to-edge sampler. Mirrors the tonemap pipeline\n // construction pattern directly above.\n if (fxaaModule !== null) {\n // FXAA BindGroupLayout: 2 entries (texture + sampler, no UBO).\n // D-2: the fxaa.wgsl fragment stage declares @binding(0) texture_2d<f32>\n // + @binding(1) sampler.\n const fxaaBglResult = runShimSyncStep(\n () =>\n rhiDevice.createBindGroupLayout({\n label: 'fxaa-bgl',\n entries: [\n {\n binding: 0,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n texture: { sampleType: 'float', viewDimension: '2d' },\n },\n {\n binding: 1,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n sampler: { type: 'filtering' },\n },\n ],\n }),\n 'webgpu-runtime-error',\n 'createBindGroupLayout(fxaa) succeeded',\n 'check device.limits.maxBindGroupsPerPipelineLayout',\n );\n if (!fxaaBglResult.ok) throw fxaaBglResult.error;\n fxaaBglHandle = fxaaBglResult.value;\n\n const fxaaPipelineLayoutResult = runShimSyncStep(\n () =>\n rhiDevice.createPipelineLayout({\n label: 'fxaa-pl',\n bindGroupLayouts: [fxaaBglResult.value],\n }),\n 'webgpu-runtime-error',\n 'createPipelineLayout(fxaa) succeeded',\n 'verify fxaa BindGroupLayout matches shader @group(0) bindings',\n );\n if (!fxaaPipelineLayoutResult.ok) throw fxaaPipelineLayoutResult.error;\n\n // M2-T4: FXAA pipeline via getOrBuildPipeline (lazy-build, not in SPEC_CONST_TABLE).\n // Color-space contract: FXAA writes bgra8unorm (NON-srgb) storage format.\n // Lazy-build via cache miss on first access.\n {\n const fxaaSpec: PipelineSpec = {\n shader: { id: 'forgeax::post::fxaa', passKind: 'post-process', variantSet: undefined },\n attachments: {\n colorFormats: [storageBufferCapable ? swapChainFormats.storage : swapChainFormats.view],\n depthFormat: undefined,\n sampleCount: 1,\n },\n geometry: {\n topology: 'triangle-list',\n stripIndexFormat: undefined,\n vertexLayout: {},\n },\n renderState: { cullMode: 'none' },\n };\n const modules = {\n vertex: fxaaModule,\n fragment: fxaaModule,\n layout: fxaaPipelineLayoutResult.value,\n };\n try {\n fxaaPipelineHandle = getOrBuildPipeline(\n fxaaSpec,\n pipelineDeviceProvider,\n pipelineCache,\n modules,\n ) as RenderPipeline;\n } catch (err) {\n if (err instanceof PipelineSpecError) throw err;\n throw new PipelineSpecError({\n code: 'pipeline-build-failed',\n detail: { cause: err },\n hint: 'createRenderPipeline (fxaa fullscreen) failed; inspect gpuMessage',\n });\n }\n }\n\n // FXAA sampler: linear filter + clamp-to-edge. Clamp-to-edge\n // prevents edge bleed when sampling at the screen extents.\n const fxaaSamplerResult = runShimSyncStep(\n () =>\n rhiDevice.createSampler({\n label: 'fxaa-sampler',\n magFilter: 'linear',\n minFilter: 'linear',\n mipmapFilter: 'linear',\n addressModeU: 'clamp-to-edge',\n addressModeV: 'clamp-to-edge',\n }),\n 'webgpu-runtime-error',\n 'createSampler (fxaa) succeeded',\n 'check device.limits.maxSamplersPerShaderStage',\n );\n if (!fxaaSamplerResult.ok) throw fxaaSamplerResult.error;\n fxaaSamplerHandle = fxaaSamplerResult.value;\n }\n\n // feat-20260531-skybox-env-background M3 / w15: skybox pipeline prebuilt.\n // When the manifest contains the skybox entry (skybox_fs marker, D-7),\n // construct the 4-entry BGL (texture_cube + sampler + View UBO + rotation UBO),\n // pipeline layout, fullscreen render pipeline (vertex = fullscreen\n // triangle from skybox.wgsl, fragment = cubemap sample + write HDR),\n // and linear clamp-to-edge sampler. Mirrors tonemap/fxaa construction\n // pattern. Skybox writes to hdrColor rgba16float, NOT to the swap-chain\n // (plan-strategy D-2: tonemap pass reads hdrColor and maps to LDR).\n if (skyboxModule !== null) {\n const skyboxBglResult = runShimSyncStep(\n () =>\n rhiDevice.createBindGroupLayout({\n label: 'skybox-bgl',\n entries: [\n {\n binding: 0,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n texture: { sampleType: 'float', viewDimension: 'cube' },\n },\n {\n binding: 1,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n sampler: { type: 'filtering' },\n },\n {\n binding: 2,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n buffer: { type: 'uniform' },\n },\n {\n binding: 3,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n buffer: { type: 'uniform' },\n },\n ],\n }),\n 'webgpu-runtime-error',\n 'createBindGroupLayout(skybox) succeeded',\n 'check device.limits.maxBindGroupsPerPipelineLayout',\n );\n if (!skyboxBglResult.ok) throw skyboxBglResult.error;\n skyboxBglHandle = skyboxBglResult.value;\n\n const skyboxPipelineLayoutResult = runShimSyncStep(\n () =>\n rhiDevice.createPipelineLayout({\n label: 'skybox-pl',\n bindGroupLayouts: [skyboxBglResult.value],\n }),\n 'webgpu-runtime-error',\n 'createPipelineLayout(skybox) succeeded',\n 'verify skybox BindGroupLayout matches shader @group(0) bindings',\n );\n if (!skyboxPipelineLayoutResult.ok) throw skyboxPipelineLayoutResult.error;\n\n // Skybox pipeline writes to hdrColor rgba16float render target (NOT\n // M2-T4: skybox pipeline via getOrBuildPipeline + SPEC_CONST_TABLE pre-warm.\n // Skybox HDR S1 + S4 entries are in SPEC_CONST_TABLE. Register module with\n // layout + fragmentEntryPoint 'skybox_fs'. The S1 variant is built via\n // getOrBuildPipeline; MSAA S4 variant catches failure gracefully (same as\n // pre-M2 behavior: warn + fire error, set handle to null).\n shaderModuleMap.set('forgeax::skybox::cube', {\n vertex: skyboxModule,\n fragment: skyboxModule,\n fragmentEntryPoint: 'skybox_fs',\n layout: skyboxPipelineLayoutResult.value,\n });\n // S1 (non-MSAA)\n {\n const skyboxSpec: PipelineSpec = {\n shader: { id: 'forgeax::skybox::cube', passKind: 'skybox', variantSet: undefined },\n attachments: {\n colorFormats: [HDR_COLOR_ATTACHMENT_FORMAT],\n depthFormat: undefined,\n sampleCount: 1,\n },\n geometry: {\n topology: 'triangle-list',\n stripIndexFormat: undefined,\n vertexLayout: {},\n },\n renderState: { cullMode: 'none' },\n };\n const modules = shaderModuleMap.get('forgeax::skybox::cube');\n if (modules === undefined) throw new Error('expected skybox module in shaderModuleMap');\n skyboxPipelineHandle = getOrBuildPipeline(\n skyboxSpec,\n pipelineDeviceProvider,\n pipelineCache,\n modules,\n ) as RenderPipeline;\n }\n // S4 (MSAA variant — graceful failure, same as pre-M2)\n {\n const skyboxMsaaSpec: PipelineSpec = {\n shader: { id: 'forgeax::skybox::cube', passKind: 'skybox', variantSet: undefined },\n attachments: {\n colorFormats: [HDR_COLOR_ATTACHMENT_FORMAT],\n depthFormat: undefined,\n sampleCount: 4,\n },\n geometry: {\n topology: 'triangle-list',\n stripIndexFormat: undefined,\n vertexLayout: {},\n },\n renderState: { cullMode: 'none' },\n };\n const modules = shaderModuleMap.get('forgeax::skybox::cube');\n if (modules === undefined) throw new Error('expected skybox module in shaderModuleMap');\n try {\n skyboxPipelineMsaaHandle = getOrBuildPipeline(\n skyboxMsaaSpec,\n pipelineDeviceProvider,\n pipelineCache,\n modules,\n ) as RenderPipeline;\n } catch (msaaErr) {\n // The MSAA variant is a graceful-degradation path -- console.warn is the\n // canonical signal for \"feature degrades, not fails\" (noConsole allows warn).\n console.warn(\n `[forgeax] skybox MSAA pipeline variant build failed at renderer init; ` +\n `non-MSAA skybox unaffected. (cause: ${String(msaaErr)})`,\n );\n // PipelineSpecError carries the underlying cause in `.detail.cause`;\n // the warn above already surfaces the message.\n skyboxPipelineMsaaHandle = null;\n }\n }\n\n // Skybox sampler: filterable (linear/linear/clamp). Clamp-to-edge\n // prevents seam artifacts at cubemap face boundaries.\n const skyboxSamplerResult = runShimSyncStep(\n () =>\n rhiDevice.createSampler({\n label: 'skybox-sampler',\n magFilter: 'linear',\n minFilter: 'linear',\n mipmapFilter: 'linear',\n addressModeU: 'clamp-to-edge',\n addressModeV: 'clamp-to-edge',\n }),\n 'webgpu-runtime-error',\n 'createSampler (skybox) succeeded',\n 'check device.limits.maxSamplersPerShaderStage',\n );\n if (!skyboxSamplerResult.ok) throw skyboxSamplerResult.error;\n skyboxSamplerHandle = skyboxSamplerResult.value;\n\n const skyboxRotationBufferResult = runShimSyncStep(\n () =>\n rhiDevice.createBuffer({\n label: 'skybox-rotation-ubo',\n size: 16,\n usage: GPU_BUFFER_USAGE_UNIFORM | GPU_BUFFER_USAGE_COPY_DST,\n mappedAtCreation: false,\n }),\n 'webgpu-runtime-error',\n 'createBuffer (skybox rotation) succeeded',\n 'check device.limits.maxUniformBufferBindingSize',\n );\n if (!skyboxRotationBufferResult.ok) throw skyboxRotationBufferResult.error;\n skyboxRotationBufferHandle = skyboxRotationBufferResult.value;\n }\n\n // feat-20260531-bloom-first-declarative-render-graph-pass / w13:\n // bloom pipeline assembly (D-1, D-4, D-6). Assembled inside the\n // (unlit+pbr+tonemap) gate for rhiDevice access but bloom modules\n // are optional — each guard is independent. When bloom modules are\n // absent (legacy manifest), handles stay null and execute closures\n // skip the bloom passes entirely (zero-overhead opt-out).\n //\n // Pipeline roster:\n // bloom-bright : 1-tex + sampler + UBO@2 BGL, rgba16float target\n // bloom-blur-h : same BGL, same module as blur-v, H-axis texelSize\n // bloom-blur-v : same BGL, same module as blur-h, V-axis texelSize\n // bloom-composite: 2-tex + sampler + UBO@3 BGL, rgba16float target\n\n // Shared bloom sampler: linear filter + clamp-to-edge (all 4 passes\n // sample from textures using fullscreen triangle UVs).\n if (bloomBrightModule !== null || bloomBlurModule !== null || bloomCompositeModule !== null) {\n const bloomSamplerResult = runShimSyncStep(\n () =>\n rhiDevice.createSampler({\n label: 'bloom-sampler',\n magFilter: 'linear',\n minFilter: 'linear',\n mipmapFilter: 'linear',\n addressModeU: 'clamp-to-edge',\n addressModeV: 'clamp-to-edge',\n }),\n 'webgpu-runtime-error',\n 'createSampler (bloom) succeeded',\n 'check device.limits.maxSamplersPerShaderStage',\n );\n if (!bloomSamplerResult.ok) throw bloomSamplerResult.error;\n bloomSamplerHandle = bloomSamplerResult.value;\n }\n\n // Bloom bright: 1-tex + sampler + UBO@2 BGL (D-4).\n if (bloomBrightModule !== null && bloomSamplerHandle !== null) {\n const brightBglResult = runShimSyncStep(\n () =>\n rhiDevice.createBindGroupLayout({\n label: 'bloom-bright-bgl',\n entries: [\n {\n binding: 0,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n texture: { sampleType: 'float', viewDimension: '2d' },\n },\n {\n binding: 1,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n sampler: { type: 'filtering' },\n },\n {\n binding: 2,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n buffer: { type: 'uniform' },\n },\n ],\n }),\n 'webgpu-runtime-error',\n 'createBindGroupLayout(bloom-bright) succeeded',\n 'check device.limits.maxBindGroupsPerPipelineLayout',\n );\n if (!brightBglResult.ok) throw brightBglResult.error;\n bloomBrightBglHandle = brightBglResult.value;\n\n const brightPlResult = runShimSyncStep(\n () =>\n rhiDevice.createPipelineLayout({\n label: 'bloom-bright-pl',\n bindGroupLayouts: [brightBglResult.value],\n }),\n 'webgpu-runtime-error',\n 'createPipelineLayout(bloom-bright) succeeded',\n 'verify bloom-bright BindGroupLayout matches shader @group(0) bindings',\n );\n if (!brightPlResult.ok) throw brightPlResult.error;\n\n // M2-T4: bloom-bright pipeline via getOrBuildPipeline (lazy-build).\n {\n const brightSpec: PipelineSpec = {\n shader: {\n id: 'forgeax::post::bloom-bright',\n passKind: 'post-process',\n variantSet: undefined,\n },\n attachments: {\n colorFormats: [HDR_COLOR_ATTACHMENT_FORMAT],\n depthFormat: undefined,\n sampleCount: 1,\n },\n geometry: {\n topology: 'triangle-list',\n stripIndexFormat: undefined,\n vertexLayout: {},\n },\n renderState: { cullMode: 'none' },\n };\n const modules = {\n vertex: bloomBrightModule,\n fragment: bloomBrightModule,\n layout: brightPlResult.value,\n };\n try {\n bloomBrightPipelineHandle = getOrBuildPipeline(\n brightSpec,\n pipelineDeviceProvider,\n pipelineCache,\n modules,\n ) as RenderPipeline;\n } catch (err) {\n if (err instanceof PipelineSpecError) throw err;\n throw new PipelineSpecError({\n code: 'pipeline-build-failed',\n detail: { cause: err },\n hint: 'createRenderPipeline (bloom-bright fullscreen) failed; inspect gpuMessage',\n });\n }\n }\n\n // Bright params UBO: 16 B std140 (threshold f32 + 12 B pad).\n const brightParamsResult = runShimSyncStep(\n () =>\n rhiDevice.createBuffer({\n label: 'bloom-bright-params-ubo',\n size: BRIGHT_PARAMS_BYTES,\n usage: GPU_BUFFER_USAGE_UNIFORM | GPU_BUFFER_USAGE_COPY_DST,\n mappedAtCreation: false,\n }),\n 'webgpu-runtime-error',\n 'createBuffer (bloom-bright params UBO) succeeded',\n 'check device.limits.maxUniformBufferBindingSize',\n );\n if (!brightParamsResult.ok) throw brightParamsResult.error;\n bloomBrightParamsBufferHandle = brightParamsResult.value;\n }\n\n // Bloom blur H/V: same BGL (1-tex + sampler + UBO@2), same module,\n // two separate pipelines with per-axis texelSize (D-1, D-4).\n if (bloomBlurModule !== null && bloomSamplerHandle !== null) {\n const blurBglResult = runShimSyncStep(\n () =>\n rhiDevice.createBindGroupLayout({\n label: 'bloom-blur-bgl',\n entries: [\n {\n binding: 0,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n texture: { sampleType: 'float', viewDimension: '2d' },\n },\n {\n binding: 1,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n sampler: { type: 'filtering' },\n },\n {\n binding: 2,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n buffer: { type: 'uniform' },\n },\n ],\n }),\n 'webgpu-runtime-error',\n 'createBindGroupLayout(bloom-blur) succeeded',\n 'check device.limits.maxBindGroupsPerPipelineLayout',\n );\n if (!blurBglResult.ok) throw blurBglResult.error;\n bloomBlurBglHandle = blurBglResult.value;\n\n const blurPlResult = runShimSyncStep(\n () =>\n rhiDevice.createPipelineLayout({\n label: 'bloom-blur-pl',\n bindGroupLayouts: [blurBglResult.value],\n }),\n 'webgpu-runtime-error',\n 'createPipelineLayout(bloom-blur) succeeded',\n 'verify bloom-blur BindGroupLayout matches shader @group(0) bindings',\n );\n if (!blurPlResult.ok) throw blurPlResult.error;\n\n // M2-T4: bloom-blur H/V pipelines via getOrBuildPipeline (lazy-build).\n // H and V share the same PSO descriptor — only per-axis texelSize UBO\n // distinguishes them at record time. getOrBuildPipeline cache-hit on the\n // second call returns the same handle (identical spec, identical PSO).\n {\n const blurSpec: PipelineSpec = {\n shader: {\n id: 'forgeax::post::bloom-blur',\n passKind: 'post-process',\n variantSet: undefined,\n },\n attachments: {\n colorFormats: [HDR_COLOR_ATTACHMENT_FORMAT],\n depthFormat: undefined,\n sampleCount: 1,\n },\n geometry: {\n topology: 'triangle-list',\n stripIndexFormat: undefined,\n vertexLayout: {},\n },\n renderState: { cullMode: 'none' },\n };\n const modules = {\n vertex: bloomBlurModule,\n fragment: bloomBlurModule,\n layout: blurPlResult.value,\n label: 'bloom-blur-h-pipeline',\n };\n try {\n bloomBlurHPipelineHandle = getOrBuildPipeline(\n blurSpec,\n pipelineDeviceProvider,\n pipelineCache,\n modules,\n ) as RenderPipeline;\n } catch (err) {\n if (err instanceof PipelineSpecError) throw err;\n throw new PipelineSpecError({\n code: 'pipeline-build-failed',\n detail: { cause: err },\n hint: 'createRenderPipeline (bloom-blur-h fullscreen) failed; inspect gpuMessage',\n });\n }\n // V is cache-hit on the same spec (identical PSO; per-axis UBO differentiates at record time).\n bloomBlurVPipelineHandle =\n bloomBlurHPipelineHandle as unknown as typeof bloomBlurVPipelineHandle;\n }\n\n // Blur params UBOs: 16 B std140 (texelSize.xy + radius + pad) each.\n // bug-20260625: one per axis -- H and V must not share a buffer (the\n // shared-buffer writeBuffer race made both passes blur vertically).\n const blurHParamsResult = runShimSyncStep(\n () =>\n rhiDevice.createBuffer({\n label: 'bloom-blur-h-params-ubo',\n size: BLUR_PARAMS_BYTES,\n usage: GPU_BUFFER_USAGE_UNIFORM | GPU_BUFFER_USAGE_COPY_DST,\n mappedAtCreation: false,\n }),\n 'webgpu-runtime-error',\n 'createBuffer (bloom-blur-h params UBO) succeeded',\n 'check device.limits.maxUniformBufferBindingSize',\n );\n if (!blurHParamsResult.ok) throw blurHParamsResult.error;\n bloomBlurHParamsBufferHandle = blurHParamsResult.value;\n\n const blurVParamsResult = runShimSyncStep(\n () =>\n rhiDevice.createBuffer({\n label: 'bloom-blur-v-params-ubo',\n size: BLUR_PARAMS_BYTES,\n usage: GPU_BUFFER_USAGE_UNIFORM | GPU_BUFFER_USAGE_COPY_DST,\n mappedAtCreation: false,\n }),\n 'webgpu-runtime-error',\n 'createBuffer (bloom-blur-v params UBO) succeeded',\n 'check device.limits.maxUniformBufferBindingSize',\n );\n if (!blurVParamsResult.ok) throw blurVParamsResult.error;\n bloomBlurVParamsBufferHandle = blurVParamsResult.value;\n }\n\n // Bloom composite: 2-tex + sampler + UBO@3 BGL (D-4, D-5).\n if (bloomCompositeModule !== null && bloomSamplerHandle !== null) {\n const compositeBglResult = runShimSyncStep(\n () =>\n rhiDevice.createBindGroupLayout({\n label: 'bloom-composite-bgl',\n entries: [\n {\n binding: 0,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n texture: { sampleType: 'float', viewDimension: '2d' },\n },\n {\n binding: 1,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n texture: { sampleType: 'float', viewDimension: '2d' },\n },\n {\n binding: 2,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n sampler: { type: 'filtering' },\n },\n {\n binding: 3,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n buffer: { type: 'uniform' },\n },\n ],\n }),\n 'webgpu-runtime-error',\n 'createBindGroupLayout(bloom-composite) succeeded',\n 'check device.limits.maxBindGroupsPerPipelineLayout',\n );\n if (!compositeBglResult.ok) throw compositeBglResult.error;\n bloomCompositeBglHandle = compositeBglResult.value;\n\n const compositePlResult = runShimSyncStep(\n () =>\n rhiDevice.createPipelineLayout({\n label: 'bloom-composite-pl',\n bindGroupLayouts: [compositeBglResult.value],\n }),\n 'webgpu-runtime-error',\n 'createPipelineLayout(bloom-composite) succeeded',\n 'verify bloom-composite BindGroupLayout matches shader @group(0) bindings',\n );\n if (!compositePlResult.ok) throw compositePlResult.error;\n\n // M2-T4: bloom-composite pipeline via getOrBuildPipeline (lazy-build).\n {\n const compositeSpec: PipelineSpec = {\n shader: {\n id: 'forgeax::post::bloom-composite',\n passKind: 'post-process',\n variantSet: undefined,\n },\n attachments: {\n colorFormats: [HDR_COLOR_ATTACHMENT_FORMAT],\n depthFormat: undefined,\n sampleCount: 1,\n },\n geometry: {\n topology: 'triangle-list',\n stripIndexFormat: undefined,\n vertexLayout: {},\n },\n renderState: { cullMode: 'none' },\n };\n const modules = {\n vertex: bloomCompositeModule,\n fragment: bloomCompositeModule,\n layout: compositePlResult.value,\n };\n try {\n bloomCompositePipelineHandle = getOrBuildPipeline(\n compositeSpec,\n pipelineDeviceProvider,\n pipelineCache,\n modules,\n ) as RenderPipeline;\n } catch (err) {\n if (err instanceof PipelineSpecError) throw err;\n throw new PipelineSpecError({\n code: 'pipeline-build-failed',\n detail: { cause: err },\n hint: 'createRenderPipeline (bloom-composite fullscreen) failed; inspect gpuMessage',\n });\n }\n }\n\n // Composite params UBO: 16 B std140 (intensity f32 + 12 B pad).\n const compositeParamsResult = runShimSyncStep(\n () =>\n rhiDevice.createBuffer({\n label: 'bloom-composite-params-ubo',\n size: COMPOSITE_PARAMS_BYTES,\n usage: GPU_BUFFER_USAGE_UNIFORM | GPU_BUFFER_USAGE_COPY_DST,\n mappedAtCreation: false,\n }),\n 'webgpu-runtime-error',\n 'createBuffer (bloom-composite params UBO) succeeded',\n 'check device.limits.maxUniformBufferBindingSize',\n );\n if (!compositeParamsResult.ok) throw compositeParamsResult.error;\n bloomCompositeParamsBufferHandle = compositeParamsResult.value;\n }\n\n // ── feat-20260612-hdrp-ssao M6 / w26 + w43 + M8 / w37 ───────────────────\n //\n // SSAO post-processing chain: 2 passes (calc + blur) with a dedicated\n // 9-entry BGL matching hdrp-ssao.wgsl @group(0) bindings 0-8 (D-A + D-D).\n // Both pipelines share the same BGL (calc binds 0-6, blur binds 7-8 +\n // reuses the 256B uniform write); the WGSL declares all entries even when\n // a given pass leaves some unused, so wgpu/dawn pipeline-layout matching\n // is one-shot.\n //\n // w37 dawn-blocker fix (carry from w27-a): pre-M8 the BGL had a single\n // sampler at binding 3 typed 'filtering' that paired with the depth\n // texture at binding 5. WebGPU requires depth textures to be sampled with\n // a non-filtering / comparison sampler — the mismatch crashed every HDRP\n // PSO build on dawn (7 dawn tests red unrelated to SSAO itself).\n // ssao_depth_sampler at binding 6 (non-filtering) is dedicated to\n // hdr_depth; the existing filtering sampler at binding 3 stays for the\n // float noise / gbuffer_normal textures.\n //\n // Fullscreen triangle vertex (vs_ssao), R8 scalar fragment output. Cull\n // none, no depth/stencil (fullscreen post-process pass).\n if (ssaoModule !== null) {\n // Dedicated SSAO BGL: 9 entries (bindings 0-8 per current WGSL).\n // 0 = uniform (SsaoUniform 256B)\n // 1 = uniform (kernel UBO)\n // 2 = texture_2d (noise)\n // 3 = sampler (filtering, for noise / normal float textures)\n // 4 = texture_2d (gbuffer_normal)\n // 5 = texture_depth_2d (hdrDepth)\n // 6 = sampler (non-filtering, dedicated to depth) -- w37\n // 7 = texture_2d (ssaoRaw, blur input) -- w37\n // 8 = sampler (filtering, for ssaoRaw) -- w37\n const ssaoBglResult = runShimSyncStep(\n () =>\n rhiDevice.createBindGroupLayout({\n label: 'ssao-bgl',\n entries: [\n {\n binding: 0,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n buffer: { type: 'uniform' },\n },\n {\n binding: 1,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n buffer: { type: 'uniform' },\n },\n {\n binding: 2,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n // hdrp-ssao-noise is rgba32float; without the\n // float32-filterable extension this format is unfilterable.\n // The ssao-data noise generator uses NEAREST/REPEAT sampling\n // so unfilterable-float is sufficient and works on dawn.\n texture: { sampleType: 'unfilterable-float', viewDimension: '2d' },\n },\n {\n binding: 3,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n // The noise sampler (binding 2 + 4) must be non-filtering\n // because binding 2 is unfilterable-float. WebGPU validation\n // pairs sampler 'filtering' kind with filterable textures\n // only; using non-filtering for the noise + gbuffer_normal\n // path keeps both samples valid.\n sampler: { type: 'non-filtering' },\n },\n {\n binding: 4,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n texture: { sampleType: 'unfilterable-float', viewDimension: '2d' },\n },\n {\n binding: 5,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n texture: { sampleType: 'depth', viewDimension: '2d' },\n },\n {\n binding: 6,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n sampler: { type: 'non-filtering' },\n },\n {\n binding: 7,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n texture: { sampleType: 'unfilterable-float', viewDimension: '2d' },\n },\n {\n binding: 8,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n // Shared with binding 3 (single sampler resource); both BGL\n // entries must declare the same sampler-type kind.\n sampler: { type: 'non-filtering' },\n },\n ],\n }),\n 'webgpu-runtime-error',\n 'createBindGroupLayout(ssao) succeeded',\n 'check device.limits.maxBindGroupsPerPipelineLayout',\n );\n if (!ssaoBglResult.ok) throw ssaoBglResult.error;\n ssaoBglHandle = ssaoBglResult.value;\n\n const ssaoPipelineLayoutResult = runShimSyncStep(\n () =>\n rhiDevice.createPipelineLayout({\n label: 'ssao-pl',\n bindGroupLayouts: [ssaoBglResult.value],\n }),\n 'webgpu-runtime-error',\n 'createPipelineLayout(ssao) succeeded',\n 'verify SSAO BindGroupLayout matches shader @group(2) bindings',\n );\n if (!ssaoPipelineLayoutResult.ok) throw ssaoPipelineLayoutResult.error;\n\n // M2-T4: SSAO calc + blur pipelines via getOrBuildPipeline (lazy-build).\n // Different fragment entry points distinguish calc (fs_ssao_calc) from\n // blur (fs_ssao_blur); distinct synthetic shader IDs ensure correct cache\n // key separation (same module, different entry points → different PSOs).\n {\n const layout = ssaoPipelineLayoutResult.value;\n const baseModules = {\n vertex: ssaoModule,\n fragment: ssaoModule,\n vertexEntryPoint: 'vs_ssao',\n layout,\n };\n // SSAO calc\n {\n const calcSpec: PipelineSpec = {\n shader: {\n id: 'forgeax::post::ssao-calc',\n passKind: 'post-process',\n variantSet: undefined,\n },\n attachments: {\n colorFormats: ['r8unorm' as unknown as GPUTextureFormat],\n depthFormat: undefined,\n sampleCount: 1,\n },\n geometry: {\n topology: 'triangle-list',\n stripIndexFormat: undefined,\n vertexLayout: {},\n },\n renderState: { cullMode: 'none' },\n };\n try {\n ssaoCalcPipelineHandle = getOrBuildPipeline(\n calcSpec,\n pipelineDeviceProvider,\n pipelineCache,\n { ...baseModules, fragmentEntryPoint: 'fs_ssao_calc' },\n ) as RenderPipeline;\n } catch (err) {\n if (err instanceof PipelineSpecError) throw err;\n throw new PipelineSpecError({\n code: 'pipeline-build-failed',\n detail: { cause: err },\n hint: 'createRenderPipeline (ssao-calc fullscreen) failed; inspect gpuMessage',\n });\n }\n }\n // SSAO blur\n {\n const blurSpec: PipelineSpec = {\n shader: {\n id: 'forgeax::post::ssao-blur',\n passKind: 'post-process',\n variantSet: undefined,\n },\n attachments: {\n colorFormats: ['r8unorm' as unknown as GPUTextureFormat],\n depthFormat: undefined,\n sampleCount: 1,\n },\n geometry: {\n topology: 'triangle-list',\n stripIndexFormat: undefined,\n vertexLayout: {},\n },\n renderState: { cullMode: 'none' },\n };\n try {\n ssaoBlurPipelineHandle = getOrBuildPipeline(\n blurSpec,\n pipelineDeviceProvider,\n pipelineCache,\n { ...baseModules, fragmentEntryPoint: 'fs_ssao_blur' },\n ) as RenderPipeline;\n } catch (err) {\n if (err instanceof PipelineSpecError) throw err;\n throw new PipelineSpecError({\n code: 'pipeline-build-failed',\n detail: { cause: err },\n hint: 'createRenderPipeline (ssao-blur fullscreen) failed; inspect gpuMessage',\n });\n }\n }\n }\n }\n }\n\n // feat-20260601-gpu-resource-store-extraction M1 (D-9 sub-contract 1): prewarm\n // the mipmap pipeline cache for the smoke texture formats while still on the\n // async `renderer.ready` path. This builds the one-time mipmap shader module +\n // per-format pipeline into the deviceCache so the record-stage texture\n // ensureResident (sync) reproduces the pre-extraction async uploadTexture\n // byte-for-byte without an async stall in the synchronous draw frame. A build\n // failure here is surfaced through ready's reject channel (structured RhiError).\n //\n // Gated on `manifestEntries.length > 0` (the same Camera-only / clear-pass\n // skip as the Step-2 pipeline compile, bug-20260519 D-3): a zero-manifest\n // world renders no material geometry, so no texture is ever made resident and\n // the mipmap shader-module build (a `createShaderModule` call) must not fire\n // -- preserving the zero-manifest \"0 createShaderModule\" invariant\n // (renderer-ready.test.ts AC-02).\n if (manifestEntries.length > 0) {\n const prewarmRes = await gpuStore.prewarmMipmapPipeline(\n rhiDevice as unknown as Parameters<GpuResourceStore['prewarmMipmapPipeline']>[0],\n MIPMAP_PREWARM_FORMATS,\n );\n if (!prewarmRes.ok) throw prewarmRes.error;\n }\n\n return {\n // feat-20260518-pbr-direct-lighting-mvp M5 / w22.10 (AC-06 dual->triple\n // pipeline + D-2 + D-10): three distinct GPU render-pipeline handles\n // backed by 2 distinct shader modules (unlit + pbr) x 2 vertex stride\n // configurations (6F builtin + 12F procedural; the 6F + pbr combination\n // does not exist per D-2). All three share the identical 4-BindGroupLayout\n // chain so material BG entries built once compose for any of the three\n // pipelines (charter P5 consistent abstraction). The legacy `pipeline`\n // alias field has been retired; consumers select per\n // (mat.materialShaderId, mesh.layoutProjection) tuple via the record-stage three-way\n // setPipeline branch (w22.11).\n // bug-20260519: BUILTIN cube migrated to 12F so the legacy\n // `unlitBuiltinPipeline` (+ its zero-stride `unlitBuiltinDummyAttrBuffer`)\n // is gone; consumers pick per `mat.materialShaderId` only via the record-stage\n // 2-way `setPipeline` branch.\n // feat-20260615-pipeline-spec-ssot M2-T4: standard material PSOs are\n // pre-warmed in SPEC_CONST_TABLE and cached in pipelineCache. Cache\n // lookup replaces the prior local-handle variables (SSOT axiom D-12).\n // feat-20260615-pipeline-spec-ssot M2-T4: standard material PSOs are\n // pre-warmed in SPEC_CONST_TABLE and cached in pipelineCache. Cache\n // lookup replaces the prior local-handle variables (SSOT axiom D-12).\n // lookupSpecInTable resolves entries by (shaderId, isHdr, sampleCount);\n // null when the spec entry's module was not compiled (empty-manifest path).\n // (see definition near SPEC_CONST boot-time pre-warm block above)\n unlitPipeline: getCachedPipelineOrNull('forgeax::default-unlit', false, 1),\n standardPipeline: getCachedPipelineOrNull('forgeax::default-standard-pbr', false, 1),\n unlitPipelineMsaa: getCachedPipelineOrNull('forgeax::default-unlit', false, 4),\n standardPipelineMsaa: getCachedPipelineOrNull('forgeax::default-standard-pbr', false, 4),\n // feat-20260625-refactor-sprite-as-transparent-mesh M3 / w14 (D-7):\n // four sprite-dedicated boot-time pre-warms are gone. Sprite PSO now\n // lands lazily through the generic per-MaterialShader pipeline cache\n // (`getMaterialShaderPipeline('forgeax::sprite', ...)`) keyed on\n // premultiplied-alpha renderState at draw time. -4 entries off\n // SPEC_CONST_TABLE (15 from 19); -4 fields off PipelineState.\n unlitPipelineHdrMsaa: getCachedPipelineOrNull('forgeax::default-unlit', true, 4),\n standardPipelineHdrMsaa: getCachedPipelineOrNull('forgeax::default-standard-pbr', true, 4),\n // feat-20260523-shader-template-instance-split M9-T03 (D-PipelineBuilder):\n // expose the shared pbr/unlit/sprite pipeline layout so the per-\n // MaterialShader pipeline cache callback (createRenderer.ts\n // getMaterialShaderPipeline) can reuse it at lazy build time without\n // re-running pbrLayouts construction. `null` when the manifest is empty\n // (Camera-only path; bug-20260519 D-3 nullable parallel to the unlit /\n // standard pipeline fields above).\n pbrPipelineLayout:\n unlitModule !== null && pbrModule !== null ? pipelineLayoutResult.value : null,\n // feat-20260609-hdrp-cluster-fragment-ggx M4.5 / w36 (D-10 option A):\n // HDRP-variant PipelineLayout (4-BGL chain with HDRP unified 7-slot\n // group(2) BGL substituted for the URP 1-slot mesh-array BGL). Built\n // at boot above (see hdrpPbrPipelineLayoutHandle); gated on the same\n // unlit/pbr module presence as `pbrPipelineLayout` so Camera-only and\n // empty-manifest paths see null on both fields. Selected per call by\n // `selectPipelineLayoutForVariant` based on the caller's variantSet.\n hdrpPbrPipelineLayout:\n unlitModule !== null && pbrModule !== null ? hdrpPbrPipelineLayoutHandle : null,\n hdrpClusterMembershipPipeline,\n hdrpClusterMembershipBindGroupLayout,\n // bug-20260611-skin-pipeline-layout: skin-variant PipelineLayout (4-BGL\n // chain with 3-entry mesh-array BGL substituted for the standard 1-entry\n // mesh-array BGL). Built at boot above (see pbrSkinPipelineLayoutHandle);\n // gated on the same unlit/pbr module presence so Camera-only and empty-\n // manifest paths see null. Selected per call by\n // `selectPipelineLayoutForVariant` when the caller passes\n // `LayoutKind = 'pbr-skin'`.\n pbrSkinPipelineLayout:\n unlitModule !== null && pbrModule !== null ? pbrSkinPipelineLayoutHandle : null,\n // feat-20260611 R2 / M8 / w28 (IS-14): record-stage skin BG plumbing.\n // Mirror the gating used by `pbrSkinPipelineLayout` -- both fields\n // come from the same `buildPbrSkinLayouts` call so they live or die\n // together. Surfaced on PipelineState so render-system-record can\n // build a 3-binding BG matching `pbr-skin-pl` (was: 1-binding\n // `pbr-mesh-bg` + `pbr-mesh-array-bgl`, which the device rejected\n // every frame with `Bind group layout pbr-skin-mesh-array-bgl ... does\n // not match layout pbr-mesh-array-bgl` + Invalid CommandBuffer +\n // queue-submit-failed).\n pbrSkinMeshBindGroupLayout:\n unlitModule !== null && pbrModule !== null ? pbrSkinMeshBindGroupLayoutHandle : null,\n // feat-20260612-skin-palette-per-frame-upload M1 / m1-2: animator-ready\n // skin-palette allocator (replaces the prior identity-buffer stub).\n // Same gating as `pbrSkinPipelineLayout` -- `null` when the skin\n // pipeline-layout build itself failed.\n skinPaletteAllocator:\n unlitModule !== null && pbrModule !== null ? skinPaletteAllocatorHandle : null,\n format: swapChainFormats.storage,\n colorAttachmentFormat: swapChainFormats.view,\n viewBindGroupLayout: viewBglResult.value,\n materialBindGroupLayout: materialBglResult.value,\n meshBindGroupLayout: meshArrayBglResult.value,\n viewUniformBuffer: viewUboResult.value,\n shadowCasterCascadeBuffer: shadowCasterCascadeUboResult.value,\n // feat-20260608-mesh-ssbo-dynamic-grow-l1-lift-1024-entity-cap M2 /\n // T-M2-05: PipelineState now references the wrapper objects owned by\n // `meshSsboController.state`. Outer wrapper-object identity is stable\n // across grow (research §F8 R1) so these field references never go\n // stale; the inner `.buffer` is mutated in place when growMeshSsbo\n // rebuilds the pair. PipelineState field types are widened to\n // `{ buffer: Buffer; sizeInBytes: number }` in T-M2-06 to match.\n materialUniformBuffer: meshSsboState.material,\n meshStorageBuffer: meshSsboState.mesh,\n pointLightsBuffer: pointLightsBufferResult.value,\n spotLightsBuffer: spotLightsBufferResult.value,\n instancesBindGroupLayout: instancesBglResult.value,\n identityInstanceBuffer: identityInstanceResult.value,\n defaultSampler: defaultSamplerResult.value,\n nearestSampler: nearestSamplerResult.value,\n fallbackTextureView: fallbackTextureViewResult.value,\n // feat-20260518 M3 / w13: the 1x1 white textureView aliases\n // `fallbackTextureView` since both serve the same purpose (default-\n // texture seed for missing sampler / texture binding entries). The\n // alias keeps the new code path declarative without duplicating the\n // GPU resource (charter F2 minimal surface).\n defaultWhiteTextureView: fallbackTextureViewResult.value,\n // Normal-slot fallback view (1x1 RGBA8 (128,128,255,255)). RG=(128,128)\n // decodes to tangent (0,0,1) under pbr.wgsl's RG-only normal decoder.\n // Distinct from defaultWhiteTextureView because RG=(255,255)=1.0 gives\n // sqrt(1 - 1 - 1) = NaN, breaking the no-normal-map case.\n defaultNormalTextureView: fallbackNormalTextureViewResult.value,\n // feat-20260519-tonemap-reinhard-mvp M2 / T-M2.5: HDR variants of the\n // unlit + standard pipelines (rgba16float colour attachment).\n unlitPipelineHdr: getCachedPipelineOrNull('forgeax::default-unlit', true, 1),\n standardPipelineHdr: getCachedPipelineOrNull('forgeax::default-standard-pbr', true, 1),\n // feat-20260520-directional-light-shadow-mapping M2 / w14 (D-1):\n // 1x1 depth32float fallback bound at viewBindGroup binding(3).\n shadowFallbackTextureView: shadowFallbackViewResult.value,\n // feat-20260612-point-light-shadows-urp-hdrp Round-2 F-1: 1x1x6\n // depth32float cube_array fallback bound at viewBindGroup binding(5)\n // when no PointLightShadow snapshots are active. Always-present\n // (24 B GPU footprint); ShadowAtlas takes over when a real frame has\n // pointShadowSnapshots.length > 0.\n shadowAtlasFallbackTextureView: shadowAtlasFallbackViewResult.value,\n // feat-20260612-point-light-shadows-urp-hdrp Round-2 F-1: 64 B point\n // shadow params UBO bound at viewBindGroup binding(6). Written per\n // frame from `frameState.pointShadowSnapshots`.\n shadowParamsBuffer: shadowParamsBufferResult.value,\n // feat-20260625-spot-light-shadow-mapping w25: the spot lightViewProj\n // matrices fold into the View UBO tail (`view.spotLightViewProj`); no\n // dedicated buffer / view-BG binding 9 (WebGL2 uniform-buffer budget).\n // feat-20260520-directional-light-shadow-mapping M2 / w15 (AC-12):\n // shadow-factor probe pipeline + supporting GPU resources. All fields\n // null when the shader manifest is empty (no shaders -> no probe).\n shadowProbePipeline: shadowProbePipelineHandle,\n shadowProbeBindGroupLayout: shadowProbeBindGroupLayoutHandle,\n shadowProbeLsmUbo: shadowProbeLsmUboHandle,\n shadowProbeInputBuf: shadowProbeInputBufHandle,\n shadowProbeOutputTex: shadowProbeOutputTexHandle,\n shadowProbeOutputView: shadowProbeOutputViewHandle,\n shadowProbeStagingBuf: shadowProbeStagingBufHandle,\n // feat-20260520-skylight-ibl-cubemap M2 round-4 / t40 amend\n // (plan-strategy D-5 round-4 REVISED): fallback Skylight identity\n // resource bundle wired in alongside the other PipelineState fields.\n // M4 record stage will narrow on `!== null`, then feed these handles\n // through `assembleMaterialWithSkylightEntries` to populate material\n // BG entries 7..13 when skylightCount === 0 (no stand-alone bg).\n skylightFallback,\n // feat-20260529-rendergraph-pass-abstraction M3 / w11 (D-2 + Finding 3):\n // per-pass mutable resource slots moved to PerPassResources.\n perPassResources: {\n depthTexture: null,\n depthTextureView: null,\n depthTextureWidth: 0,\n depthTextureHeight: 0,\n configured: false,\n hdrColorTexture: null,\n hdrColorView: null,\n hdrDepthTexture: null,\n hdrDepthView: null,\n hdrTextureWidth: 0,\n hdrTextureHeight: 0,\n hdrDepthSampleCount: 1,\n fxaaPipeline: fxaaPipelineHandle,\n fxaaBindGroupLayout: fxaaBglHandle,\n fxaaSampler: fxaaSamplerHandle,\n taaResolvePipeline: taaResolveResources?.pipeline ?? null,\n taaResolveBindGroupLayout: taaResolveResources?.bindGroupLayout ?? null,\n taaResolveSampler: taaResolveResources?.sampler ?? null,\n taaResolveParamsBuffer: null,\n // feat-20260604-learn-render-4.10-anti-aliasing-msaa M2 / w7: MSAA\n // attachment slots. All null/0 until the first antialias='msaa' frame.\n msaaColorTexture: null,\n msaaColorView: null,\n msaaSpriteColorTexture: null,\n msaaSpriteColorView: null,\n msaaDepthTexture: null,\n msaaDepthView: null,\n msaaTextureWidth: 0,\n msaaTextureHeight: 0,\n hdrColorMsaaTexture: null,\n hdrColorMsaaView: null,\n skyboxPipeline: skyboxPipelineHandle,\n skyboxPipelineMsaa: skyboxPipelineMsaaHandle,\n skyboxBindGroupLayout: skyboxBglHandle,\n skyboxSampler: skyboxSamplerHandle,\n skyboxRotationBuffer: skyboxRotationBufferHandle,\n atmosphereCubemapPipeline: atmosphereCubemapPipelineHandle,\n atmosphereCubemapBindGroupLayout: atmosphereCubemapBglHandle,\n atmosphereIrradiancePipeline: atmosphereIrradiancePipelineHandle,\n atmospherePrefilterPipeline: atmospherePrefilterPipelineHandle,\n atmosphereIblParamsBindGroupLayout: atmosphereIblParamsBglHandle,\n atmosphereIblSkyBindGroupLayout: atmosphereIblSkyBglHandle,\n atmosphereBackgroundPipeline: atmosphereBackgroundPipelineHandle,\n atmosphereBackgroundBindGroupLayout: atmosphereBackgroundBglHandle,\n atmosphereParamsBuffer: atmosphereParamsBufferHandle,\n atmosphereCubeVertexBuffer: atmosphereCubeVertexBufferHandle,\n shadowTexture: null,\n shadowMapSize: 0,\n shadowCascadeCount: 0,\n shadowAtlasWidth: 0,\n shadowAtlasHeight: 0,\n shadowSampler: shadowSamplerResult.value,\n shadowLightSpaceMatrix: null,\n shadowCsmLightViewProj: null,\n shadowCsmSelection: null,\n shadowLightDirection: null,\n shadowDepthBias: 0.005,\n shadowNormalBias: 0.05,\n shadowPcfKernelSize: 3,\n // feat-20260531-bloom-first-declarative-render-graph-pass / w13 + w16:\n // bloom per-pass resource slots. Pipeline handles assembled during\n // buildReadyWebGPU (marker-triage + compile + createRenderPipeline).\n // Intermediate textures are allocate in the execute closures at 1/2-res\n // (ensureLazyTexture, slot width/height tracking for size-drift rebuild).\n // BindGroup caches survive until the intermediate view is invalidated\n // by a resize (width/height drift forces null).\n bloomBrightPipeline: bloomBrightPipelineHandle,\n bloomBlurHPipeline: bloomBlurHPipelineHandle,\n bloomBlurVPipeline: bloomBlurVPipelineHandle,\n bloomCompositePipeline: bloomCompositePipelineHandle,\n bloomBrightBindGroupLayout: bloomBrightBglHandle,\n bloomBlurBindGroupLayout: bloomBlurBglHandle,\n bloomCompositeBindGroupLayout: bloomCompositeBglHandle,\n bloomSampler: bloomSamplerHandle,\n bloomBrightParamsBuffer: bloomBrightParamsBufferHandle,\n bloomBlurHParamsBuffer: bloomBlurHParamsBufferHandle,\n bloomBlurVParamsBuffer: bloomBlurVParamsBufferHandle,\n bloomCompositeParamsBuffer: bloomCompositeParamsBufferHandle,\n bloomBrightTexture: null,\n bloomBrightView: null,\n bloomBrightWidth: 0,\n bloomBrightHeight: 0,\n bloomBlurHTexture: null,\n bloomBlurHView: null,\n bloomBlurHWidth: 0,\n bloomBlurHHeight: 0,\n bloomBlurVTexture: null,\n bloomBlurVView: null,\n bloomBlurVWidth: 0,\n bloomBlurVHeight: 0,\n // feat-20260612-hdrp-ssao M6 / w26 + M8 / w38: SSAO pipeline slots.\n ssaoCalcPipeline: ssaoCalcPipelineHandle,\n ssaoBlurPipeline: ssaoBlurPipelineHandle,\n ssaoBgl: ssaoBglHandle,\n // M8 / w38: lazy-allocated on first SSAO record frame. Sampler kinds\n // and the 1x1 ssaoRaw fallback view are constant across frames and\n // cached after first construction.\n ssaoFilteringSampler: null,\n ssaoDepthSampler: null,\n ssaoFallbackRawView: null,\n },\n };\n}\n\n/**\n * feat-20260612-rhi-destroy-renderer-dispose-gpu-lifecycle / M5 / w21\n * (plan-strategy D-3 method A): wrap a thrown sub-step value into a\n * structured `RhiError` with a stable `code` so the dispose cascade can\n * fan out the failure through `errorRegistry.fire` without losing the\n * cause string. Each step's wrapper carries the step name so AI users\n * inspecting `err.hint` see which sub-step failed.\n */\nfunction wrapDisposeError(cause: unknown, step: string): RhiError {\n if (cause instanceof RhiError) return cause;\n const message = cause instanceof Error ? cause.message : String(cause);\n return new RhiError({\n code: 'webgpu-runtime-error',\n expected: `${step} completes during Renderer.dispose() without throwing`,\n hint: `dispose sub-step '${step}' threw: ${message}; cascade continues to subsequent steps`,\n });\n}\n\nfunction ensureContextConfigured(\n internals: WebGPURendererInternals,\n state: PipelineState,\n errorRegistry: RhiErrorListenerRegistry,\n): void {\n if (state.perPassResources.configured) return;\n // M6 / w41 (feat-20260510-rhi-resource-creation): configure goes through\n // the forgeax `RhiCanvasContext` surface; the shim resolves the forgeax\n // RhiDevice back to the underlying raw GPUDevice via RAW_DEVICE_MAP\n // internally so the spec slot still gets a valid raw handle while AI-user-\n // facing code only sees the RHI surface (charter proposition 5).\n // The configure descriptor (WebGL2-fallback gate: storage-cap proxy ->\n // sRGB view format + usage bits) is the shared SSOT `configureSurface`\n // (render-system.ts), also used by the F2 surface-outdated reconfigure\n // branch so the two cannot drift (architecture-principles #1 SSOT).\n const resolvedDevice = internals.pack.instrumentation?.resolveSurfaceDevice?.(internals.device);\n if (resolvedDevice !== undefined && !resolvedDevice.ok) {\n errorRegistry.fire(resolvedDevice.error);\n return;\n }\n const surfaceDevice = resolvedDevice === undefined ? internals.device : resolvedDevice.value;\n const cfgResult = configureSurface(\n internals.context,\n surfaceDevice,\n state.format,\n state.colorAttachmentFormat,\n );\n if (!cfgResult.ok) {\n errorRegistry.fire(cfgResult.error);\n return;\n }\n state.perPassResources.configured = true;\n // bug-20260612: write the actually-configured swap-chain storage format\n // to a globalThis probe so AC-02 / AC-03 verification (Playwright\n // page.evaluate / vitest browser project) can read the value without\n // needing an Inspector RPC roundtrip or a yet-unimplemented\n // canvasContext.getConfiguration(). Always-on (single string property,\n // no runtime cost); naming aligns with existing globalThis.__forgeax*\n // counters (smoke-camera-pose probe lineage). View format is the\n // `${storage}-srgb` partner — derived, not duplicated.\n (globalThis as { __forgeaxSwapChainFormat?: GPUTextureFormat }).__forgeaxSwapChainFormat =\n state.format as unknown as GPUTextureFormat;\n}\n\n/**\n * Convert a synchronous RHI shim call that may throw a non-RhiError exception\n * into the canonical `Result<T, RhiError>` shape. AI users `await\n * renderer.ready` and consume `.code` / `.expected` / `.hint` regardless of\n * whether the underlying shim returned `Result.err` directly or threw a raw\n * Error (charter proposition 4 explicit failure baseline).\n */\nfunction runShimSyncStep<T>(\n fn: () => Result<T, RhiError>,\n fallbackCode:\n | 'shader-compile-failed'\n | 'webgpu-runtime-error'\n | 'queue-write-buffer-out-of-bounds',\n expected: string,\n hint: string,\n): Result<T, RhiError> {\n try {\n return fn();\n } catch (caught) {\n if (caught instanceof RhiError) {\n return err(caught);\n }\n const detail = caught instanceof Error ? caught.message : String(caught);\n return err(\n new RhiError({\n code: fallbackCode,\n expected,\n hint: `${hint} (cause: ${detail})`,\n }),\n );\n }\n}\n\n/** Async variant of `runShimSyncStep`. */\nasync function runShimStep<T>(\n fn: () => Promise<Result<T, RhiError>>,\n fallbackCode: 'shader-compile-failed' | 'webgpu-runtime-error',\n expected: string,\n hint: string,\n): Promise<Result<T, RhiError>> {\n try {\n return await fn();\n } catch (caught) {\n if (caught instanceof RhiError) {\n return err(caught);\n }\n const detail = caught instanceof Error ? caught.message : String(caught);\n return err(\n new RhiError({\n code: fallbackCode,\n expected,\n hint: `${hint} (cause: ${detail})`,\n }),\n );\n }\n}\n"]}
|