@forgeax/engine-render 0.1.34 → 0.1.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (273) hide show
  1. package/README.md +69 -3
  2. package/dist/assembly/device-feature-admission.d.ts +2 -2
  3. package/dist/assembly/host-contract.d.ts +3 -2
  4. package/dist/assembly/host-contract.d.ts.map +1 -1
  5. package/dist/assembly/recovery/renderer-recover.d.ts.map +1 -1
  6. package/dist/assembly/render-target-host.d.ts +5 -0
  7. package/dist/assembly/render-target-host.d.ts.map +1 -1
  8. package/dist/assembly/renderer-facade.d.ts.map +1 -1
  9. package/dist/assembly/webgpu-renderer.d.ts +1 -0
  10. package/dist/assembly/webgpu-renderer.d.ts.map +1 -1
  11. package/dist/assembly/webgpu-vertex-layouts.d.ts.map +1 -1
  12. package/dist/authoring.mjs +2 -4
  13. package/dist/authoring.mjs.map +1 -1
  14. package/dist/chunk-2OZAS3WU.mjs +3489 -0
  15. package/dist/chunk-2OZAS3WU.mjs.map +1 -0
  16. package/dist/{chunk-UI5SFODX.mjs → chunk-BZQ4CDRF.mjs} +2338 -1991
  17. package/dist/chunk-BZQ4CDRF.mjs.map +1 -0
  18. package/dist/{chunk-MKDIT2EM.mjs → chunk-CJOV2XLO.mjs} +216 -261
  19. package/dist/chunk-CJOV2XLO.mjs.map +1 -0
  20. package/dist/chunk-D6WSBXJ2.mjs +1842 -0
  21. package/dist/chunk-D6WSBXJ2.mjs.map +1 -0
  22. package/dist/{chunk-HEB564WF.mjs → chunk-DRF6OULX.mjs} +4 -4
  23. package/dist/{chunk-HEB564WF.mjs.map → chunk-DRF6OULX.mjs.map} +1 -1
  24. package/dist/{chunk-OCDLEI6I.mjs → chunk-OB5WAFYH.mjs} +117 -5
  25. package/dist/chunk-OB5WAFYH.mjs.map +1 -0
  26. package/dist/{chunk-ODZWR6JQ.mjs → chunk-OEYKKMXG.mjs} +2042 -27
  27. package/dist/chunk-OEYKKMXG.mjs.map +1 -0
  28. package/dist/chunk-RIPAEGI6.mjs +48 -0
  29. package/dist/chunk-RIPAEGI6.mjs.map +1 -0
  30. package/dist/{chunk-ELJFJ2BU.mjs → chunk-X2KA6WHM.mjs} +29 -4
  31. package/dist/chunk-X2KA6WHM.mjs.map +1 -0
  32. package/dist/{chunk-BLXGONR2.mjs → chunk-XSFB7XXQ.mjs} +51 -4
  33. package/dist/chunk-XSFB7XXQ.mjs.map +1 -0
  34. package/dist/cloud/frame-context.d.ts +2 -2
  35. package/dist/cloud/frame-context.d.ts.map +1 -1
  36. package/dist/construct-renderer.mjs +936 -2140
  37. package/dist/construct-renderer.mjs.map +1 -1
  38. package/dist/device/device-scope.d.ts.map +1 -1
  39. package/dist/device/gpu-residency.d.ts +19 -19
  40. package/dist/device/gpu-residency.d.ts.map +1 -1
  41. package/dist/errors/render.d.ts +3 -2
  42. package/dist/errors/render.d.ts.map +1 -1
  43. package/dist/extract/material-context.d.ts +7 -0
  44. package/dist/extract/material-context.d.ts.map +1 -0
  45. package/dist/features/host.d.ts +5 -0
  46. package/dist/features/host.d.ts.map +1 -1
  47. package/dist/features/particle-mesh-layout.d.ts +19 -0
  48. package/dist/features/particle-mesh-layout.d.ts.map +1 -0
  49. package/dist/features/plan.d.ts +2 -0
  50. package/dist/features/plan.d.ts.map +1 -1
  51. package/dist/features/types.d.ts +8 -0
  52. package/dist/features/types.d.ts.map +1 -1
  53. package/dist/glyph-text-layout-system.d.ts +1 -1
  54. package/dist/glyph-text-layout-system.d.ts.map +1 -1
  55. package/dist/gpu-driven/production-raster.d.ts +1 -1
  56. package/dist/gpu-driven/production-raster.d.ts.map +1 -1
  57. package/dist/gpu-driven/shadow-ownership.d.ts +3 -3
  58. package/dist/gpu-driven/shadow-ownership.d.ts.map +1 -1
  59. package/dist/gpu-driven/shadow-views.d.ts +1 -1
  60. package/dist/gpu-driven/shadow-views.d.ts.map +1 -1
  61. package/dist/gpu-driven/view-gpu.d.ts +1 -1
  62. package/dist/gpu-driven/view-gpu.d.ts.map +1 -1
  63. package/dist/ibl/frame-resources.d.ts.map +1 -1
  64. package/dist/ibl/skylight-bind-group.d.ts +4 -4
  65. package/dist/ibl/skylight-bind-group.d.ts.map +1 -1
  66. package/dist/index.d.ts +3 -0
  67. package/dist/index.d.ts.map +1 -1
  68. package/dist/index.mjs +542 -9
  69. package/dist/index.mjs.map +1 -1
  70. package/dist/instances.d.ts +3 -4
  71. package/dist/instances.d.ts.map +1 -1
  72. package/dist/internal.mjs +7 -8
  73. package/dist/internal.mjs.map +1 -1
  74. package/dist/pbr-pipeline.d.ts +3 -3
  75. package/dist/pbr-pipeline.d.ts.map +1 -1
  76. package/dist/pipeline/standard-output/lut-gpu.d.ts +2 -2
  77. package/dist/pipeline/standard-output/lut-gpu.d.ts.map +1 -1
  78. package/dist/pipeline/standard-output/resources.d.ts +2 -2
  79. package/dist/pipeline/standard-output/resources.d.ts.map +1 -1
  80. package/dist/publication/contract.d.ts +77 -0
  81. package/dist/publication/contract.d.ts.map +1 -0
  82. package/dist/publication/dependencies.d.ts +7 -0
  83. package/dist/publication/dependencies.d.ts.map +1 -0
  84. package/dist/publication/prepare-geometry.d.ts +9 -0
  85. package/dist/publication/prepare-geometry.d.ts.map +1 -0
  86. package/dist/publication/programs.d.ts +5 -0
  87. package/dist/publication/programs.d.ts.map +1 -0
  88. package/dist/publication/publisher.d.ts +34 -0
  89. package/dist/publication/publisher.d.ts.map +1 -0
  90. package/dist/publication/receiver.d.ts +29 -0
  91. package/dist/publication/receiver.d.ts.map +1 -0
  92. package/dist/publication/resource-scope.d.ts +18 -0
  93. package/dist/publication/resource-scope.d.ts.map +1 -0
  94. package/dist/publication/targets.d.ts +33 -0
  95. package/dist/publication/targets.d.ts.map +1 -0
  96. package/dist/publication/video.d.ts +5 -0
  97. package/dist/publication/video.d.ts.map +1 -0
  98. package/dist/record/fold-buckets.d.ts +3 -3
  99. package/dist/record/fold-buckets.d.ts.map +1 -1
  100. package/dist/record/frame-snapshot.d.ts +6 -6
  101. package/dist/record/frame-snapshot.d.ts.map +1 -1
  102. package/dist/record/frame.d.ts +5 -4
  103. package/dist/record/frame.d.ts.map +1 -1
  104. package/dist/record/helpers.d.ts +2 -2
  105. package/dist/record/helpers.d.ts.map +1 -1
  106. package/dist/record/main-pass-geometry.d.ts +2 -2
  107. package/dist/record/main-pass-geometry.d.ts.map +1 -1
  108. package/dist/record/main-pass-material.d.ts +7 -9
  109. package/dist/record/main-pass-material.d.ts.map +1 -1
  110. package/dist/record/main-pass-sprite-draws.d.ts +3 -16
  111. package/dist/record/main-pass-sprite-draws.d.ts.map +1 -1
  112. package/dist/record/main-pass.d.ts.map +1 -1
  113. package/dist/record/prepared-material-bindings.d.ts +2 -3
  114. package/dist/record/prepared-material-bindings.d.ts.map +1 -1
  115. package/dist/record/render-context.d.ts +4 -2
  116. package/dist/record/render-context.d.ts.map +1 -1
  117. package/dist/record/shadow-pass.d.ts +2 -2
  118. package/dist/record/shadow-pass.d.ts.map +1 -1
  119. package/dist/record/sprite-instance-buffer.d.ts +31 -0
  120. package/dist/record/sprite-instance-buffer.d.ts.map +1 -0
  121. package/dist/record/target-capture-graph.d.ts +19 -0
  122. package/dist/record/target-capture-graph.d.ts.map +1 -0
  123. package/dist/record/typed-frame-graph.d.ts +2 -13
  124. package/dist/record/typed-frame-graph.d.ts.map +1 -1
  125. package/dist/record/view-ubo.d.ts.map +1 -1
  126. package/dist/record/volume-params.d.ts +2 -2
  127. package/dist/record/volume-params.d.ts.map +1 -1
  128. package/dist/recovery/render-system-candidate.d.ts +5 -12
  129. package/dist/recovery/render-system-candidate.d.ts.map +1 -1
  130. package/dist/render-contract.d.ts +4 -1
  131. package/dist/render-contract.d.ts.map +1 -1
  132. package/dist/render-system-extract-tail.d.ts.map +1 -1
  133. package/dist/render-system-extract.d.ts +2 -0
  134. package/dist/render-system-extract.d.ts.map +1 -1
  135. package/dist/render-system-presentation.d.ts +2 -2
  136. package/dist/render-system-presentation.d.ts.map +1 -1
  137. package/dist/render-system-projections.d.ts +3 -2
  138. package/dist/render-system-projections.d.ts.map +1 -1
  139. package/dist/render-system-residency.d.ts +2 -2
  140. package/dist/render-system-residency.d.ts.map +1 -1
  141. package/dist/render-system.d.ts +3 -7
  142. package/dist/render-system.d.ts.map +1 -1
  143. package/dist/scene/render-scene.d.ts +8 -4
  144. package/dist/scene/render-scene.d.ts.map +1 -1
  145. package/dist/scene/render-source.d.ts +42 -0
  146. package/dist/scene/render-source.d.ts.map +1 -0
  147. package/dist/scene/source-systems.d.ts +6 -0
  148. package/dist/scene/source-systems.d.ts.map +1 -0
  149. package/dist/systems/skin-palette-allocator.d.ts.map +1 -1
  150. package/dist/systems/skin-palette-types.d.ts +10 -0
  151. package/dist/systems/skin-palette-types.d.ts.map +1 -1
  152. package/dist/systems/transparent-dispatch.d.ts +2 -2
  153. package/dist/systems/transparent-dispatch.d.ts.map +1 -1
  154. package/dist/systems/transparent-sort-config.d.ts +2 -1
  155. package/dist/systems/transparent-sort-config.d.ts.map +1 -1
  156. package/dist/temporal/index.mjs +6 -7
  157. package/dist/typed-shadow-passes.d.ts.map +1 -1
  158. package/package.json +21 -21
  159. package/src/__tests__/auto-exposure-transaction.integration.test.ts +4 -9
  160. package/src/__tests__/device-feature-admission.unit.test.ts +3 -2
  161. package/src/__tests__/device-scope-lifecycle.unit.test.ts +26 -0
  162. package/src/__tests__/gpu-driven-pbr.dawn.test.ts +3 -4
  163. package/src/__tests__/gpu-driven-production.integration.test.ts +18 -1
  164. package/src/__tests__/gpu-driven-shadow-views.unit.test.ts +23 -0
  165. package/src/__tests__/ktx2-basis-gpu-consumer.dawn.test.ts +4 -1
  166. package/src/__tests__/main-pass-material-medium-selection.unit.test.ts +0 -1
  167. package/src/__tests__/material-vertex-texture.browser.test.ts +7 -0
  168. package/src/__tests__/material-vertex-texture.dawn.test.ts +7 -0
  169. package/src/__tests__/material-vertex-texture.fixture.ts +31 -0
  170. package/src/__tests__/materials-standard-contract.unit.test.ts +0 -1
  171. package/src/__tests__/physical-clearcoat.integration.test.ts +23 -23
  172. package/src/__tests__/physical-material-budget.unit.test.ts +40 -0
  173. package/src/__tests__/recovery-candidate-prepare.contract.test.ts +5 -0
  174. package/src/__tests__/render-error-code-owner.test-d.ts +1 -0
  175. package/src/__tests__/renderer-factory-material-contract.unit.test.ts +107 -5
  176. package/src/__tests__/runtime-material-program.integration.test.ts +79 -0
  177. package/src/__tests__/vertex-layouts-ssot.unit.test.ts +23 -3
  178. package/src/assembly/device-feature-admission.ts +2 -2
  179. package/src/assembly/host-contract.ts +5 -2
  180. package/src/assembly/recovery/renderer-recover.ts +9 -0
  181. package/src/assembly/render-target-host.ts +57 -47
  182. package/src/assembly/renderer-facade.ts +3 -1
  183. package/src/assembly/webgpu-ready.ts +1 -1
  184. package/src/assembly/webgpu-renderer.ts +101 -70
  185. package/src/assembly/webgpu-vertex-layouts.ts +2 -9
  186. package/src/cloud/frame-context.ts +2 -2
  187. package/src/device/device-scope.ts +3 -0
  188. package/src/device/gpu-residency.ts +26 -25
  189. package/src/errors/render.ts +3 -1
  190. package/src/extract/material-context.ts +21 -0
  191. package/src/features/host.ts +13 -5
  192. package/src/features/particle-mesh-layout.ts +25 -0
  193. package/src/features/plan.ts +2 -0
  194. package/src/features/types.ts +8 -0
  195. package/src/glyph-text-layout-system.ts +2 -2
  196. package/src/gpu-driven/production-raster.ts +9 -3
  197. package/src/gpu-driven/shadow-ownership.ts +3 -3
  198. package/src/gpu-driven/shadow-views.ts +27 -2
  199. package/src/gpu-driven/view-gpu.ts +5 -0
  200. package/src/ibl/frame-resources.ts +0 -1
  201. package/src/ibl/skylight-bind-group.ts +13 -25
  202. package/src/index.ts +9 -0
  203. package/src/instances.ts +9 -6
  204. package/src/pbr-pipeline.ts +15 -18
  205. package/src/pipeline/standard-output/lut-gpu.ts +3 -3
  206. package/src/pipeline/standard-output/resources.ts +2 -2
  207. package/src/publication/__tests__/derived-geometry.integration.test.ts +177 -0
  208. package/src/publication/__tests__/features.integration.test.ts +173 -0
  209. package/src/publication/__tests__/programs.unit.test.ts +25 -0
  210. package/src/publication/__tests__/publication.integration.test.ts +415 -0
  211. package/src/publication/__tests__/targets.integration.test.ts +120 -0
  212. package/src/publication/__tests__/video.browser.test.ts +50 -0
  213. package/src/publication/contract.ts +104 -0
  214. package/src/publication/dependencies.ts +54 -0
  215. package/src/publication/prepare-geometry.ts +94 -0
  216. package/src/publication/programs.ts +45 -0
  217. package/src/publication/publisher.ts +645 -0
  218. package/src/publication/receiver.ts +297 -0
  219. package/src/publication/resource-scope.ts +31 -0
  220. package/src/publication/targets.ts +182 -0
  221. package/src/publication/video.ts +33 -0
  222. package/src/record/__tests__/material-bg-cache.unit.test.ts +15 -1
  223. package/src/record/__tests__/prepared-runtime-material.integration.test.ts +134 -0
  224. package/src/record/__tests__/sprite-material-abi.unit.test.ts +8 -10
  225. package/src/record/__tests__/video-texture-view.unit.test.ts +9 -9
  226. package/src/record/fold-buckets.ts +8 -5
  227. package/src/record/frame-snapshot.ts +6 -6
  228. package/src/record/frame.ts +87 -28
  229. package/src/record/helpers.ts +2 -2
  230. package/src/record/main-pass-geometry.ts +21 -2
  231. package/src/record/main-pass-material.ts +37 -33
  232. package/src/record/main-pass-sprite-draws.ts +6 -152
  233. package/src/record/main-pass.ts +8 -7
  234. package/src/record/prepared-material-bindings.ts +16 -37
  235. package/src/record/render-context.ts +4 -2
  236. package/src/record/shadow-pass.ts +65 -7
  237. package/src/record/sprite-instance-buffer.ts +155 -0
  238. package/src/record/target-capture-graph.ts +258 -0
  239. package/src/record/typed-frame-graph.ts +11 -207
  240. package/src/record/view-ubo.ts +1 -1
  241. package/src/record/volume-params.ts +6 -6
  242. package/src/recovery/render-system-candidate.ts +10 -18
  243. package/src/render-contract.ts +6 -1
  244. package/src/render-system-extract-tail.ts +48 -23
  245. package/src/render-system-extract.ts +11 -2
  246. package/src/render-system-presentation.ts +2 -2
  247. package/src/render-system-projections.ts +3 -2
  248. package/src/render-system-residency.ts +2 -2
  249. package/src/render-system.ts +82 -54
  250. package/src/scene/render-scene.ts +110 -100
  251. package/src/scene/render-source.ts +90 -0
  252. package/src/scene/source-systems.ts +33 -0
  253. package/src/systems/skin-palette-allocator.ts +1 -0
  254. package/src/systems/skin-palette-types.ts +11 -0
  255. package/src/systems/transparent-dispatch.ts +2 -2
  256. package/src/systems/transparent-sort-config.ts +3 -1
  257. package/src/typed-shadow-passes.ts +36 -5
  258. package/dist/chunk-BLXGONR2.mjs.map +0 -1
  259. package/dist/chunk-ELJFJ2BU.mjs.map +0 -1
  260. package/dist/chunk-ILQ5MEZF.mjs +0 -32
  261. package/dist/chunk-ILQ5MEZF.mjs.map +0 -1
  262. package/dist/chunk-MKDIT2EM.mjs.map +0 -1
  263. package/dist/chunk-OCDLEI6I.mjs.map +0 -1
  264. package/dist/chunk-ODZWR6JQ.mjs.map +0 -1
  265. package/dist/chunk-RXZ3RGOU.mjs +0 -53
  266. package/dist/chunk-RXZ3RGOU.mjs.map +0 -1
  267. package/dist/chunk-SHFUFJ5N.mjs +0 -1781
  268. package/dist/chunk-SHFUFJ5N.mjs.map +0 -1
  269. package/dist/chunk-UI5SFODX.mjs.map +0 -1
  270. package/dist/chunk-UINHLCZA.mjs +0 -2389
  271. package/dist/chunk-UINHLCZA.mjs.map +0 -1
  272. package/dist/chunk-WEX45HKH.mjs +0 -1524
  273. package/dist/chunk-WEX45HKH.mjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/pipeline/standard-output/auto-exposure/inspection.ts","../src/errors/render.ts","../src/features/motion-blur/motion-blur-params.ts","../src/device/device-scope.ts","../src/gpu-texture-usage.ts","../src/gpu-usage.ts","../src/prepare/extended-lighting/resources.ts","../src/shadow-atlas.ts","../src/record/frame-snapshot.ts","../src/errors/gpu-driven.ts","../src/instances.ts","../src/scene/visibility/budget.ts","../src/render-contract.ts","../src/targets/material-source.ts","../src/gpu-stage.ts","../src/pbr-pipeline.ts","../src/systems/pass-selector.ts","../src/gpu-driven/prepared-draw.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,WAAoB,OAAA,EAAwB;AACrD,IAAA,IAAI,cAAc,MAAA,EAAW;AAC3B,MAAA,IAAI,KAAK,OAAA,CAAQ,IAAA,GAAO,GAAG,IAAA,CAAK,aAAA,IAAiB,KAAK,OAAA,CAAQ,IAAA;AAC9D,MAAA,IAAA,CAAK,QAAQ,KAAA,EAAM;AAAA,IACrB,CAAA,MAAO;AACL,MAAA,IACE,KAAK,OAAA,CAAQ,MAAA,CAAO,IAAA,CAAK,GAAA,CAAI,EAAE,SAAA,EAAW,GAAI,OAAA,KAAY,MAAA,GAAY,EAAC,GAAI,EAAE,SAAQ,EAAI,CAAC,CAAA,EAC1F;AACA,QAAA,IAAA,CAAK,aAAA,IAAiB,CAAA;AAAA,MACxB;AAAA,IACF;AAAA,EACF;AAAA,EAEA,OAAA,GAAyC;AACvC,IAAA,OAAO;AAAA,MACL,MAAM,IAAA,CAAK,IAAA;AAAA,MACX,QAAQ,IAAA,CAAK,MAAA;AAAA,MACb,SAAS,IAAA,CAAK,OAAA;AAAA,MACd,eAAe,IAAA,CAAK;AAAA,KACtB;AAAA,EACF;AACF","file":"chunk-2OZAS3WU.mjs","sourcesContent":["import type { CameraExposure } from '../../../components/camera';\n\nexport type AutoExposureErrorCode =\n | 'auto-exposure-invalid-parameter'\n | 'auto-exposure-capability-unavailable'\n | 'auto-exposure-stale-generation'\n | 'auto-exposure-stage-failed';\n\nexport interface AutoExposureInvalidParameterDetail {\n readonly field: string;\n readonly value: number;\n readonly expected: string;\n}\n\nexport interface AutoExposureCapabilityUnavailableDetail {\n readonly capability: 'compute' | 'storage-buffer' | 'float-filterable';\n readonly generation: number;\n}\n\nexport interface AutoExposureStaleGenerationDetail {\n readonly expectedGeneration: number;\n readonly actualGeneration: number;\n}\n\nexport interface AutoExposureStageFailedDetail {\n readonly stage: 'prepare' | 'record';\n readonly operation: string;\n readonly cause: unknown;\n}\n\nexport type AutoExposureErrorDetailByCode = {\n 'auto-exposure-invalid-parameter': AutoExposureInvalidParameterDetail;\n 'auto-exposure-capability-unavailable': AutoExposureCapabilityUnavailableDetail;\n 'auto-exposure-stale-generation': AutoExposureStaleGenerationDetail;\n 'auto-exposure-stage-failed': AutoExposureStageFailedDetail;\n};\n\nexport type AutoExposureErrorDetail = AutoExposureErrorDetailByCode[AutoExposureErrorCode];\n\nexport class AutoExposureInvalidParameterError extends Error {\n readonly code = 'auto-exposure-invalid-parameter' as const;\n readonly expected = ERROR_POLICY[this.code].expected;\n readonly hint = ERROR_POLICY[this.code].hint;\n constructor(readonly detail: AutoExposureInvalidParameterDetail) {\n super(`auto-exposure-invalid-parameter: ${detail.field}`);\n this.name = 'AutoExposureInvalidParameterError';\n }\n}\n\nexport class AutoExposureCapabilityUnavailableError extends Error {\n readonly code = 'auto-exposure-capability-unavailable' as const;\n readonly expected = ERROR_POLICY[this.code].expected;\n readonly hint = ERROR_POLICY[this.code].hint;\n constructor(readonly detail: AutoExposureCapabilityUnavailableDetail) {\n super(`auto-exposure-capability-unavailable: ${detail.capability}`);\n this.name = 'AutoExposureCapabilityUnavailableError';\n }\n}\n\nexport class AutoExposureStaleGenerationError extends Error {\n readonly code = 'auto-exposure-stale-generation' as const;\n readonly expected = ERROR_POLICY[this.code].expected;\n readonly hint = ERROR_POLICY[this.code].hint;\n constructor(readonly detail: AutoExposureStaleGenerationDetail) {\n super(\n `auto-exposure-stale-generation: ${detail.actualGeneration} != ${detail.expectedGeneration}`,\n );\n this.name = 'AutoExposureStaleGenerationError';\n }\n}\n\nexport class AutoExposureStageFailedError extends Error {\n readonly code = 'auto-exposure-stage-failed' as const;\n readonly expected = ERROR_POLICY[this.code].expected;\n readonly hint = ERROR_POLICY[this.code].hint;\n constructor(readonly detail: AutoExposureStageFailedDetail) {\n super(`auto-exposure-stage-failed: ${detail.operation}`);\n this.name = 'AutoExposureStageFailedError';\n }\n}\n\nexport type AutoExposureError =\n | AutoExposureInvalidParameterError\n | AutoExposureCapabilityUnavailableError\n | AutoExposureStaleGenerationError\n | AutoExposureStageFailedError;\n\ntype AutoExposureErrorInput = {\n [C in AutoExposureErrorCode]: {\n readonly code: C;\n readonly detail: AutoExposureErrorDetailByCode[C];\n };\n}[AutoExposureErrorCode];\n\nexport type AutoExposureErrorRecord = {\n [C in AutoExposureErrorCode]: {\n readonly code: C;\n readonly expected: string;\n readonly hint: string;\n readonly detail: AutoExposureErrorDetailByCode[C];\n };\n}[AutoExposureErrorCode];\n\nexport type AutoExposureResetReason =\n | 'camera-change'\n | 'manual-mode'\n | 'device-lost'\n | 'stale-generation';\n\nexport interface AutoExposureCost {\n readonly histogramBytes: number;\n /** Logical stages retained for the inspect contract: clear, histogram, adapt. */\n readonly passCount: number;\n /** The logical stages share one real timestamped compute pass. */\n readonly physicalPassCount: number;\n}\n\nexport interface AutoExposureReceipt {\n readonly frameId: number;\n readonly committed: boolean;\n}\n\n/**\n * Describes where the detached `actual` value came from. A successful live\n * GPU submission is intentionally not a CPU observation: its numeric result\n * remains resident in the GPU state buffer until an explicit readback owner\n * is requested. Keeping that state distinct prevents fallback from being\n * presented as the measured exposure.\n */\nexport type AutoExposureActualState = 'accepted' | 'fallback' | 'gpu-resident';\n\nexport interface AutoExposureInspection {\n readonly requested: CameraExposure;\n readonly actual: number | null;\n readonly actualState: AutoExposureActualState;\n readonly fallback: number;\n readonly lastKnownGood: number;\n readonly targetGeneration: number;\n readonly recentFailure?: AutoExposureError;\n readonly reset: readonly AutoExposureResetReason[];\n readonly cost: AutoExposureCost;\n readonly receipt: AutoExposureReceipt;\n}\n\nexport interface AutoExposureInspectionInput\n extends Omit<AutoExposureInspection, 'actualState' | 'recentFailure'> {\n readonly actualState?: AutoExposureActualState;\n readonly recentFailure?: AutoExposureError | AutoExposureErrorRecord;\n}\n\nconst ERROR_POLICY: Readonly<\n Record<AutoExposureErrorCode, { readonly expected: string; readonly hint: string }>\n> = {\n 'auto-exposure-invalid-parameter': {\n expected: 'camera auto-exposure parameters are finite and within their declared ranges',\n hint: 'inspect the field and provide a finite value before rebuilding the camera output',\n },\n 'auto-exposure-capability-unavailable': {\n expected: 'the auto-exposure stage has the required device capability',\n hint: 'inspect live capabilities and retry the same camera generation',\n },\n 'auto-exposure-stale-generation': {\n expected: 'the prepared auto-exposure state matches the camera target generation',\n hint: 'discard stale prepared state and rebuild from the latest camera snapshot',\n },\n 'auto-exposure-stage-failed': {\n expected: 'the auto-exposure stage completes its declared operation',\n hint: 'inspect the structured cause, preserve lastKnownGood, and retry the stage',\n },\n};\n\nexport function createAutoExposureError(\n input: AutoExposureErrorInput | AutoExposureErrorRecord,\n): AutoExposureError {\n if (\n input instanceof AutoExposureInvalidParameterError ||\n input instanceof AutoExposureCapabilityUnavailableError ||\n input instanceof AutoExposureStaleGenerationError ||\n input instanceof AutoExposureStageFailedError\n ) {\n return input;\n }\n switch (input.code) {\n case 'auto-exposure-invalid-parameter':\n return new AutoExposureInvalidParameterError(input.detail);\n case 'auto-exposure-capability-unavailable':\n return new AutoExposureCapabilityUnavailableError(input.detail);\n case 'auto-exposure-stale-generation':\n return new AutoExposureStaleGenerationError(input.detail);\n case 'auto-exposure-stage-failed':\n return new AutoExposureStageFailedError(input.detail);\n }\n}\n\nfunction cloneExposure(exposure: CameraExposure): CameraExposure {\n if (exposure.kind === 'manual') return { ...exposure };\n return {\n ...exposure,\n rangeEv: [exposure.rangeEv[0], exposure.rangeEv[1]],\n rates: [exposure.rates[0], exposure.rates[1]],\n };\n}\n\nfunction cloneFailure(error: AutoExposureError | undefined): AutoExposureError | undefined {\n if (error === undefined) return undefined;\n return Object.freeze({\n ...error,\n detail: Object.freeze({ ...error.detail }),\n }) as AutoExposureError;\n}\n\n/** Project detached bounded facts; GPU handles and histogram buckets never cross this boundary. */\nexport function createAutoExposureInspection(\n input: AutoExposureInspectionInput,\n): Readonly<AutoExposureInspection> {\n const base = {\n requested: cloneExposure(input.requested),\n actual: input.actual,\n actualState: input.actualState ?? (input.actual === null ? 'gpu-resident' : 'accepted'),\n fallback: input.fallback,\n lastKnownGood: input.lastKnownGood,\n targetGeneration: input.targetGeneration,\n reset: Object.freeze([...input.reset]),\n cost: Object.freeze({ ...input.cost }),\n receipt: Object.freeze({ ...input.receipt }),\n };\n if (input.recentFailure === undefined) return Object.freeze(base);\n const recentFailure = cloneFailure(createAutoExposureError(input.recentFailure));\n if (recentFailure === undefined) return Object.freeze(base);\n return Object.freeze({ ...base, recentFailure });\n}\n","import type { RenderPublicationError } from '../publication/contract';\n// @forgeax/engine-render -- render cluster error classes.\n//\n// feat-20260704-runtime-tier1-decomposition M2 / w8 (D-3): the monolithic\n// errors.ts RuntimeErrorCode / RuntimeError top-level aggregate unions are\n// decomposed into five per-cluster files (render / asset / skin / recover /\n// environment). Each cluster owns a closed *ErrorCode code union + a closed\n// *Error class union; error class names, .code literals, and .detail shapes\n// are preserved byte-for-byte (OOS-4: zero semantic change).\n//\n// The render cluster holds the shadow / HDRP cluster-forward + deferred /\n// g-buffer / point-shadow-atlas / video-upload / vertex-storage-buffer render\n// path errors. ShadowInvalidConfigError is consumed by the DirectionalLight /\n// SpotLight / PointLightShadow component validators (forward cross-directory\n// import, no cycle -- research Finding C2).\n\nimport type {\n RenderSurfaceFailureDetail,\n SurfaceFailureCode,\n SurfaceFailureKind,\n} from '@forgeax/engine-render-graph';\nimport type { DeviceResourceKind, DeviceScopeReceipt } from '../device/resource-types';\nimport type { SunCardinalityError } from '../environment/frame';\nimport type { MotionBlurValidationError } from '../features/motion-blur/motion-blur-params';\nimport type {\n PreparedKind,\n RenderFeatureCapabilityKey,\n RenderFeatureRecovery,\n RenderFeatureStage,\n} from '../features/vocabulary';\nimport type { AutoExposureError } from '../pipeline/standard-output/auto-exposure/inspection';\nimport type { SceneDataLane, SceneDataSchemaId } from '../temporal/scene-data';\nimport type { TransmissionCapabilityFact } from '../transmission/backdrop';\nimport type { CloudLayerError } from './cloud';\nimport type { RecoveryOutcome, RecoveryPhase } from './recover';\n\n// Public render errors keep one machine-readable order: closed `code`,\n// expected state, actionable `hint`, then typed `detail`. Consumers branch on\n// that shape and never use Error.message as a protocol.\n\nexport type {\n AutoExposureCapabilityUnavailableDetail,\n AutoExposureError,\n AutoExposureErrorCode,\n AutoExposureErrorDetail,\n AutoExposureErrorDetailByCode,\n AutoExposureErrorRecord,\n AutoExposureInspection,\n AutoExposureInspectionInput,\n AutoExposureInvalidParameterDetail,\n AutoExposureReceipt,\n AutoExposureResetReason,\n AutoExposureStageFailedDetail,\n AutoExposureStaleGenerationDetail,\n} from '../pipeline/standard-output/auto-exposure/inspection';\nexport {\n AutoExposureCapabilityUnavailableError,\n AutoExposureInvalidParameterError,\n AutoExposureStageFailedError,\n AutoExposureStaleGenerationError,\n} from '../pipeline/standard-output/auto-exposure/inspection';\n\nexport interface LifecycleConstructionFailureDetail {\n readonly owner: string;\n readonly generation: number;\n readonly operation: 'create' | 'dispose';\n readonly resourceKind: DeviceResourceKind;\n readonly cause: unknown;\n readonly cleanupFailures: readonly {\n readonly resourceKind: DeviceResourceKind;\n readonly cause: unknown;\n }[];\n readonly receipt: DeviceScopeReceipt;\n}\n\nexport class LifecycleConstructionError extends Error {\n readonly code = 'lifecycle-construction-failed' as const;\n readonly expected = 'all DeviceScope resources establish and terminate in order';\n readonly hint = 'inspect detail and cleanupFailures, then recover or rebuild the DeviceScope';\n readonly detail: LifecycleConstructionFailureDetail;\n\n constructor(detail: LifecycleConstructionFailureDetail) {\n super(`lifecycle-construction-failed: ${detail.resourceKind} lifecycle transaction failed`);\n this.name = 'LifecycleConstructionError';\n this.detail = detail;\n }\n}\n\nconst SURFACE_FAILURE_POLICY: Readonly<\n Record<SurfaceFailureCode, { readonly expected: string; readonly hint: string }>\n> = {\n 'surface-allocation-failed': {\n expected: 'the required surface resource can be allocated with its declared format and usage',\n hint: 'inspect the capability detail, release transient resources, and retry the candidate graph',\n },\n 'surface-attachment-failed': {\n expected: 'the float target is renderable as the declared attachment',\n hint: 'verify float color attachment support and retry without hiding the failure',\n },\n 'surface-sampled-read-failed': {\n expected: 'the float target can be sampled by the next post-processing stage',\n hint: 'verify sampled-read support for the declared format before rebuilding the graph',\n },\n 'surface-view-domain-failed': {\n expected: 'surface storage and display views preserve their declared color domains',\n hint: 'repair the explicit format/domain pair and retry the candidate graph',\n },\n 'surface-raw-endpoint-failed': {\n expected: 'the surface presentation endpoint has descriptor, acquisition, and validation proof',\n hint: 'run the concrete presentation probe; keep the last-known-good surface when proof is absent',\n },\n};\n\n/** Render-surface failure with an exhaustive code and actionable detail. */\nexport class RenderSurfaceError<\n Code extends SurfaceFailureCode = SurfaceFailureCode,\n> extends Error {\n readonly code: Code;\n readonly expected: string;\n readonly hint: string;\n readonly detail: RenderSurfaceFailureDetail;\n\n constructor(code: Code, detail: RenderSurfaceFailureDetail) {\n const policy = SURFACE_FAILURE_POLICY[code];\n if (policy === undefined) {\n throw new Error(`unknown render surface failure code: ${code}`);\n }\n super(`[RenderSurfaceError ${code}] expected: ${policy.expected}; hint: ${policy.hint}`);\n this.name = 'RenderSurfaceError';\n this.code = code;\n this.expected = policy.expected;\n this.hint = policy.hint;\n this.detail = detail;\n }\n}\n\nexport type { RenderSurfaceFailureDetail, SurfaceFailureCode, SurfaceFailureKind };\n\nexport type RenderSurfaceExpectedError = {\n readonly [Code in SurfaceFailureCode]: RenderSurfaceError<Code>;\n}[SurfaceFailureCode];\n\n/** Construct the closed surface error from its failure-stage discriminant. */\nexport function createRenderSurfaceError(\n kind: SurfaceFailureKind,\n detail: RenderSurfaceFailureDetail,\n): RenderSurfaceExpectedError {\n return new RenderSurfaceError(`surface-${kind}-failed` as SurfaceFailureCode, detail);\n}\n\nexport type LightResourceFailureReason = 'asset' | 'format' | 'capability' | 'capacity';\n\nexport interface LightResourceUnavailableDetail {\n readonly entity: number;\n readonly feature: 'ies' | 'cookie' | 'probe';\n readonly generation: number;\n readonly sourceKey: string;\n readonly reason: LightResourceFailureReason;\n}\n\nexport class LightResourceUnavailableError extends Error {\n readonly code = 'light-resource-unavailable' as const;\n readonly expected: string;\n readonly hint: string;\n readonly detail: LightResourceUnavailableDetail;\n\n constructor(\n detail: LightResourceUnavailableDetail,\n expected: string,\n actual: string,\n hint: string,\n ) {\n super(`light-resource-unavailable: ${detail.feature} ${actual}`);\n this.name = 'LightResourceUnavailableError';\n this.expected = expected;\n this.hint = hint;\n this.detail = detail;\n }\n}\n\nexport function createLightResourceUnavailable(input: {\n readonly entity: number;\n readonly feature: LightResourceUnavailableDetail['feature'];\n readonly generation: number;\n readonly sourceKey: string;\n readonly reason: LightResourceFailureReason;\n readonly expected: string;\n readonly actual: string;\n readonly hint: string;\n}): LightResourceUnavailableError {\n return new LightResourceUnavailableError(\n {\n entity: input.entity,\n feature: input.feature,\n generation: input.generation,\n sourceKey: input.sourceKey,\n reason: input.reason,\n },\n input.expected,\n input.actual,\n input.hint,\n );\n}\n\nexport interface TemporalFrameSubmitDetail {\n readonly reason: 'queue-submit-failed';\n}\n\nexport class TemporalFrameSubmitError extends Error {\n readonly code = 'temporal-frame-submit-rejected' as const;\n readonly expected = 'the staged frame is accepted by queue.submit before temporal facts advance';\n readonly hint = 'inspect the queue submission and retry the frame after the device is available';\n readonly detail: TemporalFrameSubmitDetail;\n\n constructor(reason: 'queue-submit-failed') {\n super(`temporal-frame-submit-rejected: ${reason}`);\n this.name = 'TemporalFrameSubmitError';\n this.detail = { reason };\n }\n}\n// ── ShadowInvalidConfigError ──────────────────────────────────────────────\n\n/**\n * Detail for `RuntimeErrorCode 'shadow-invalid-config'`.\n *\n * The four fields are the only recovery surface: AI users read the invalid\n * field, actual value, structured bound, and reason without parsing prose.\n */\nexport type ShadowInvalidConfigBound =\n | { readonly kind: 'range'; readonly min: number; readonly max: number }\n | { readonly kind: 'lower-bound'; readonly operator: '>' | '>='; readonly value: number }\n | { readonly kind: 'allowed-values'; readonly values: readonly number[] };\n\nexport interface ShadowInvalidConfigDetail {\n readonly field: string;\n readonly actual: number;\n readonly bound: ShadowInvalidConfigBound;\n readonly reason: string;\n}\n\n/**\n * Structured error for shadow component config validation failures.\n *\n * Emitted by Directional, Point, and Spot shadow validation. All three\n * component owners share this error class so `switch (err.code)` on\n * `RuntimeErrorCode` needs one branch (charter P4 — closed-union SSOT).\n * Four-field surface:\n * - `.code = 'shadow-invalid-config'` (closed RuntimeErrorCode)\n * - `.expected` — expected-state description (programmatic predicate form)\n * - `.hint` — actionable recovery guidance (imperative; AI users paste into\n * spawn calls).\n * - `.detail = { field, actual, bound, reason }` — structured values.\n */\nexport class ShadowInvalidConfigError extends Error {\n readonly code = 'shadow-invalid-config' as const;\n readonly expected: string;\n readonly hint: string;\n readonly detail: ShadowInvalidConfigDetail;\n\n constructor(\n field: string,\n actual: number,\n minOrBound: number | ShadowInvalidConfigBound,\n maxOrComparator?: number | '>' | '>=',\n reason?: string,\n ) {\n const bound: ShadowInvalidConfigBound =\n typeof minOrBound === 'number'\n ? typeof maxOrComparator === 'number'\n ? { kind: 'range', min: minOrBound, max: maxOrComparator }\n : {\n kind: 'lower-bound',\n operator: maxOrComparator === '>' ? '>' : '>=',\n value: minOrBound,\n }\n : minOrBound;\n const resolvedReason = reason ?? shadowBoundReason(bound);\n const expected = shadowBoundExpected(field, bound);\n const hint = `set ${field} to ${resolvedReason}; got ${actual}`;\n super(`shadow component .${field} is invalid: ${resolvedReason}; got ${actual}`);\n this.name = 'ShadowInvalidConfigError';\n this.hint = hint;\n this.expected = expected;\n this.detail = { field, actual, bound, reason: resolvedReason };\n }\n}\n\nfunction shadowBoundExpected(field: string, bound: ShadowInvalidConfigBound): string {\n switch (bound.kind) {\n case 'range':\n return `${field} in [${bound.min}, ${bound.max}]`;\n case 'lower-bound':\n return `${field} ${bound.operator} ${bound.value}`;\n case 'allowed-values':\n return `${field} in {${bound.values.join(', ')}}`;\n }\n}\n\nfunction shadowBoundReason(bound: ShadowInvalidConfigBound): string {\n switch (bound.kind) {\n case 'range':\n return `a value in [${bound.min}, ${bound.max}]`;\n case 'lower-bound':\n return `a value ${bound.operator} ${bound.value}`;\n case 'allowed-values':\n return `one of [${bound.values.join(', ')}]`;\n }\n}\n\n// ── EquirectProjectionFailedError ────────────────────────────────────────────\n\n/**\n * Detail for `RuntimeErrorCode 'equirect-projection-failed'`.\n *\n * Emitted when the equirect-to-cubemap IBL projection fails for the equirect\n * handle referenced by a `Skylight` / `SkyboxBackground` component. The handle\n * id is carried so AI users can trace which equirect source failed projection.\n * Degradation: the record arm records `status:'failed'`, binds the white-cube\n * fallback, fires this error ONCE, and does NOT retry the projection.\n *\n * feat-20260630 D-5: structured error with detail carrying the handle id.\n */\nexport interface EquirectProjectionFailedDetail {\n readonly handle: number;\n}\n\n/**\n * Structured error for a failed equirect-to-cubemap IBL projection.\n *\n * Emitted by the record stage when the internal cubemap projection for an\n * equirect handle returns a failure (or records `status:'failed'`). Four-field\n * surface per AGENTS.md error model:\n * - `.code = 'equirect-projection-failed'` (closed RuntimeErrorCode)\n * - `.expected` — equirect-to-cubemap projection + IBL precompute succeeds\n * - `.hint` — declare `Skylight{equirect}` with a valid HDR equirect source;\n * check `device.caps.rgba16floatRenderable`. The projection is internal —\n * there is no user upload call to retry\n * - `.detail = { handle }` — the numeric equirect handle id for diagnostics\n */\nexport class EquirectProjectionFailedError extends Error {\n readonly code = 'equirect-projection-failed' as const;\n readonly expected: string;\n readonly hint: string;\n readonly detail: EquirectProjectionFailedDetail;\n\n constructor(handle: number) {\n const expected = `equirect handle ${handle} projects to a GPU cubemap + IBL precompute`;\n const hint =\n `equirect handle ${handle} referenced by Skylight/SkyboxBackground failed projection; ` +\n `declare Skylight{equirect} with a valid HDR equirect source and check device.caps.rgba16floatRenderable. ` +\n `The projection is internal (no user upload call); the record arm does not retry`;\n super(`equirect handle ${handle} cubemap projection failed`);\n this.name = 'EquirectProjectionFailedError';\n this.expected = expected;\n this.hint = hint;\n this.detail = { handle };\n }\n}\n\n// ── StandardLightBudgetExceededError ──────────────────────────────────────\n\n/** The finite local-light budget that a Standard frame agreed to admit. */\nexport interface StandardLightBudgetExceededDetail {\n readonly actual: number;\n readonly budget: number;\n}\n\n/**\n * Structured refusal for a Standard frame whose finite local-light set is\n * outside the selected profile budget. The frame is rejected as a whole; the\n * record owner must not slice the input or submit a partial membership set.\n */\nexport class StandardLightBudgetExceededError extends Error {\n readonly code = 'standard-light-budget-exceeded' as const;\n readonly expected: string;\n readonly hint: string;\n readonly detail: StandardLightBudgetExceededDetail;\n\n constructor(actual: number, budget: number) {\n const expected = `light count <= ${budget}`;\n const hint =\n `${actual} finite local lights exceed Standard budget ${budget}; ` +\n 'reduce the local-light set or select a profile with a supported budget';\n super(`Standard light budget exceeded: ${actual} > ${budget}`);\n this.name = 'StandardLightBudgetExceededError';\n this.expected = expected;\n this.hint = hint;\n this.detail = { actual, budget };\n }\n}\n\n// ── StandardClusterIndexOverflowError ──────────────────────────────────────\n\n/** Cluster membership entries that could not fit the single shared index list. */\nexport interface StandardClusterIndexOverflowDetail {\n readonly actual: number;\n readonly capacity: number;\n}\n\n/**\n * Structured refusal for a membership producer that exceeded the shared\n * Cluster index-list capacity. No truncated list is uploaded and no graph is\n * submitted for the rejected frame.\n */\nexport class StandardClusterIndexOverflowError extends Error {\n readonly code = 'standard-cluster-index-overflow' as const;\n readonly expected: string;\n readonly hint: string;\n readonly detail: StandardClusterIndexOverflowDetail;\n\n constructor(actual: number, capacity: number) {\n const expected = `light index list entries <= ${capacity}`;\n const hint =\n `cluster binner overflow: writeCount ${actual} exceeds capacity ${capacity}; ` +\n 'reduce finite local lights or choose a supported cluster layout';\n super(`Standard cluster index list overflow: ${actual} > ${capacity}`);\n this.name = 'StandardClusterIndexOverflowError';\n this.expected = expected;\n this.hint = hint;\n this.detail = { actual, capacity };\n }\n}\n\n// ── StandardClusterTransportUnavailableError ───────────────────────────────\n\nexport interface StandardClusterTransportUnavailableDetail {\n readonly requested: number;\n readonly admitted: 0;\n}\n\n/**\n * Structured capability refusal. Standard never turns an unproven transport\n * into a smaller direct-light lane; the caller receives the exact requested\n * local-light count and an admitted count of zero.\n */\nexport class StandardClusterTransportUnavailableError extends Error {\n readonly code = 'standard-cluster-transport-unavailable' as const;\n readonly expected = 'all requested local lights have a proven Cluster transport';\n readonly hint: string;\n readonly detail: StandardClusterTransportUnavailableDetail;\n\n constructor(\n requested: number,\n hint = 'enable a proven Cluster storage transport before drawing',\n ) {\n super(`Standard Cluster transport unavailable for ${requested} local lights`);\n this.name = 'StandardClusterTransportUnavailableError';\n this.hint = hint;\n this.detail = { requested, admitted: 0 };\n }\n}\n\n// ── StandardProfileInvalidError ───────────────────────────────────────────\n\nexport interface StandardProfileInvalidDetail {\n readonly field: string;\n readonly actual: unknown;\n}\n\n/** Structured validation failure for the single Standard profile surface. */\nexport class StandardProfileInvalidError extends Error {\n readonly code = 'standard-profile-invalid' as const;\n readonly expected: string;\n readonly hint: string;\n readonly detail: StandardProfileInvalidDetail;\n\n constructor(message: string, detail?: StandardProfileInvalidDetail) {\n super(message);\n this.name = 'StandardProfileInvalidError';\n this.detail = detail ?? { field: 'profile', actual: message };\n if (this.detail.field === 'clusterGrid') {\n this.expected = 'clusterGrid.{x,y,z} each positive integer in [1, 64]';\n this.hint =\n 'set clusterGrid.x, clusterGrid.y, and clusterGrid.z to positive integers in [1, 64]';\n } else {\n this.expected = 'StandardProfile contains only supported fields and values';\n this.hint = 'repair the Standard profile fields and retry setProfile';\n }\n }\n}\n\n// ── PointShadowAtlasUninitializedError ─────────────────────────────────────\n\n/**\n * Structured error for `ShadowAtlas.faceView` called before `ensure()`\n * allocated the cube_array texture. Replaces the prior bare\n * `throw new Error()` (Round-2 F-4: P3 closed-union compliance).\n *\n * - `.code = 'point-shadow-atlas-uninitialized'`\n * - `.expected` — call `ensure()` before iterating face views\n * - `.hint` — gate `faceView` on `isAllocated()` or call `ensure()` once\n * in the per-frame extract step before recording the 6 x N caster passes\n * - `.detail = undefined` (no per-call data needed)\n */\nexport class PointShadowAtlasUninitializedError extends Error {\n readonly code = 'point-shadow-atlas-uninitialized' as const;\n readonly expected: string;\n readonly hint: string;\n\n constructor() {\n const expected = 'ShadowAtlas.ensure() invoked before faceView()';\n const hint =\n 'Gate faceView on isAllocated() or call ensure() once in the per-frame extract step before iterating face views';\n super('ShadowAtlas.faceView called before ensure(); the cube_array texture is not allocated');\n this.name = 'PointShadowAtlasUninitializedError';\n this.expected = expected;\n this.hint = hint;\n }\n}\n\n// ── PointShadowAtlasBoundsViolationError ───────────────────────────────────\n\n/**\n * Detail for `RuntimeErrorCode 'point-shadow-atlas-bounds-violation'`.\n *\n * Emitted by `ShadowAtlas.faceView` when `layer` falls outside `[0, layers)`\n * or `face` falls outside `[0, 6)`. Both axes are reported as\n * `{ axis, value, max }` so AI users discriminate without parsing the message.\n */\nexport interface PointShadowAtlasBoundsViolationDetail {\n readonly axis: 'layer' | 'face';\n readonly value: number;\n readonly max: number;\n}\n\n/**\n * Structured error for `ShadowAtlas.faceView(layer, face)` arguments outside\n * the allocated atlas range. Replaces the prior bare `throw new Error()`\n * (Round-2 F-4: P3 closed-union compliance).\n *\n * - `.code = 'point-shadow-atlas-bounds-violation'`\n * - `.expected` — `0 <= layer < layers && 0 <= face < 6`\n * - `.hint` — clamp `shadowAtlasLayer` or face index before calling\n * `faceView`; the layer cap is the renderer-owned ShadowAtlas capacity\n * - `.detail = { axis, value, max }` — discriminates layer vs face\n */\nexport class PointShadowAtlasBoundsViolationError extends Error {\n readonly code = 'point-shadow-atlas-bounds-violation' as const;\n readonly expected: string;\n readonly hint: string;\n readonly detail: PointShadowAtlasBoundsViolationDetail;\n\n constructor(axis: 'layer' | 'face', value: number, max: number) {\n const expected = `0 <= ${axis} < ${max}`;\n const hint =\n axis === 'layer'\n ? `clamp PointLight.shadowAtlasLayer to [0, ${max}); the cap on layers equals PointLightShadow cardinality (4)`\n : `clamp face index to [0, ${max}); cube faces are indexed 0..5 in +X/-X/+Y/-Y/+Z/-Z order`;\n super(`ShadowAtlas.faceView ${axis} out of range: ${value} (must be in [0, ${max}))`);\n this.name = 'PointShadowAtlasBoundsViolationError';\n this.expected = expected;\n this.hint = hint;\n this.detail = { axis, value, max };\n }\n}\n\n// ── VideoUploadUnsupportedError ─────────────────────────────────────────\n\n/**\n * Structured error for `RuntimeErrorCode 'video-upload-unsupported'`\n * (feat-20260623-world-space-video-asset M3 / w11 — AC-10).\n *\n * Fired by the per-frame record stage (`videoTextureView`) when a VideoPlayer\n * entity can reach neither video upload path this frame: the general\n * `copyExternalImageToTexture` path (no host HTMLVideoElement resolved via\n * `VideoSourceProvider`) AND the high-perf `GPUExternalTexture` path\n * (capability absent). The engine surfaces this explicit failure rather than\n * silently rendering a stale/garbage texture (charter P3, plan-strategy D-6).\n * - `.code = 'video-upload-unsupported'`\n * - `.expected` — at least one upload path available (host element or\n * GPUExternalTexture capability)\n * - `.hint` — actionable recovery: use a static texture or switch backend\n * - `.detail` — undefined (no narrowed detail variant)\n */\nexport class VideoUploadUnsupportedError extends Error {\n readonly code = 'video-upload-unsupported' as const;\n readonly expected: string;\n readonly hint: string;\n\n constructor() {\n const expected =\n 'at least one video upload path available: a host HTMLVideoElement (general copyExternalImageToTexture path) or GPUExternalTexture capability (high-perf path)';\n const hint =\n 'this backend exposes no usable video upload path; render a static texture instead, or switch to a WebGPU backend that supports video texture upload';\n super('video upload unsupported — no general or high-perf path available');\n this.name = 'VideoUploadUnsupportedError';\n this.expected = expected;\n this.hint = hint;\n }\n}\n\n// ── VertexStorageBufferUnavailableError ─────────────────────────────────\n\n/**\n * Structured error for missing vertex-stage storage buffer capability.\n *\n * Emitted at createRenderer time (cap-gate).\n * - `.code = 'vertex-storage-buffer-unavailable'`\n * - `.expected` — device.caps supports vertex-stage storage buffer\n * - `.hint` — switch to a WebGPU adapter with vertex storage buffer support or use uniform-buffer fallback (OOS-uniform-palette)\n * - `.detail` — undefined (no narrowed detail variant)\n */\nexport class VertexStorageBufferUnavailableError extends Error {\n readonly code = 'vertex-storage-buffer-unavailable' as const;\n readonly expected: string;\n readonly hint: string;\n\n constructor() {\n const expected =\n 'device.caps supports vertex-stage storage buffer (maxStorageBuffersPerShaderStage >= 1)';\n const hint =\n 'this device does not support vertex-stage storage buffers; skinning requires vertex-stage storage buffer access (OOS-uniform-palette fallback not implemented)';\n super('vertex-stage storage buffer unavailable — skinning cannot operate');\n this.name = 'VertexStorageBufferUnavailableError';\n this.expected = expected;\n this.hint = hint;\n }\n}\n\n// ── VertexColorVariantConflictError ───────────────────────────────────────\n\nexport interface VertexColorVariantConflictDetail {\n readonly authored: true;\n readonly authoredValue: string;\n readonly projected: boolean;\n}\n\n/** The authored color axis disagrees with the canonical geometry projection. */\nexport class VertexColorVariantConflictError extends Error {\n readonly code = 'vertex-color-variant-conflict' as const;\n readonly expected: string;\n readonly hint: string;\n readonly detail: VertexColorVariantConflictDetail;\n\n constructor(authoredValue: string, projected: boolean) {\n const expected = `VERTEX_COLOR_AVAILABLE=${projected ? 'true' : 'false'}`;\n const hint =\n 'derive the shader variant from the mesh VertexLayoutProjection; COLOR_0 presence is a geometry fact';\n super(`authored vertex-color variant ${authoredValue} disagrees with projected ${expected}`);\n this.name = 'VertexColorVariantConflictError';\n this.expected = expected;\n this.hint = hint;\n this.detail = { authored: true, authoredValue, projected };\n }\n}\n\n// ── Skin palette/material validation errors ────────────────────────────────\n\n/** Detail for a palette buffer that exceeds the device storage limit. */\nexport interface SkinPaletteOverflowDetail {\n readonly requestedBytes: number;\n readonly limit: number;\n}\n\n/**\n * Structured render error for a skin palette allocation that exceeds the\n * device storage-buffer binding limit. The allocator that emits this error\n * lives in render, so the error belongs to the render union rather than the\n * renderer-independent skinning binding package.\n */\nexport class SkinPaletteOverflowError extends Error {\n readonly code = 'skin-palette-overflow' as const;\n readonly expected: string;\n readonly hint: string;\n readonly detail: SkinPaletteOverflowDetail;\n\n constructor(requestedBytes: number, limit: number) {\n const expected = `skinned joint palette (${requestedBytes} B) fits within device.limits.maxStorageBufferBindingSize (${limit} B)`;\n const hint =\n 'palette buffer exceeds device maxStorageBufferBindingSize; reduce skinned entity count or split into multiple palette buffers (OOS-skin-palette-batch)';\n super(`skin palette buffer needs ${requestedBytes} B, exceeds device limit ${limit} B`);\n this.name = 'SkinPaletteOverflowError';\n this.expected = expected;\n this.hint = hint;\n this.detail = { requestedBytes, limit };\n }\n}\n\n/** Detail for a skinned entity using a non-skin material shader. */\nexport interface SkinMaterialMismatchDetail {\n readonly entity: number;\n readonly actualShader: string | undefined;\n}\n\n/** Structured render error for a Skin/non-skin-material mismatch. */\nexport class SkinMaterialMismatchError extends Error {\n readonly code = 'skin-material-mismatch' as const;\n readonly expected: string;\n readonly hint: string;\n readonly detail: SkinMaterialMismatchDetail;\n\n constructor(entity: number, actualShader: string | undefined) {\n const expected = \"Skin entity's first material program module === 'forgeax::pbr-skin'\";\n const hint = `entity ${entity} has Skin but the first material program module is ${actualShader ?? '<empty>'}; load the mesh via the gltf importer (cooker auto-routes 'forgeax::pbr-skin' for skinned primitives), or remove the Skin component to render the entity unskinned with Materials.standard / Materials.unlit`;\n super(\n `Skin / material mismatch on entity ${entity}: expected forgeax::pbr-skin, got ${actualShader ?? '<empty>'}`,\n );\n this.name = 'SkinMaterialMismatchError';\n this.expected = expected;\n this.hint = hint;\n this.detail = { entity, actualShader };\n }\n}\n\n/** Detail for a pbr-skin material whose mesh lacks skin attributes. */\nexport interface MaterialSkinAttrMissingDetail {\n readonly entity: number;\n readonly missing: 'skinIndex' | 'skinWeight' | 'both';\n}\n\n/** Structured render error for a pbr-skin material/mesh attribute mismatch. */\nexport class MaterialSkinAttrMissingError extends Error {\n readonly code = 'material-skin-attr-missing' as const;\n readonly expected: string;\n readonly hint: string;\n readonly detail: MaterialSkinAttrMissingDetail;\n\n constructor(entity: number, missing: 'skinIndex' | 'skinWeight' | 'both') {\n const expected = 'pbr-skin material requires mesh.attributes.skinIndex + skinWeight';\n const hint = `entity ${entity} uses forgeax::pbr-skin but its MeshAsset is missing ${missing}; switch the entity to a skinned glTF mesh authored with JOINTS_0 + WEIGHTS_0, or change the material to a non-skin shader via Materials.standard / Materials.unlit`;\n super(\n `material/skin attribute mismatch on entity ${entity}: pbr-skin material with mesh missing ${missing}`,\n );\n this.name = 'MaterialSkinAttrMissingError';\n this.expected = expected;\n this.hint = hint;\n this.detail = { entity, missing };\n }\n}\n\nexport interface TransmissionCapabilityMissingDetail {\n readonly material: string;\n readonly capability: 'transmission';\n readonly stage: 'prepare' | 'record';\n readonly lane: 'standard-forward';\n readonly format: string;\n readonly missing: readonly TransmissionCapabilityFact[];\n}\n\nexport class TransmissionCapabilityMissingError extends Error {\n readonly code = 'transmission-capability-missing' as const;\n readonly expected = 'the renderer exposes the transmission capability for this material';\n readonly hint = 'disable transmission or provide the renderer capability before drawing';\n readonly detail: TransmissionCapabilityMissingDetail;\n\n constructor(\n material: string,\n stage: 'prepare' | 'record',\n evidence: {\n readonly lane: 'standard-forward';\n readonly format: string;\n readonly missing: readonly TransmissionCapabilityFact[];\n },\n ) {\n super(`transmission capability is missing for material '${material}'`);\n this.name = 'TransmissionCapabilityMissingError';\n this.detail = { material, capability: 'transmission', stage, ...evidence };\n }\n}\n\n// -- RenderFeature errors ---------------------------------------------------\n\nexport type RenderFeatureErrorCode =\n | 'render-feature-registration-conflict'\n | 'render-feature-stage-failed'\n | 'render-feature-capability-missing'\n | 'render-feature-pass-order-conflict'\n | 'render-feature-preparation-failed'\n | 'render-feature-prepared-state-mismatch'\n | 'render-feature-draw-recording-failed';\n\nexport interface RenderFeatureRegistrationConflictDetail {\n readonly featureIdentity: string;\n readonly order: number;\n readonly conflictingOrder: number;\n}\n\nexport interface RenderFeatureCleanupFailure {\n readonly featureIdentity: string;\n readonly order: number;\n readonly code: string;\n}\n\nexport interface RenderFeatureStageFailedDetail {\n readonly featureIdentity: string;\n readonly order: number;\n readonly stage: RenderFeatureStage;\n readonly recovery: RenderFeatureRecovery;\n readonly cleanupFailures?: readonly RenderFeatureCleanupFailure[];\n /** Original stage exception when the feature did not return a RenderError. */\n readonly cause?: unknown;\n}\n\nexport interface RenderFeatureCapabilityMissingDetail {\n readonly featureIdentity: string;\n readonly order: number;\n readonly capability: RenderFeatureCapabilityKey;\n}\n\nexport interface RenderFeaturePassOrderConflictDetail {\n readonly featureIdentity: string;\n readonly order: number;\n readonly passIdentity: string;\n readonly dependencyIdentity: string;\n}\n\nexport interface RenderFeaturePreparationFailedDetail {\n readonly featureIdentity: string;\n readonly order: number;\n readonly stage: 'prepare';\n readonly operation: string;\n readonly resourceKind: PreparedKind;\n readonly resourceName: string;\n readonly reason: string;\n readonly recovery: RenderFeatureRecovery;\n}\n\nexport type RenderFeaturePreparedStateMismatchDetail =\n | {\n readonly featureIdentity: string;\n readonly order: number;\n readonly stage: 'contribute';\n readonly operation: string;\n readonly resourceKind: PreparedKind;\n readonly reason: 'missing-prepared-state';\n readonly missingResource: string;\n readonly recovery: RenderFeatureRecovery;\n }\n | {\n readonly featureIdentity: string;\n readonly order: number;\n readonly stage: 'contribute';\n readonly operation: string;\n readonly resourceKind: PreparedKind;\n readonly reason: 'foreign-feature';\n readonly expectedFeatureIdentity: string;\n readonly actualFeatureIdentity: string;\n readonly recovery: RenderFeatureRecovery;\n }\n | {\n readonly featureIdentity: string;\n readonly order: number;\n readonly stage: 'contribute';\n readonly operation: string;\n readonly resourceKind: PreparedKind;\n readonly reason: 'foreign-kind';\n readonly expectedKind: PreparedKind;\n readonly actualKind: PreparedKind;\n readonly recovery: RenderFeatureRecovery;\n }\n | {\n readonly featureIdentity: string;\n readonly order: number;\n readonly stage: 'contribute';\n readonly operation: string;\n readonly resourceKind: PreparedKind;\n readonly reason: 'generation-mismatch';\n readonly expectedGeneration: number;\n readonly actualGeneration: number;\n readonly recovery: RenderFeatureRecovery;\n }\n | {\n readonly featureIdentity: string;\n readonly order: number;\n readonly stage: 'contribute';\n readonly operation: string;\n readonly resourceKind: PreparedKind;\n readonly reason: 'layout-mismatch';\n readonly expectedLayout: string;\n readonly actualLayout: string;\n readonly recovery: RenderFeatureRecovery;\n }\n | {\n readonly featureIdentity: string;\n readonly order: number;\n readonly stage: 'contribute';\n readonly operation: string;\n readonly resourceKind: PreparedKind;\n readonly reason: 'format-mismatch';\n readonly expectedFormat: string;\n readonly actualFormat: string;\n readonly recovery: RenderFeatureRecovery;\n };\n\nexport interface RenderFeatureDrawRecordingFailedDetail {\n readonly featureIdentity: string;\n readonly order: number;\n readonly stage: 'record';\n readonly operation: string;\n readonly resourceKind: PreparedKind;\n readonly reason: string;\n readonly backendReason: string;\n readonly recovery: RenderFeatureRecovery;\n}\n\nexport type RenderFeatureErrorDetailByCode = {\n 'render-feature-registration-conflict': RenderFeatureRegistrationConflictDetail;\n 'render-feature-stage-failed': RenderFeatureStageFailedDetail;\n 'render-feature-capability-missing': RenderFeatureCapabilityMissingDetail;\n 'render-feature-pass-order-conflict': RenderFeaturePassOrderConflictDetail;\n 'render-feature-preparation-failed': RenderFeaturePreparationFailedDetail;\n 'render-feature-prepared-state-mismatch': RenderFeaturePreparedStateMismatchDetail;\n 'render-feature-draw-recording-failed': RenderFeatureDrawRecordingFailedDetail;\n};\n\n/** Machine-readable four-field diagnostic exposed by every feature error. */\nexport type RenderFeatureErrorDescriptor = {\n [Code in RenderFeatureErrorCode]: {\n readonly code: Code;\n readonly expected: string;\n readonly hint: string;\n readonly detail: RenderFeatureErrorDetailByCode[Code];\n };\n}[RenderFeatureErrorCode];\n\nconst renderFeatureRecoveryHintByRecovery = {\n 'next-frame': (featureIdentity: string, stage: RenderFeatureStage) =>\n `correct '${featureIdentity}' ${stage} data and retry on the next frame`,\n 'renderer-recover': (featureIdentity: string, _stage: RenderFeatureStage) =>\n `wait for renderer recovery before retrying '${featureIdentity}'`,\n registration: (featureIdentity: string, _stage: RenderFeatureStage) =>\n `correct '${featureIdentity}' registration before retrying`,\n} satisfies Record<\n RenderFeatureRecovery,\n (featureIdentity: string, stage: RenderFeatureStage) => string\n>;\n\nexport class RenderFeatureRegistrationConflictError extends Error {\n readonly code = 'render-feature-registration-conflict' as const;\n readonly expected: string;\n readonly hint: string;\n readonly detail: RenderFeatureRegistrationConflictDetail;\n\n constructor(featureIdentity: string, order: number, conflictingOrder: number) {\n const expected = `feature identity '${featureIdentity}' is unique`;\n const hint = `rename '${featureIdentity}' or remove the duplicate feature before registration`;\n super(`render feature registration conflict for '${featureIdentity}'`);\n this.name = 'RenderFeatureRegistrationConflictError';\n this.expected = expected;\n this.hint = hint;\n this.detail = { featureIdentity, order, conflictingOrder };\n }\n}\n\nexport class RenderFeatureStageFailedError extends Error {\n readonly code = 'render-feature-stage-failed' as const;\n readonly expected: string;\n readonly hint: string;\n readonly detail: RenderFeatureStageFailedDetail;\n\n constructor(\n featureIdentity: string,\n order: number,\n stage: RenderFeatureStage,\n recovery: RenderFeatureRecovery,\n cause?: unknown,\n ) {\n const expected = `feature '${featureIdentity}' completes its ${stage} stage without an error`;\n const hint = renderFeatureRecoveryHintByRecovery[recovery](featureIdentity, stage);\n super(`render feature '${featureIdentity}' failed during ${stage}`);\n this.name = 'RenderFeatureStageFailedError';\n this.expected = expected;\n this.hint = hint;\n this.detail = {\n featureIdentity,\n order,\n stage,\n recovery,\n ...(cause === undefined ? {} : { cause }),\n };\n }\n}\n\nexport class RenderFeatureCapabilityMissingError extends Error {\n readonly code = 'render-feature-capability-missing' as const;\n readonly expected: string;\n readonly hint: string;\n readonly detail: RenderFeatureCapabilityMissingDetail;\n\n constructor(\n featureIdentity: string,\n order: number,\n capability: RenderFeatureCapabilityMissingDetail['capability'],\n ) {\n const expected = `device capability '${capability}' is available for feature '${featureIdentity}'`;\n const hint = `disable '${featureIdentity}' or use a device with '${capability}' capability`;\n super(`render feature '${featureIdentity}' requires missing capability '${capability}'`);\n this.name = 'RenderFeatureCapabilityMissingError';\n this.expected = expected;\n this.hint = hint;\n this.detail = { featureIdentity, order, capability };\n }\n}\n\nexport class RenderFeaturePassOrderConflictError extends Error {\n readonly code = 'render-feature-pass-order-conflict' as const;\n readonly expected: string;\n readonly hint: string;\n readonly detail: RenderFeaturePassOrderConflictDetail;\n\n constructor(\n featureIdentity: string,\n order: number,\n passIdentity: string,\n dependencyIdentity: string,\n ) {\n const expected = `feature pass '${passIdentity}' follows dependency '${dependencyIdentity}'`;\n const hint = `reorder '${featureIdentity}' passes so '${passIdentity}' follows '${dependencyIdentity}'`;\n super(`render feature '${featureIdentity}' pass order conflict`);\n this.name = 'RenderFeaturePassOrderConflictError';\n this.expected = expected;\n this.hint = hint;\n this.detail = { featureIdentity, order, passIdentity, dependencyIdentity };\n }\n}\n\nexport class RenderFeaturePreparationFailedError extends Error {\n readonly code = 'render-feature-preparation-failed' as const;\n readonly expected: string;\n readonly hint: string;\n readonly detail: RenderFeaturePreparationFailedDetail;\n\n constructor(\n featureIdentity: string,\n order: number,\n operation: string,\n resourceKind: RenderFeaturePreparationFailedDetail['resourceKind'],\n resourceName: string,\n reason: string,\n recovery: RenderFeatureRecovery,\n ) {\n const expected = `${resourceKind} '${resourceName}' is prepared during ${operation}`;\n const hint = `repair '${resourceName}' and retry feature '${featureIdentity}' on ${recovery}`;\n super(`render feature '${featureIdentity}' preparation failed for '${resourceName}'`);\n this.name = 'RenderFeaturePreparationFailedError';\n this.expected = expected;\n this.hint = hint;\n this.detail = {\n featureIdentity,\n order,\n stage: 'prepare',\n operation,\n resourceKind,\n resourceName,\n reason,\n recovery,\n };\n }\n}\n\nexport class RenderFeaturePreparedStateMismatchError extends Error {\n readonly code = 'render-feature-prepared-state-mismatch' as const;\n readonly expected: string;\n readonly hint: string;\n readonly detail: RenderFeaturePreparedStateMismatchDetail;\n\n constructor(detail: RenderFeaturePreparedStateMismatchDetail) {\n const expected = `${detail.resourceKind} state is compatible for '${detail.operation}'`;\n const hint = `repair '${detail.reason}' for feature '${detail.featureIdentity}' and retry`;\n super(`render feature '${detail.featureIdentity}' prepared state mismatch`);\n this.name = 'RenderFeaturePreparedStateMismatchError';\n this.expected = expected;\n this.hint = hint;\n this.detail = detail;\n }\n}\n\nexport class RenderFeatureDrawRecordingFailedError extends Error {\n readonly code = 'render-feature-draw-recording-failed' as const;\n readonly expected: string;\n readonly hint: string;\n readonly detail: RenderFeatureDrawRecordingFailedDetail;\n\n constructor(\n featureIdentity: string,\n order: number,\n operation: string,\n resourceKind: RenderFeatureDrawRecordingFailedDetail['resourceKind'],\n reason: string,\n backendReason: string,\n recovery: RenderFeatureRecovery,\n ) {\n const expected = `${resourceKind} recording succeeds for '${operation}'`;\n const hint = `repair '${reason}' and retry feature '${featureIdentity}' after ${recovery}`;\n super(`render feature '${featureIdentity}' draw recording failed`);\n this.name = 'RenderFeatureDrawRecordingFailedError';\n this.expected = expected;\n this.hint = hint;\n this.detail = {\n featureIdentity,\n order,\n stage: 'record',\n operation,\n resourceKind,\n reason,\n backendReason,\n recovery,\n };\n }\n}\n\n// ── ObservationUnavailableError ───────────────────────────────────────────\n\nexport type ObservationUnavailableReason =\n | 'no-frame'\n | 'resource'\n | 'copy-src'\n | 'stale'\n | 'identity'\n | 'format'\n | 'readback-failed';\n\nexport interface ObservationUnavailableDetail {\n readonly reason: ObservationUnavailableReason;\n readonly recovery: 'draw-current-frame' | 'enable-copy-src' | 'retry-readback';\n}\n\n/** A producer-owned current-frame observation could not be made available. */\nexport class ObservationUnavailableError extends Error {\n readonly code = 'observation-unavailable' as const;\n readonly expected: string;\n readonly hint: string;\n readonly detail: ObservationUnavailableDetail;\n\n constructor(reason: ObservationUnavailableReason, hint: string) {\n let recovery: ObservationUnavailableDetail['recovery'];\n if (reason === 'copy-src') recovery = 'enable-copy-src';\n else if (reason === 'resource' || reason === 'readback-failed') recovery = 'retry-readback';\n else recovery = 'draw-current-frame';\n super(`current-frame observation unavailable: ${reason}`);\n this.name = 'ObservationUnavailableError';\n this.expected = 'a fresh producer-owned rgba16float current-frame observation';\n this.hint = hint;\n this.detail = { reason, recovery };\n }\n}\n\nexport type SceneDataUnavailableReason =\n | 'capability-missing'\n | 'producer-missing'\n | 'coverage-incomplete'\n | 'renderer-recovering';\nexport interface SceneDataUnavailableDetail {\n readonly featureIdentity: string;\n readonly schema: SceneDataSchemaId;\n readonly lane: SceneDataLane;\n readonly reason: SceneDataUnavailableReason;\n readonly missingContributorIds: readonly string[];\n readonly omittedMissingContributorCount: number;\n readonly recovery: 'enable-capability' | 'next-frame' | 'renderer-recover';\n}\nexport class SceneDataUnavailableError extends Error {\n readonly code = 'scene-data-unavailable' as const;\n readonly expected = 'the requested semantic scene data is available for the active plan';\n readonly hint: string;\n readonly detail: SceneDataUnavailableDetail;\n constructor(detail: SceneDataUnavailableDetail) {\n const hint =\n detail.recovery === 'enable-capability'\n ? 'enable rgba16floatRenderable and retry the current frame'\n : detail.recovery === 'renderer-recover'\n ? 'wait for renderer recovery, then retry the frame'\n : 'restore the producer coverage and retry on the next frame';\n super(`scene data '${detail.schema}' unavailable for '${detail.featureIdentity}'`);\n this.name = 'SceneDataUnavailableError';\n this.hint = hint;\n this.detail = Object.freeze({\n ...detail,\n missingContributorIds: Object.freeze([...detail.missingContributorIds].slice(0, 32)),\n omittedMissingContributorCount: Math.max(\n detail.omittedMissingContributorCount,\n Math.max(0, detail.missingContributorIds.length - 32),\n ),\n });\n }\n}\n\nexport class TaaUnavailableError extends Error {\n readonly code = 'taa-unavailable' as const;\n readonly expected =\n 'Standard TAA has a renderable rgba16float target and a complete resolve path';\n readonly hint =\n 'enable rgba16float rendering or select none/fxaa explicitly; do not treat TAA as no-AA';\n readonly detail: {\n readonly reason: 'capability' | 'topology' | 'history';\n readonly observed?: string;\n };\n constructor(reason: 'capability' | 'topology' | 'history', observed?: string) {\n super(`taa-unavailable: ${reason}`);\n this.name = 'TaaUnavailableError';\n this.detail = observed === undefined ? { reason } : { reason, observed };\n }\n}\n\nexport interface FrameReceiptStaleDetail {\n readonly frameId: number;\n readonly receiptGeneration: number;\n readonly currentGeneration: number;\n}\n\n/** Receipt-bound observation failed closed at a generation fence. */\nexport class FrameReceiptStaleError extends Error {\n readonly code = 'frame-receipt-stale' as const;\n readonly expected = 'the observation receipt belongs to the active device generation';\n readonly hint = 'draw a new frame and call observe with its returned FrameReceipt';\n readonly detail: FrameReceiptStaleDetail;\n\n constructor(detail: FrameReceiptStaleDetail) {\n super('frame receipt belongs to a retired device generation');\n this.name = 'FrameReceiptStaleError';\n this.detail = detail;\n }\n}\n\nexport interface RendererContractFailureDetail {\n readonly operation: 'construct' | 'attach' | 'draw' | 'request-observation' | 'observe';\n readonly cause: string;\n}\n\n/** Structured boundary failure while adapting an owner contract. */\nexport class RendererContractFailureError extends Error {\n readonly code = 'renderer-contract-failed' as const;\n readonly expected = 'renderer owner contracts remain valid at the public boundary';\n readonly hint = 'repair the owner contract and retry the operation';\n readonly detail: RendererContractFailureDetail;\n\n constructor(operation: RendererContractFailureDetail['operation'], cause: string) {\n super(`renderer ${operation} contract failed: ${cause}`);\n this.name = 'RendererContractFailureError';\n this.detail = { operation, cause };\n }\n}\n\nexport interface EnvironmentSourceConflictDetail {\n readonly owners: readonly {\n readonly kind: 'image' | 'atmosphere';\n readonly entityKey: number;\n readonly sourceKey: string;\n }[];\n}\n\nexport class EnvironmentSourceConflictError extends Error {\n readonly code = 'environment-source-conflict' as const;\n readonly expected = 'exactly one environment source owns the frame';\n readonly hint = 'remove all but one image or atmosphere environment owner';\n readonly detail: EnvironmentSourceConflictDetail;\n\n constructor(owners: readonly EnvironmentSourceConflictDetail['owners'][number][]) {\n super('environment source owners conflict');\n this.name = 'EnvironmentSourceConflictError';\n this.detail = { owners: owners.map((owner) => Object.freeze({ ...owner })) };\n }\n}\n\nexport interface FogCardinalityDetail {\n readonly count: number;\n}\n\nexport class FogCardinalityError extends Error {\n readonly code = 'fog-cardinality' as const;\n readonly expected = 'zero or one Fog owner contributes to a frame';\n readonly hint = 'remove extra Fog owners so the resource owner has at most one';\n readonly detail: FogCardinalityDetail;\n\n constructor(count: number) {\n super(`Fog owner cardinality is ${count}`);\n this.name = 'FogCardinalityError';\n this.detail = { count };\n }\n}\n\nexport interface TaaCapsInsufficientDetail {\n readonly required: readonly string[];\n readonly available: readonly string[];\n}\n\nexport class TaaCapsInsufficientError extends Error {\n readonly code = 'taa-caps-insufficient' as const;\n readonly expected = 'the backend exposes the capabilities required by TAA';\n readonly hint = 'select a backend with the required TAA capabilities or disable TAA on Camera';\n readonly detail: TaaCapsInsufficientDetail;\n\n constructor(required: readonly string[], available: readonly string[]) {\n super('TAA capabilities are insufficient');\n this.name = 'TaaCapsInsufficientError';\n this.detail = { required: [...required], available: [...available] };\n }\n}\n\nexport interface EnvironmentGenerationFailedDetail {\n readonly sourceKey: string;\n readonly stage: 'prepare' | 'build' | 'execute' | 'finish' | 'submit';\n}\n\nexport class EnvironmentGenerationFailedError extends Error {\n readonly code = 'environment-generation-failed' as const;\n readonly expected = 'the selected environment generation completes its owner stage';\n readonly hint = 'inspect the stage and sourceKey, then retry after correcting the environment';\n readonly detail: EnvironmentGenerationFailedDetail;\n\n constructor(sourceKey: string, stage: EnvironmentGenerationFailedDetail['stage']) {\n super(`environment generation failed during ${stage}`);\n this.name = 'EnvironmentGenerationFailedError';\n this.detail = { sourceKey, stage };\n }\n}\n\nexport interface AtmosphereInvalidParameterDetail {\n readonly field: string;\n readonly value: number;\n}\n\nexport interface AtmosphereParameterRange {\n readonly min: number;\n readonly max: number;\n}\n\nexport class AtmosphereInvalidParameterError extends Error {\n readonly code = 'atmosphere-invalid-parameter' as const;\n readonly expected: string;\n readonly hint: string;\n readonly detail: AtmosphereInvalidParameterDetail;\n\n constructor(field: string, value: number, range: AtmosphereParameterRange) {\n super(`Atmosphere.${field} is invalid`);\n this.name = 'AtmosphereInvalidParameterError';\n this.detail = { field, value };\n const rangeText = Number.isFinite(range.max)\n ? `[${range.min}, ${range.max}]`\n : `>= ${range.min}`;\n this.expected = `Atmosphere.${field} must be finite and ${rangeText}`;\n this.hint = `set Atmosphere.${field} to a finite value ${rangeText}`;\n }\n}\n\nexport interface DynamicResolutionInvalidParameterDetail {\n readonly field: 'targetGpuMs' | 'minScale' | 'maxScale';\n readonly value: number;\n readonly expected: string;\n}\n\nexport class DynamicResolutionInvalidParameterError extends Error {\n readonly code = 'dynamic-resolution-invalid-parameter' as const;\n readonly expected: string;\n readonly hint: string;\n readonly detail: DynamicResolutionInvalidParameterDetail;\n\n constructor(detail: DynamicResolutionInvalidParameterDetail) {\n super(`DynamicResolution.${detail.field} is invalid`);\n this.name = 'DynamicResolutionInvalidParameterError';\n this.expected = `DynamicResolution.${detail.field} must be ${detail.expected}`;\n this.hint = `set DynamicResolution.${detail.field} to a value that is ${detail.expected}`;\n this.detail = detail;\n }\n}\n\nexport interface DynamicResolutionRequiresTaaDetail {\n readonly antialias: 'none' | 'fxaa' | 'msaa';\n}\n\nexport class DynamicResolutionRequiresTaaError extends Error {\n readonly code = 'dynamic-resolution-requires-taa' as const;\n readonly expected = \"DynamicResolution requires Camera.antialias to be 'taa'\";\n readonly hint = \"set Camera.antialias to 'taa' or remove DynamicResolution before retrying\";\n readonly detail: DynamicResolutionRequiresTaaDetail;\n\n constructor(detail: DynamicResolutionRequiresTaaDetail) {\n super('DynamicResolution requires TAA');\n this.name = 'DynamicResolutionRequiresTaaError';\n this.detail = detail;\n }\n}\n\nexport interface DynamicResolutionTimingUnavailableDetail {\n readonly generation: number;\n readonly operation: 'timestamp-query';\n}\n\nexport class DynamicResolutionTimingUnavailableError extends Error {\n readonly code = 'dynamic-resolution-timing-unavailable' as const;\n readonly expected = 'adaptive resolution receives a completed GPU timing sample';\n readonly hint = 'use fixed minScale=maxScale or retry after timestamp support is available';\n readonly detail: DynamicResolutionTimingUnavailableDetail;\n\n constructor(detail: DynamicResolutionTimingUnavailableDetail) {\n super(`DynamicResolution timing is unavailable for generation ${detail.generation}`);\n this.name = 'DynamicResolutionTimingUnavailableError';\n this.detail = detail;\n }\n}\n\nexport type DynamicResolutionError =\n | DynamicResolutionInvalidParameterError\n | DynamicResolutionRequiresTaaError\n | DynamicResolutionTimingUnavailableError;\n\nexport interface BarrelDistortionInvalidParameterDetail {\n readonly field: 'width' | 'height' | 'strength' | 'centerX' | 'centerY';\n readonly value: number;\n readonly expected: string;\n}\n\nexport class BarrelDistortionInvalidParameterError extends Error {\n readonly code = 'barrel-distortion-invalid-parameter' as const;\n readonly expected: string;\n readonly hint: string;\n readonly detail: BarrelDistortionInvalidParameterDetail;\n\n constructor(detail: BarrelDistortionInvalidParameterDetail) {\n super(`BarrelDistortion.${detail.field} is invalid`);\n this.name = 'BarrelDistortionInvalidParameterError';\n this.expected = `BarrelDistortion.${detail.field} must be ${detail.expected}`;\n this.hint = `set BarrelDistortion.${detail.field} to a value that is ${detail.expected}`;\n this.detail = detail;\n }\n}\n\nexport interface OwnerStageFailedDetail {\n readonly owner: 'environment' | 'temporal' | 'fog' | 'renderer';\n readonly stage: 'extract' | 'prepare' | 'record' | 'finish' | 'submit';\n}\n\nexport class OwnerStageFailedError extends Error {\n readonly code = 'owner-stage-failed' as const;\n readonly expected = 'the owner completes its current frame stage';\n readonly hint = 'inspect the owner and stage, keep the last-known-good frame, and retry';\n readonly detail: OwnerStageFailedDetail;\n\n constructor(owner: OwnerStageFailedDetail['owner'], stage: OwnerStageFailedDetail['stage']) {\n super(`${owner} owner failed during ${stage}`);\n this.name = 'OwnerStageFailedError';\n this.detail = { owner, stage };\n }\n}\n\nexport interface RendererOperationCause {\n readonly code: string;\n readonly expected: string;\n readonly hint: string;\n readonly detail?: unknown;\n}\n\nexport interface RendererOperationDetailByCode {\n readonly 'world-lease-invalid': {\n readonly operation: 'attach' | 'draw';\n readonly cause: RendererOperationCause;\n };\n readonly 'frame-input-invalid': {\n readonly operation: 'draw' | 'set-profile' | 'request-observation';\n readonly cause: RendererOperationCause;\n };\n readonly 'scene-projection-failed': {\n readonly operation: 'draw';\n readonly cause: RendererOperationCause;\n };\n readonly 'asset-binding-failed': {\n readonly operation: 'draw';\n readonly cause: RendererOperationCause;\n };\n readonly 'feature-plan-failed': {\n readonly operation: 'draw';\n readonly cause: RendererOperationCause;\n };\n readonly 'graph-build-failed': {\n readonly operation: 'draw' | 'set-profile';\n readonly cause: RendererOperationCause;\n };\n readonly 'device-operation-failed': {\n readonly operation: 'draw' | 'complete-frame' | 'renderer-event';\n readonly frameId?: number;\n readonly deviceGeneration?: number;\n readonly cause: RendererOperationCause;\n };\n readonly 'surface-unavailable': {\n readonly operation: 'release-surface' | 'restore-surface';\n readonly cause: RendererOperationCause;\n };\n readonly 'renderer-state-invalid': {\n readonly operation: 'draw' | 'set-profile' | 'request-observation' | 'recover' | 'dispose';\n readonly state: string;\n readonly cause?: RendererOperationCause;\n };\n readonly 'recovery-failed': {\n readonly operation: 'recover';\n readonly phase: RecoveryPhase;\n readonly oldGeneration: number;\n readonly candidateGeneration: number;\n readonly attempt: number;\n readonly elapsedMs: number;\n readonly retryable: boolean;\n readonly guidance: 'retry' | 'repair-owner' | 'rebuild-renderer';\n readonly owner: string;\n readonly resourceKind: string;\n readonly lastOutcome: RecoveryOutcome;\n readonly rehydratedRoots: number;\n readonly staleLossEvents: number;\n readonly cleanupFailures: readonly RendererOperationCause[];\n readonly cause: RendererOperationCause;\n };\n readonly 'cleanup-failed': {\n readonly operation: 'dispose';\n readonly causes: readonly RendererOperationCause[];\n };\n}\n\nexport type RendererOperationErrorCode = keyof RendererOperationDetailByCode;\n\nconst RENDERER_OPERATION_ERROR_POLICY = {\n 'world-lease-invalid': {\n expected: 'every render World is represented by a live lease owned by this Renderer',\n hint: 'attach the World to this Renderer and use the returned lease',\n },\n 'frame-input-invalid': {\n expected: 'the frame input references attached leases and a valid immutable RenderProfile',\n hint: 'repair the frame input and retry draw or setProfile',\n },\n 'scene-projection-failed': {\n expected: 'the attached World projects into the renderer-owned RenderScene',\n hint: 'inspect the structured cause, repair the World publication, and retry draw',\n },\n 'asset-binding-failed': {\n expected: 'all frame assets resolve to valid renderer-owned bindings',\n hint: 'inspect the structured cause, rebuild or cold-cook the asset, and retry draw',\n },\n 'feature-plan-failed': {\n expected: 'every installed RenderFeature produces a valid declarative plan',\n hint: 'inspect the feature cause, repair its plan, and retry draw',\n },\n 'graph-build-failed': {\n expected: 'the Standard graph builds from the active profile and feature plans',\n hint: 'inspect the graph cause, repair the profile or plan, and retry',\n },\n 'device-operation-failed': {\n expected: 'the active device generation completes the renderer-owned operation',\n hint: 'inspect renderer state and the structured cause, then retry or recover',\n },\n 'surface-unavailable': {\n expected: 'the presentation surface accepts the requested lifecycle operation',\n hint: 'inspect renderer state, then restore the surface or create a new Renderer',\n },\n 'renderer-state-invalid': {\n expected: 'the Renderer is in a state that accepts the requested operation',\n hint: 'inspect renderer state and choose retry, restoreSurface, recover, or stop',\n },\n 'recovery-failed': {\n expected: 'one recovery attempt publishes a complete replacement device generation',\n hint: 'inspect the structured cause and retry recover after the host-selected delay',\n },\n 'cleanup-failed': {\n expected: 'Renderer disposal completes every registered cleanup in reverse ownership order',\n hint: 'inspect the ordered cleanup causes; the Renderer remains disposed and must not be reused',\n },\n} as const satisfies Readonly<\n Record<RendererOperationErrorCode, { readonly expected: string; readonly hint: string }>\n>;\n\n/** Public renderer-operation failure with a code-narrowed structured detail. */\nexport class RendererOperationError<Code extends RendererOperationErrorCode> extends Error {\n readonly code: Code;\n readonly expected: string;\n readonly hint: string;\n readonly detail: RendererOperationDetailByCode[Code];\n\n constructor(code: Code, detail: RendererOperationDetailByCode[Code]) {\n const policy = RENDERER_OPERATION_ERROR_POLICY[code];\n super(`${code}: ${policy.expected}`);\n this.name = 'RendererOperationError';\n this.code = code;\n this.expected = policy.expected;\n this.hint = policy.hint;\n this.detail = detail;\n }\n}\n\nexport type RendererExpectedOperationError = {\n readonly [Code in RendererOperationErrorCode]: RendererOperationError<Code>;\n}[RendererOperationErrorCode];\n\n// -- Points/Lines admission errors -------------------------------------------\n\nexport interface PointsLinesInvalidStyleDetail {\n readonly entity: number;\n readonly component: 'Points' | 'Lines' | 'Points/Lines';\n readonly field: string;\n readonly value: number | string | undefined;\n readonly expected: string;\n}\n\nexport class PointsLinesInvalidStyleError extends Error {\n readonly code = 'points-lines-invalid-style' as const;\n readonly expected: string;\n readonly hint: string;\n readonly detail: PointsLinesInvalidStyleDetail;\n\n constructor(detail: PointsLinesInvalidStyleDetail) {\n super(`invalid ${detail.component} style at ${detail.field}`);\n this.name = 'PointsLinesInvalidStyleError';\n this.expected = detail.expected;\n this.hint = `repair entity ${detail.entity} ${detail.component}.${detail.field} and retry admission`;\n this.detail = detail;\n }\n}\n\nexport interface PointsLinesTopologyMismatchDetail {\n readonly entity: number;\n readonly submesh: number;\n readonly expected: string;\n readonly actual: string;\n}\n\nexport class PointsLinesTopologyMismatchError extends Error {\n readonly code = 'points-lines-topology-mismatch' as const;\n readonly expected: string;\n readonly hint: string;\n readonly detail: PointsLinesTopologyMismatchDetail;\n\n constructor(detail: PointsLinesTopologyMismatchDetail) {\n super(`Points/Lines topology mismatch at submesh ${detail.submesh}`);\n this.name = 'PointsLinesTopologyMismatchError';\n this.expected = `submesh ${detail.submesh} topology is ${detail.expected}`;\n this.hint = `rebuild entity ${detail.entity} with ${detail.expected} geometry before retrying Points/Lines admission`;\n this.detail = detail;\n }\n}\n\nexport interface PointsLinesStyleUnsupportedDetail {\n readonly lane: string;\n readonly field: string;\n readonly member: string;\n readonly supported: readonly string[];\n}\n\nexport class PointsLinesStyleUnsupportedError extends Error {\n readonly code = 'points-lines-style-unsupported' as const;\n readonly expected: string;\n readonly hint: string;\n readonly detail: PointsLinesStyleUnsupportedDetail;\n\n constructor(detail: PointsLinesStyleUnsupportedDetail) {\n super(`unsupported Points/Lines ${detail.field} member ${detail.member}`);\n this.name = 'PointsLinesStyleUnsupportedError';\n this.expected = `${detail.field} is one of ${detail.supported.join(', ')}`;\n this.hint = `use a supported Points/Lines ${detail.field} member or wait for a later milestone`;\n this.detail = detail;\n }\n}\n\nexport interface PointsLinesMaterialUnsupportedDetail {\n readonly entity: number;\n readonly material: string;\n readonly pass: string;\n readonly module: string;\n readonly reason: string;\n}\n\nexport class PointsLinesMaterialUnsupportedError extends Error {\n readonly code = 'points-lines-material-unsupported' as const;\n readonly expected = 'one engine-owned unlit forward MaterialAsset pass';\n readonly hint: string;\n readonly detail: PointsLinesMaterialUnsupportedDetail;\n\n constructor(detail: PointsLinesMaterialUnsupportedDetail) {\n super(`Points/Lines material is unsupported on entity ${detail.entity}`);\n this.name = 'PointsLinesMaterialUnsupportedError';\n this.hint = `use Materials.unlit without a shadow-caster pass for entity ${detail.entity}`;\n this.detail = detail;\n }\n}\n\nexport interface PointsLinesBudgetExceededDetail {\n readonly lane: string;\n readonly requested: number;\n readonly limit: number;\n readonly unit: 'points' | 'segments' | 'vertices' | 'indices' | 'bytes' | 'draws';\n}\n\nexport class PointsLinesBudgetExceededError extends Error {\n readonly code = 'points-lines-budget-exceeded' as const;\n readonly expected: string;\n readonly hint: string;\n readonly detail: PointsLinesBudgetExceededDetail;\n\n constructor(detail: PointsLinesBudgetExceededDetail) {\n super(`Points/Lines ${detail.unit} budget exceeded`);\n this.name = 'PointsLinesBudgetExceededError';\n this.expected = `${detail.unit} <= ${detail.limit}`;\n this.hint = `reduce Points/Lines ${detail.unit} or split the entity into bounded equivalent batches`;\n this.detail = detail;\n }\n}\n\nexport interface PointsLinesPrepareFailedDetail {\n readonly owner: string;\n readonly generation: number;\n readonly stage: 'prepare';\n readonly cause: string;\n readonly lastKnownGood: boolean;\n}\n\nexport class PointsLinesPrepareFailedError extends Error {\n readonly code = 'points-lines-prepare-failed' as const;\n readonly expected = 'the complete Points/Lines candidate validates before publication';\n readonly hint: string;\n readonly detail: PointsLinesPrepareFailedDetail;\n\n constructor(detail: PointsLinesPrepareFailedDetail) {\n super(`Points/Lines prepare failed at generation ${detail.generation}`);\n this.name = 'PointsLinesPrepareFailedError';\n this.hint = detail.lastKnownGood\n ? 'retain the last known good candidate, repair the producer, and retry prepare'\n : 'repair the producer and retry prepare; the failed first candidate produces zero draw';\n this.detail = detail;\n }\n}\n\n// -- RenderTarget errors ------------------------------------------------------\n\nexport interface RenderTargetDescriptorInvalidDetail {\n readonly field: string;\n readonly value: unknown;\n readonly expected: string;\n}\n\nexport class RenderTargetDescriptorInvalidError extends Error {\n readonly code = 'render-target-descriptor-invalid' as const;\n readonly expected: string;\n readonly hint: string;\n readonly detail: RenderTargetDescriptorInvalidDetail;\n\n constructor(detail: RenderTargetDescriptorInvalidDetail) {\n super(`render-target-descriptor-invalid: ${detail.field} does not satisfy ${detail.expected}`);\n this.name = 'RenderTargetDescriptorInvalidError';\n this.expected = detail.expected;\n this.hint = `set RenderTargetDescriptor.${detail.field} to the expected value, then retry create or resize`;\n this.detail = detail;\n }\n}\n\nexport interface RenderTargetCapabilityMissingDetail {\n readonly operation: 'create' | 'resize' | 'source' | 'readback';\n readonly requested: string;\n readonly capability: string;\n readonly actual: string;\n}\n\nexport class RenderTargetCapabilityMissingError extends Error {\n readonly code = 'render-target-capability-missing' as const;\n readonly expected: string;\n readonly hint: string;\n readonly detail: RenderTargetCapabilityMissingDetail;\n\n constructor(detail: RenderTargetCapabilityMissingDetail) {\n super(\n `render-target-capability-missing: ${detail.capability} does not admit ${detail.requested}`,\n );\n this.name = 'RenderTargetCapabilityMissingError';\n this.expected = `${detail.capability} admits ${detail.requested}`;\n this.hint = `choose an admitted target descriptor or use a backend providing ${detail.capability}`;\n this.detail = detail;\n }\n}\n\nexport type RenderTargetStateInvalidReason =\n | 'foreign-renderer'\n | 'destroyed'\n | 'uninitialized'\n | 'generation-mismatch'\n | 'readback-without-intent';\n\nexport interface RenderTargetStateInvalidDetail {\n readonly operation: 'inspect' | 'resize' | 'source' | 'readback' | 'destroy';\n readonly reason: RenderTargetStateInvalidReason;\n readonly state: 'uninitialized' | 'candidate' | 'active' | 'rebuilding' | 'destroyed';\n readonly generation: number;\n}\n\nexport class RenderTargetStateInvalidError extends Error {\n readonly code = 'render-target-state-invalid' as const;\n readonly expected: string;\n readonly hint: string;\n readonly detail: RenderTargetStateInvalidDetail;\n\n constructor(detail: RenderTargetStateInvalidDetail) {\n super(`render-target-state-invalid: ${detail.operation} cannot use ${detail.reason}`);\n this.name = 'RenderTargetStateInvalidError';\n this.expected = `target state permits ${detail.operation}`;\n this.hint =\n 'use the Renderer that created the target, then initialize, recover, or stop using the destroyed token';\n this.detail = detail;\n }\n}\n\nexport interface RenderTargetOperationFailedDetail {\n readonly operation: 'create' | 'resize' | 'source' | 'readback' | 'destroy' | 'recover';\n readonly stage: 'allocation' | 'compile' | 'write' | 'submit' | 'copy' | 'retire';\n readonly generation: number;\n readonly cause: unknown;\n readonly recovery: 'retry' | 'recover' | 'retain-last-known-good';\n}\n\nexport class RenderTargetOperationFailedError extends Error {\n readonly code = 'render-target-operation-failed' as const;\n readonly expected: string;\n readonly hint: string;\n readonly detail: RenderTargetOperationFailedDetail;\n\n constructor(detail: RenderTargetOperationFailedDetail) {\n super(`render-target-operation-failed: ${detail.operation} failed during ${detail.stage}`);\n this.name = 'RenderTargetOperationFailedError';\n this.expected = `${detail.operation} completes ${detail.stage}`;\n this.hint =\n 'inspect detail.cause, then retry, recover the Renderer, or retain the last-known-good generation';\n this.detail = detail;\n }\n}\n\nexport interface ReflectionProbeBudgetExceededDetail {\n readonly actual: number;\n readonly budget: number;\n}\n\nexport class ReflectionProbeBudgetExceededError extends Error {\n readonly code = 'reflection-probe-budget-exceeded' as const;\n readonly expected: string;\n readonly hint: string;\n readonly detail: ReflectionProbeBudgetExceededDetail;\n\n constructor(actual: number, budget: number) {\n super(`reflection-probe-budget-exceeded: ${actual} > ${budget}`);\n this.name = 'ReflectionProbeBudgetExceededError';\n this.expected = `reflection probe work <= ${budget}`;\n this.hint = 'reduce probe updates for this frame or raise the RenderProfile probe budget';\n this.detail = { actual, budget };\n }\n}\n\nexport interface RenderIntentInvalidDetail {\n readonly component: 'CubeCamera' | 'ReflectionProbe';\n readonly field: 'updateIntent';\n readonly value: number;\n readonly allowed: readonly [0, 1, 2];\n}\n\nexport class RenderIntentInvalidError extends Error {\n readonly code = 'render-intent-invalid' as const;\n readonly expected: string;\n readonly hint: string;\n readonly detail: RenderIntentInvalidDetail;\n\n constructor(component: RenderIntentInvalidDetail['component'], value: number) {\n super(`render-intent-invalid: ${component}.updateIntent is not an admitted value`);\n this.name = 'RenderIntentInvalidError';\n this.expected = `${component}.updateIntent is one of 0, 1, or 2`;\n this.hint = `set ${component}.updateIntent to 0, 1, or 2`;\n this.detail = { component, field: 'updateIntent', value, allowed: [0, 1, 2] };\n }\n}\n\nexport interface VolumeOwnerConflictDetail {\n readonly ownerCount: number;\n}\n\nexport class VolumeOwnerConflictError extends Error {\n readonly code = 'volume-owner-conflict' as const;\n readonly expected = 'at most eight local VolumetricFog owners per rendered World';\n readonly hint = 'reduce simultaneously visible volume owners and retry extraction';\n readonly detail: VolumeOwnerConflictDetail;\n\n constructor(ownerCount: number) {\n super(`volume-owner-conflict: received ${ownerCount} owners`);\n this.name = 'VolumeOwnerConflictError';\n this.detail = { ownerCount };\n }\n}\n\nexport interface VolumeDensityShapeMismatchDetail {\n readonly guid: string;\n readonly viewDimension: string;\n}\n\nexport class VolumeDensityShapeMismatchError extends Error {\n readonly code = 'volume-density-shape-mismatch' as const;\n readonly expected = 'density is a linear 3D TextureAsset';\n readonly hint = 'bind a verified linear texture with viewDimension 3d';\n readonly detail: VolumeDensityShapeMismatchDetail;\n\n constructor(guid: string, viewDimension: string) {\n super(`volume-density-shape-mismatch: ${viewDimension} density is not 3d`);\n this.name = 'VolumeDensityShapeMismatchError';\n this.detail = { guid, viewDimension };\n }\n}\n\nexport interface VolumeInvalidBoundsDetail {\n readonly min: readonly [number, number, number];\n readonly max: readonly [number, number, number];\n}\n\nexport class VolumeInvalidBoundsError extends Error {\n readonly code = 'volume-invalid-bounds' as const;\n readonly expected = 'bounds are finite and max is greater than min on every axis';\n readonly hint = 'set finite non-degenerate volume bounds';\n readonly detail: VolumeInvalidBoundsDetail;\n\n constructor(bounds: VolumeInvalidBoundsDetail) {\n super('volume-invalid-bounds: bounds must be finite and non-degenerate');\n this.name = 'VolumeInvalidBoundsError';\n this.detail = bounds;\n }\n}\n\nexport interface VolumeInvalidParametersDetail {\n readonly field: string;\n readonly value: unknown;\n}\n\nexport class VolumeInvalidParametersError extends Error {\n readonly code = 'volume-invalid-parameters' as const;\n readonly expected = 'volume parameters remain finite and inside their closed ranges';\n readonly hint = 'repair extinction, albedo, emission, anisotropy, maxDistance, or sampling';\n readonly detail: VolumeInvalidParametersDetail;\n\n constructor(input: {\n readonly maxDistance?: number;\n readonly anisotropy?: number;\n readonly sampling?: string;\n }) {\n const invalidSampling =\n input.sampling !== undefined && input.sampling !== 'noise' && input.sampling !== 'density';\n const field = invalidSampling\n ? 'sampling'\n : input.maxDistance !== undefined && input.maxDistance <= 0\n ? 'maxDistance'\n : 'parameters';\n const value = invalidSampling\n ? input.sampling\n : field === 'maxDistance'\n ? input.maxDistance\n : input.anisotropy;\n super(`volume-invalid-parameters: ${field} is outside the authored range`);\n this.name = 'VolumeInvalidParametersError';\n this.detail = { field, value };\n }\n}\n\nexport type VolumeError =\n | VolumeOwnerConflictError\n | VolumeDensityShapeMismatchError\n | VolumeInvalidBoundsError\n | VolumeInvalidParametersError;\n\nexport interface ProjectorBindingDetail {\n readonly guid: string;\n readonly status: 'pending' | 'invalid' | 'bind-failed';\n}\n\nexport class ProjectorBindingError extends Error {\n readonly code = 'projector-binding-failed' as const;\n readonly expected = 'authored projector is accepted and bound for both surface and volume';\n readonly hint =\n 'inspect the projector Meta/Pack receipt, repair the source, and retry with the same GUID';\n readonly detail: ProjectorBindingDetail;\n\n constructor(guid: string, status: ProjectorBindingDetail['status']) {\n super(`projector binding failed for ${guid}: ${status}`);\n this.name = 'ProjectorBindingError';\n this.detail = { guid, status };\n }\n}\n\n// -- RenderErrorCode / RenderError closed unions --------------------------------\n\n/**\n * Closed union of render-cluster error codes. AI users perform exhaustive\n * `switch (err.code)` without default; TS guards completeness.\n */\nexport type RenderErrorCode = RenderError['code'];\n\n/**\n * Closed union of the render-cluster structured error classes, each carrying a\n * `RenderErrorCode` discriminant on `.code`.\n */\nexport type RenderError =\n | RenderPublicationError\n | LifecycleConstructionError\n | AutoExposureError\n | RendererExpectedOperationError\n | FrameReceiptStaleError\n | RendererContractFailureError\n | ObservationUnavailableError\n | SceneDataUnavailableError\n | TaaUnavailableError\n | ShadowInvalidConfigError\n | EquirectProjectionFailedError\n | StandardLightBudgetExceededError\n | StandardClusterIndexOverflowError\n | StandardClusterTransportUnavailableError\n | StandardProfileInvalidError\n | PointShadowAtlasUninitializedError\n | PointShadowAtlasBoundsViolationError\n | VideoUploadUnsupportedError\n | VertexStorageBufferUnavailableError\n | VertexColorVariantConflictError\n | SkinPaletteOverflowError\n | SkinMaterialMismatchError\n | MaterialSkinAttrMissingError\n | TransmissionCapabilityMissingError\n | RenderFeatureRegistrationConflictError\n | RenderFeatureStageFailedError\n | RenderFeatureCapabilityMissingError\n | RenderFeaturePassOrderConflictError\n | RenderFeaturePreparationFailedError\n | RenderFeaturePreparedStateMismatchError\n | RenderFeatureDrawRecordingFailedError\n | EnvironmentSourceConflictError\n | FogCardinalityError\n | SunCardinalityError\n | TaaCapsInsufficientError\n | EnvironmentGenerationFailedError\n | AtmosphereInvalidParameterError\n | BarrelDistortionInvalidParameterError\n | CloudLayerError\n | DynamicResolutionInvalidParameterError\n | DynamicResolutionRequiresTaaError\n | DynamicResolutionTimingUnavailableError\n | MotionBlurValidationError\n | OwnerStageFailedError\n | PointsLinesInvalidStyleError\n | PointsLinesTopologyMismatchError\n | PointsLinesStyleUnsupportedError\n | PointsLinesMaterialUnsupportedError\n | PointsLinesBudgetExceededError\n | PointsLinesPrepareFailedError\n | LightResourceUnavailableError\n | RenderTargetDescriptorInvalidError\n | RenderTargetCapabilityMissingError\n | RenderTargetStateInvalidError\n | RenderTargetOperationFailedError\n | ReflectionProbeBudgetExceededError\n | RenderIntentInvalidError\n | ProjectorBindingError\n | VolumeError;\n","import { err, ok, type Result } from '@forgeax/engine-types';\n\nexport interface MotionBlurParams {\n readonly shutterAngle: number;\n readonly maxRadiusPixels: number;\n readonly sampleCount: number;\n /** Target presentation rate used to convert frame displacement to exposure. 0 follows frame time. */\n readonly targetFps: number;\n}\n\n/** WGSL uniform size for the renderer-owned Motion Blur parameter block. */\nexport const MOTION_BLUR_PARAMS_BYTE_SIZE = 32;\n\n/** The only quality tiers the shader is allowed to execute. */\nexport type MotionBlurSampleTier = 0 | 4 | 8 | 16;\n\nexport const DEFAULT_MOTION_BLUR_PARAMS: MotionBlurParams = Object.freeze({\n shutterAngle: 180,\n maxRadiusPixels: 32,\n sampleCount: 8,\n targetFps: 60,\n});\n\nexport interface MotionBlurInvalidParamsDetail {\n readonly field: keyof MotionBlurParams;\n readonly value: unknown;\n readonly min: number;\n readonly max: number;\n readonly integer?: boolean;\n}\n\nexport class MotionBlurValidationError extends Error {\n readonly code = 'motion-blur-invalid-params' as const;\n readonly expected: string;\n readonly hint: string;\n readonly detail: MotionBlurInvalidParamsDetail;\n\n constructor(detail: MotionBlurInvalidParamsDetail) {\n const integer = detail.integer === true ? 'integer ' : '';\n const expected = `${detail.field} ${integer}in [${detail.min}, ${detail.max}]`;\n super(`motion-blur-invalid-params: ${expected}`);\n this.name = 'MotionBlurValidationError';\n this.expected = expected;\n this.hint = `set ${detail.field} to an ${integer}value in [${detail.min}, ${detail.max}]`;\n this.detail = detail;\n }\n}\n\nfunction validateField(\n field: keyof MotionBlurParams,\n value: number,\n min: number,\n max: number,\n integer = false,\n): MotionBlurValidationError | undefined {\n if (\n !Number.isFinite(value) ||\n value < min ||\n value > max ||\n (integer && !Number.isInteger(value))\n ) {\n return new MotionBlurValidationError({\n field,\n value,\n min,\n max,\n ...(integer ? { integer } : {}),\n });\n }\n return undefined;\n}\n\nexport function validateMotionBlurParams(\n input: Partial<MotionBlurParams> | undefined,\n): Result<MotionBlurParams, MotionBlurValidationError> {\n const value = input ?? {};\n const shutterAngle = value.shutterAngle ?? DEFAULT_MOTION_BLUR_PARAMS.shutterAngle;\n const maxRadiusPixels = value.maxRadiusPixels ?? DEFAULT_MOTION_BLUR_PARAMS.maxRadiusPixels;\n const sampleCount = value.sampleCount ?? DEFAULT_MOTION_BLUR_PARAMS.sampleCount;\n const targetFps = value.targetFps ?? DEFAULT_MOTION_BLUR_PARAMS.targetFps;\n const shutterError = validateField('shutterAngle', shutterAngle, 0, 360);\n if (shutterError !== undefined) return err(shutterError);\n const radiusError = validateField('maxRadiusPixels', maxRadiusPixels, 0, 64);\n if (radiusError !== undefined) return err(radiusError);\n const sampleError = validateField('sampleCount', sampleCount, 4, 16, true);\n if (sampleError !== undefined) return err(sampleError);\n const targetFpsError = validateField('targetFps', targetFps, 0, 240, true);\n if (targetFpsError !== undefined) return err(targetFpsError);\n return ok(Object.freeze({ shutterAngle, maxRadiusPixels, sampleCount, targetFps }));\n}\n\nexport function motionBlurTemporalDemand(params: MotionBlurParams | undefined): boolean {\n return params !== undefined && params.shutterAngle > 0 && params.maxRadiusPixels > 0;\n}\n\n/** Round authored work down to the bounded shader tiers without changing exposure length. */\nexport function effectiveMotionBlurSampleCount(sampleCount: number): MotionBlurSampleTier {\n if (!Number.isFinite(sampleCount) || sampleCount < 4) return 0;\n if (sampleCount < 8) return 4;\n if (sampleCount < 16) return 8;\n return 16;\n}\n\n/** Reject a frame interval that cannot represent a stable temporal pair. */\nexport function isMotionBlurIntervalValid(frameDeltaSeconds: number): boolean {\n return Number.isFinite(frameDeltaSeconds) && frameDeltaSeconds > 0 && frameDeltaSeconds <= 0.1;\n}\n\n/**\n * Convert current-to-previous frame displacement into the authored target-rate exposure.\n * Invalid intervals return zero so callers can commit a fresh baseline without blurring it.\n */\nexport function motionBlurExposureScale(frameDeltaSeconds: number, targetFps: number): number {\n if (!isMotionBlurIntervalValid(frameDeltaSeconds)) return 0;\n if (\n !Number.isFinite(targetFps) ||\n targetFps < 0 ||\n targetFps > 240 ||\n !Number.isInteger(targetFps)\n ) {\n return 0;\n }\n if (targetFps === 0) return 1;\n return 1 / (targetFps * frameDeltaSeconds);\n}\n\n/**\n * Derive a render interval from the host sample clock before ECS time policy\n * clamps it. A finite raw pair is never clamped here, so a hitch remains\n * visible to temporal admission.\n */\nexport function motionBlurSampleDelta(\n sampleTimeSeconds: number | undefined,\n previousSampleTimeSeconds: number | undefined,\n fallbackDeltaSeconds: number,\n): number {\n // An explicitly supplied non-finite sample is a temporal discontinuity. Do\n // not silently replace it with ECS delta: that would turn a corrupt host or\n // replay clock into an apparently valid blur interval.\n if (\n (sampleTimeSeconds !== undefined && !Number.isFinite(sampleTimeSeconds)) ||\n (previousSampleTimeSeconds !== undefined && !Number.isFinite(previousSampleTimeSeconds))\n ) {\n return Number.NaN;\n }\n if (Number.isFinite(sampleTimeSeconds) && Number.isFinite(previousSampleTimeSeconds)) {\n return (sampleTimeSeconds as number) - (previousSampleTimeSeconds as number);\n }\n return fallbackDeltaSeconds;\n}\n\nexport function resolveMotionBlurParams(\n input: Partial<MotionBlurParams> | undefined,\n): Result<MotionBlurParams | undefined, MotionBlurValidationError> {\n if (input === undefined) return ok(undefined);\n return validateMotionBlurParams(input);\n}\n","import { err, ok, type Result } from '@forgeax/engine-types';\nimport { LifecycleConstructionError } from '../errors/render';\nimport type { DeviceResourceKind, DeviceScopeReceipt } from './resource-types';\n\nexport {\n DEVICE_RESOURCE_KINDS,\n type DeviceResourceKind,\n type DeviceScopeReceipt,\n} from './resource-types';\n\nexport type DeviceScopeState = 'active' | 'retiring' | 'retired' | 'abandoned' | 'disposed';\n\nexport interface ResourceRef<T> {\n readonly kind: DeviceResourceKind;\n readonly owner: string;\n readonly generation: number;\n readonly value: T;\n isCurrent(scope: DeviceScope): boolean;\n isStale(scope: DeviceScope): boolean;\n}\n\nexport class DeviceResourceRef<T> implements ResourceRef<T> {\n readonly kind: DeviceResourceKind;\n readonly owner: string;\n readonly generation: number;\n readonly value: T;\n\n constructor(kind: DeviceResourceKind, owner: string, generation: number, value: T) {\n this.kind = kind;\n this.owner = owner;\n this.generation = generation;\n this.value = value;\n }\n\n isCurrent(scope: DeviceScope): boolean {\n return scope.accepts(this);\n }\n\n isStale(scope: DeviceScope): boolean {\n return !this.isCurrent(scope);\n }\n}\n\ninterface OwnedResource {\n readonly ref: DeviceResourceRef<unknown>;\n readonly cleanup: (value: unknown) => void | Promise<void>;\n}\n\nfunction idempotentCleanup<T>(\n cleanup: (value: T) => void | Promise<void>,\n): (value: T) => void | Promise<void> {\n let cleaned = false;\n return (value: T) => {\n if (cleaned) return;\n cleaned = true;\n return cleanup(value);\n };\n}\n\nexport class DeviceScope {\n readonly generation: number;\n readonly owner: string;\n readonly parent: DeviceScope | undefined;\n private lifecycleState: DeviceScopeState = 'active';\n private readonly resources = new Map<ResourceRef<unknown>, OwnedResource>();\n private readonly children: DeviceScope[] = [];\n\n private constructor(generation: number, owner: string, parent?: DeviceScope) {\n this.generation = generation;\n this.owner = owner;\n this.parent = parent;\n parent?.children.push(this);\n }\n\n static create(generation: number, owner: string): DeviceScope {\n if (!Number.isSafeInteger(generation) || generation < 0) {\n throw new RangeError('DeviceScope generation must be a non-negative safe integer.');\n }\n if (owner.length === 0) throw new TypeError('DeviceScope owner must not be empty.');\n return new DeviceScope(generation, owner);\n }\n\n get state(): DeviceScopeState {\n return this.lifecycleState;\n }\n\n get childrenSnapshot(): readonly DeviceScope[] {\n return [...this.children];\n }\n\n /** Create a renderer-owned child scope without exposing a second device owner. */\n createChild(owner: string): DeviceScope {\n if (this.lifecycleState !== 'active') {\n throw new Error('Cannot create a child DeviceScope from an inactive scope.');\n }\n if (owner.length === 0) throw new TypeError('DeviceScope child owner must not be empty.');\n return new DeviceScope(this.generation, owner, this);\n }\n\n ref<T>(kind: DeviceResourceKind, value: T): ResourceRef<T> {\n const ref = new DeviceResourceRef(kind, this.owner, this.generation, value);\n this.resources.set(ref, { ref, cleanup: () => undefined });\n return ref;\n }\n\n accepts(ref: ResourceRef<unknown>): boolean {\n return (\n this.lifecycleState === 'active' &&\n ref.owner === this.owner &&\n ref.generation === this.generation\n );\n }\n\n isAlive(): boolean {\n return this.lifecycleState === 'active';\n }\n\n resourceDelta(): number {\n return this.resources.size;\n }\n\n /** @internal */\n _adopt<T>(\n kind: DeviceResourceKind,\n value: T,\n cleanup: (value: T) => void | Promise<void>,\n ): ResourceRef<T> {\n const ref = new DeviceResourceRef(kind, this.owner, this.generation, value);\n this.resources.set(ref, {\n ref,\n cleanup: idempotentCleanup(cleanup) as (resource: unknown) => void | Promise<void>,\n });\n return ref;\n }\n\n /** @internal Remove ownership only after the resource's cleanup succeeded. */\n _release(ref: ResourceRef<unknown>): void {\n this.resources.delete(ref);\n }\n\n /** @internal */\n _clearResources(): OwnedResource[] {\n const resources = [...this.resources.values()];\n this.resources.clear();\n for (const resource of resources.reverse()) {\n try {\n const pending = resource.cleanup(resource.ref.value);\n if (pending instanceof Promise) void pending.catch(() => undefined);\n } catch {\n // Synchronous scope termination is bounded; transaction cleanup owns\n // structured failure collection during construction and replacement.\n }\n }\n return resources;\n }\n\n /** Mark an active child as retiring without releasing in-flight resources. */\n beginRetire(): void {\n if (this.lifecycleState === 'active') this.lifecycleState = 'retiring';\n }\n\n private clearChildren(): void {\n for (const child of [...this.children].reverse()) {\n child.retire();\n }\n }\n\n private detachChild(child: DeviceScope): void {\n const index = this.children.indexOf(child);\n if (index >= 0) this.children.splice(index, 1);\n }\n\n retire(): void {\n if (this.lifecycleState !== 'active' && this.lifecycleState !== 'retiring') return;\n this.lifecycleState = 'retiring';\n this.clearChildren();\n this._clearResources();\n this.lifecycleState = 'retired';\n this.parent?.detachChild(this);\n }\n\n abandon(): void {\n if (this.lifecycleState !== 'active') return;\n this.lifecycleState = 'abandoned';\n this.clearChildren();\n this._clearResources();\n this.parent?.detachChild(this);\n }\n\n dispose(): void {\n if (this.lifecycleState === 'disposed') return;\n this.lifecycleState = 'disposed';\n this.clearChildren();\n this._clearResources();\n this.parent?.detachChild(this);\n }\n\n async replace(\n generation: number,\n resources: readonly LifecycleResourceSpec<unknown>[],\n ): Promise<LifecycleResult> {\n const replacement = new DeviceScope(generation, this.owner, this);\n const transaction = new LifecycleTransaction(replacement);\n for (const resource of resources) transaction.add(resource);\n const result = await transaction.commit();\n if (!result.ok) {\n replacement.abandon();\n return result;\n }\n if (!this.isAlive()) {\n replacement.dispose();\n return transaction.failure('dispose');\n }\n // The replacement is now the new owner. Detach it before retiring the\n // old parent so parent cleanup cannot retire the just-published child.\n this.detachChild(replacement);\n this.retire();\n return ok(replacement);\n }\n\n /** @internal */\n _receipt(): DeviceScopeReceipt {\n return {\n owner: this.owner,\n generation: this.generation,\n resourceCount: this.resources.size,\n };\n }\n}\n\nexport interface LifecycleResourceSpec<T> {\n readonly kind: DeviceResourceKind;\n readonly create: () => T | Promise<T>;\n readonly cleanup: (value: T) => void | Promise<void>;\n}\n\nexport interface LifecycleCleanupFailure {\n readonly resourceKind: DeviceResourceKind;\n readonly cause: unknown;\n}\n\nexport interface LifecycleFailure {\n readonly primary: LifecycleConstructionError;\n readonly cleanupFailures: readonly LifecycleCleanupFailure[];\n readonly receipt: DeviceScopeReceipt;\n}\n\nexport type LifecycleResult = Result<DeviceScope, LifecycleFailure>;\n\nexport interface LifecycleTransactionOptions {\n readonly failureAt?: number;\n}\n\ninterface CreatedResource {\n readonly spec: LifecycleResourceSpec<unknown>;\n readonly value: unknown;\n readonly cleanup: (value: unknown) => void | Promise<void>;\n}\n\nexport class LifecycleTransaction {\n private readonly resources: LifecycleResourceSpec<unknown>[] = [];\n private readonly options: LifecycleTransactionOptions;\n private committed = false;\n\n constructor(\n private readonly scope: DeviceScope,\n options: LifecycleTransactionOptions = {},\n ) {\n this.options = options;\n }\n\n add<T>(spec: LifecycleResourceSpec<T>): this {\n if (this.committed) throw new Error('LifecycleTransaction is already committed.');\n this.resources.push(spec as LifecycleResourceSpec<unknown>);\n return this;\n }\n\n async commit(): Promise<LifecycleResult> {\n if (this.committed) return this.failure('create');\n this.committed = true;\n const created: CreatedResource[] = [];\n for (let index = 0; index < this.resources.length; index += 1) {\n const spec = this.resources[index];\n if (spec === undefined) continue;\n try {\n if (this.options.failureAt === index + 1) {\n throw new Error(`injected lifecycle failure at ${index + 1}`);\n }\n const value = await spec.create();\n if (!this.scope.isAlive()) {\n await this.cleanupOne(value, created, idempotentCleanup(spec.cleanup));\n return this.failure('dispose');\n }\n created.push({ spec, value, cleanup: idempotentCleanup(spec.cleanup) });\n } catch (cause) {\n const cleanupFailures = await this.cleanupCreated(created);\n return this.failure('create', spec.kind, cleanupFailures, cause);\n }\n }\n if (!this.scope.isAlive()) {\n const cleanupFailures = await this.cleanupCreated(created);\n return this.failure('dispose', this.resources.at(-1)?.kind ?? 'listener', cleanupFailures);\n }\n for (const item of created) this.scope._adopt(item.spec.kind, item.value, item.spec.cleanup);\n return ok(this.scope);\n }\n\n failure(\n operation: 'create' | 'dispose',\n resourceKind: DeviceResourceKind = this.resources.at(-1)?.kind ?? 'listener',\n cleanupFailures: readonly LifecycleCleanupFailure[] = [],\n cause: unknown = undefined,\n ): LifecycleResult {\n return err({\n primary: new LifecycleConstructionError({\n owner: this.scope.owner,\n generation: this.scope.generation,\n operation,\n resourceKind,\n cause,\n cleanupFailures,\n receipt: this.scope._receipt(),\n }),\n cleanupFailures,\n receipt: this.scope._receipt(),\n });\n }\n\n private async cleanupCreated(\n created: readonly CreatedResource[],\n ): Promise<LifecycleCleanupFailure[]> {\n const failures: LifecycleCleanupFailure[] = [];\n for (let index = created.length - 1; index >= 0; index -= 1) {\n const item = created[index];\n if (item === undefined) continue;\n try {\n await item.cleanup(item.value);\n } catch (cause) {\n failures.push({ resourceKind: item.spec.kind, cause });\n }\n }\n return failures;\n }\n\n private async cleanupOne(\n value: unknown,\n created: readonly CreatedResource[],\n cleanup: (value: unknown) => void | Promise<void>,\n ): Promise<void> {\n await this.cleanupCreated(created);\n try {\n await cleanup(value);\n } catch {\n // The terminal dispose result is intentionally bounded; prior cleanup\n // evidence remains in the transaction failure shape.\n }\n }\n}\n","// @forgeax/engine-runtime - render package texture usage values.\n//\n// Keep the WebGPU bit values in one dependency-free owner because render\n// package descriptor and graph builders also run against null and WebGL2-\n// compatible RHI shims where the browser's GPUTextureUsage global is absent.\n\nexport const GPU_TEXTURE_USAGE_COPY_SRC = 0x01;\nexport const GPU_TEXTURE_USAGE_COPY_DST = 0x02;\nexport const GPU_TEXTURE_USAGE_TEXTURE_BINDING = 0x04;\nexport const GPU_TEXTURE_USAGE_STORAGE_BINDING = 0x08;\nexport const GPU_TEXTURE_USAGE_RENDER_ATTACHMENT = 0x10;\nexport const GPU_TEXTURE_USAGE_RENDER_ATTACHMENT_AND_TEXTURE_BINDING =\n GPU_TEXTURE_USAGE_RENDER_ATTACHMENT | GPU_TEXTURE_USAGE_TEXTURE_BINDING;\n","// @forgeax/engine-runtime - render package GPU buffer usage values.\n//\n// Keep the WebGPU bit values in one dependency-free owner because the render\n// package also runs against the null and WebGL2-compatible RHI shims where the\n// browser's GPUBufferUsage global is unavailable.\n\nexport const GPU_BUFFER_USAGE_VERTEX = 0x20;\nexport const GPU_BUFFER_USAGE_INDEX = 0x10;\nexport const GPU_BUFFER_USAGE_COPY_DST = 0x08;\nexport const GPU_BUFFER_USAGE_COPY_SRC = 0x04;\nexport const GPU_BUFFER_USAGE_UNIFORM = 0x40;\nexport const GPU_BUFFER_USAGE_STORAGE = 0x80;\nexport const GPU_BUFFER_USAGE_INDIRECT = 0x100;\nexport const GPU_BUFFER_USAGE_MAP_READ = 0x01;\nexport const GPU_BUFFER_USAGE_QUERY_RESOLVE = 0x200;\n","import type { Buffer, Result, RhiDevice, Sampler, Texture } from '@forgeax/engine-rhi';\nimport { RhiError } from '@forgeax/engine-rhi';\nimport { err, ok } from '@forgeax/engine-types';\nimport type { DeviceScope } from '../../device/device-scope';\nimport { LifecycleTransaction } from '../../device/lifecycle-transaction';\nimport {\n GPU_TEXTURE_USAGE_COPY_DST,\n GPU_TEXTURE_USAGE_TEXTURE_BINDING,\n} from '../../gpu-texture-usage';\nimport { GPU_BUFFER_USAGE_COPY_DST, GPU_BUFFER_USAGE_UNIFORM } from '../../gpu-usage';\n\nexport const EXTENDED_LIGHTING_TOPOLOGY = 'extendedLighting' as const;\nexport const IES_SLICE_CAPACITY = 32;\nexport const COOKIE_SLICE_CAPACITY = 32;\nexport const PROBE_RECORD_CAPACITY = 64;\nexport const IES_SLICE_WIDTH = 256;\nexport const IES_SLICE_HEIGHT = 128;\nexport const COOKIE_SLICE_SIZE = 256;\nexport const COOKIE_MATRIX_BYTES = 32 * 16 * Float32Array.BYTES_PER_ELEMENT;\n/**\n * Minimum per-stage sampled-texture limit for the shared PBR + extended-\n * lighting pipeline-layout topology. The current BGL closure reserves 19\n * sampled textures for the URP path and 21 for the HDRP/Probe path after the\n * material IBL and transmission injections; WebGPU validates this pipeline-\n * layout count even when a compiled shader variant does not read every\n * optional entry.\n */\nexport const EXTENDED_LIGHTING_REQUIRED_SAMPLED_TEXTURES = 21;\n\n/**\n * Keep shader-variant selection and resource admission on one capability fact.\n * An omitted limit is treated as unavailable: a caller must not claim the\n * extended topology without a numeric device limit proving it fits.\n */\nexport function extendedLightingSampledTextureCapacityAvailable(\n maxSampledTexturesPerShaderStage: number | undefined,\n): boolean {\n return (\n maxSampledTexturesPerShaderStage !== undefined &&\n maxSampledTexturesPerShaderStage >= EXTENDED_LIGHTING_REQUIRED_SAMPLED_TEXTURES\n );\n}\n\nexport interface ExtendedLightingCapabilityResult {\n readonly admitted: boolean;\n readonly topology: typeof EXTENDED_LIGHTING_TOPOLOGY;\n readonly reason: string | undefined;\n}\n\nexport interface ExtendedLightingResourceInput {\n readonly device: RhiDevice | undefined;\n readonly scope: DeviceScope;\n readonly iesSliceCount: number;\n readonly cookieSliceCount: number;\n readonly cookieMatrices: number;\n readonly iesData?: Uint8Array | undefined;\n readonly cookieData?: Uint8Array | undefined;\n readonly cookieMatrixData?: Float32Array | undefined;\n}\n\nexport interface ExtendedLightingResourceCandidate {\n readonly topology: typeof EXTENDED_LIGHTING_TOPOLOGY;\n readonly generation: number;\n readonly scope: DeviceScope;\n readonly iesSliceCount: number;\n readonly cookieSliceCount: number;\n readonly cookieMatrices: number;\n readonly sampler: Sampler;\n readonly iesTexture: Texture | undefined;\n readonly cookieTexture: Texture | undefined;\n readonly cookieMatrixBuffer: Buffer | undefined;\n readonly descriptorBytes: number;\n readonly uploadCount: number;\n}\n\nexport interface ExtendedLightingResourceInspection {\n readonly topology: typeof EXTENDED_LIGHTING_TOPOLOGY;\n readonly generation: number;\n readonly status: 'empty' | 'candidate' | 'accepted';\n readonly accepted: boolean;\n readonly resourceCount: number;\n readonly descriptorBytes: number;\n readonly uploadCount: number;\n readonly blendInvalidations: number;\n readonly passCount: number;\n}\n\nfunction failure(expected: string, actual: string): Result<never, RhiError> {\n return err(\n new RhiError({\n code: 'webgpu-runtime-error',\n expected,\n hint: 'repair the extended lighting resource facts and retry the candidate generation',\n detail: { error: { code: 'extended-lighting-resource', message: actual } },\n }),\n );\n}\n\nfunction validCount(value: number, capacity: number): boolean {\n return Number.isSafeInteger(value) && value >= 0 && value <= capacity;\n}\n\n/** Derive admission from the RHI facts; no backend-kind policy is involved. */\nexport function deriveExtendedLightingCapability(\n device: Pick<RhiDevice, 'caps' | 'limits'>,\n): ExtendedLightingCapabilityResult {\n const maxSampledTextures = device.limits.maxSampledTexturesPerShaderStage;\n if (!extendedLightingSampledTextureCapacityAvailable(maxSampledTextures)) {\n return {\n admitted: false,\n topology: EXTENDED_LIGHTING_TOPOLOGY,\n reason: `maxSampledTexturesPerShaderStage ${maxSampledTextures ?? 0} < ${EXTENDED_LIGHTING_REQUIRED_SAMPLED_TEXTURES}`,\n };\n }\n const maxLayers = device.limits.maxTextureArrayLayers ?? 0;\n const maxUniformBuffers = device.limits.maxUniformBuffersPerShaderStage ?? 0;\n if (maxLayers < IES_SLICE_CAPACITY) {\n return {\n admitted: false,\n topology: EXTENDED_LIGHTING_TOPOLOGY,\n reason: `maxTextureArrayLayers ${maxLayers} < ${IES_SLICE_CAPACITY}`,\n };\n }\n if (maxUniformBuffers < 1) {\n return {\n admitted: false,\n topology: EXTENDED_LIGHTING_TOPOLOGY,\n reason: `maxUniformBuffersPerShaderStage ${maxUniformBuffers} < 1`,\n };\n }\n if (\n !device.caps.storageBuffer ||\n !device.caps.rgba16floatRenderable ||\n !device.caps.samplerAliasing\n ) {\n return {\n admitted: false,\n topology: EXTENDED_LIGHTING_TOPOLOGY,\n reason: 'required storage-buffer, rgba16float, or sampler capability is unavailable',\n };\n }\n return { admitted: true, topology: EXTENDED_LIGHTING_TOPOLOGY, reason: undefined };\n}\n\nfunction createTexture(\n device: RhiDevice,\n label: string,\n format: 'r16float' | 'rgba8unorm',\n width: number,\n height: number,\n layers: number,\n): Result<Texture, RhiError> {\n return device.createTexture({\n label,\n size: { width, height, depthOrArrayLayers: layers },\n mipLevelCount: 1,\n sampleCount: 1,\n dimension: '2d',\n format,\n usage: GPU_TEXTURE_USAGE_COPY_DST | GPU_TEXTURE_USAGE_TEXTURE_BINDING,\n viewFormats: [],\n textureBindingViewDimension: undefined,\n });\n}\n\nfunction requireResource<T>(result: Result<T, RhiError>): T {\n if (!result.ok) throw result.error;\n return result.value;\n}\n\nfunction writeTextureSlices(\n device: RhiDevice,\n texture: Texture,\n data: Uint8Array | undefined,\n bytesPerRow: number,\n height: number,\n layerCount: number,\n width: number,\n): number {\n if (data === undefined || layerCount === 0) return 0;\n const bytesPerSlice = bytesPerRow * height;\n const requiredBytes = bytesPerSlice * layerCount;\n if (data.byteLength < requiredBytes) {\n throw new Error(`extended lighting texture upload requires ${requiredBytes} bytes`);\n }\n for (let layer = 0; layer < layerCount; layer += 1) {\n const start = layer * bytesPerSlice;\n requireResource(\n device.queue.writeTexture(\n { texture, mipLevel: 0, origin: { x: 0, y: 0, z: layer } },\n data.subarray(start, start + bytesPerSlice),\n { offset: 0, bytesPerRow, rowsPerImage: height },\n { width, height, depthOrArrayLayers: 1 },\n ),\n );\n }\n return layerCount;\n}\n\n/** Build a complete candidate; nothing is adopted until the transaction commits. */\nexport async function createExtendedLightingResourceCandidate(\n input: ExtendedLightingResourceInput,\n): Promise<Result<ExtendedLightingResourceCandidate, RhiError>> {\n const { device, scope } = input;\n if (device === undefined) return failure('a live RHI device is required', 'device is undefined');\n if (!validCount(input.iesSliceCount, IES_SLICE_CAPACITY)) {\n return failure(`IES slice count <= ${IES_SLICE_CAPACITY}`, String(input.iesSliceCount));\n }\n if (!validCount(input.cookieSliceCount, COOKIE_SLICE_CAPACITY)) {\n return failure(\n `Cookie slice count <= ${COOKIE_SLICE_CAPACITY}`,\n String(input.cookieSliceCount),\n );\n }\n if (!validCount(input.cookieMatrices, COOKIE_SLICE_CAPACITY)) {\n return failure(`Cookie matrix count <= ${COOKIE_SLICE_CAPACITY}`, String(input.cookieMatrices));\n }\n const capability = deriveExtendedLightingCapability(device);\n if (!capability.admitted)\n return failure('extendedLighting capability admission', capability.reason ?? 'unavailable');\n if (\n input.cookieMatrixData !== undefined &&\n input.cookieMatrixData.byteLength < input.cookieMatrices * 16 * Float32Array.BYTES_PER_ELEMENT\n ) {\n return failure(\n 'cookie matrix upload payload',\n `requires ${input.cookieMatrices * 16 * Float32Array.BYTES_PER_ELEMENT} bytes`,\n );\n }\n\n const transaction = new LifecycleTransaction(scope);\n let iesTexture: Texture | undefined;\n let cookieTexture: Texture | undefined;\n let cookieMatrixBuffer: Buffer | undefined;\n let sampler: Sampler | undefined;\n let uploadCount = 0;\n transaction.add({\n kind: 'texture',\n create: () => {\n const created = requireResource(\n createTexture(\n device,\n 'extended-lighting-ies',\n 'r16float',\n IES_SLICE_WIDTH,\n IES_SLICE_HEIGHT,\n IES_SLICE_CAPACITY,\n ),\n );\n uploadCount += writeTextureSlices(\n device,\n created,\n input.iesData,\n IES_SLICE_WIDTH * 2,\n IES_SLICE_HEIGHT,\n input.iesSliceCount,\n IES_SLICE_WIDTH,\n );\n iesTexture = created;\n return created;\n },\n cleanup: (value) => {\n const destroyed = device.destroyTexture(value);\n if (!destroyed.ok) throw destroyed.error;\n },\n });\n transaction.add({\n kind: 'texture',\n create: () => {\n const created = requireResource(\n createTexture(\n device,\n 'extended-lighting-cookie',\n 'rgba8unorm',\n COOKIE_SLICE_SIZE,\n COOKIE_SLICE_SIZE,\n COOKIE_SLICE_CAPACITY,\n ),\n );\n uploadCount += writeTextureSlices(\n device,\n created,\n input.cookieData,\n COOKIE_SLICE_SIZE * 4,\n COOKIE_SLICE_SIZE,\n input.cookieSliceCount,\n COOKIE_SLICE_SIZE,\n );\n cookieTexture = created;\n return created;\n },\n cleanup: (value) => {\n const destroyed = device.destroyTexture(value);\n if (!destroyed.ok) throw destroyed.error;\n },\n });\n transaction.add({\n kind: 'buffer',\n create: () => {\n const created = requireResource(\n device.createBuffer({\n label: 'extended-lighting-cookie-matrices',\n size: COOKIE_MATRIX_BYTES,\n usage: GPU_BUFFER_USAGE_COPY_DST | GPU_BUFFER_USAGE_UNIFORM,\n mappedAtCreation: false,\n }),\n );\n if (input.cookieMatrixData !== undefined && input.cookieMatrices > 0) {\n requireResource(device.queue.writeBuffer(created, 0, input.cookieMatrixData));\n uploadCount += 1;\n }\n cookieMatrixBuffer = created;\n return created;\n },\n cleanup: (value) => {\n const destroyed = device.destroyBuffer(value);\n if (!destroyed.ok) throw destroyed.error;\n },\n });\n transaction.add({\n // Samplers are bindable GPU resources, not host listeners. Keeping the\n // lifecycle kind aligned with the resource's actual renderer role makes\n // scope inspection and rollback receipts truthful.\n kind: 'binding',\n create: () => {\n const created = requireResource(\n device.createSampler({\n label: 'extended-lighting-clamp-linear',\n addressModeU: 'clamp-to-edge',\n addressModeV: 'clamp-to-edge',\n addressModeW: 'clamp-to-edge',\n magFilter: 'linear',\n minFilter: 'linear',\n mipmapFilter: 'nearest',\n }),\n );\n sampler = created;\n return created;\n },\n cleanup: () => undefined,\n });\n const committed = await transaction.commit();\n if (!committed.ok)\n return failure(committed.error.primary.expected, committed.error.primary.message);\n if (\n iesTexture === undefined ||\n cookieTexture === undefined ||\n cookieMatrixBuffer === undefined ||\n sampler === undefined\n ) {\n return failure(\n 'complete extendedLighting candidate resources',\n 'resource transaction returned an incomplete set',\n );\n }\n return ok({\n topology: EXTENDED_LIGHTING_TOPOLOGY,\n generation: scope.generation,\n scope,\n iesSliceCount: input.iesSliceCount,\n cookieSliceCount: input.cookieSliceCount,\n cookieMatrices: input.cookieMatrices,\n sampler,\n iesTexture,\n cookieTexture,\n cookieMatrixBuffer,\n descriptorBytes:\n IES_SLICE_WIDTH * IES_SLICE_HEIGHT * 2 * IES_SLICE_CAPACITY +\n COOKIE_SLICE_SIZE * COOKIE_SLICE_SIZE * 4 * COOKIE_SLICE_CAPACITY +\n COOKIE_MATRIX_BYTES,\n uploadCount,\n });\n}\n\nexport function inspectExtendedLightingResources(\n scope: DeviceScope,\n): ExtendedLightingResourceInspection {\n return {\n topology: EXTENDED_LIGHTING_TOPOLOGY,\n generation: scope.generation,\n status: 'empty',\n accepted: false,\n resourceCount: 0,\n descriptorBytes: 0,\n uploadCount: 0,\n blendInvalidations: 0,\n passCount: 0,\n };\n}\n","// @forgeax/engine-runtime - ShadowAtlas (cube_array depth atlas for point-light shadows).\n//\n// feat-20260612-point-light-shadows-urp-hdrp M3 / T-M3-1 (plan-strategy §D-1).\n//\n// Lazy-allocated `texture_depth_cube_array` (depth32float) + per-face 2D\n// TextureView cache. One layer per admitted shadow-casting PointLight; the\n// renderer owns the bounded atlas admission policy. Total texel footprint at\n// the 512x512 default = 4 layers x 6 faces x 512 x 512 x 4 B = 24 MiB.\n//\n// Why a separate module (vs inlining into createRenderer / pipelineState):\n// - zero-shadow scene path stays allocation-free (AC-09): we never call\n// `device.createTexture` on the cube_array unless `ensure(...)` is invoked\n// from the extract / record path on a frame that has at least one\n// PointLightShadow snapshot.\n// - face-view cache is keyed (layer, face) and built lazily during the\n// per-light shadow caster pass; the cache is invalidated together with the\n// atlas when `dispose()` runs (renderer teardown or layers re-allocation).\n// - the helper descriptors live in `@forgeax/engine-rhi`\n// (`cubeArrayDepthDescriptor` / `cubeArrayDepthFaceView` /\n// `comparisonSamplerDescriptor`) per T-M0-3; this file is the runtime-side\n// owner of the GPU resources they describe.\n//\n// Lifecycle:\n// 1. `new ShadowAtlas(device, { faceSize, layers })` — construct the\n// manager; no GPU work yet.\n// 2. `atlas.ensure()` — first call allocates the cube_array texture +\n// cube_array sampling view + comparison sampler (idempotent thereafter).\n// 3. `atlas.faceView(layer, face)` — lazy 2D depth view used as a render-\n// pass attachment for the corresponding cube face. Cached per (layer,\n// face).\n// 4. `atlas.dispose()` — releases the GPU resources and clears caches.\n// `ensure()` after `dispose()` re-allocates from scratch.\n\nimport {\n comparisonSamplerDescriptor,\n cubeArrayDepthDescriptor,\n cubeArrayDepthFaceView,\n type RhiDevice,\n type Sampler,\n type Texture,\n type TextureView,\n} from '@forgeax/engine-rhi';\n\nimport {\n PointShadowAtlasBoundsViolationError,\n PointShadowAtlasUninitializedError,\n} from './errors/render';\nimport { GPU_TEXTURE_USAGE_RENDER_ATTACHMENT_AND_TEXTURE_BINDING } from './gpu-texture-usage';\n\n/**\n * Construction options for {@link ShadowAtlas}.\n */\nexport interface ShadowAtlasOptions {\n /** Per-face square size in pixels. Default 512 (PointLightShadow.mapSize default). */\n readonly faceSize?: number;\n /** Number of cube layers. Default is the renderer atlas admission capacity. */\n readonly layers?: number;\n}\n\n/** Default per-face square size in pixels. Mirrors PointLightShadow.mapSize default. */\nexport const SHADOW_ATLAS_DEFAULT_FACE_SIZE = 512;\n/** Default cube layer count. Renderer-owned point-shadow admission capacity. */\nexport const SHADOW_ATLAS_DEFAULT_LAYERS = 4;\n\n/**\n * Cube-array depth atlas for point-light shadows.\n *\n * Shape: `texture_depth_cube_array` (depth32float) with `layers` and per-\n * face size `faceSize x faceSize`. The cube_array sampling view feeds\n * `@group(0) @binding(5)` in URP shaders; the per-face 2D view feeds the\n * shadow-caster render pass attachment for one (layer, face) at a time\n * (WebGPU forbids cube views as render-pass attachments).\n *\n * Construction performs no GPU work. The first `ensure()` call allocates the\n * texture + view + sampler. `dispose()` releases everything; later `ensure()`\n * calls re-allocate.\n *\n * @example Lazy allocation in the extract / record path:\n * ```\n * if (lights.pointShadow.length > 0) {\n * atlas.ensure();\n * for (const ps of lights.pointShadow) {\n * for (let face = 0; face < 6; face++) {\n * const view = atlas.faceView(ps.shadowAtlasLayer, face);\n * // ... begin shadow caster pass with `view` as the depth attachment\n * }\n * }\n * }\n * ```\n */\nexport class ShadowAtlas {\n /** Backing cube_array depth texture. `null` until `ensure()` has run. */\n private texture: Texture | null = null;\n /**\n * Whole-atlas cube_array sampling view used by URP shaders that bind the\n * atlas at `@group(0) @binding(5)`. `null` until `ensure()` has run.\n */\n private cubeArrayView: TextureView | null = null;\n /** Comparison sampler for `texture_depth_cube_array`. */\n private compareSampler: Sampler | null = null;\n /** Per-face 2D depth view cache, keyed by `layer * 6 + face`. */\n private readonly faceViews = new Map<number, TextureView>();\n /** Per-face label cache (debug aid). Reused on re-creation. */\n private readonly device: RhiDevice;\n /** Per-face square size in pixels. */\n readonly faceSize: number;\n /** Cube layer count. */\n readonly layers: number;\n\n constructor(device: RhiDevice, options: ShadowAtlasOptions = {}) {\n this.device = device;\n this.faceSize = options.faceSize ?? SHADOW_ATLAS_DEFAULT_FACE_SIZE;\n this.layers = options.layers ?? SHADOW_ATLAS_DEFAULT_LAYERS;\n }\n\n /**\n * Returns `true` once the atlas texture is allocated. Used by the extract /\n * record path to gate \"no PointLightShadow → no allocation\" (AC-09) — the\n * caller calls {@link ensure} on a frame that has at least one snapshot;\n * before that, `isAllocated()` stays `false` and tests can assert no GPU\n * resources were created.\n */\n isAllocated(): boolean {\n return this.texture !== null;\n }\n\n /**\n * Lazy-allocate the atlas texture + cube_array sampling view + comparison\n * sampler. Idempotent: subsequent calls are zero-cost no-ops once the\n * resources exist.\n *\n * Throws (via the RHI error registry) on allocation failure. This is the\n * only path that touches the GPU — keeping it inside one method makes the\n * \"zero-shadow scene = zero allocation\" gate easy to enforce: the renderer\n * never calls this method on a frame with no PointLightShadow entities.\n */\n ensure(): void {\n if (this.texture !== null) return;\n const usage = GPU_TEXTURE_USAGE_RENDER_ATTACHMENT_AND_TEXTURE_BINDING;\n const texDesc = cubeArrayDepthDescriptor(this.faceSize, this.layers, usage);\n const texRes = this.device.createTexture(texDesc);\n if (!texRes.ok) throw texRes.error;\n this.texture = texRes.value;\n\n const viewRes = this.device.createTextureView(this.texture, {\n label: 'shadow-atlas-cube-array-view',\n dimension: 'cube-array',\n aspect: 'depth-only',\n baseArrayLayer: 0,\n arrayLayerCount: 6 * this.layers,\n baseMipLevel: 0,\n mipLevelCount: 1,\n });\n if (!viewRes.ok) {\n this.device.destroyTexture(this.texture);\n this.texture = null;\n throw viewRes.error;\n }\n this.cubeArrayView = viewRes.value;\n\n const sampRes = this.device.createSampler(comparisonSamplerDescriptor());\n if (!sampRes.ok) {\n this.device.destroyTexture(this.texture);\n this.texture = null;\n this.cubeArrayView = null;\n throw sampRes.error;\n }\n this.compareSampler = sampRes.value;\n }\n\n /**\n * Whole-atlas cube_array sampling view (`texture_depth_cube_array`). Returns\n * `null` if the atlas is not yet allocated; the caller should gate on a\n * non-null pointShadow array before calling {@link ensure} + this getter.\n */\n getAtlasView(): TextureView | null {\n return this.cubeArrayView;\n }\n\n /**\n * Comparison sampler (`compare: 'less'`) for cube_array depth sampling.\n * Returns `null` if the atlas is not yet allocated.\n */\n getComparisonSampler(): Sampler | null {\n return this.compareSampler;\n }\n\n /**\n * Backing texture handle. Returns `null` if the atlas is not yet allocated.\n */\n getTexture(): Texture | null {\n return this.texture;\n }\n\n /**\n * Lazy 2D depth view selecting `(layer, face)` (the caller passes\n * `shadowAtlasLayer` from the snapshot and a face index 0..5). Used as the\n * depth attachment of the shadow-caster render pass for one cube face.\n *\n * Caches per `(layer, face)` so the per-frame shadow loop pays zero\n * `createTextureView` cost after the first allocation. Cache is cleared on\n * {@link dispose}.\n *\n * @throws PointShadowAtlasUninitializedError if the atlas is not yet\n * allocated (caller must call {@link ensure} first).\n * @throws PointShadowAtlasBoundsViolationError if `layer` or `face` is out\n * of range.\n * @throws RhiError if the underlying `createTextureView` fails.\n */\n faceView(layer: number, face: number): TextureView {\n if (this.texture === null) {\n throw new PointShadowAtlasUninitializedError();\n }\n if (layer < 0 || layer >= this.layers) {\n throw new PointShadowAtlasBoundsViolationError('layer', layer, this.layers);\n }\n if (face < 0 || face >= 6) {\n throw new PointShadowAtlasBoundsViolationError('face', face, 6);\n }\n const key = layer * 6 + face;\n const cached = this.faceViews.get(key);\n if (cached !== undefined) return cached;\n const desc = cubeArrayDepthFaceView(layer, face);\n const r = this.device.createTextureView(this.texture, desc);\n if (!r.ok) throw r.error;\n this.faceViews.set(key, r.value);\n return r.value;\n }\n\n /**\n * Release the GPU resources and clear the per-face view cache. Idempotent;\n * subsequent calls are zero-cost. After dispose, `isAllocated()` returns\n * `false` and the next `ensure()` re-allocates from scratch.\n */\n dispose(): void {\n this.faceViews.clear();\n if (this.texture !== null) {\n this.device.destroyTexture(this.texture);\n this.texture = null;\n }\n this.cubeArrayView = null;\n this.compareSampler = null;\n }\n}\n","import type { RenderResourceScope } from '../publication/resource-scope';\n// @forgeax/engine-runtime - RenderSystem record stage: frame-snapshot.\n// Extracted from render-system-record.ts (feat-20260704 M3/w17, pure move).\n\nimport type { RenderReadVersion } from '@forgeax/engine-ecs/projection';\nimport { vec3 } from '@forgeax/engine-math';\nimport type {\n CompiledRenderGraphInfo,\n ResolvedColorTargetDescriptor,\n} from '@forgeax/engine-render-graph';\nimport type {\n BindGroup,\n BindGroupLayout,\n Buffer,\n RhiDevice,\n Texture,\n TextureView,\n} from '@forgeax/engine-rhi';\nimport type { MaterialShaderArtifact } from '@forgeax/engine-shader';\nimport type { BarrelDistortionMapping } from '../barrel-distortion';\nimport type { ClusterBinScratch } from '../cluster-binner';\nimport type { DirectionalShadowQuality } from '../components/directional-shadow-filter';\nimport type { EnvironmentGeneration } from '../environment/generation';\nimport type { EnvironmentLifecycle } from '../environment/lifecycle';\nimport type { DepthOfFieldParams } from '../features/depth-of-field/depth-of-field-params';\nimport type { GpuBuffer } from '../gpu-resource';\nimport type { MotionBlurExecutionReceipt } from '../inspection-types';\nimport type { InstanceProjectionStore } from '../instances';\nimport type { IblBindingInspection } from '../mesh-material-bindings';\nimport type { StandardLightingInspection } from '../pipeline/standard-lighting/inspection';\nimport type { AutoExposureGpuResources } from '../pipeline/standard-output/auto-exposure/gpu';\nimport type { AutoExposureState } from '../pipeline/standard-output/auto-exposure/state';\nimport type { StandardLutGpuResources } from '../pipeline/standard-output/lut-gpu';\nimport type { StandardLutCandidate, StandardLutState } from '../pipeline/standard-output/lut-state';\nimport type { PointShadowInspection } from '../point-shadow-inspection';\nimport type { SsrSpatialAdmission } from '../ssr/admission';\nimport type { SsrHistoryCandidate, SsrHistoryOwner } from '../ssr/history';\nimport type { TemporalGpuState } from '../temporal/gpu';\nimport type { TemporalView } from '../temporal/view';\n\nexport type TemporalCommitOutcome =\n | { readonly kind: 'none' }\n | { readonly kind: 'off'; readonly view: TemporalView }\n | { readonly kind: 'taa'; readonly view: TemporalView };\n\n/** CPU transaction metadata staged beside the renderer-owned GPU candidate. */\nexport interface PendingAutoExposureState {\n readonly state: AutoExposureState;\n readonly generation: number;\n readonly deviceEpoch: number;\n readonly frameId: number;\n}\n\n/** CPU POD staged beside the renderer-owned LUT resources until submit. */\nexport interface PendingStandardLutState {\n readonly state: StandardLutState;\n readonly candidate?: StandardLutCandidate;\n readonly remove: boolean;\n readonly targetGeneration: number;\n readonly deviceEpoch: number;\n}\n\n/**\n * feat-20260708-composited-multi-world-rendering M1 / D-1 / D-9:\n * worldId-entityKey composite key helper. Formula: `worldId * 2^32 + entityKey`.\n *\n * worldId is the index into `worlds[]` (the `draw` call argument). entityKey\n * is the packed Entity u32 (encodeEntity(indexSlot, generation)) surfaced\n * through `RenderableSnapshot.entityKey`.\n *\n * Key properties:\n * - worldId=0 identity: `worldEntityKey(0, k) === k` — single-world path\n * cache behavior is bit-for-bit unchanged (AC-03 regression guarantee).\n * - JS safe integer: worldId < 2^21 keeps the composite key below\n * Number.MAX_SAFE_INTEGER (2^53).\n * - SSOT: all cache-key compositing consumers import this single helper;\n * no inline `worldId * 2^32 + k` duplication (D-9).\n *\n * @internal — exported for unit test + glyph/tilemap/record consumers;\n * not part of the public @forgeax/engine-runtime API surface.\n */\nexport function worldEntityKey(worldId: number, entityKey: number): number {\n return worldId * 4294967296 + entityKey; // 2^32 = 4294967296\n}\n\n/**\n * Cache identity for a renderer-owned instance collection.\n *\n * A collection can be rebound from one entity to another while retaining the\n * same count, revision, and extraction archetype. The collection id is the\n * owner identity in that case; the entity cache key is only the compatibility\n * fallback for legacy snapshots that predate the collection field.\n */\nexport function instanceCollectionCacheKey(\n worldId: number,\n instance: { readonly cacheKey: number; readonly collectionId?: number },\n): number {\n // Keep collection entries in a disjoint numeric namespace from the shared\n // legacy sprite/fold cache. Fold keys occupy -1..-(2^32), while ordinary\n // world/entity keys are non-negative; this range starts below both.\n return -(0x1_0000_0000 + worldEntityKey(worldId, instance.collectionId ?? instance.cacheKey));\n}\n\n/**\n * Cross-frame cache entry for a material bind group whose source material and\n * all resolved GPU resources are stable. The material snapshot identity is\n * the extract-layer invalidation token; the builder only stores entries after\n * all explicit resource handles resolved to resident GPU objects.\n */\nexport interface MaterialBgAssemblyCacheEntry {\n readonly material: MaterialSnapshot;\n /** Invalidates when a texture/sampler residency identity changes. */\n readonly materialResourceEpoch: number;\n readonly materialBgl: BindGroupLayout;\n /** Buffer identity changes when the shared material capacity grows. */\n readonly materialBuffer: Buffer;\n readonly sceneMaterialBuffer?: Buffer;\n readonly skylightResources: SkylightBindGroupResources;\n readonly bindGroup: BindGroup;\n}\n\nimport type { CompiledRenderGraph } from '@forgeax/engine-render-graph';\nimport type { MaterialRenderState, RenderPipelineAsset } from '@forgeax/engine-types';\nimport type { MeshGpuHandles } from '../device/gpu-residency';\nimport type { SkylightBindGroupResources } from '../ibl/skylight-bind-group';\nimport type { InstanceBufferCacheEntry } from '../instance-buffer-cache';\nimport type { CameraSnapshot, VolumetricFogFrameContext } from '../render-contract';\nimport type { RenderPipeline as RenderPipelineDef, RenderPipelineFrame } from '../render-pipeline';\nimport type {\n DispatchEntry,\n MaterialSnapshot,\n PointShadowSnapshot,\n RenderableSnapshot,\n SpotLightSnapshot,\n} from '../render-system-extract';\nimport type { ProbeBlendRecord } from '../scene/probe-blend-record';\nimport type { ShadowAtlas } from '../shadow-atlas';\nimport type {\n TemporalFrame,\n TemporalFrameInput,\n TemporalFrameTransaction,\n} from '../temporal/frame';\nimport type { VolumetricFogInspection } from '../volume/inspection';\nimport type { VolumeTemporalSignature } from '../volume/temporal';\n\n/** Retained probe record bytes carried with one extracted render frame. */\nexport interface ProbeBlendFrameSnapshot {\n readonly records: readonly ProbeBlendRecord[];\n readonly recordByteLength: 160;\n}\n\n/** Renderer-owned GPU cache entry for one object's 160B probe record. */\nexport interface ProbeBlendBufferCacheEntry {\n readonly generation: number;\n readonly bytes: Uint8Array;\n}\n\n/**\n * feat-20260608-create-app-param-surface-trim / M1 / D-8 (q8 user lock):\n * fallback clear color when the world carries no Camera entity. Opaque\n * black `[0, 0, 0, 1]`, replacing the historical\n * `[0.06, 0.06, 0.08, 1.0]` dark-slate sentinel. Single SSOT consumed by\n * the synthetic CameraSnapshot built when `cameras.length === 0`\n * (Case B in `recordFrame`) and read directly by tests\n * (`zero-camera-clear-fallback.test.ts`). AC-05.\n */\nexport const ZERO_CAMERA_CLEAR_FALLBACK: readonly [number, number, number, number] = [0, 0, 0, 1];\n\nexport interface FrameObservationSource {\n readonly texture: Texture;\n readonly descriptor: ResolvedColorTargetDescriptor;\n readonly frameId: number;\n readonly pipelineId: 'forgeax::standard';\n readonly backendId: string;\n}\n\n/** Internal test/diagnostic view of one compiled graph color target. */\nexport interface CurrentGraphTarget {\n readonly name: string;\n readonly texture: Texture;\n /** Stable opaque identity for this RHI handle during the renderer lifetime. */\n readonly textureIdentity: number;\n readonly descriptor: ResolvedColorTargetDescriptor;\n readonly frameId: number;\n /** Monotonic identity of the compiled graph that owns this texture. */\n readonly graphGeneration: number;\n}\n\nconst textureIdentities = new WeakMap<object, number>();\nlet nextTextureIdentity = 1;\n\nconst opaqueResourceIdentities = new WeakMap<object, number>();\nlet nextOpaqueResourceIdentity = 1;\n\n/** Stable detached identity for a renderer-owned opaque resource handle. */\nexport function getOpaqueResourceIdentity(resource: object): number {\n const existing = opaqueResourceIdentities.get(resource);\n if (existing !== undefined) return existing;\n const identity = nextOpaqueResourceIdentity++;\n opaqueResourceIdentities.set(resource, identity);\n return identity;\n}\n\n/**\n * Project an opaque RHI texture handle to a stable diagnostic identity.\n * RHI handles intentionally expose no serializable fields; object identity is\n * the only valid comparison boundary for a copy-time capture.\n */\nexport function getTextureIdentity(texture: Texture): number {\n const object = texture as object;\n const existing = textureIdentities.get(object);\n if (existing !== undefined) return existing;\n const identity = nextTextureIdentity++;\n textureIdentities.set(object, identity);\n return identity;\n}\n\nexport type GraphTargetCaptureReadbackValidation =\n | { readonly ok: true }\n | {\n readonly ok: false;\n readonly code:\n | 'capture-readback-length'\n | 'capture-readback-untouched-sentinel'\n | 'capture-readback-empty'\n | 'capture-readback-non-finite';\n };\n\n/** Validate a mapped rgba16float capture before a consumer decodes its values. */\nexport function validateGraphTargetCaptureReadback(input: {\n readonly bytes: Uint8Array;\n readonly expectedByteLength: number;\n readonly sentinel?: Uint8Array;\n readonly allowZero?: boolean;\n}): GraphTargetCaptureReadbackValidation {\n const { bytes, expectedByteLength, sentinel, allowZero = false } = input;\n if (bytes.byteLength !== expectedByteLength)\n return { ok: false, code: 'capture-readback-length' };\n if (sentinel?.every((value, index) => bytes[index] === value)) {\n return { ok: false, code: 'capture-readback-untouched-sentinel' };\n }\n if (!allowZero && bytes.every((value) => value === 0)) {\n return { ok: false, code: 'capture-readback-empty' };\n }\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n let index = 0;\n // Inspect both half-float exponents per word. DataView also preserves\n // little-endian capture semantics for unaligned slices and host byte orders.\n for (; index + 3 < bytes.byteLength; index += 4) {\n const word = view.getUint32(index, true);\n if ((word & 0x7c00) === 0x7c00 || (word & 0x7c000000) === 0x7c000000)\n return { ok: false, code: 'capture-readback-non-finite' };\n }\n if (index + 1 < bytes.byteLength && (view.getUint16(index, true) & 0x7c00) === 0x7c00)\n return { ok: false, code: 'capture-readback-non-finite' };\n return { ok: true };\n}\n\n/**\n * Receipt delivered after a selected pass-replay raster pass has encoded.\n * The depth view and target handles are the frame-resolved objects used by\n * the graph; the numeric texture identity is derived by getTextureIdentity.\n */\nexport interface GraphTargetPassReplayReceipt {\n readonly passName: string;\n readonly executionIndex: number;\n readonly resolvedDepthStencilAttachmentView: TextureView;\n readonly graphGeneration: number;\n readonly targetName: string;\n readonly targetView: TextureView;\n readonly targetTexture: Texture;\n readonly targetTextureIdentity: number;\n}\n\nexport type GraphTargetPassReplayCallback = (receipt: GraphTargetPassReplayReceipt) => void;\n\n/** Receipt delivered once after a complete selected prefix reaches its boundary pass. */\nexport interface GraphTargetPassReplayPrefixReceipt extends GraphTargetPassReplayReceipt {\n /** The compiled-order prefix that was replayed. */\n readonly replayPassNames: readonly string[];\n /** The unique depth-bearing raster pass used as the observation anchor. */\n readonly depthAttachmentPassName: string;\n /** The final pass in the selected prefix. */\n readonly observeAfterPassName: string;\n readonly depthAttachmentExecutionIndex: number;\n}\n\nexport type GraphTargetPassReplayPrefixCallback = (\n receipt: GraphTargetPassReplayPrefixReceipt,\n) => void;\n\n/** Internal readback request consumed by the record encoder in the same submit. */\nexport type GraphTargetCaptureRequest =\n | {\n /** The default preserves the original target-copy request shape. */\n readonly kind?: 'target-copy';\n readonly name: string;\n /** Optional one-shot pass selection for internal graph-target diagnostics. */\n readonly replayPassNames?: readonly string[];\n readonly buffer: Buffer;\n readonly bytesPerRow: number;\n readonly width: number;\n readonly height: number;\n /** Descriptor contract checked against the resolved target at copy time. */\n readonly expected: {\n readonly format: ResolvedColorTargetDescriptor['format'];\n readonly width: number;\n readonly height: number;\n readonly usage: number;\n /** Optional caller binding; when present it is checked at copy time. */\n readonly identity?: {\n readonly graphGeneration: number;\n readonly frameId: number;\n readonly textureIdentity: number;\n };\n };\n }\n | {\n /** Execute selected compiled passes without requesting a target copy. */\n readonly kind: 'pass-replay';\n readonly replayPassNames: readonly string[];\n /** Optional graph target used to validate the selected pass attachment. */\n readonly targetName?: string;\n /** Optional callback invoked after each selected pass encodes. */\n readonly onPassEncoded?: GraphTargetPassReplayCallback;\n /** Optional one-shot callback invoked after the selected prefix boundary encodes. */\n readonly depthAttachmentPassName?: string;\n readonly observeAfterPassName?: string;\n readonly onPrefixEncoded?: GraphTargetPassReplayPrefixCallback;\n };\n\n/** Renderer-private readback request for the Standard fallback MRT. */\nexport interface ReflectionFallbackReadbackRequest {\n readonly name: string;\n readonly buffer: Buffer;\n readonly bytesPerRow: number;\n readonly width: number;\n readonly height: number;\n readonly expected: {\n readonly format: ResolvedColorTargetDescriptor['format'];\n readonly width: number;\n readonly height: number;\n readonly usage: number;\n readonly graphGeneration: number;\n readonly frameId: number;\n readonly textureIdentity: number;\n };\n encoded: boolean;\n}\n/**\n * Build a synthetic CameraSnapshot the record stage uses when the world\n * carries no Camera entity. Identity-shaped projection / view inputs\n * keep the existing matrix math numerically stable; clear-color quartet\n * sourced from `ZERO_CAMERA_CLEAR_FALLBACK` so the swap-chain still\n * paints `[0, 0, 0, 1]` (AI-user friendly observable signal that the\n * `'render-system-no-camera'` diagnostic fired without leaving stale\n * pixels on screen).\n */\nexport function makeZeroCameraFallbackSnapshot(): CameraSnapshot {\n // Identity world mat4 so `mat4.invert(world)` yields identity view.\n const identityWorld = new Float32Array(16);\n identityWorld[0] = 1;\n identityWorld[5] = 1;\n identityWorld[10] = 1;\n identityWorld[15] = 1;\n return {\n position: vec3.create(0, 0, 0),\n world: identityWorld,\n fov: Math.PI / 4,\n aspect: 1,\n near: 0.1,\n far: 100,\n // feat-20260613 M6 / w20: synthetic camera defaults to perspective so\n // the CSM extract path stays consistent with the previously-implicit\n // perspective shape (unchanged behavior; explicit field).\n projection: 'perspective',\n orthoLeft: -1,\n orthoRight: 1,\n orthoBottom: -1,\n orthoTop: 1,\n tonemap: 'none',\n exposure: 1.0,\n whitePoint: 4.0,\n antialias: 'none',\n bloom: 'off',\n bloomThreshold: 1.0,\n bloomIntensity: 1.0,\n bloomSoftKnee: 0.5,\n bloomScatter: 0.7,\n clearColor: ZERO_CAMERA_CLEAR_FALLBACK,\n };\n}\n\n/**\n * Per-RenderSystem mutable frame state.\n *\n * Owned by the `createRenderSystem` closure; advanced once per\n * `recordFrame` invocation. The `instanceBuffers` map holds the per-entity\n * GPU storage buffers for Instances-bearing entities (cache key = the\n * renderer-owned collection id, with the packed Entity u32 retained only for\n * legacy snapshots); entries are recreated when the `archVersion` bumps or\n * `byteLength` changes.\n *\n * feat-20260518-pbr-direct-lighting-mvp M3 / w14 (AC-17 a): the\n * `warnedZeroLightStandard` flag latches the first-frame warning that\n * fires when the world contains a StandardMaterial entity but zero\n * DirectionalLight entries — once latched the next 100 frames suppress\n * the warning so the AI user is not flooded with repeated noise (charter\n * P3 silent failure -> explicit warning at most once per RenderSystem\n * lifetime).\n */\nexport interface RenderFrameState {\n frameNumber: number;\n /** Actual Surface commands staged for the renderer-owned submission fence. */\n surfaceSubmissionObservation:\n | import('../surface/submission-observation').SurfaceSubmissionCandidate\n | undefined;\n /** Exact producer artifacts accepted by the last submitted GPU frame. */\n recoveryMaterialArtifacts?: ReadonlyMap<string, MaterialShaderArtifact> | undefined;\n /** Exact ShadowCaster artifacts accepted by the last submitted GPU frame. */\n recoveryShadowMaterialArtifacts?: ReadonlyMap<string, MaterialShaderArtifact> | undefined;\n /** Last successful Motion Blur compute execution; failed submits retain the prior receipt. */\n motionBlurExecution?: MotionBlurExecutionReceipt;\n /** Final-submit Standard IBL binding-chain receipt for this frame. */\n iblBindingInspection?: IblBindingInspection;\n /** Demand for the frame-local Standard fallback MRT. */\n reflectionFallbackDemand?: boolean;\n /** Whether the active camera explicitly requested SSR this frame. */\n ssrRequested?: boolean | undefined;\n /** Current renderer-owned SSR spatial admission projection. */\n ssrSpatialAdmission?: SsrSpatialAdmission | undefined;\n /** Persistent SSR history owner; candidate is promoted only after submit. */\n ssrHistoryOwner?: SsrHistoryOwner | undefined;\n ssrHistoryCandidate?: SsrHistoryCandidate | undefined;\n /** Reused CPU parameter payload for the SSR temporal resolve. */\n ssrTemporalParamsPayload?: Uint8Array | undefined;\n /** Last camera identity used by the SSR history reset seam. */\n ssrLastCameraEntity?: number | undefined;\n ssrLastHistoryVersion?: number | undefined;\n /** Monotonic compiled-graph identity used by diagnostic readbacks. */\n graphGeneration: number;\n /** Number of successfully submitted TAA frames; failed attempts do not advance it. */\n successfulTemporalFrameIndex?: number;\n /** The renderer-owned accepted-submit temporal fact consumed by consumers. */\n temporalFrame?: TemporalFrame | undefined;\n /** The sole transaction that advances temporal history after queue.submit. */\n readonly temporalFrameTransaction: TemporalFrameTransaction;\n /** Staged input is consumed only by the graph submit owner. */\n temporalFrameInput: TemporalFrameInput | undefined;\n /** Optional graph resource lookup used by low-level record helpers and tests. */\n perFrameGraph?: {\n readonly getColorTargetDescriptor: (key: string) => ResolvedColorTargetDescriptor | undefined;\n readonly getColorTargetView: (key: string) => TextureView | undefined;\n readonly getColorTargetTexture: (key: string) => Texture | undefined;\n readonly graphGeneration: number;\n } | null;\n graphTargetCapture?: GraphTargetCaptureRequest | undefined;\n /** One-frame producer-owned copy target for fallback MRT readback. */\n reflectionFallbackReadback?: ReflectionFallbackReadbackRequest | undefined;\n /** Last successfully rendered static directional shadow atlas token. */\n directionalShadowCache: DirectionalShadowCache | null;\n /** Last successfully submitted camera post-process mode. */\n lastSuccessfulBloom: 'off' | 'on';\n /** Bloom record receipts staged by this frame; cleared on abort. */\n bloomFrameReceipts?: BloomFrameReceipts | undefined;\n /** Set by a directional shadow pass when this frame refreshed the atlas. */\n directionalShadowCacheRecorded: boolean;\n /** The sole compiled owner for compute, copy, feature, and raster work. */\n compiledFrameGraph: CompiledRenderGraph<RenderPipelineFrame> | null;\n compiledFrameGraphTopologyKey: string | null;\n /** Monotonic generation of successfully promoted compiled graphs. */\n compiledFrameGraphGeneration: number;\n /**\n * DoF graph candidate staged until the surrounding frame transaction\n * submits. The previous graph, access projection, generation, and lighting\n * signature are restored together when encoding or submission aborts.\n */\n depthOfFieldPreviousGraph: CompiledRenderGraph<RenderPipelineFrame> | null;\n depthOfFieldPreviousGraphKey: string | null;\n depthOfFieldPreviousPerFrameGraph?: RenderFrameState['perFrameGraph'];\n depthOfFieldPreviousGraphGeneration: number;\n depthOfFieldPreviousStandardLightingGraphSignature: string;\n depthOfFieldCandidateGraph: CompiledRenderGraph<RenderPipelineFrame> | null;\n /** DoF graph/params detached at the same successful-submit boundary. */\n depthOfFieldAccepted?:\n | {\n readonly params: DepthOfFieldParams;\n readonly graph: CompiledRenderGraphInfo;\n readonly deviceGeneration: number;\n }\n | undefined;\n /** A DoF candidate was present when the frame failed to submit. */\n depthOfFieldLastSubmitFailed?: boolean | undefined;\n /**\n * General graph replacement staged by the barrel/output path. The candidate\n * is promoted only after the surrounding command buffer submits; failed\n * encode/finish/submit restores the complete graph projection as one unit.\n */\n barrelDistortionPreviousGraph?: CompiledRenderGraph<RenderPipelineFrame> | null;\n barrelDistortionPreviousGraphKey?: string | null;\n barrelDistortionPreviousPerFrameGraph?: RenderFrameState['perFrameGraph'];\n barrelDistortionPreviousGraphGeneration?: number;\n barrelDistortionPreviousCompiledGraphGeneration?: number;\n barrelDistortionPreviousStandardLightingGraphSignature?: string;\n barrelDistortionCandidateGraph?: CompiledRenderGraph<RenderPipelineFrame> | null;\n /**\n * Last-known-good graph held while a volume topology candidate is tested.\n * The candidate is promoted only after its command buffer is submitted;\n * failed encoding/finish/submit restores this graph and its topology key.\n */\n volumetricFogPreviousGraph: CompiledRenderGraph<RenderPipelineFrame> | null;\n volumetricFogPreviousGraphKey: string | null;\n volumetricFogCandidateGraph: CompiledRenderGraph<RenderPipelineFrame> | null;\n /** Two renderer-owned parameter slots; only the pending slot is writable. */\n volumetricFogParamsBuffers: [Buffer | null, Buffer | null];\n /** Candidate parameter slot, promoted only after queue submission succeeds. */\n volumetricFogParamsPendingSlot: 0 | 1 | null;\n /** Parameter slot consumed by the last accepted volume frame. */\n volumetricFogParamsAcceptedSlot: 0 | 1 | null;\n /** CPU copy of the accepted parameter payload for degraded-frame staging. */\n volumetricFogAcceptedParams: Float32Array | undefined;\n /** CPU copy of the current candidate payload before submit. */\n volumetricFogPendingParams: Float32Array | undefined;\n /** Last candidate/accepted volume projection exposed through inspect(). */\n volumetricFogInspection: VolumetricFogInspection;\n /** Accepted volume POD/context retained while a later candidate degrades. */\n volumetricFogAccepted: import('../render-system-extract').ExtractedVolumetricFog | undefined;\n volumetricFogAcceptedContext: VolumetricFogFrameContext | undefined;\n /** Accepted graph identity and ping-pong slot for temporal volume history. */\n volumetricFogHistoryGraph: CompiledRenderGraph<RenderPipelineFrame> | null;\n volumetricFogHistorySlot: 0 | 1 | null;\n volumetricFogHistorySignature: VolumeTemporalSignature | null;\n readonly retiredCompiledFrameGraphs: Set<CompiledRenderGraph<RenderPipelineFrame>>;\n /** Physical outputs projected by typed graph passes for downstream observers. */\n currentFrameObservationSource: FrameObservationSource | undefined;\n /** Completed-frame source for the producer-owned fallback MRT. */\n reflectionFallbackObservationSource?: FrameObservationSource | undefined;\n /** Completion fence for the producer-owned fallback row/readback promotion. */\n reflectionFallbackCompletion?: Promise<void> | undefined;\n /** Camera antialias mode for the last successfully submitted graph. */\n lastSuccessfulCameraAntialias: CameraSnapshot['antialias'] | undefined;\n /** Last accepted output-space barrel mapping, promoted with the picture. */\n lastSuccessfulBarrelDistortion: BarrelDistortionMapping | undefined;\n /** Whether the current frame graph was retained from an accepted LKG. */\n barrelDistortionGraphResolution?: 'accepted' | 'retained';\n /** Staged TAA GPU state is promoted only after queue.submit succeeds. */\n temporalGpuState: TemporalGpuState | undefined;\n /** Device-scoped auto-exposure buffers imported by the Standard graph. */\n autoExposureGpuResources?: AutoExposureGpuResources | undefined;\n /** Candidate auto-exposure buffers; promoted only after queue.submit succeeds. */\n pendingAutoExposureGpuResources?: AutoExposureGpuResources | undefined;\n /** Accepted auto-exposure inspection state; promoted only after submit. */\n autoExposureState?: AutoExposureState | undefined;\n /** Candidate auto-exposure inspection state; cleared on any failed frame. */\n pendingAutoExposureState?: PendingAutoExposureState | undefined;\n /** Prepared ordinary TextureAsset LUT candidate for the Standard graph. */\n standardLutGpuResources?: StandardLutGpuResources | undefined;\n /** Candidate LUT resources; promoted only after queue.submit succeeds. */\n pendingStandardLutGpuResources?: StandardLutGpuResources | undefined;\n /** Accepted LUT inspection state; promoted only after submit. */\n standardLutState: StandardLutState;\n /** Candidate LUT inspection state; cleared on any failed frame. */\n pendingStandardLutState?: PendingStandardLutState | undefined;\n /** Last successful TAA GPU state; candidate replacement stays staged until submit. */\n activeTemporalGpuState: TemporalGpuState | undefined;\n /** Submitted temporal generations retained until their queue fence resolves. */\n readonly retiringTemporalGpuStates: Set<TemporalGpuState>;\n /** The accepted graph currently owns CloudLayer ping-pong history. */\n cloudHistoryActive?: boolean;\n /** Candidate CloudLayer history ownership, promoted only after submit. */\n pendingCloudHistoryActive?: boolean;\n /** Last successful projection; candidate frames never overwrite it. */\n lastSuccessfulTemporalView: TemporalView | undefined;\n pendingTemporalCommit: TemporalCommitOutcome;\n /** Staged environment generation is promoted only after queue.submit succeeds. */\n environmentGeneration: EnvironmentGeneration | undefined;\n environmentFrame?: import('../environment/frame').SelectedEnvironmentFrame | undefined;\n pendingAtmospherePublish?: (() => void) | undefined;\n readonly environmentLifecycle: EnvironmentLifecycle | undefined;\n currentDirectionalShadowView: TextureView | null;\n currentSpotShadowView: TextureView | null;\n readonly instanceBuffers: Map<number, InstanceBufferCacheEntry>;\n /** Renderer-private World projection receiving record-stage residency facts. */\n readonly instanceCollections?: InstanceProjectionStore;\n /** Stable buffers for renderer-owned collections split by device cap. */\n readonly instanceBufferChunks?: Map<string, InstanceBufferCacheEntry>;\n /** Per-object ProbeBlendRecord buffers; upload is one atomic 160B write. */\n readonly probeBlendBuffers: Map<number, ProbeBlendBufferCacheEntry>;\n /** One renderer-owned record array; each object selects its 256B-aligned lane. */\n probeBlendRecordBuffer?: GpuBuffer;\n probeBlendRecordBufferCapacity: number;\n /** Last producer revision fully uploaded to the current device buffer. */\n probeBlendRecordProjection?: {\n readonly projection: import('../scene/probe-blend').ProbeBlendBufferProjection;\n readonly device: RhiDevice;\n readonly buffer: GpuBuffer | undefined;\n };\n /** Per-entity vertex buffers for the Standard CPU morph lane. */\n readonly morphBuffers?: Map<number, MorphBufferCacheEntry>;\n readonly hdrpClusterBinScratch: ClusterBinScratch;\n /** Reusable HDRP cluster output buffers; sized once and grown only if the grid/cap changes. */\n hdrpClusterGridScratch: Uint32Array | null;\n hdrpLightIndexListScratch: Uint32Array | null;\n /** Device-owned membership binding; layout and device must match the active pipeline. */\n hdrpClusterMembership: {\n readonly device: RhiDevice;\n readonly layout: BindGroupLayout;\n readonly bindGroup: BindGroup;\n /** Cluster buffer identity keeps this group aligned with grown bundles. */\n readonly clusterGridBuffer: Buffer;\n } | null;\n /**\n * Signature of the Standard lighting declaration accepted by the compiled\n * graph. Payload uploads and membership bindings must match this signature;\n * a failed candidate never changes it.\n */\n standardLightingGraphSignature: string;\n /** Last prepared Standard transport facts projected for Renderer.inspect(). */\n standardLightingInspection?: StandardLightingInspection | undefined;\n /** Last submitted point-shadow atlas budget projection. */\n pointShadowInspection?: PointShadowInspection | undefined;\n transientInstanceBuffers: InstanceBufferCacheEntry[];\n warnedZeroLightStandard: boolean;\n /**\n * feat-20260608-multi-light-warn-once M3: once-warn latch for the\n * single-directional authoring constraint. Standard local lights use the\n * unified Cluster budget; there is no per-kind local-light cap.\n */\n warnedMultiLightDirectional: boolean;\n /**\n * feat-20260630-equirect-kind-internalized-ibl-declarative-skyligh M3 / w19:\n * once-warn latches for >1 Skylight / >1 SkyboxBackground entity. Fire at most\n * once per RenderSystem lifetime so the multi-entity warn (which names the\n * winning entity handle, F-8) does not flood the console every frame.\n */\n warnedMultiSkylight: boolean;\n warnedMultiSkybox: boolean;\n /** feat-20260531-skybox-env-background M3 / w20: once-warn when camera\n * tonemap is 'none' but a SkyboxBackground entity exists. Skybox needs\n * the HDR render target allocated by the tonemap path; without it the\n * skybox pass is skipped (plan-strategy D-2 NOTE). */\n warnedSkyboxTonemapNone: boolean;\n /**\n * Per-handle warn-once anchor for the missing baseColor-texture fallback,\n * shared by every textured material path (sprite / sprite-lit / standard-pbr\n * / pbr-skin / unlit — feat-20260520-2d-sprite-layer-mvp M-3 / w25 seeded it\n * for sprites; feat-future-pbr-missing-texture-fallback-explicit generalised\n * it to PBR/skin so GLB textures that fail to reach the GPU no longer render\n * silently flat). A `Set<number>` keyed by the raw Handle<TextureAsset> id -\n * the writer fires `console.warn` exactly once per missing texture handle per\n * RenderSystem lifetime so AI users see a single actionable message without\n * per-frame log flooding. The set lives across frames so the second frame on\n * the same missing handle stays silent (charter P3 explicit failure:\n * warn-once preserves signal / noise floor while structured RhiError below\n * stays per-frame fire).\n *\n * Note on the WeakSet/Set choice: plan-strategy mentions WeakSet but\n * Handle values are numeric brand u32s (not object references), so\n * WeakSet<object> is not applicable; Set<number> gives identical\n * warn-once-per-handle semantics at zero additional cost (charter F1\n * minimal surface; the per-RenderSystem lifetime cap is the upper\n * bound).\n */\n readonly warnedMissingBaseColorTextureHandles: Set<number>;\n /**\n * feat-20260527-sprite-nineslice M2 / w11 + M4 / w16 (AC-16): once-per-\n * renderable guard for the `nineslice.scale-too-small` metric increment.\n * Keyed by `renderableIndex` so the second frame on the same mis-scaled\n * entity does NOT keep bumping the counter — AI users see one counter\n * tick per offending entity per RenderSystem lifetime, matching the\n * single-event semantics of the structured fail-fast (charter P3:\n * machine-readable signal, not a per-frame inflation). M4 retired the\n * placeholder console.warn; the increment lands on the per-Renderer\n * EngineMetrics through `runtime.metrics.increment(...)`.\n */\n readonly warnedNineSliceScaleEntities: Set<number>;\n /**\n * feat-20260630-equirect-kind-internalized-ibl-declarative-skyligh M3 / w18:\n * per-handle fire-once anchor for the lazy equirect-to-cubemap projection\n * failure. A `Set<number>` keyed by the raw Handle<EquirectAsset> id - the\n * record arm fires the structured `EquirectProjectionFailedError` exactly\n * once per failed source per RenderSystem lifetime (the store records\n * `status:'failed'` permanently and never retries, R-2 / AC-09; without this\n * latch the record arm would re-fire the error every frame). The set lives\n * across frames so the second frame on the same failed handle stays silent\n * (charter P3: warn-once preserves signal / noise floor).\n */\n readonly firedEquirectProjectionFailedHandles: Set<number>;\n /**\n * feat-20260622-handle-to-id-allocator-elimination M1 / w3: per-frame\n * bind group caches converted to nested WeakMap chain roots (D-3).\n * Each root is a WeakMap<object, WeakMap<...>> walked by\n * getOrCreateFromChain; the chain depth varies by variant\n * (view-main = 7, mesh = 1, hdrp-unified = 5, skin = 2).\n * Roots are stable between device recoveries and replaced when the renderer\n * swaps to a fresh device. Chain keys are always inner buffer handles, never\n * wrappers (D-3).\n */\n viewBindGroupCache: WeakMap<object, unknown>;\n meshBindGroupCache: WeakMap<object, unknown>;\n /**\n * feat-20260622-handle-to-id-allocator-elimination M1 / w2: per-entity\n * bind group caches scoped by entityKey (packed u32 as number).\n * Outer Map<number, WeakMap<handle, ...>> lets GC collect entries for\n * destroyed entities whose handles are unreachable; per-entity material\n * and instances share the same two-level shape (D-1). The inner WeakMap\n * value is opaque (`unknown`) because `getOrCreateFromChain` walks a\n * variable-depth chain — intermediate handles map to nested WeakMaps and\n * only the final handle maps to the variant->BindGroup leaf Map. Direct\n * readers (HDRP shadow-instances read end) assert the leaf shape locally.\n */\n /**\n * feat-20260708-composited-multi-world-rendering M1 / D-1a #2: outer Map\n * keyed by `worldEntityKey(worldId, entityKey)`. Inner WeakMap unchanged.\n */\n readonly materialBgPerEntity: Map<number, WeakMap<object, unknown>>;\n /**\n * feat-20260708-composited-multi-world-rendering M1 / D-1a #3: outer Map\n * keyed by `worldEntityKey(worldId, entityKey)`. Inner WeakMap unchanged.\n */\n readonly instancesBgPerEntity: Map<number, WeakMap<object, unknown>>;\n /** Identity-keyed instances BGs shared across entities using the same buffer. */\n readonly instancesBgShared: WeakMap<object, unknown>;\n /**\n * feat-20260622-handle-to-id-allocator-elimination M1 / w2: cross-entity\n * shared material bind group cache (OQ-1 option A). Outer key is the\n * material shaderId string; inner chain is a WeakMap keyed by the same\n * handle objects used in per-entity chains. Reuses the generic\n * `getOrCreatePerEntity` helper with outerKey string|number (D-1).\n */\n readonly materialBgShared: Map<string, WeakMap<object, unknown>>;\n /** Cross-frame fast path for fully-resident, immutable material snapshots. */\n readonly materialBgAssemblyCache: Map<string, MaterialBgAssemblyCacheEntry>;\n /** Opaque shadow fallback bindings follow physical resources across scene replacement. */\n shadowMaterialBindGroups: WeakMap<object, unknown>;\n /**\n * Post-process bind group cache: nested WeakMap chain root shared by the\n * built-in bloom (bright / blur-H / blur-V / composite), FXAA, and HDRP SSAO\n * (calc / blur) fullscreen passes. Each of these passes samples graph-owned\n * transient render targets (hdrColor / ldrColor / bloom* / ssaoRaw /\n * gbuf0 / hdrDepth); on canvas resize the graph retires the old physical\n * textures and allocates new ones, so the bind group must be rebuilt to\n * reference the new TextureView identity. Keying the cache on the physical\n * TextureView (or `::tex` texture handle for passes that recreate their bound\n * view every frame) makes invalidation automatic: a resized target yields a\n * new key object -> WeakMap miss -> factory rebuild, and dead views are GC'd\n * (same identity-invalidation mechanism as view/mesh caches, D-3). Replaces\n * the pre-fix `pp.*BindGroup === null` single-slot caches that never\n * invalidated on resize and submitted destroyed textures.\n */\n postProcessBgCache: WeakMap<object, unknown>;\n /**\n * Raw handle of the currently installed RenderPipelineAsset (0 = builtin).\n * Installation brands the next candidate topology; the prior compiled graph\n * remains last-known-good until the candidate compiles successfully.\n */\n installedPipelineHandle: number;\n /**\n * Active topology declaration resolved from the pipeline registry.\n */\n activePipeline: RenderPipelineDef;\n /**\n * Install-time config projected into `RenderPipelineTopology.config`.\n */\n installedPipelineConfig: RenderPipelineAsset['config'];\n /**\n * feat-20260608-cluster-lighting M5 / w20 + M6 / w23 + M5 / w22:\n * once-per-frame fire dedup set for Standard per-frame fail-soft errors\n * (`standard-light-budget-exceeded`, `standard-cluster-index-overflow`). Cleared\n * at the end of each frame so the next frame re-fires if the condition\n * persists. Set<string> keyed by RuntimeErrorCode literal.\n */\n standardOncePerFrameFired: Set<string>;\n /**\n * feat-20260612-point-light-shadows-urp-hdrp M3 / T-M3-2 (plan-strategy §D-1).\n * Lazily-allocated cube_array shadow atlas owned by the RenderSystem\n * lifetime. `null` until the first frame whose `lights.pointShadow` is\n * non-empty (zero-shadow scenes never allocate; AC-09). The atlas is\n * disposed by the renderer dispose path; subsequent frames with a non-empty\n * snapshot list re-allocate.\n */\n pointShadowAtlas: ShadowAtlas | null;\n /**\n * feat-20260612-point-light-shadows-urp-hdrp M3 / T-M3-2 (plan-strategy §D-3):\n * per-frame projection of `lights.pointShadow` from the extract stage. The\n * typed point-shadow pass reads this list to drive the 6 x N face iteration.\n * Empty array means the topology declares no point-shadow passes.\n */\n pointShadowSnapshots: readonly PointShadowSnapshot[];\n /**\n * feat-20260622-chunk-gpu-instancing-sprite-tilemap M1 / w4 (D-1):\n * last fold-pass output, computed at `recordFrame` entry from the\n * transparent-sort-ordered dispatch + mode-gate (D-5: only mode 0\n * folds; other modes yield singleton buckets). Currently an\n * observational compute — the drawIndexed swap (1 instanced draw per\n * fold bucket) is the follow-on integration that wires each bucket\n * into the sprite-pass / geometry-pass dispatch loops. The bucket\n * count is the source of truth for `render.instancing.foldedDraws`\n * metric (M3 / w13) — every fold-eligible bucket (bucketSize >= 1\n * under mode 0 AND not bypassed) contributes one increment.\n */\n lastFoldBucketCount: number;\n /**\n * feat-20260625-spot-light-shadow-mapping M2 / w9 (D-2): per-frame projection\n * of `lights.spot` from the extract stage. The typed spot-shadow graph\n * pass reads this list to render each\n * castShadow spot's perspective depth into its `spotShadowDepth` atlas tile\n * (viewport keyed on `shadowAtlasTile`). `recordFrame` writes it before\n * graph execution. Spots with `shadowAtlasTile < 0` (castShadow:false,\n * degenerate direction, or clipped beyond cap 4) are skipped — zero\n * shadow-casting spots means zero spot shadow passes (AC-03).\n */\n spotShadowSnapshots: readonly SpotLightSnapshot[];\n}\n\nexport interface MorphBufferCacheEntry {\n readonly buffer: GpuBuffer;\n readonly byteLength: number;\n}\n\n/**\n * feat-20260518-pbr-direct-lighting-mvp M5 / w22.11 (D-2 + D-10 + AC-06):\n * mutable per-frame dispatch counter object owned by `createRenderSystem`\n * and bumped here at the actual `pass.setPipeline(...)` call site (the\n * only point with both `mat.materialShaderId` and `mesh.layoutProjection` in scope).\n * Unlit / custom shader pipeline dispatch tracked here.\n */\nexport interface DispatchCounts {\n unlit: number;\n /** feat-20260523 M4-T07: 'standard' counter removed; schema-driven\n * materials are tracked via materialShaderId in the pipeline cache. */\n}\n\n/**\n * feat-20260531-per-frame-bind-group-cache M1 / w4: per-frame\n * createBindGroup counter. Closure-mutable object aligned with\n * DispatchCounts precedent. Reset in draw(world) entry, bumped on\n * cache-miss createBindGroup calls (M2-M4).\n */\nexport interface BindGroupCounts {\n createBindGroup: number;\n /**\n * Debug-only: records the variant of every cache-miss BindGroup created via\n * `getOrCreateFromChain` for unit-test observability. Production paths do\n * not read this array.\n */\n keys: string[];\n}\n\n/**\n * Successful Bloom record operations staged for the current frame. These\n * counters are promoted only after the shared renderer queue submission.\n */\nexport interface BloomFrameReceipts {\n readonly uploadCount: number;\n readonly bindGroupCount: number;\n readonly encodeCount: number;\n}\n\n/**\n * A renderable resolved against the AssetRegistry for the current frame:\n * its source snapshot, the GPU mesh handles, the row index used to correlate\n * transparent-sort output back to this entry, and an optional per-material\n * renderState override (bug-20260527-renderstate-pipeline-dispatch-gap D-4).\n * Module-scoped so RenderPipelineContext can type `validated` / `validatedOrdered`\n * without a dynamic type escape (was a recordFrame-local interface before F-4).\n */\nexport interface ValidatedRenderable {\n readonly source: RenderableSnapshot;\n /** RenderResourceScope that owns the renderable's asset handles and material snapshots. */\n readonly world?: RenderResourceScope;\n readonly mesh: MeshGpuHandles;\n readonly renderableIndex: number;\n readonly renderState: MaterialRenderState | undefined;\n /**\n * Canonical authored material-variant request folded from the selected\n * pass's `defines` map. Capability axes are merged at the renderer seam;\n * this field carries only the pass-owned selection into record.\n */\n readonly variantSet?: string | undefined;\n /**\n * w10: per-pass stencil reference value folded from\n * {@link DispatchEntry.stencilReference} (draw-call dynamic state). The draw\n * loop calls `pass.setStencilReference(stencilReference ?? 0)` before each\n * draw; `undefined` falls back to the WebGPU default 0 (semantic no-op).\n */\n readonly stencilReference: number | undefined;\n}\n\n/**\n * Cross-frame validity token for the directional shadow atlas.\n *\n * The atlas is a render target, not authored state. Keeping its validity\n * token beside the other RenderFrameState caches lets recordFrame skip a\n * static caster submission without teaching the public render-pipeline\n * contract about caching. Every source that can change caster depth is part\n * of the token: world mutation, asset catalogue, graph/target identity, CSM\n * matrices, and the GPU mesh-residency epoch.\n *\n * @internal\n */\nexport interface DirectionalShadowCache {\n readonly worlds: readonly RenderResourceScope[];\n readonly worldStateTokens: readonly DirectionalShadowWorldState[];\n readonly assetCatalogEpoch: number;\n readonly pipelineHandle: number;\n readonly graphTopologyKey: string | null;\n readonly shadowMapSize: number;\n readonly cascadeCount: number;\n readonly directionalShadowQuality: DirectionalShadowQuality;\n readonly lightViewProj: readonly Float32Array[];\n readonly meshResidencyEpoch: number;\n}\n\n/**\n * ECS state that can change the contents of a directional shadow map.\n *\n * The ECS-owned RenderReadLease is the only render-facing mutation boundary.\n * Its version is intentionally conservative: any published RenderResourceScope change\n * invalidates the cached atlas, while render never reaches through RenderResourceScope for\n * component-clock storage.\n */\nexport interface DirectionalShadowWorldState {\n readonly worldIdentity: string;\n readonly version: RenderReadVersion;\n}\n","import type { MaterialShaderArtifactReceipt } from '@forgeax/engine-shader';\n\nexport type GpuDrivenPreparationErrorCode =\n | 'missing-material-receipt'\n | 'material-abi-not-executable'\n | 'missing-uv'\n | 'reflection-mismatch'\n | 'vertex-input-mismatch'\n | 'alpha-mask-mismatch'\n | 'resource-not-ready'\n | 'stale-generation'\n | 'skin-receipt-mismatch'\n | 'shadow-ownership';\n\nexport type GpuDrivenPreparationReason =\n | 'material-receipt-missing'\n | 'material-abi-not-executable'\n | 'uv-set-missing'\n | 'reflection-receipt-mismatch'\n | 'vertex-semantic-mismatch'\n | 'alpha-mask-receipt-missing'\n | 'material-resource-missing'\n | 'generation-stale'\n | 'skin-address-missing'\n | 'shadow-ownership-missing';\n\n/** Closed next action; AI callers never need to parse an error message. */\nexport type GpuDrivenRecoveryAction =\n | 'rebuild-producer'\n | 'route-cpu-lane'\n | 'retry-same-draw'\n | 'rebuild-generation'\n | 'stop-promotion';\n\nexport interface GpuDrivenPreparationErrorDetail {\n readonly reason: GpuDrivenPreparationReason;\n readonly owner: 'material' | 'geometry' | 'skin' | 'generation' | 'shadow';\n readonly expected?: string;\n readonly actual?: string;\n readonly expectedGeneration?: number;\n readonly actualGeneration?: number;\n readonly recovery?: GpuDrivenRecoveryAction;\n}\n\nconst ERROR_POLICY: Readonly<\n Record<\n GpuDrivenPreparationErrorCode,\n {\n readonly expected: string;\n readonly hint: string;\n readonly recovery: GpuDrivenRecoveryAction;\n }\n >\n> = {\n 'missing-material-receipt': {\n expected: 'a producer-owned material program receipt is present',\n hint: 'cook and load the selected material program artifact, then retry preparation',\n recovery: 'rebuild-producer',\n },\n 'material-abi-not-executable': {\n expected: 'the published material ABI fits the GPU Scene submission layout',\n hint: 'recook the material with a scene-index ABI supported by the GPU-driven owner or keep it on its authored lane',\n recovery: 'route-cpu-lane',\n },\n 'missing-uv': {\n expected: 'the geometry exposes every UV set named by the material receipt',\n hint: 'repair the geometry UV semantic or route the draw to the CPU semantic lane',\n recovery: 'route-cpu-lane',\n },\n 'reflection-mismatch': {\n expected: 'the loaded reflection receipt matches the artifact layout identity',\n hint: 'rebuild the material artifact and reflection from one source, then retry',\n recovery: 'rebuild-producer',\n },\n 'vertex-input-mismatch': {\n expected: 'geometry vertex semantics match the material reflection receipt',\n hint: 'repair the geometry vertex semantic layout or route the draw to the CPU lane',\n recovery: 'route-cpu-lane',\n },\n 'alpha-mask-mismatch': {\n expected: 'the Alpha Mask cutoff is present in the material receipt',\n hint: 'declare the pass coverage cutoff in the material schema and recook it',\n recovery: 'rebuild-producer',\n },\n 'resource-not-ready': {\n expected: 'all material resource slots have resolved handles',\n hint: 'resolve the declared texture and sampler resources before recording',\n recovery: 'retry-same-draw',\n },\n 'stale-generation': {\n expected: 'receipt and prepared inputs belong to the requested generation',\n hint: 'discard stale GPU facts, rebuild the producer receipt, and retry the same draw',\n recovery: 'rebuild-generation',\n },\n 'skin-receipt-mismatch': {\n expected: 'skinned geometry has a current palette address receipt',\n hint: 'rebuild the Skin palette receipt for this generation before recording',\n recovery: 'rebuild-producer',\n },\n 'shadow-ownership': {\n expected: 'every declared ShadowCaster pass has one GPU-compatible draw-item owner',\n hint: 'repair the ShadowCaster producer membership or keep the residual on its explicit CPU lane',\n recovery: 'route-cpu-lane',\n },\n};\n\nexport class GpuDrivenPreparationError extends Error {\n readonly code: GpuDrivenPreparationErrorCode;\n readonly expected: string;\n readonly hint: string;\n readonly detail: GpuDrivenPreparationErrorDetail;\n\n constructor(code: GpuDrivenPreparationErrorCode, detail: GpuDrivenPreparationErrorDetail) {\n const policy = ERROR_POLICY[code];\n super(`[GpuDrivenPreparationError ${code}] ${policy.expected}`);\n this.name = 'GpuDrivenPreparationError';\n this.code = code;\n this.expected = policy.expected;\n this.hint = policy.hint;\n this.detail = Object.freeze({\n ...detail,\n recovery: detail.recovery ?? policy.recovery,\n });\n }\n}\n\nexport interface GpuDrivenPreparedMaterial {\n readonly receipt: MaterialShaderArtifactReceipt;\n readonly resourceSlots: MaterialShaderArtifactReceipt['resourceSlots'];\n readonly uvSets: MaterialShaderArtifactReceipt['uvSets'];\n readonly vertexInputs: MaterialShaderArtifactReceipt['vertexInputs'];\n readonly alphaMask: MaterialShaderArtifactReceipt['alphaMask'];\n}\n","import { InstanceTransformsStrideMismatchError } from '@forgeax/engine-ecs/projection';\nimport type { RhiErrorCode } from '@forgeax/engine-rhi';\n\nconst MATRIX_STRIDE = 16;\n\n/** Renderer projection identity; never stored in a World or SceneAsset. */\nexport type InstanceCollectionId = number & {\n readonly __forgeaxInstanceCollectionId: unique symbol;\n};\nexport interface InstanceCollectionInfo {\n readonly collectionId: InstanceCollectionId;\n readonly count: number;\n readonly revision: number;\n}\nexport interface InstanceDirtyRange {\n start: number;\n end: number;\n}\nexport interface InstanceCollectionSnapshot extends InstanceCollectionInfo {\n readonly transforms: Float32Array;\n readonly generations: Uint32Array;\n}\nexport type InstanceSubmissionLane =\n | 'unresident'\n | 'direct-storage'\n | 'chunked-storage'\n | 'direct-uniform'\n | 'chunked-uniform'\n | 'unavailable';\nexport type InstanceBackendKind = 'webgpu' | 'wgpu-native' | 'wgpu-webgl2' | 'null' | 'unknown';\nexport type InstanceCollectionFailureCode = RhiErrorCode | 'queue-write-buffer-failed';\nexport interface InstanceCollectionFailureFacts {\n readonly requestedBytes: number;\n readonly supportedBytes: number | undefined;\n readonly backend: InstanceBackendKind;\n readonly owner: 'renderer.instances';\n readonly cause: string;\n readonly recovery: string;\n}\nexport interface InstanceCollectionInspection extends InstanceCollectionInfo {\n readonly residentGeneration: number | undefined;\n readonly lane: InstanceSubmissionLane;\n readonly uploadRanges: readonly InstanceDirtyRange[];\n readonly uploadedBytes: number;\n readonly requestedBytes: number;\n readonly supportedBytes: number | undefined;\n readonly backend: InstanceBackendKind;\n readonly owner: 'renderer.instances';\n readonly error:\n | {\n readonly code: InstanceCollectionFailureCode;\n readonly expected: string;\n readonly hint: string;\n readonly detail: InstanceCollectionFailureFacts;\n }\n | undefined;\n}\n\nexport class InstanceTransformsError extends Error {\n readonly code = 'instance-transforms-invalid' as const;\n readonly expected = 'finite column-major mat4 values, with transforms.length a multiple of 16';\n readonly hint = 'repair Instances.transforms in the World or source SceneAsset and retry';\n constructor(\n readonly detail: { readonly actualLength: number; readonly nonFiniteIndex?: number },\n ) {\n super('Instances.transforms must contain complete finite matrices');\n this.name = 'InstanceTransformsError';\n }\n}\nexport function validateInstanceTransforms(\n transforms: ArrayLike<number>,\n): InstanceTransformsError | InstanceTransformsStrideMismatchError | undefined {\n if (transforms.length % MATRIX_STRIDE !== 0)\n return new InstanceTransformsStrideMismatchError(transforms.length);\n for (let index = 0; index < transforms.length; index++) {\n if (!Number.isFinite(transforms[index]))\n return new InstanceTransformsError({\n actualLength: transforms.length,\n nonFiniteIndex: index,\n });\n }\n return undefined;\n}\n\n/** A new allocation must receive the complete payload, including after recovery. */\nexport function instanceUploadRangesForResident(\n activeIsNew: boolean,\n dirtyRanges: readonly InstanceDirtyRange[],\n fullRange: InstanceDirtyRange,\n): readonly InstanceDirtyRange[] {\n return activeIsNew ? [fullRange] : dirtyRanges;\n}\n\ninterface Projection extends InstanceCollectionSnapshot {\n readonly world: object;\n readonly entity: number;\n}\ninterface Residency {\n readonly frameNumber: number;\n readonly residentGeneration: number | undefined;\n readonly lane: InstanceSubmissionLane;\n readonly uploadRanges: readonly InstanceDirtyRange[];\n readonly uploadedBytes: number;\n readonly requestedBytes: number;\n readonly supportedBytes: number | undefined;\n readonly backend: InstanceBackendKind;\n readonly error: InstanceCollectionInspection['error'];\n}\n\n/** Rebuildable renderer projection. All authoring and entity lifetime belong to World. */\nexport class InstanceProjectionStore {\n private nextId = 1;\n private nextGeneration = 1;\n private identities = new WeakMap<object, Map<number, InstanceCollectionId>>();\n private readonly records = new Map<InstanceCollectionId, Projection>();\n private readonly residency = new Map<InstanceCollectionId, Residency>();\n\n project(\n world: object,\n entity: number,\n transforms: ArrayLike<number>,\n ): InstanceCollectionSnapshot {\n const collectionId =\n this.identities.get(world)?.get(entity) ?? (this.nextId++ as InstanceCollectionId);\n const previous = this.records.get(collectionId);\n if (\n previous !== undefined &&\n previous.transforms.length === transforms.length &&\n previous.transforms.every((value, index) => Object.is(value, transforms[index]))\n )\n return previous;\n const count = transforms.length / MATRIX_STRIDE;\n // Ordinals are identities within the authored array. Pose edits retain them;\n // resizing seeds topology anew so new instances cannot inherit old motion.\n const generations =\n previous?.count === count\n ? previous.generations\n : Uint32Array.from({ length: count }, () => this.nextGeneration++);\n const record: Projection = {\n collectionId,\n world,\n entity,\n transforms: new Float32Array(transforms),\n generations,\n count,\n revision: (previous?.revision ?? 0) + 1,\n };\n return record;\n }\n\n /** Called only after the owning RenderScene accepts its prepared changes. */\n accept(\n world: object,\n entity: number,\n snapshot: {\n readonly collectionId?: InstanceCollectionId;\n readonly revision?: number;\n readonly transforms: Float32Array;\n readonly generations?: Uint32Array;\n },\n ): void {\n const { collectionId, revision, transforms, generations } = snapshot;\n if (collectionId === undefined || revision === undefined || generations === undefined) return;\n let entities = this.identities.get(world);\n if (entities === undefined) {\n entities = new Map();\n this.identities.set(world, entities);\n }\n entities.set(entity, collectionId);\n this.records.set(collectionId, {\n collectionId,\n revision,\n transforms,\n generations,\n count: transforms.length / MATRIX_STRIDE,\n world,\n entity,\n });\n }\n\n release(world: object, entity: number): void {\n const entities = this.identities.get(world);\n const id = entities?.get(entity);\n if (id === undefined) return;\n entities?.delete(entity);\n this.records.delete(id);\n this.residency.delete(id);\n }\n retain(ids: ReadonlySet<InstanceCollectionId>): void {\n for (const record of this.records.values()) {\n if (!ids.has(record.collectionId)) this.release(record.world, record.entity);\n }\n }\n dispose(): void {\n this.records.clear();\n this.residency.clear();\n this.identities = new WeakMap();\n }\n _resetResidency(): void {\n this.residency.clear();\n }\n\n _reportResidency(\n input: Omit<Residency, 'error' | 'lane'> & {\n readonly collectionId: InstanceCollectionId;\n readonly lane: Exclude<InstanceSubmissionLane, 'unresident' | 'unavailable'>;\n },\n ): void {\n if (!this.records.has(input.collectionId)) return;\n const previous = this.residency.get(input.collectionId);\n const sameFrame = previous?.frameNumber === input.frameNumber && previous.error === undefined;\n const ranges = [...(sameFrame ? previous.uploadRanges : []), ...input.uploadRanges]\n .map((range) => ({ ...range }))\n .sort((a, b) => a.start - b.start);\n const uploadRanges: InstanceDirtyRange[] = [];\n for (const range of ranges) {\n const last = uploadRanges.at(-1);\n if (last !== undefined && range.start <= last.end) last.end = Math.max(last.end, range.end);\n else uploadRanges.push(range);\n }\n this.residency.set(input.collectionId, {\n ...input,\n uploadRanges,\n uploadedBytes: input.uploadedBytes + (sameFrame ? previous.uploadedBytes : 0),\n error: undefined,\n });\n }\n _reportFailure(input: {\n readonly collectionId: InstanceCollectionId;\n readonly code: InstanceCollectionFailureCode;\n readonly expected: string;\n readonly hint: string;\n readonly facts: InstanceCollectionFailureFacts;\n }): void {\n if (!this.records.has(input.collectionId)) return;\n this.residency.set(input.collectionId, {\n frameNumber: -1,\n residentGeneration: undefined,\n lane: 'unavailable',\n uploadRanges: [],\n uploadedBytes: 0,\n requestedBytes: input.facts.requestedBytes,\n supportedBytes: input.facts.supportedBytes,\n backend: input.facts.backend,\n error: {\n code: input.code,\n expected: input.expected,\n hint: input.hint,\n detail: { ...input.facts },\n },\n });\n }\n _inspections(frameNumber: number): readonly InstanceCollectionInspection[] {\n return [...this.records.values()].map((record) => {\n const resident = this.residency.get(record.collectionId);\n const current = resident?.frameNumber === frameNumber;\n return {\n collectionId: record.collectionId,\n count: record.count,\n revision: record.revision,\n residentGeneration: resident?.residentGeneration,\n lane: resident?.lane ?? 'unresident',\n uploadRanges: current ? resident.uploadRanges.map((range) => ({ ...range })) : [],\n uploadedBytes: current ? resident.uploadedBytes : 0,\n requestedBytes: resident?.requestedBytes ?? record.transforms.byteLength,\n supportedBytes: resident?.supportedBytes,\n backend: resident?.backend ?? 'unknown',\n owner: 'renderer.instances',\n error: resident?.error,\n };\n });\n }\n}\n","export const DEFAULT_CONFIGURED_QUERY_BUDGET = 2048;\nexport const MAX_QUERY_BUDGET = 4096;\nexport const VISIBILITY_CANDIDATE_COUNT = 100_000;\nexport const VISIBILITY_OCCLUDED_COUNT = 90_000;\n\nexport interface VisibilityBudget {\n readonly configuredQueryBudget: number;\n readonly effectiveQueryBudget: number;\n readonly oneSweepCandidates: number;\n readonly oneSweepOccluded: number;\n readonly settleSubmits: number;\n readonly retestSubmits: number;\n readonly expirySubmits: number;\n}\n\n/** Derive every renderer visibility window from one bounded query budget. */\nexport function createVisibilityBudget(\n configuredQueryBudget = DEFAULT_CONFIGURED_QUERY_BUDGET,\n): VisibilityBudget {\n if (!Number.isSafeInteger(configuredQueryBudget) || configuredQueryBudget <= 0) {\n throw new RangeError('configuredQueryBudget must be a positive safe integer');\n }\n const effectiveQueryBudget = Math.min(configuredQueryBudget, MAX_QUERY_BUDGET);\n const oneSweepCandidates = oneSweep(VISIBILITY_CANDIDATE_COUNT, effectiveQueryBudget);\n const oneSweepOccluded = oneSweep(VISIBILITY_OCCLUDED_COUNT, effectiveQueryBudget);\n const retestSubmits = Math.max(6, oneSweepOccluded);\n return Object.freeze({\n configuredQueryBudget,\n effectiveQueryBudget,\n oneSweepCandidates,\n oneSweepOccluded,\n settleSubmits: 2 * oneSweepCandidates,\n retestSubmits,\n expirySubmits: Math.max(8, retestSubmits + oneSweepOccluded),\n });\n}\n\nfunction oneSweep(candidateCount: number, effectiveQueryBudget: number): number {\n return Math.ceil(candidateCount / effectiveQueryBudget);\n}\n","import type { AssetRuntimeError } from '@forgeax/engine-assets-runtime';\nimport type { World } from '@forgeax/engine-ecs';\nimport type { RenderReadLease } from '@forgeax/engine-ecs/projection';\nimport type { Vec3 } from '@forgeax/engine-math';\nimport type { ProfileFrameToken, Profiler } from '@forgeax/engine-profiler';\nimport type {\n ColorValueDomain,\n RenderGraphError,\n RenderGraphGenerationAllocationInspection,\n RenderGraphResourceAllocationInspection,\n} from '@forgeax/engine-render-graph';\nimport type {\n BindGroupLayout,\n Buffer,\n Result,\n RhiCanvasSurfacePresentationProof,\n RhiCaps,\n RhiCommandEncoder,\n RhiDevice,\n RhiError,\n RhiInstance,\n RhiRenderPassEncoder,\n RenderPipeline as RhiRenderPipeline,\n Sampler,\n Texture,\n TextureFormat,\n TextureView,\n} from '@forgeax/engine-rhi';\nimport type { SkinError } from '@forgeax/engine-skinning';\nimport type { ImageError } from '@forgeax/engine-types';\nimport type { RhiBackendInstrumentation } from './assembly/backend-contract.js';\nimport type { CloudLayerInspection } from './cloud/inspection.js';\nimport type { BarrelDistortionData } from './components/barrel-distortion.js';\nimport type { Antialias, BloomEnabled, CameraExposure, Tonemap } from './components/camera.js';\nimport type { DynamicResolutionData } from './components/dynamic-resolution.js';\nimport type { ScreenSpaceReflectionData } from './components/screen-space-reflection.js';\nimport type { EnvironmentInspection } from './environment/inspection.js';\nimport type { GpuDrivenPreparationError } from './errors/gpu-driven.js';\nimport type { RecoveryOutcome, RecoveryPhase } from './errors/recover.js';\nimport type { RenderError } from './errors/render.js';\nimport type {\n DepthOfFieldParams,\n DepthOfFieldRequestFailure,\n} from './features/depth-of-field/depth-of-field-params.js';\nimport type { RenderFeature, RenderFeatureDiagnostics } from './features/types.js';\nimport type { PostProcessShaderEntry } from './fullscreen-post-process-pass.js';\nimport type {\n BloomInspection,\n DepthOfFieldInspection,\n DirectionalShadowInspection,\n LightInspection,\n LodOcclusionInspection,\n MotionBlurInspection,\n ReflectionProbeInspection,\n RenderFeatureGraphInspection,\n RenderFeatureHostInspection,\n RenderSceneInspection,\n SsrDependenciesInspection,\n SsrSpatialInspection,\n TemporalTargetInspection,\n TransmissionInspection,\n} from './inspection-types.js';\nimport type { InstanceCollectionInspection } from './instances.js';\nimport type { RenderExtent } from './pipeline/render-extent.js';\nimport type { PublishedRenderFrameInput, RenderPublicationIdentity } from './publication/contract';\nimport type { RenderSceneBounds } from './scene/render-scene-types.js';\nimport type { SsrAdmissionIdentity } from './ssr/identity.js';\nimport type {\n RenderTarget,\n RenderTargetDescriptor,\n RenderTargetReadbackData,\n RenderTargetReadbackRequest,\n RenderTargetReadbackTicket,\n RenderTargetTextureSource,\n RenderTargetTextureSourceOptions,\n} from './targets/contracts.js';\nimport type { TemporalInspection } from './temporal/inspection.js';\n\nexport type { TransmissionInspection } from './inspection-types.js';\nexport type { PointsLinesInspection } from './points-lines/inspection.js';\n\nimport type {\n DynamicGeometryCandidate,\n DynamicGeometryError,\n DynamicGeometryInspection,\n DynamicGeometryOrdering,\n DynamicGeometryPrepareInput,\n DynamicGeometryReceipt,\n} from './dynamic-geometry.js';\nimport type {\n IblBindingInspection,\n MeshMaterialBindingObservation,\n} from './mesh-material-bindings.js';\nimport type { StandardLightingInspection } from './pipeline/standard-lighting/inspection.js';\nimport type { AutoExposureInspection } from './pipeline/standard-output/auto-exposure/inspection.js';\nimport type { StandardLutInspection } from './pipeline/standard-output/lut-state.js';\nimport type { StandardProfile } from './pipeline/standard-profile.js';\nimport type { PointShadowInspection } from './point-shadow-inspection.js';\nimport type { PostProcessError } from './post-process-errors.js';\nimport type {\n GpuPassTimingObservation,\n GpuPassTimingOptions,\n} from './record/gpu-pass-timing/index.js';\nimport type { VolumeTimingObservation } from './record/gpu-timing.js';\nimport type { SurfaceDynamicInputFrame } from './surface/dynamic-input.js';\nimport type { TemporalView } from './temporal/view.js';\nimport type { VolumetricFogInspection } from './volume/inspection.js';\n\nexport type {\n CubeCameraFace,\n CubeCameraUpdateIntent,\n} from './components/cube-camera.js';\n\nexport interface CubeCameraSnapshot {\n readonly entityKey?: number;\n readonly target: RenderTarget;\n readonly position: readonly [number, number, number];\n readonly near: number;\n readonly far: number;\n readonly updateIntent: import('./components/cube-camera').CubeCameraUpdateIntent;\n readonly requestVersion: number;\n readonly faceBudget: number;\n}\n\nexport type RenderResult<T, E> =\n | { readonly ok: true; readonly value: T }\n | { readonly ok: false; readonly error: E };\n\n/** The only World data boundary accepted by the M6 renderer contract. */\nexport type RenderWorldLease = RenderReadLease;\n\n/** Camera-owned color/exposure facts projected once at the frame boundary. */\nexport interface CameraOutputSnapshot {\n readonly exposure: CameraExposure;\n readonly temperature: number;\n readonly tint: number;\n readonly colorLut: number;\n readonly colorLutStrength: number;\n}\n\n/**\n * Camera facts shared by extract, record, and scene owners.\n *\n * The extract stage resolves ECS camera state once and publishes this closed\n * POD contract. Keeping it beside the render lifecycle contracts prevents\n * extract from depending on the record implementation owner.\n */\nexport interface CameraSnapshot {\n /** Stable ECS identity used by the frame plan's camera authority fact. */\n readonly entityKey?: number;\n /** Auxiliary logical target; physical views remain renderer-owned. */\n readonly target?: RenderTarget;\n /** World index supplied by the multi-world extract merge. */\n readonly worldId?: number;\n /** Camera-owned history generation forwarded into the frame plan. */\n readonly historyVersion?: number;\n /** World-space camera translation (mat4.getTranslation of GlobalTransform.world). */\n readonly position: Vec3;\n /** Resolved world-space camera mat4, copied from GlobalTransform.world. */\n readonly world: Float32Array;\n readonly fov: number;\n readonly aspect: number;\n readonly near: number;\n readonly far: number;\n /** Camera projection variant used by view and shadow matrix builders. */\n readonly projection: 'perspective' | 'orthographic';\n readonly orthoLeft: number;\n readonly orthoRight: number;\n readonly orthoBottom: number;\n readonly orthoTop: number;\n readonly tonemap: Tonemap;\n readonly exposure: number;\n readonly whitePoint: number;\n /** Camera schema output projection consumed by Standard prepare/inspection. */\n readonly output?: CameraOutputSnapshot;\n readonly antialias: Antialias;\n /** Optional detached Camera companion for fixed or adaptive scaling. */\n readonly dynamicResolution?: DynamicResolutionData;\n readonly bloom: BloomEnabled;\n readonly bloomThreshold: number;\n readonly bloomIntensity: number;\n readonly bloomSoftKnee: number;\n readonly bloomScatter: number;\n readonly clearColor: readonly [number, number, number, number];\n /** Optional active-camera SSR authoring fact, copied from the ECS schema. */\n readonly screenSpaceReflection?: ScreenSpaceReflectionData;\n /** Renderer-owned temporal projection used by Standard's TAA producer. */\n readonly temporal?: TemporalView;\n /** Active-camera depth-of-field parameters, present only when demanded. */\n readonly depthOfField?: DepthOfFieldParams;\n /** Structured DoF validation facts; invalid requests remain inspectable. */\n readonly depthOfFieldError?: DepthOfFieldRequestFailure;\n /** Active-camera motion blur parameters, present only when demanded. */\n readonly motionBlur?: {\n readonly shutterAngle: number;\n readonly maxRadiusPixels: number;\n readonly sampleCount: number;\n /** Target presentation rate; zero follows the accepted frame interval. */\n readonly targetFps?: number;\n };\n /** Optional active-camera barrel projection, copied from the ECS schema. */\n readonly barrelDistortion?: BarrelDistortionData;\n}\n\n/** Stable identity owned by the Standard feature host for output transform. */\nexport const STANDARD_OUTPUT_TRANSFORM_FEATURE_ID = 'forgeax::standard::output-transform';\n\n/** Stable identity for the special FXAA pass' per-frame output policy UBO. */\nexport const FXAA_POST_PROCESS_ID = 'forgeax::post::fxaa';\n\nexport type {\n EnvironmentFrame,\n EnvironmentSource,\n FogFrame,\n FramePlan,\n} from './extract/environment.js';\nexport type { TemporalView } from './temporal/view.js';\n\n/**\n * Render-graph state exposed to pipeline declarations. Concrete pipeline\n * caches stay in the assembly owner; graph code only needs the two target\n * formats that affect fullscreen descriptors.\n */\ninterface RenderPipelineStateView {\n readonly format: TextureFormat;\n readonly colorAttachmentFormat: TextureFormat;\n /** Renderer-owned View UBO shared by Standard lighting, shadows, and fog. */\n readonly viewUniformBuffer: Buffer;\n /** Fallback resources keep the shared view layout valid when no projector is authored. */\n readonly defaultWhiteTextureView: TextureView;\n readonly defaultSampler: Sampler;\n}\n\n/**\n * Narrow runtime capability consumed by typed graph primitives. The concrete\n * RenderSystemRuntime structurally satisfies this contract, but the public\n * frame surface does not depend on that assembly owner.\n */\ninterface RenderPipelineObservationCapture {\n readonly domain: 'linear-hdr' | 'linear-ldr' | 'final-srgb';\n readonly format: TextureFormat;\n readonly device: RhiDevice;\n readonly texture: Texture;\n readonly buffer: Buffer;\n readonly frameNumber: number;\n readonly deviceGeneration: number;\n readonly graphGeneration: number;\n readonly backendId: string;\n readonly width: number;\n readonly height: number;\n readonly bytesPerRow: number;\n}\n\ninterface RenderPipelineObservationCaptureOwner {\n readonly register: (capture: RenderPipelineObservationCapture) => void;\n readonly consume: (frameNumber: number) => readonly RenderPipelineObservationCapture[];\n readonly drain: () => readonly RenderPipelineObservationCapture[];\n}\n\ninterface RenderPipelineRuntime {\n readonly device: RhiDevice;\n /** Current renderer device generation used to fence graph captures. */\n readonly deviceGeneration?: number | undefined;\n /** Public receipt identity reserved for the frame currently being encoded. */\n readonly observationFrameId?: number | undefined;\n /** Renderer-issued graph fence populated by the graph owner during encoding. */\n observationGraphGeneration?: number | undefined;\n /** Per-renderer bridge for receipt-bound graph color captures. */\n readonly observationCaptureOwner?: RenderPipelineObservationCaptureOwner | undefined;\n /**\n * Domains armed for the frame currently being encoded. An absent or empty\n * set is the normal zero-cost path; typed graph capture passes remain\n * declared for topology inspection but do not allocate or copy anything.\n */\n readonly observationCaptureDomains?: readonly FrameObservationDomain[] | undefined;\n /** Runtime-owned shader module factory used by built-in graph producers. */\n readonly shaderModuleFactory?: {\n createShaderModule(input: {\n readonly code: string;\n readonly label?: string | undefined;\n }): import('@forgeax/engine-types').Result<\n import('@forgeax/engine-rhi').ShaderModule,\n RhiError\n >;\n };\n /** Immediate factory used by same-frame built-in producers after runtime warm-up. */\n readonly immediateShaderModuleFactory?: {\n createShaderModule(input: {\n readonly code: string;\n readonly label?: string | undefined;\n }): import('@forgeax/engine-types').Result<\n import('@forgeax/engine-rhi').ShaderModule,\n RhiError\n >;\n };\n readonly errorRegistry: { fire(error: RendererError): void };\n readonly debugOverlay?: RenderDebugOverlay | undefined;\n readonly lookupPostProcess?: (id: string) => PostProcessShaderEntry | undefined;\n readonly getPostProcessParamsBuffer?: (id: string) => Buffer | undefined;\n readonly getPostProcessPipeline?: (\n id: string,\n bgl: BindGroupLayout,\n colorFormats: readonly GPUTextureFormat[],\n entry?: PostProcessShaderEntry,\n ) => RhiRenderPipeline | null;\n}\n\n/**\n * Render-owned declaration for an app-provided debug overlay. App owns the\n * concrete DebugDraw instance and its GPU lifecycle; Render only records this\n * capability in the typed graph.\n */\nexport interface RenderDebugOverlay {\n encode(\n pass: RhiRenderPassEncoder,\n viewProj: import('@forgeax/engine-math').Mat4,\n ): Result<void, unknown>;\n}\n\n/**\n * The leaf frame context consumed by RenderPipeline and graph primitives.\n * Concrete assembly data is added only by the internal record extension in\n * render-system.ts, so this contract never imports the RenderSystem owner.\n */\nexport interface RenderPipelineContext {\n readonly pipelineState: RenderPipelineStateView;\n readonly runtime: RenderPipelineRuntime;\n readonly encoder: RhiCommandEncoder;\n readonly view: TextureView;\n readonly clear: readonly [number, number, number, number] | number[];\n readonly targetW: number;\n readonly targetH: number;\n /** Renderer-owned output/internal dimensions shared by Standard consumers. */\n readonly extent?: RenderExtent;\n readonly currentTexture: Texture;\n readonly camera: CameraSnapshot;\n /** Per-frame post-process parameter bytes keyed by shader id. */\n readonly postProcessParams: ReadonlyMap<string, Uint8Array>;\n readonly msaaActive: boolean;\n readonly geometryColorResolveView: TextureView | null;\n readonly ldrSpriteColorView: TextureView | null;\n /** Renderer-owned volume resources prepared from the authored ECS snapshot. */\n readonly volumetricFog?: VolumetricFogFrameContext;\n /** Renderer-owned SpotLight projector resources, independent of fog. */\n readonly spotLightProjector?: SpotLightProjectorFrameContext;\n /** Build-time composed utility sources for the renderer-owned volume passes. */\n readonly volumetricFogShaders?: VolumetricFogShaderSources;\n /** Build-time composed utility sources for the renderer-owned SSR passes. */\n readonly ssrShaders?: SsrShaderSources;\n /** Build-time composed utility sources for the renderer-owned atmosphere passes. */\n readonly atmosphereShaders?: AtmosphereShaderSources;\n}\n\n/** Stable utility entry-point sources emitted by the shader manifest. */\nexport interface VolumetricFogShaderSources {\n readonly inject: string;\n readonly temporal: string;\n readonly integrate: string;\n readonly composite: string;\n}\n\n/** Stable utility entry-point sources emitted by the shader manifest. */\nexport interface SsrShaderSources {\n readonly hiz: string;\n readonly hizReduce: string;\n readonly trace: string;\n readonly temporal: string;\n readonly compose: string;\n}\n\n/** Stable analytic-atmosphere entry-point sources emitted by the shader manifest. */\nexport interface AtmosphereShaderSources {\n readonly ibl: string;\n readonly cube: string;\n readonly background: string;\n}\n\n/**\n * GPU resources for one validated volumetric-fog candidate. The record stage\n * owns residency and parameter uploads; graph passes consume this narrow view\n * and never reach into AssetRegistry or World.\n */\nexport interface VolumetricFogFrameContext {\n readonly additional?: readonly {\n readonly densityTexture: Texture;\n readonly densityView: TextureView;\n readonly densityGeneration: number;\n }[];\n readonly densityTexture: Texture;\n readonly densityView: TextureView;\n readonly paramsBuffer: Buffer;\n readonly densityGeneration: number;\n /** Accepted graph-owned history slot; null means first frame/reset. */\n readonly historyReadSlot: 0 | 1 | null;\n /** Pending graph-owned history slot; promoted only after queue.submit succeeds. */\n readonly historyWriteSlot: 0 | 1;\n readonly historyValid: boolean;\n /** Accepted SpotLight projector resources resolved by the GPU residency owner. */\n readonly projectorTexture?: Texture;\n readonly projectorView?: TextureView;\n readonly projectorSampler?: Sampler;\n}\n\n/**\n * GPU resources for the single surface SpotLight projector binding. The\n * projector is a SpotLight-owned cookie and therefore remains available when\n * volumetric fog is disabled; volume integration may reuse the same tuple.\n */\nexport interface SpotLightProjectorFrameContext {\n readonly texture: Texture;\n readonly view: TextureView;\n readonly sampler: Sampler;\n /** Spot-light index in ExtractedLights.spot for the accepted texture. */\n readonly spotIndex?: number;\n /** Unified Standard Cluster slot index (points precede spots). */\n readonly lightSlotIndex?: number;\n}\n\n/**\n * The sole public renderer contract. Consume it in this order:\n * `state()` -> `inspect()` -> `recover()` when degraded -> `draw()` and its\n * `FrameReceipt`. Concrete assembly stays behind the host; callers retain only\n * leases, receipts, inspection PODs, and recovery Result values.\n */\nexport interface Renderer {\n /** Publish one renderer-owned read-only Surface dynamic page for the next frame. */\n setSurfaceDynamicInput(frame: SurfaceDynamicInputFrame | undefined): void;\n attach(world: World): RenderResult<RenderWorldLease, RenderError>;\n /** Prepare a standard MeshAsset for the active device generation. */\n prepareDynamicGeometry(\n input: DynamicGeometryPrepareInput,\n ): Result<DynamicGeometryCandidate, DynamicGeometryError>;\n /** Admit a prepared candidate; publication is tied to the next FrameReceipt. */\n acceptDynamicGeometry(\n candidate: DynamicGeometryCandidate,\n ordering: DynamicGeometryOrdering,\n ): Result<DynamicGeometryCandidate, DynamicGeometryError>;\n /**\n * Atomically swap distinct entities in one attached World. Returned failures\n * retain old bindings; an uncertain rollback throws to require paired rebuild.\n * Invoke inside PhysicsWorld.admitDerivedShapeCandidates commitGeometry.\n */\n acceptDynamicGeometryCandidates(\n candidates: readonly DynamicGeometryCandidate[],\n ordering: DynamicGeometryOrdering,\n ): Result<readonly DynamicGeometryCandidate[], DynamicGeometryError>;\n dynamicGeometryReceipt(candidate: DynamicGeometryCandidate): DynamicGeometryReceipt | undefined;\n cancelDynamicGeometry(candidate: DynamicGeometryCandidate): Result<void, DynamicGeometryError>;\n retireDynamicGeometry(candidate: DynamicGeometryCandidate): Result<void, DynamicGeometryError>;\n draw(\n input: RenderFrameInput | PublishedRenderFrameInput,\n ): RenderResult<FrameReceipt, RenderError>;\n /**\n * Arm one upcoming submitted frame for explicit color-domain observation.\n * Observation buffers are not created, copied, mapped, or retained until a\n * host calls this method before `draw()`. The demand is consumed only by a\n * successful submit; a failed frame keeps it armed for a retry.\n *\n * This optional extension keeps older injected Renderer test doubles source\n * compatible while concrete Engine renderers always implement it.\n */\n requestObservation?: (\n domains: readonly FrameObservationDomain[],\n ) => RenderResult<void, RenderError>;\n createRenderTarget(descriptor: RenderTargetDescriptor): RenderResult<RenderTarget, RenderError>;\n resizeRenderTarget(\n target: RenderTarget,\n descriptor: RenderTargetDescriptor,\n ): RenderResult<void, RenderError>;\n createRenderTargetTextureSource(\n target: RenderTarget,\n options: RenderTargetTextureSourceOptions,\n ): RenderResult<RenderTargetTextureSource, RenderError>;\n requestTargetReadback(\n target: RenderTarget,\n request: RenderTargetReadbackRequest,\n ): RenderResult<RenderTargetReadbackTicket, RenderError>;\n destroyRenderTarget(target: RenderTarget): RenderResult<void, RenderError>;\n setProfile(profile: RenderProfile): RenderResult<void, RenderError>;\n state(): RendererState;\n /** Detached world bounds for one record in the last extracted World; undefined if unavailable. */\n bounds(world: World, entity: number): RenderSceneBounds | undefined;\n inspect(): RenderInspection;\n observe(\n receipt: FrameReceipt,\n request: FrameObservationRequest,\n ): Promise<RenderResult<FrameReceiptObservation, RenderError>>;\n subscribe(listener: (event: RendererEvent) => void): () => void;\n releaseSurface(): RenderResult<void, RenderError>;\n restoreSurface(): RenderResult<void, RenderError>;\n /** Recover only from device-lost; a healthy renderer returns a guard error. */\n recover(): Promise<RenderResult<void, RenderError>>;\n dispose(): Promise<RenderResult<void, RenderError>>;\n}\n\n/**\n * The single public renderer lifecycle authority. This closed union is the\n * frame gate: only `alive` admits World update and draw; `device-lost` and\n * `recovering` are explicit recovery states; `faulted` requires recreation;\n * `disposed` is terminal.\n */\nexport type RendererState = 'alive' | 'device-lost' | 'recovering' | 'faulted' | 'disposed';\n\n/** Immutable, inspectable quality and budget policy for the Standard pipeline. */\nexport type RenderProfile = StandardProfile;\n\n/** Ordered events projected from renderer state and expected-operation failures. */\nexport type RendererEvent =\n | {\n readonly kind: 'state-changed';\n readonly previous: RendererState;\n readonly current: RendererState;\n }\n | { readonly kind: 'error'; readonly error: RenderError }\n /** Emitted only after the renderer's sole submit path returns a receipt. */\n | {\n readonly kind: 'frame-submitted';\n readonly frameId: number;\n readonly deviceGeneration: number;\n /** Compiled graph identity paired with the submitted picture. */\n readonly graphGeneration?: number;\n /** The exact draw receipt, for observation when App owns the draw loop. */\n readonly receipt: FrameReceipt;\n };\n\n/** Package-local listener alias used by the renderer assembly implementation. */\nexport type RendererEventListener = (event: RendererEvent) => void;\n\n/**\n * Camera authority supplied for one frame; Render owns the lease contract and\n * the host releases it with the frame lifecycle. It is intentionally bound to\n * the attached scene lease and never accepts a backend object.\n */\nexport interface FrameCamera {\n readonly lease: RenderWorldLease;\n readonly entityKey?: number;\n}\n\n/**\n * Environment authority supplied for one frame. The scene/environment owner\n * supplies the identity; the host validates it against the attached lease.\n */\nexport interface FrameEnvironment {\n readonly lease: RenderWorldLease;\n readonly identity?: string;\n}\n\n/**\n * Receipt-bound observation selection. The request is consumed by `observe`\n * only with the matching FrameReceipt after `receipt.completed` and returns a\n * structured Result error when the generation or frame identity is stale.\n */\nexport type FrameObservationDomain = 'linear-hdr' | 'linear-ldr' | 'final-srgb';\n\nexport type FrameObservationInclude =\n | 'timings'\n | 'draws'\n | 'bindings'\n | 'target-readbacks'\n | FrameObservationDomain;\n\nexport interface FrameObservationRequest {\n readonly include: readonly FrameObservationInclude[];\n readonly targetReadbacks?: readonly RenderTargetReadbackTicket[];\n}\n\n/**\n * Immutable synchronous proof that the sole host-owned submit reached the\n * queue. It is the only successful synchronous draw signal. Its\n * `deviceGeneration` fences stale work, and every observation request must use\n * this exact receipt; a recovery retry must obtain a new one.\n */\nexport interface FrameReceipt {\n readonly frameId: number;\n readonly deviceGeneration: number;\n /** Whether this frame can present the active scene without a readiness fallback. */\n readonly presentation: FramePresentation;\n /** Backend identity captured at submit and checked before observation. */\n readonly backendId?: RhiCaps['backendKind'];\n /** Monotonic compiled graph identity used by renderer-issued observations. */\n readonly graphGeneration?: number;\n /**\n * Effective output mapping for the submitted camera, including identity\n * when this receipt has an accepted camera context. `undefined` means that\n * no submitted display context is available; consumers must fail closed and\n * must not infer identity or read the live World camera.\n */\n readonly barrelDistortion?: import('./barrel-distortion.js').BarrelDistortionMapping;\n readonly completed: Promise<RenderResult<void, RenderError>>;\n}\n\n/** Producer-derived presentation readiness for one submitted frame. */\nexport type FramePresentation = 'pending' | 'ready';\n\n/**\n * The sole public draw input; World objects never cross this boundary. Render\n * owns extraction and graph interpretation, while the host owns encoding,\n * finish, submit, and recovery of the attached lease generation.\n */\nexport interface RenderFrameInput {\n readonly leases: readonly RenderWorldLease[];\n readonly camera: FrameCamera;\n readonly environment: FrameEnvironment;\n /**\n * Monotonic host render-sample time in seconds. This is captured before ECS\n * applies its simulation delta clamp, then accepted with frame submission.\n * Omitting it keeps direct renderer callers on the ECS-clock fallback.\n */\n readonly sampleTimeSeconds?: number;\n /**\n * Mark the next submitted frame as a fresh temporal baseline. App sets this\n * on resume so a short wall-clock pause cannot be mistaken for a valid\n * motion pair; direct replay callers may use the same explicit lifecycle\n * boundary.\n */\n readonly temporalReset?: boolean;\n /** Fixed-step publication consumed by dynamic geometry candidates. */\n readonly fixedStep?: number;\n /** Optional profiler correlation token owned by App and consumed by Render. */\n readonly profileFrame?: ProfileFrameToken;\n /**\n * Select the geometry submission command lane while retaining the same\n * extracted scene and material inputs. This is an acceptance/debug seam;\n * both lanes remain subject to the ordinary resource and generation gates.\n */\n readonly geometryLane?: 'automatic' | 'direct';\n}\n\n/** Detached, bounded observation metadata tied to one FrameReceipt and request. */\nexport interface FrameReceiptObservation {\n readonly frameId: number;\n readonly deviceGeneration: number;\n readonly include: readonly FrameObservationInclude[];\n /** Receipt-bound Render-owned GPU pass facts; absent when not requested. */\n readonly timings?: GpuPassTimingObservation | undefined;\n /** Receipt-bound volume GPU timing facts; absent when not requested. */\n readonly volumeTimings?: VolumeTimingObservation | undefined;\n readonly targetReadbacks?: readonly RenderTargetReadbackData[];\n /** Independent raw bytes captured from the requested linear/display domains. */\n readonly observations?: readonly FrameDomainObservation[] | undefined;\n}\n\nexport interface FrameDomainObservation {\n readonly domain: FrameObservationDomain;\n readonly bytes: Uint8Array;\n readonly metadata: {\n readonly frameId: number;\n readonly deviceGeneration: number;\n readonly backendId?: RhiCaps['backendKind'];\n /** Native texture format of the copied attachment, including BGRA order. */\n readonly format: TextureFormat;\n readonly graphGeneration: number;\n readonly textureIdentity: number;\n readonly readbackIdentity: number;\n readonly width: number;\n readonly height: number;\n readonly bytesPerRow: number;\n readonly footprint: {\n readonly resourceCount: number;\n readonly bindGroupCount: number;\n };\n };\n}\n\n/** Stable backend facts for the Standard output transform projection. */\nexport interface RenderOutputInspection {\n /** Camera-owned auto-exposure facts, detached from GPU state when available. */\n readonly autoExposure?: AutoExposureInspection;\n /** Renderer-owned detached LUT residency and receipt facts. */\n readonly standardLut?: StandardLutInspection;\n readonly outputTransform?: typeof STANDARD_OUTPUT_TRANSFORM_FEATURE_ID;\n readonly displayEncoded: boolean;\n readonly intermediateFormat?: TextureFormat;\n /** Concrete surface route committed by configureSurface. */\n readonly surfaceProfile?: 'dual-view' | 'raw-only';\n /** Pass names from the same committed graph as the output facts. */\n readonly graphPassNames: readonly string[];\n /** Detached descriptor for the graph-owned output target, when present. */\n readonly standardOutputColor?: RenderStandardOutputColorInspection;\n readonly surfaceStorage: TextureFormat;\n readonly surfaceDisplay: TextureFormat;\n readonly endpoint: 'surface.storage.raw';\n readonly capability: 'rgba16float-renderable' | 'surface-raw-endpoint' | 'unavailable';\n readonly presentationProof?: RhiCanvasSurfacePresentationProof;\n readonly error:\n | {\n readonly code: string;\n readonly expected: string;\n readonly hint: string;\n readonly detail?: unknown;\n }\n | undefined;\n}\n\n/** Detached descriptor for the graph-owned display-encoded intermediate. */\nexport interface RenderStandardOutputColorInspection {\n readonly format: TextureFormat;\n readonly domain?: ColorValueDomain;\n readonly width: number;\n readonly height: number;\n readonly sampleCount: number;\n readonly usage: number;\n}\n\n/** Stable identity refs for a renderer-owned frame observation. */\nexport interface RenderObservationInspection {\n readonly observationId: string;\n readonly frameId: number;\n /** Camera antialias mode used by the frame carrying this observation. */\n readonly antialias?: Antialias;\n /** Surface route committed for the same frame graph. */\n readonly surfaceProfile?: 'dual-view' | 'raw-only';\n /** Capability fact used when resolving a raw-only float target. */\n readonly rgba16floatRenderable?: boolean;\n /** Exact pass names and target descriptor from the committed graph. */\n readonly passNames: readonly string[];\n readonly standardOutputColor?: RenderStandardOutputColorInspection;\n /** Monotonic, renderer-owned observation resource facts; no GPU handles. */\n readonly resourceStats?: {\n readonly allocationCount: number;\n readonly liveCount: number;\n readonly peakLiveCount: number;\n readonly mapCount: number;\n readonly readbackCount: number;\n readonly liveByteLength: number;\n };\n}\n\n/**\n * Detached renderer facts for host diagnostics and capability selection.\n *\n * The snapshot contains only POD values. It never exposes a device, queue,\n * registry, encoder, or live renderer-owned collection. Read `state` and the\n * bounded `recovery` detail before choosing to wait, retry, repair an owner,\n * or recreate the Renderer; this projection is not a proof of Browser/Dawn\n * execution.\n */\nexport interface RenderInspection {\n readonly state: RendererState;\n /** Bounded detached facts for the current or last recovery attempt. */\n readonly recovery: {\n readonly phase: RecoveryPhase | null;\n readonly fromGeneration: number;\n readonly candidateGeneration: number;\n readonly attempt: number;\n readonly elapsedMs: number;\n readonly lastOutcome: RecoveryOutcome;\n readonly failedOwner?: string;\n readonly failedResourceKind?: string;\n readonly rehydratedRoots: number;\n readonly staleLossEvents: number;\n };\n readonly surface: 'available' | 'released';\n readonly profile: RenderProfile;\n readonly capabilities: Readonly<RhiCaps>;\n readonly frame: {\n readonly frameId: number;\n readonly deviceGeneration: number;\n };\n /** Effective output mapping and accepted/LKG identity for the last picture. */\n readonly barrelDistortion: import('./inspection-types').BarrelDistortionInspection;\n /** Renderer-owned authored volume projection and submit/LKG state. */\n readonly volumetricFog?: VolumetricFogInspection;\n /** Renderer-owned procedural cloud projection from the latest resource-owner extract. */\n readonly cloudLayer?: CloudLayerInspection;\n readonly features: readonly string[];\n /** Truthful lifecycle facts for every registered declarative feature. */\n readonly featureDiagnostics: readonly RenderFeatureDiagnostics[];\n /** Detached signature and prepared-resource counters for feature planning. */\n readonly featureHost?: RenderFeatureHostInspection;\n /** Detached typed-graph compile/reuse and candidate lifecycle counters. */\n readonly featureGraph?: RenderFeatureGraphInspection;\n /** Detached material texture-source probe counters from the last extract. */\n readonly materialTextureSources?: import('./inspection-types').MaterialTextureSourceInspection;\n readonly frustumStats: { readonly culled: number; readonly total: number };\n readonly visibilityStats: { readonly explicitlyHidden: number };\n /** Renderer-owned large-instance residency and upload facts. */\n readonly instanceCollections: readonly InstanceCollectionInspection[];\n /** Standard MeshAsset dynamic-candidate lifecycle facts. */\n readonly dynamicGeometry?: DynamicGeometryInspection;\n readonly renderScene: RenderSceneInspection;\n /** Detached logical allocation facts for graph-created render targets. */\n readonly renderGraphResourceAllocation?: RenderGraphResourceAllocationInspection;\n /** Detached logical allocation facts across graph generations. */\n readonly renderGraphGenerationAllocation?: RenderGraphGenerationAllocationInspection;\n readonly reflectionProbes: ReflectionProbeInspection;\n /** Renderer-owned SSR dependency seam; consumer facts are projected from live owners. */\n readonly ssrDependencies: SsrDependenciesInspection;\n /** Renderer-owned SSR spatial status and bounded execution facts. */\n readonly ssr: SsrSpatialInspection;\n /** Last completed transmission candidate facts, detached from GPU handles. */\n readonly transmission?: TransmissionInspection;\n /** Last prepared Standard transport facts, detached from GPU handles. */\n readonly standardLighting?: StandardLightingInspection;\n /** Renderer-owned point-shadow atlas budget facts from the last frame. */\n readonly pointShadow?: PointShadowInspection;\n readonly meshMaterialBindings: readonly MeshMaterialBindingObservation[];\n /** Final-submit Standard IBL binding-chain receipt, when diagnostics ran. */\n readonly iblBinding?: IblBindingInspection;\n readonly perFramePassNames: readonly string[];\n readonly bindGroupCounts: {\n readonly createBindGroup: number;\n readonly keys: readonly string[];\n };\n /**\n * Recovery evidence projected from production owners. Graph, residency,\n * submit, and receipt fields are observations, not recovery test fixtures.\n */\n readonly recoveryEvidence: {\n readonly producerRoots: readonly {\n readonly kind: string;\n readonly owner: string;\n readonly candidateScope: 'device-scope';\n readonly visibility: 'visible-workset' | 'non-visible-lazy';\n readonly disabledWork: 'zero' | 'lazy';\n }[];\n readonly graph: {\n readonly ready: boolean;\n readonly generation: number;\n readonly passCount: number;\n readonly resourceCount: number;\n };\n readonly residency: { readonly meshResidencyEpoch: number };\n readonly submissions: {\n readonly count: number;\n readonly lastGeneration: number | undefined;\n };\n readonly receipts: {\n readonly count: number;\n readonly lastGeneration: number | undefined;\n };\n };\n /**\n * Output-transform facts from the same committed graph and physical surface.\n * Keep this as one named subtree so AI consumers do not have to guess which\n * detached fields belong to the output contract versus renderer lifecycle.\n */\n readonly output: RenderOutputInspection;\n readonly observation: RenderObservationInspection;\n readonly environment: EnvironmentInspection;\n readonly temporal: TemporalInspection;\n readonly bloom: BloomInspection;\n /** Candidate/accepted/LKG facts for the single extendedLighting topology. */\n readonly extendedLighting: LightInspection;\n readonly directionalShadow: DirectionalShadowInspection;\n /** Semantic Standard temporal target metadata; no graph or RHI handles. */\n readonly temporalTarget?: TemporalTargetInspection;\n /** Renderer-owned Motion Blur facts; absent when no component is active. */\n readonly motionBlur?: MotionBlurInspection;\n /** Renderer-owned Depth of Field facts; absent when no component is active. */\n readonly depthOfField?: DepthOfFieldInspection;\n /** Bounded renderer-owned LOD/occlusion facts; absent before a candidate frame. */\n readonly lodOcclusion?: LodOcclusionInspection;\n}\n\n/** Backend marker — single-element union preserved for future extensibility (D-2). */\n/**\n * `renderer.draw(worlds, options)` owner options\n * (feat-20260709-editor-world-partition M1 / w6, plan-strategy §2 D-3).\n *\n * The single `owner` index that previously served BOTH the surfaced cameras\n * and the singleton render resources (skylight / skybox / postProcessParams) is\n * split into two independent indices:\n * - `cameraOwner` — the world whose cameras are surfaced.\n * - `resourceOwner` — the world whose skylight / skybox / postProcessParams\n * are surfaced.\n *\n * Both owners are always explicit. Single-world callers pass zero for both;\n * composite callers may select different worlds.\n */\nexport type DrawOwnerOptions = {\n readonly cameraOwner: number;\n readonly resourceOwner: number;\n /** Optional FrameCamera entity selection; absent preserves ActiveCamera semantics. */\n readonly cameraEntityKey?: number;\n /** Monotonic host render-sample time in seconds, before the ECS delta clamp. */\n readonly sampleTimeSeconds?: number;\n /** Explicit pause/resume or replay lifecycle boundary for temporal owners. */\n readonly temporalReset?: boolean;\n readonly profileFrame?: ProfileFrameToken;\n readonly geometryLane?: 'automatic' | 'direct';\n};\n\n/** Information attached to a device-loss notification. */\nexport interface RendererLostInfo {\n /** Concise machine-readable cause, mapped to a single vocabulary. */\n reason: string;\n /** Free-form description (UA / extension / driver text). */\n message: string;\n}\n\n/** Listener registered through `Renderer.onLost`. */\nexport type RendererLostListener = (info: RendererLostInfo) => void;\n\n/**\n * Composite error type retained for package-local renderer diagnostics. The\n * public Renderer projects expected operation failures through the single\n * `subscribe` event stream and its `error` event; this type does NOT define a\n * error; it only references the cluster unions whose members can arrive here.\n * As such it is an external wire alias (AGENTS.md Change stance add-only wire\n * exception), NOT the eliminated cross-cluster `RuntimeError` SSOT (D-3).\n *\n * Composition = `RhiError | RenderError | AssetRuntimeError | SkinError |\n * GpuDrivenPreparationError | PostProcessError`. The GPU preparation arm is\n * the renderer-owned producer contract: its closed `code` and typed `detail`\n * identify the material, geometry, skin, generation, or shadow owner without making\n * RHI errors carry render policy. `RecoverError` and `EngineEnvironmentError`\n * are intentionally excluded — neither is ever emitted through the Renderer\n * event stream (`RecoverError` returns from `recover()`,\n * `EngineEnvironmentError` throws at construction).\n *\n * AI consumers do `switch (err.code)` over the union: the disjoint\n * `RhiErrorCode` / `RenderErrorCode` / `AssetRuntimeErrorCode` / `SkinErrorCode`\n * / `GpuDrivenPreparationErrorCode` / `PostProcessErrorCode` literal sets let\n * TS narrow each arm to the concrete\n * class (charter P3 union discoverability — every fan-out member is reachable\n * in an exhaustive switch, no untyped escape). Example:\n *\n * ```ts\n * renderer.subscribe((event) => {\n * if (event.kind !== 'error') return;\n * switch (event.error.code) {\n * case 'asset-not-registered': // AssetRuntimeError arm, err narrowed here\n * return report(err.hint);\n * // ...one arm per RhiErrorCode | RenderErrorCode | AssetRuntimeErrorCode\n * // | SkinErrorCode | GpuDrivenPreparationErrorCode |\n * // PostProcessErrorCode member; no default needed,\n * // TS flags every unhandled code at compile time.\n * }\n * });\n * ```\n */\nexport type RendererError =\n | RhiError\n | RenderGraphError\n | ImageError\n | RenderError\n | GpuDrivenPreparationError\n | AssetRuntimeError\n | SkinError\n | PostProcessError;\n\n/**\n * Package-local error listener retained for host assembly. Public consumers\n * use `Renderer.subscribe` and receive `RendererEvent` instead.\n */\nexport type RendererErrorListener = (error: RendererError) => void;\n\n/**\n * Built-in graph pass owners used as nested children of `record/graph-execute`.\n * Unknown extension pass names use the explicit `other` bucket so custom\n * pipelines retain a bounded catalog while the default render workload gets\n * actionable owner attribution.\n */\nexport const RENDER_GRAPH_EXECUTION_PHASE_CATALOG = [\n 'record/graph-execute/point-shadow',\n 'record/graph-execute/cluster-binner-upload',\n 'record/graph-execute/g-buffer',\n 'record/graph-execute/g-buffer/geometry-loop',\n 'record/graph-execute/g-buffer/material-bind-groups',\n 'record/graph-execute/g-buffer/pipeline-selection',\n 'record/graph-execute/g-buffer/draw-submit',\n 'record/graph-execute/ssao-calc',\n 'record/graph-execute/ssao-blur',\n 'record/graph-execute/lighting',\n 'record/graph-execute/forward',\n 'record/graph-execute/forward/geometry-loop',\n 'record/graph-execute/forward/material-bind-groups',\n 'record/graph-execute/forward/pipeline-selection',\n 'record/graph-execute/forward/draw-submit',\n 'record/graph-execute/output-transform',\n 'record/graph-execute/present',\n 'record/graph-execute/debug-overlay',\n 'record/graph-execute/shadow',\n 'record/graph-execute/spot-shadow',\n 'record/graph-execute/skybox',\n 'record/graph-execute/main',\n 'record/graph-execute/fxaa',\n 'record/graph-execute/bloom-downsample',\n 'record/graph-execute/bloom-upsample',\n 'record/graph-execute/bloom-composite',\n 'record/graph-execute/ssr-hiz',\n 'record/graph-execute/ssr-trace',\n 'record/graph-execute/ssr-temporal',\n 'record/graph-execute/ssr-reflection-mip',\n 'record/graph-execute/ssr-compose',\n 'record/graph-execute/other',\n] as const;\n\nexport type RenderGraphExecutionPhase = (typeof RENDER_GRAPH_EXECUTION_PHASE_CATALOG)[number];\n\n/** Bounded producer-owned children of the scene-state record owner. */\nexport const RENDER_HDRP_BINNER_PHASE_CATALOG = [\n 'record/scene-state/hdrp-cluster/binner/light-bounds-and-occupancy',\n 'record/scene-state/hdrp-cluster/binner/light-bounds-and-occupancy/light-aabb',\n 'record/scene-state/hdrp-cluster/binner/light-bounds-and-occupancy/cluster-occupancy',\n 'record/scene-state/hdrp-cluster/binner/cluster-reserve',\n 'record/scene-state/hdrp-cluster/binner/input-preparation',\n 'record/scene-state/hdrp-cluster/binner/bin-core',\n 'record/scene-state/hdrp-cluster/binner/light-index-write',\n 'record/scene-state/hdrp-cluster/binner/light-index-write/bounds-read',\n 'record/scene-state/hdrp-cluster/binner/light-index-write/cluster-write',\n] as const;\n\nexport const RENDER_HDRP_CLUSTER_PHASE_CATALOG = [\n 'record/scene-state/hdrp-cluster/binner',\n ...RENDER_HDRP_BINNER_PHASE_CATALOG,\n 'record/scene-state/hdrp-cluster/payload-packing',\n 'record/scene-state/hdrp-cluster/buffer-upload',\n] as const;\n\nexport type RenderHdrpClusterPhase = (typeof RENDER_HDRP_CLUSTER_PHASE_CATALOG)[number];\n\nexport const RENDER_SCENE_STATE_PHASE_CATALOG = [\n 'record/scene-state/fold-buckets',\n 'record/scene-state/lighting-prep',\n 'record/scene-state/ambient-resolution',\n 'record/scene-state/directional-shadow-cache',\n 'record/scene-state/hdrp-cluster',\n ...RENDER_HDRP_CLUSTER_PHASE_CATALOG,\n] as const;\n\n/**\n * Opt-in boundaries inside one `Renderer.draw` call. The observer is a\n * diagnostics seam only: it receives wall-time boundaries and must never be\n * required for rendering correctness. The stage names mirror the existing\n * engine-owned Extract / Prepare / Record orchestration so a host can measure\n * attribution without guessing from RHI command counts.\n */\nexport const RENDER_RECORD_PHASE_CATALOG = [\n 'record/occlusion-query-submit',\n 'record/occlusion-global-advance',\n 'record/scene-state',\n ...RENDER_SCENE_STATE_PHASE_CATALOG,\n 'record/swapchain',\n 'record/render-graph',\n 'record/target-views',\n 'record/validation',\n 'record/dispatch-plan',\n 'record/uploads',\n 'record/bind-groups',\n 'record/graph-execute',\n ...RENDER_GRAPH_EXECUTION_PHASE_CATALOG,\n] as const;\n\nexport type RenderRecordPhase = (typeof RENDER_RECORD_PHASE_CATALOG)[number];\n\nexport const RENDER_PHASE_CATALOG = [\n 'extract',\n 'occlusion-prepare',\n 'bind-groups',\n 'features',\n 'sort',\n 'record',\n ...RENDER_RECORD_PHASE_CATALOG,\n] as const;\n\nexport type RenderPhase = (typeof RENDER_PHASE_CATALOG)[number];\n\nexport type RenderPhaseSkipReason =\n | 'feature-host-unavailable'\n | 'feature-host-empty'\n | 'pipeline-state-unavailable'\n | 'camera-unavailable';\n\n/** First-version options bag (intentionally empty; reserved for v0.1). */\nexport interface RendererOptions {\n /** Bind a source session before receiving any publication. */\n readonly publicationSource?: RenderPublicationIdentity;\n /** Producer-owned features installed by the renderer host. */\n readonly features?: readonly RenderFeature<unknown>[] | undefined;\n /** Standard profile consumed by the single renderer-owned pipeline. */\n readonly standardProfile?: RenderProfile | undefined;\n /** Explicit profiler capability shared by App and Render. */\n readonly profiler?: Profiler | undefined;\n /** Explicitly request timestamp-query for receipt-bound GPU profiling. */\n readonly captureGpuTimings?: boolean | undefined;\n /** Opt into full-frame reflection fallback pixel readback and hashing for diagnostics. */\n readonly captureReflectionFallbackReadback?: boolean | undefined;\n /** Optional host-owned RHI lifecycle instrumentation, such as recording. */\n readonly rhiInstrumentation?: RhiBackendInstrumentation | undefined;\n /** Optional bounded GPU pass timing facts; this is not frame latency. */\n readonly gpuPassTiming?: GpuPassTimingOptions | undefined;\n /**\n * Exact source/tree/lock/build identity binding for the renderer-owned SSR seam.\n * Opts into one format-capability probe during device-generation initialization;\n * camera ScreenSpaceReflection still controls all per-frame SSR work.\n */\n readonly ssrIdentity?: SsrAdmissionIdentity | undefined;\n // feat-20260608-create-app-param-surface-trim / M1 / AC-02: `clearColor`\n // was deleted as a one-cut breaking change (AGENTS.md Change stance +\n // requirements constraint #1: no deprecation window, no shim). Scene\n // clear color now lives on the Camera entity (`clearColor`, an inline\n // array<f32,4> column as of feat-20260709 M3); zero-Camera fallback uses\n // `ZERO_CAMERA_CLEAR_FALLBACK = [0, 0, 0, 1]` from\n // `render-system-record`. AI users that pass `{ clearColor: [...] }` on\n // RendererOptions still get a TS2353 excess-property error at compile time.\n //\n // feat-20260608-create-app-param-surface-trim / M2 / AC-06 + D-3:\n // `shaderManifestUrl` was deleted from RendererOptions and moved to\n // the third-arg `BundlerOptions` (build-tool injection channel). The\n // fallback literal '/shaders/manifest.json' stays at the createRenderer\n // body site (D-2 q5-A) so the LO 1.1 zero-config takeoff path keeps\n // working without explicit injection. AI users that pass\n // `{ shaderManifestUrl: '...' }` to RendererOptions get a TS2353\n // excess-property error at compile time pointing them to the third\n // arg (charter P1 progressive disclosure -- the message names\n // BundlerOptions, not a free-form string).\n /**\n * M3 D-P4 escape hatch (feat-20260511-rhi-wgpu-impl): explicit\n * `RhiInstance` injection bypasses the dynamic-import auto-select\n * facade. When set, `createRenderer` uses this instance verbatim and\n * neither concrete backend adapter is imported dynamically (charter\n * proposition 5 discoverable opt-in /\n * plan-strategy §6 M3 + §7.4 escape hatch + Bevy\n * `RenderCreation::Manual` partial equivalent).\n *\n * Typical use cases:\n * - Testing / debugging — inject a deterministic stub.\n * - Pinning a specific backend even when the browser adapter is present,\n * for cross-shim regression tests.\n * - Advanced AI users implementing their own `RhiInstance` shim.\n *\n * AI users who want the default behaviour leave this field omitted;\n * `navigator.gpu` presence/absence drives the dynamic import (see the\n * `createRenderer` JSDoc for the full auto-select decision tree).\n */\n readonly rhi?: RhiInstance | undefined;\n}\n\n// ────────────────────────────────────────────────────────────────────────────\n// Renderer health / recover surface (feat-20260621-renderer-health-recover-skeleton M1)\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Closed union of renderer health states.\n *\n * 3 members per plan-strategy D-1:\n * - `'alive'` — healthy baseline (registry not yet fired)\n * - `'device-lost'` — device loss detected\n * - `'internal-fault'` — internal renderer fault\n *\n * AI users exhaustively switch on `HealthReason` without default; TS guards\n * completeness.\n */\nexport type HealthReason = 'alive' | 'device-lost' | 'internal-fault';\n\n/** Detail for `HealthReason 'device-lost'`. */\nexport interface HealthDetailDeviceLost {\n readonly lostReason: 'unknown' | 'destroyed';\n readonly message: string;\n}\n\n/** Detail for `HealthReason 'internal-fault'`. */\nexport interface HealthDetailInternalFault {\n readonly message: string;\n}\n\n/**\n * Pull-style health snapshot — discriminated union by `reason`.\n *\n * Per plan-strategy D-2: `switch(snap.reason)` narrows `snap.detail` to the\n * per-reason detail type automatically, with zero `as` casts. `alive` has no\n * `.detail` field; `device-lost` / `internal-fault` have a required `.detail`\n * of the respective variant.\n *\n * - `recoverable` — explicit snapshot data owned by the lifecycle authority\n */\nexport type HealthSnapshot =\n | { readonly reason: 'alive'; readonly recoverable: boolean }\n | {\n readonly reason: 'device-lost';\n readonly detail: HealthDetailDeviceLost;\n readonly recoverable: boolean;\n }\n | {\n readonly reason: 'internal-fault';\n readonly detail: HealthDetailInternalFault;\n readonly recoverable: boolean;\n };\n\n/**\n * Maps `HealthReason` to recoverable boolean per the derive table\n * (requirements section \"range\"):\n *\n * | reason | recoverable |\n * |:---------------|:-----------|\n * | `'alive'` | false |\n * | `'device-lost'`| true |\n * | `'internal-fault'` | false |\n */\n/** Callback type for `Renderer.onHealthChange`. */\nexport type HealthChangeListener = (snapshot: HealthSnapshot) => void;\n","import type { TextureView } from '@forgeax/engine-rhi';\nimport type { RenderError } from '../errors/render';\nimport {\n RenderTargetDescriptorInvalidError,\n RenderTargetStateInvalidError,\n} from '../errors/render';\nimport type { RenderResult } from '../render-contract';\nimport type {\n RenderTarget,\n RenderTargetDescriptor,\n RenderTargetTextureSource,\n RenderTargetTextureSourceOptions,\n} from './contracts';\n\nexport interface RenderTargetMaterialSourceView {\n readonly dimension: RenderTargetTextureSourceOptions['dimension'];\n readonly mipLevel: number;\n readonly resolveRequired: boolean;\n}\n\nexport interface RenderTargetMaterialSourceBinding {\n readonly source: RenderTargetTextureSource;\n readonly target: RenderTarget;\n readonly generation: number;\n readonly shape: RenderTargetDescriptor['shape'];\n readonly format: RenderTargetDescriptor['format'];\n readonly view: RenderTargetMaterialSourceView;\n /** Renderer-local physical view, present only for the active generation. */\n readonly textureView?: TextureView;\n}\n\nexport interface RenderTargetMaterialSourceExpectation {\n readonly target: RenderTarget;\n readonly generation: number;\n readonly shape: RenderTargetDescriptor['shape'];\n readonly format: RenderTargetDescriptor['format'];\n readonly dimension: RenderTargetTextureSourceOptions['dimension'];\n readonly mipLevel: number;\n}\n\nconst sourceBindings = new WeakMap<object, RenderTargetMaterialSourceBinding>();\nconst targetIdentities = new WeakMap<object, number>();\nlet nextTargetIdentity = 1;\n\nfunction targetIdentity(target: RenderTarget): number {\n const object = target as object;\n const existing = targetIdentities.get(object);\n if (existing !== undefined) return existing;\n const identity = nextTargetIdentity;\n nextTargetIdentity += 1;\n targetIdentities.set(object, identity);\n return identity;\n}\n\nfunction sourceToken(): RenderTargetTextureSource {\n return Object.freeze({}) as RenderTargetTextureSource;\n}\n\n/** Resolve a source only inside the renderer-owned material projection. */\nexport function resolveRenderTargetMaterialSource(\n source: RenderTargetTextureSource,\n): RenderTargetMaterialSourceBinding | undefined {\n return sourceBindings.get(source as object);\n}\n\n/**\n * Returns the stable renderer-local resource identity used by batch grouping.\n * The opaque source object is intentionally not stringified: target identity,\n * device generation, and view subresource are the producer-owned facts that\n * determine whether two draws may share one material bind group.\n */\nexport function renderTargetMaterialSourceIdentity(\n source: RenderTargetTextureSource,\n): string | undefined {\n const binding = resolveRenderTargetMaterialSource(source);\n if (binding === undefined) return undefined;\n return [\n targetIdentity(binding.target),\n binding.generation,\n binding.shape,\n binding.format,\n binding.view.dimension,\n binding.view.mipLevel,\n binding.view.resolveRequired ? 1 : 0,\n ].join(':');\n}\n\nfunction invalid(\n field: string,\n value: unknown,\n expected: string,\n): RenderResult<never, RenderError> {\n return {\n ok: false,\n error: new RenderTargetDescriptorInvalidError({ field, value, expected }),\n };\n}\n\nexport function createRenderTargetMaterialSource(\n target: RenderTarget,\n descriptor: RenderTargetDescriptor,\n options: RenderTargetTextureSourceOptions & { readonly generation: number },\n): RenderResult<RenderTargetMaterialSourceBinding, RenderError> {\n if (options.aspect !== 'color') return invalid('aspect', options.aspect, 'color');\n if (options.dimension !== descriptor.shape) {\n return invalid('dimension', options.dimension, `dimension matches ${descriptor.shape}`);\n }\n const mipCount =\n descriptor.mipLevels === 1\n ? 1\n : Math.floor(Math.log2(Math.max(descriptor.width, descriptor.height))) + 1;\n if (!Number.isInteger(options.mipLevel) || options.mipLevel < 0 || options.mipLevel >= mipCount) {\n return invalid('mipLevel', options.mipLevel, `an admitted mip level below ${mipCount}`);\n }\n if (!Number.isInteger(options.generation) || options.generation < 0) {\n return invalid('generation', options.generation, 'a non-negative device generation');\n }\n const result: RenderResult<RenderTargetMaterialSourceBinding, RenderError> = {\n ok: true,\n value: Object.freeze({\n source: sourceToken(),\n target,\n generation: options.generation,\n shape: descriptor.shape,\n format: descriptor.format,\n view: Object.freeze({\n dimension: options.dimension,\n mipLevel: options.mipLevel,\n resolveRequired: descriptor.sampleCount === 4,\n }),\n }),\n };\n sourceBindings.set(result.value.source as object, result.value);\n return result;\n}\n\nexport function validateRenderTargetMaterialSource(\n binding: RenderTargetMaterialSourceBinding,\n expected: RenderTargetMaterialSourceExpectation,\n): RenderResult<void, RenderError> {\n if (binding.target !== expected.target) {\n return {\n ok: false,\n error: new RenderTargetStateInvalidError({\n operation: 'source',\n reason: 'foreign-renderer',\n state: 'active',\n generation: binding.generation,\n }),\n };\n }\n if (binding.generation !== expected.generation) {\n return {\n ok: false,\n error: new RenderTargetStateInvalidError({\n operation: 'source',\n reason: 'generation-mismatch',\n state: 'active',\n generation: binding.generation,\n }),\n };\n }\n if (binding.shape !== expected.shape || binding.format !== expected.format) {\n return invalid(\n 'descriptor',\n { shape: binding.shape, format: binding.format },\n 'matching target descriptor',\n );\n }\n if (\n binding.view.dimension !== expected.dimension ||\n binding.view.mipLevel !== expected.mipLevel\n ) {\n return invalid('view', binding.view, 'matching target view subresource');\n }\n return { ok: true, value: undefined };\n}\n","// @forgeax/engine-runtime - render package shader-stage visibility values.\n//\n// Keep the WebGPU bit values in one dependency-free owner because render\n// package layout builders also run against the null and WebGL2-compatible RHI\n// shims where the browser's GPUShaderStage global is unavailable.\n\nexport const GPU_SHADER_STAGE_VERTEX = 0x1;\nexport const GPU_SHADER_STAGE_FRAGMENT = 0x2;\nexport const GPU_SHADER_STAGE_COMPUTE = 0x4;\n","// pbr-pipeline.ts -- PBR / unlit pipeline-layout factories (M4 round-4 D-5).\n//\n// Anchors:\n// - plan-strategy D-5 (round-4 REVISED): the PBR pipeline keeps a 4-slot\n// pipeline layout `[view, material, mesh-array, instances]`. The\n// material BGL grows from the derived user region by appending the 7\n// Skylight resources via `mergeSkylightIntoMaterialBgl`. The\n// unlit pipeline keeps its 7-entry material BGL (no Skylight binding\n// 7..12 contamination) so unlit demos don't carry IBL state.\n// - charter P4: same pipeline layout shape drives Skylight present +\n// absent paths -- AI users do not branch on Skylight existence.\n// - feat-20260520-skylight-ibl-cubemap M4 / t59 (round-4): the\n// pipeline-layout construction migrates out of `createRenderer.ts`\n// into this dedicated module so M4 round-4 tests can mock the device\n// and inspect the captured descriptors without standing up the full\n// createRenderer + asset registry + manifest stack.\n//\n// The factory functions return both the captured handles AND the\n// `bindGroupLayouts` array passed to `device.createPipelineLayout`. Callers\n// (the createRenderer step that wires the standard + standard-HDR\n// `RenderPipeline` instances) consume the result by name; tests inspect\n// `device.createBindGroupLayout.mock.calls` to verify shape (t57).\n\nimport type {\n BindGroup,\n BindGroupEntry,\n BindGroupLayout,\n Buffer,\n PipelineLayout,\n RhiDevice,\n Sampler,\n TextureFormat,\n TextureView,\n} from '@forgeax/engine-rhi';\nimport {\n type ShaderCatalog,\n STANDARD_PHYSICAL_TEXTURE_FIELDS,\n STANDARD_PIPELINE_PARAM_SCHEMA,\n standardPhysicalTextureFields,\n} from '@forgeax/engine-shader';\nimport { derive, type ParamSchemaEntry } from '@forgeax/engine-types';\nimport { GPU_SHADER_STAGE_FRAGMENT, GPU_SHADER_STAGE_VERTEX } from './gpu-stage';\nimport type { PipelineSpec } from './pipeline-spec-types';\n\n// Stub PipelineSpec used by the BGL-only call sites. The dispatcher only reads\n// `spec.shader` when a registry is supplied for reflection; for caps-driven\n// kinds (pbr-view / pbr-mesh-array / pbr-instances / pbr-skin-mesh-array) and\n// for the no-registry material path the spec content is unused. A single\n// frozen stub keeps the call sites readable and is allocation-free.\n//\n// D-13 round-2 dispatcher landing — see plan-decisions D-13.\nconst BGL_ONLY_SPEC_STUB: PipelineSpec = Object.freeze({\n shader: { id: '', passKind: 'forward', variantSet: undefined },\n attachments: { colorFormats: [], depthFormat: undefined, sampleCount: 1 },\n geometry: { topology: 'triangle-list', vertexLayout: {} },\n renderState: undefined,\n}) as PipelineSpec;\n\n// ─── Device owner ───────────────────────────────────────────────────────────\n\n/** The PBR layout builder consumes only the two creation methods it owns. */\nexport type PbrPipelineDevice = Pick<RhiDevice, 'createBindGroupLayout' | 'createPipelineLayout'>;\n\n// ─── Result shape ───────────────────────────────────────────────────────────\n\nexport interface PbrPipelineLayoutBundle {\n /** Pipeline layout passed to `createRenderPipeline({ layout })`. */\n readonly pipelineLayout: PipelineLayout;\n /** view BindGroupLayout (slot 0). */\n readonly viewBgl: BindGroupLayout;\n /**\n * PBR material BindGroupLayout (slot 1) -- derived user-region entries plus\n * Skylight and transmission injection.\n */\n readonly materialBgl: BindGroupLayout;\n /** Per-entity mesh BindGroupLayout (slot 2). */\n readonly meshArrayBgl: BindGroupLayout;\n /** Per-instance storage BindGroupLayout (slot 3). */\n readonly instancesBgl: BindGroupLayout;\n /** Probe-enabled slot-3 BGL; aliases `instancesBgl` when probes are unavailable. */\n readonly probeInstancesBgl: BindGroupLayout;\n /** Same pipeline layout with the probe-enabled slot-3 BGL, when supported. */\n readonly probePipelineLayout: PipelineLayout | null;\n /**\n * Same 4 layouts in slot order. Useful for assertion sites that check the\n * pipeline-layout `bindGroupLayouts` array shape (t57 (a) + (d)).\n */\n readonly bindGroupLayouts: readonly [\n BindGroupLayout,\n BindGroupLayout,\n BindGroupLayout,\n BindGroupLayout,\n ];\n}\n\n/** Derives the Standard PBR attachment list without allocating a closed path. */\nexport function standardPbrColorFormats(\n baseFormat: TextureFormat,\n fallbackDemand: boolean,\n): readonly TextureFormat[] {\n return fallbackDemand ? [baseFormat, 'rgba16float'] : [baseFormat];\n}\n\n// ─── Base entries (round-4 SSOT) ────────────────────────────────────────────\n\n/**\n * The built-in standard-PBR material paramSchema's texture/user-region shape,\n * used as the fallback when the material BGL is built without a registry\n * (the caps-driven `buildPbrPipelineLayouts` seam). Declares the canonical\n * Standard user-region textures + a numeric UBO run; `derive()` collapses the\n * numerics into binding 0 and emits one sampler/texture pair per declared\n * texture. Physical map pairs stay outside this boot region and are appended\n * only for an authored root that declares them. The shared PBR parameter\n * contract comes from the shader package; this module only derives the GPU\n * layout.\n */\n/**\n * Build the PBR material BGL **user-region** from a paramSchema via the\n * `derive()` SSOT (D-1). The user-region is binding 0 (the run-merged material\n * UBO) followed by one sampler/texture pair per declared texture. Engine\n * injection (IBL + transmission) is appended AFTER this region by the caller via\n * `appendInjection`, with start binding = `userRegion.length` — so a 4-texture\n * custom schema (e.g. parallax + heightTexture) shifts the injection region by\n * one sampler/texture pair automatically.\n *\n * The canonical `STANDARD_PIPELINE_PARAM_SCHEMA` currently declares seven\n * non-physical textures, so this derives to binding 0 UBO + seven pairs = 15\n * entries. IBL and transmission injection are appended after that region;\n * authored physical maps are appended after the engine-owned injections.\n *\n * One material-UBO convention is layered on top of the pure `derive()` output:\n * binding 0 is patched to `{ type: 'uniform', hasDynamicOffset: true }` with\n * `VERTEX | FRAGMENT` visibility. The material UBO is bound with a per-submesh\n * dynamic offset (`render-system-record.ts setBindGroup(1, bg, [offset])`) and\n * the vertex stage reads material params, so this is required for GPU\n * validation. `derive()` stays FRAGMENT-only / no-dynamic-offset for its other\n * consumers (it is the generic SSOT, not the material-UBO authority).\n *\n * @param paramSchema - the material shader's paramSchema (defaults to the\n * built-in standard-PBR shape when omitted, for the caps-driven seam).\n */\nexport function buildPbrMaterialUserRegionEntries(\n paramSchema: readonly ParamSchemaEntry[] = STANDARD_PIPELINE_PARAM_SCHEMA,\n excludedTextureFields: readonly string[] = [],\n): GPUBindGroupLayoutEntry[] {\n const excluded = new Set(excludedTextureFields);\n for (const field of standardPhysicalTextureFields(paramSchema)) excluded.add(field);\n const derived = derive(\n excluded.size === 0\n ? paramSchema\n : paramSchema.filter(\n (entry) => !excluded.has(entry.name) || !entry.type.startsWith('texture'),\n ),\n );\n // Project the engine-owned entry shape into the DOM WebGPU descriptor. Omit\n // absent optional members so exactOptionalPropertyTypes remains true at the\n // boundary instead of leaking an `undefined` property into the descriptor.\n let entries = derived.bglEntries.map(\n (entry): GPUBindGroupLayoutEntry => ({\n binding: entry.binding,\n visibility:\n entry.texture !== undefined || entry.sampler !== undefined\n ? GPU_SHADER_STAGE_VERTEX | GPU_SHADER_STAGE_FRAGMENT\n : entry.visibility,\n ...(entry.buffer === undefined ? {} : { buffer: entry.buffer }),\n ...(entry.sampler === undefined ? {} : { sampler: entry.sampler }),\n ...(entry.texture === undefined ? {} : { texture: entry.texture }),\n ...(entry.storageTexture === undefined ? {} : { storageTexture: entry.storageTexture }),\n }),\n );\n // The record path always owns one dynamic material-UBO slot, even when an\n // authored shader declares no numeric parameters (an empty paramSchema).\n // Reserve that slot here so the IBL/transmission injection starts at the\n // same binding used by `buildPerSubmeshMaterialBg`; otherwise binding 0 in\n // the layout is a cube texture while the record path submits a UBO.\n const ubo = entries[0];\n if (ubo !== undefined && ubo.binding === 0 && ubo.buffer?.type === 'uniform') {\n entries[0] = {\n binding: 0,\n visibility: GPU_SHADER_STAGE_VERTEX | GPU_SHADER_STAGE_FRAGMENT,\n buffer: { type: 'uniform', hasDynamicOffset: true },\n };\n } else {\n entries = [\n {\n binding: 0,\n visibility: GPU_SHADER_STAGE_VERTEX | GPU_SHADER_STAGE_FRAGMENT,\n buffer: { type: 'uniform', hasDynamicOffset: true },\n },\n ...entries.map((entry) => ({ ...entry, binding: entry.binding + 1 })),\n ];\n }\n return entries;\n}\n\n// ─── appendInjection — generic engine-injection BGL appender (M3 / w15) ──────\n//\n// Decision anchors (plan-strategy §2):\n// - D-6 appendInjection(bgl, kind) replaces the previous hardcoded\n// emissive/AO start-binding literal (=14). The starting binding\n// number is computed from `bgl.length`, byte-equivalent to\n// `derive(schema).userRegionBindingEnd` when `bgl` is the BGL list\n// derive returned for the user paramSchema.\n// - R-1 the 14-slot user-region assumption breaks once D-3 merges UBO;\n// appendInjection lets the material BGL grow / shrink without\n// churning every injection site.\n//\n// Closed union of injection kinds (plan-strategy §2 D-6):\n// - 'shadow' reserved for future material-level shadow injection\n// (sampler_comparison + texture_depth_2d, 2 entries).\n// The active shadow bindings live in the view BGL today\n// (group(0) bindings 3..7); this kind is the seam for\n// each per-material shadow override surface a future feat\n// wires onto group(1).\n// - 'ibl' the 6 IBL / Skylight entries (irradiance / prefilter\n// cube + brdfLut 2d + 2 samplers + intensity uniform).\n// Used by `buildPbrPipelineLayouts` after the user-region\n// user paramSchema entries are emitted.\n// - 'lightmap' the 4 emissive + occlusion entries (sampler + texture\n// pair x 2). The historical name is \"emissive/AO\"; we\n// keep that meaning under the generic 'lightmap' label\n// (per-surface secondary-lighting injection) so future\n// lightmap support lands without renaming the kind.\n// - 'transmission' the engine-owned sampler + backdrop texture pair. The\n// record stage supplies a real backdrop only for the active\n// transmission pass; all other variants bind layout-safe\n// placeholders because their shaders do not read these slots.\nexport type InjectionKind = keyof typeof INJECTION_KIND_LENGTHS;\n\nconst IBL_INJECTION_LENGTH = 6;\nconst LIGHTMAP_INJECTION_LENGTH = 4;\nconst SHADOW_INJECTION_LENGTH = 2;\nconst TRANSMISSION_INJECTION_LENGTH = 2;\n\n/**\n * Append the engine-injection BGL entries for the given `kind` after the\n * user-region BGL entries, with binding numbers starting at `bgl.length`.\n *\n * The function reads `bgl.length` (NOT a hardcoded constant) so each\n * user-region size — derived from `derive(schema).userRegionBindingEnd` or\n * computed manually — flows through to the injection start binding without\n * a coupled edit.\n *\n * Returns ONLY the injected entries; the caller spreads them after `bgl`:\n *\n * ```ts\n * const merged = [...userBgl, ...appendInjection(userBgl, 'ibl')];\n * device.createBindGroupLayout({ entries: merged });\n * ```\n */\nexport function appendInjection(\n bgl: readonly GPUBindGroupLayoutEntry[],\n kind: InjectionKind,\n): GPUBindGroupLayoutEntry[] {\n const start = bgl.length;\n switch (kind) {\n case 'ibl':\n return [\n // binding start+0: irradianceMap (texture_cube)\n {\n binding: start,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n texture: { sampleType: 'float', viewDimension: 'cube' },\n },\n // binding start+1: irradianceSampler\n {\n binding: start + 1,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n sampler: { type: 'filtering' },\n },\n // binding start+2: prefilterMap (texture_cube)\n {\n binding: start + 2,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n texture: { sampleType: 'float', viewDimension: 'cube' },\n },\n // binding start+3: prefilterSampler\n {\n binding: start + 3,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n sampler: { type: 'filtering' },\n },\n // binding start+4: brdfLut (texture_2d)\n {\n binding: start + 4,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n texture: { sampleType: 'float', viewDimension: '2d' },\n },\n // binding start+5: uniform { intensity: f32 }\n {\n binding: start + 5,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n buffer: { type: 'uniform' },\n },\n ];\n case 'lightmap':\n return [\n // emissive sampler + texture pair\n {\n binding: start,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n sampler: { type: 'filtering' },\n },\n {\n binding: start + 1,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n texture: { sampleType: 'float', viewDimension: '2d' },\n },\n // occlusion sampler + texture pair\n {\n binding: start + 2,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n sampler: { type: 'filtering' },\n },\n {\n binding: start + 3,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n texture: { sampleType: 'float', viewDimension: '2d' },\n },\n ];\n case 'shadow':\n return [\n {\n binding: start,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n sampler: { type: 'comparison' },\n },\n {\n binding: start + 1,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n texture: { sampleType: 'depth', viewDimension: '2d' },\n },\n ];\n case 'transmission':\n return [\n {\n binding: start,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n sampler: { type: 'filtering' },\n },\n {\n binding: start + 1,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n texture: { sampleType: 'float', viewDimension: '2d' },\n },\n ];\n }\n}\n\n/**\n * Append the renderer-owned inputs required by the Engine single-layer\n * medium template. They intentionally live after the normal IBL and\n * transmission injections so authored parameter schemas remain the only\n * source of the prefix. The raw-depth texture is an r32float producer\n * resource and therefore uses the unfilterable-float/non-filtering pair.\n */\nexport function appendSingleLayerMediumInjection(\n bgl: readonly GPUBindGroupLayoutEntry[],\n): GPUBindGroupLayoutEntry[] {\n const start = bgl.length;\n return [\n {\n binding: start,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n sampler: { type: 'non-filtering' },\n },\n {\n binding: start + 1,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n texture: { sampleType: 'unfilterable-float', viewDimension: '2d' },\n },\n {\n binding: start + 2,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n sampler: { type: 'filtering' },\n },\n {\n binding: start + 3,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n texture: { sampleType: 'float', viewDimension: '2d' },\n },\n {\n binding: start + 4,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n sampler: { type: 'non-filtering' },\n },\n {\n binding: start + 5,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n texture: { sampleType: 'unfilterable-float', viewDimension: '2d' },\n },\n ];\n}\n\n// Closed-set length sentinels — the map is the membership owner.\nexport const INJECTION_KIND_LENGTHS = {\n shadow: SHADOW_INJECTION_LENGTH,\n ibl: IBL_INJECTION_LENGTH,\n lightmap: LIGHTMAP_INJECTION_LENGTH,\n transmission: TRANSMISSION_INJECTION_LENGTH,\n};\n\nexport function physicalTextureFields(paramSchema: readonly ParamSchemaEntry[]): readonly string[] {\n return standardPhysicalTextureFields(paramSchema);\n}\n\nexport function appendTextureInjection(\n _bgl: readonly GPUBindGroupLayoutEntry[],\n fields: readonly string[],\n): GPUBindGroupLayoutEntry[] {\n const fieldSet = new Set(fields);\n // Physical resources use the Standard root's fixed slots (26 + canonical\n // index * 2). Do not compact an authored subset: the shader template and\n // scene-index receipt share these canonical bindings, while gaps simply\n // represent physical axes omitted by the selected root contract.\n return standardPhysicalTextureFields(\n STANDARD_PIPELINE_PARAM_SCHEMA.concat(\n fields.map((name) => ({ name, type: 'texture2d' as const })),\n ),\n ).flatMap((field) => {\n if (!fieldSet.has(field)) return [];\n const canonicalIndex = STANDARD_PHYSICAL_TEXTURE_FIELDS.indexOf(field);\n const binding = 26 + canonicalIndex * 2;\n return [\n {\n binding,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n sampler: { type: 'filtering' as const },\n },\n {\n binding: binding + 1,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n texture: { sampleType: 'float' as const, viewDimension: '2d' as const },\n },\n ];\n });\n}\n\n/**\n * Return the stable identity of the merged material bind-group layout.\n *\n * This is deliberately derived from the same descriptor builder consumed by\n * the device path. Callers use it to keep pipeline, bind-group, and\n * frame-local lookup caches on one layout identity even when equivalent\n * paramSchema arrays were allocated independently.\n */\nexport function materialBindGroupLayoutIdentity(\n shaderId: string,\n paramSchema: readonly ParamSchemaEntry[],\n): string {\n const descriptor = buildBindGroupLayoutDescriptor(\n {\n shader: { id: shaderId, passKind: 'forward', variantSet: undefined },\n attachments: { colorFormats: [], depthFormat: undefined, sampleCount: 1 },\n geometry: { topology: 'triangle-list', vertexLayout: {} },\n renderState: undefined,\n },\n { kind: 'pbr-material-merged', materialParamSchema: paramSchema },\n );\n // Descriptor shape alone cannot distinguish two Standard roots that expose\n // the same number of physical texture pairs under different semantic names.\n // The resource order is part of the admitted root contract, so include the\n // canonical physical projection in the cache identity while keeping the\n // actual WebGPU descriptor owned by the builder above.\n return JSON.stringify({\n entries: descriptor.entries,\n physicalTextureFields: physicalTextureFields(paramSchema),\n });\n}\n\n/**\n * Caps shape consumed by the BGL factory functions for storage-buffer vs\n * uniform-buffer branching. Mirrors the two fields the engine reads from\n * `RhiCaps` (plan D-4 + D-5).\n */\nexport interface PbrCaps {\n readonly storageBuffer: boolean;\n /**\n * Whether the selected material variant declares the optional extended\n * lighting view resources. The default keeps the historical helper shape\n * for callers that build the canonical full PBR layout; the renderer passes\n * the device/variant decision explicitly.\n */\n readonly extendedLighting?: boolean;\n /** Selects the optional binding(1) ProbeBlendRecord lane. */\n readonly probeBlend?: boolean;\n /** Whether the device can carry the optional SpotLight projector texture. */\n readonly projectorAvailable?: boolean;\n /** Omit unused backdrop slots on minimum-limit devices; physical slots stay fixed. */\n readonly transmissionBackdrop?: boolean;\n}\n\n/**\n * The view BGL entry list. binding 0 = view UBO (vertex + fragment);\n * binding 3 = directional shadowMap atlas (texture_depth_2d, vertex+fragment).\n * feat-20260613-csm-cascaded-shadow-maps: this is the CSM atlas — N\n * cascades tiled into one 2D depth texture, sampled via per-cascade UV\n * mapping in `lighting-directional.wgsl`. Single binding survives N=1..4\n * (no array-layer form; cascades live in viewport offsets per the\n * check-csm-unique-shadow-path grep gate).\n * binding 4 = shadow comparison sampler (shared by directional + point);\n * binding 5 = point shadow cube_array depth atlas (texture_depth_cube_array;\n * fragment-only). feat-20260612-point-light-shadows-urp-hdrp Round-2 F-1.\n * binding 6 = point shadow params UBO (`array<vec4<f32>, 4>`, 64 B;\n * fragment-only). One lane per shadow-casting point light slot\n * (shadowAtlasLayer in [0, 4)) carrying `(near, far, depthBias, normalBias)`.\n * binding 7 = shadowCasterCascade UBO (16 B; vertex + fragment). Per-pass\n * cascade-index uniform consumed exclusively by `shadow_caster.wgsl` to\n * pick `view.lightViewProj_X` for the cascade currently being rasterized\n * (feat-20260613-csm-cascaded-shadow-maps M5 / w28). Forward PBR shaders\n * declare the binding via `common.wgsl` but do not reference it; WebGPU\n * still requires a populated entry on every view BG so the host writes a\n * stable singleton buffer.\n * binding 8 = spot shadow atlas (texture_depth_2d; fragment-only).\n * feat-20260625-spot-light-shadow-mapping M3 / w14 (D-5). A single 2D depth\n * texture holding up to 4 spot shadows in a 2x2 tile grid. ALWAYS-ON (no caps\n * gate — `texture_depth_2d` is compat-safe everywhere), matching the\n * unconditional `spotShadowMap` WGSL declaration in common.wgsl. Reuses the\n * comparison sampler at binding 4 (no binding 9). Every view BG must populate\n * binding 8 (real spotShadowDepth view when spot shadows run, else a 1x1\n * fallback depth view cleared to fully-lit).\n *\n * Mirrors feat-20260519-light-casters M3 D-S1 layout +\n * feat-20260520-directional-light-shadow-mapping M2 / w14 (D-1) shadow\n * map binding +\n * feat-20260612-point-light-shadows-urp-hdrp Round-2 F-1 BGL hookup\n * (always-on bindings 5/6 paired with the unconditional `POINT_SHADOW_AVAILABLE`\n * define registered in vite-plugin-shader) +\n * feat-20260613-csm-cascaded-shadow-maps M5 / w28 (binding 7 cascade UBO).\n * binding 10 (Points/Lines viewport UBO; always bound for the shared view\n * layout and consumed only by the dedicated points-lines shader).\n * Isolated here so M4 round-4 tests can recreate the layout.\n *\n * Local lights are not part of the view group. Standard material variants\n * consume the one Cluster payload in group(2), while this group retains only\n * camera and shadow resources.\n */\nexport function buildPbrViewBglEntries(caps: PbrCaps): GPUBindGroupLayoutEntry[] {\n const entries: GPUBindGroupLayoutEntry[] = [\n {\n binding: 0,\n visibility: GPU_SHADER_STAGE_VERTEX | GPU_SHADER_STAGE_FRAGMENT,\n // View captures use the same bind group with a per-face view slot.\n // Keeping this dynamic is also valid for the display slot at offset 0.\n buffer: { type: 'uniform', hasDynamicOffset: true },\n },\n {\n binding: 3,\n visibility: GPU_SHADER_STAGE_VERTEX | GPU_SHADER_STAGE_FRAGMENT,\n texture: { sampleType: 'depth', viewDimension: '2d' },\n },\n {\n binding: 4,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n sampler: { type: 'comparison' },\n },\n // feat-20260612-point-light-shadows-urp-hdrp Round-2 F-1: point shadow\n // cube_array depth atlas. Bound to either the real ShadowAtlas\n // cube_array view (when point shadows are active) or a 1x1x6 fallback\n // cube_array view cleared to 1.0 (fully lit). Visibility is FRAGMENT\n // only -- the directional binding 3 is VERTEX|FRAGMENT for shadow\n // probe-debug sampling, but the cube atlas has no host-side probe path.\n {\n binding: 5,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n texture: { sampleType: 'depth', viewDimension: 'cube-array' },\n },\n // feat-20260612-point-light-shadows-urp-hdrp Round-2 F-1: point shadow\n // params UBO. Carries `array<vec4<f32>, 4>` = 64 B with one lane per\n // shadow-casting point light slot (shadowAtlasLayer in [0, 4)). Each\n // lane stores `(near, far, depthBias, normalBias)` so the fragment-shader\n // depth-ref reconstruction (lighting-punctual.wgsl evalPointShadowed)\n // can avoid sampling DirectLightSlot for the URP path. The shared\n // DirectLightSlot metadata remains the identity owner, so binding 6 is\n // unused on HDRP shaders even though the BGL declares it (charter P4 single SSOT\n // BGL across pipelines; the HDRP variant simply doesn't reference the\n // binding in WGSL, which is allowed).\n {\n binding: 6,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n buffer: { type: 'uniform' },\n },\n // feat-20260613-csm-cascaded-shadow-maps M5 / w28: shadowCasterCascade\n // UBO (16 B). Carries the 0-based cascade index of the shadow pass\n // currently being rasterized so `shadow_caster.wgsl` can index into\n // `view.lightViewProj_X` per cascade. Shifted from binding 5 to\n // binding 7 on 2026-06-13 to make room for point-shadow bindings 5/6\n // (they predate this feat in main; CSM's slot was the optimal-yield\n // give since point-shadow needs FRAGMENT-only and the cascade UBO\n // needs vertex-stage too — keeping cascade higher avoids interleaving\n // visibility flags within the contiguous shadow-binding cluster).\n {\n binding: 7,\n visibility: GPU_SHADER_STAGE_VERTEX | GPU_SHADER_STAGE_FRAGMENT,\n buffer: { type: 'uniform' },\n },\n // feat-20260625-spot-light-shadow-mapping M3 / w14 (D-5): spot shadow\n // atlas. A single `texture_depth_2d` holding up to 4 spot shadows in a 2x2\n // tile grid (urp-pipeline.ts spotShadowDepth). FRAGMENT-only — the spot\n // shadow factor is reconstructed at fragment time via perspective-divide in\n // `evalSpotShadowed` (lighting-punctual.wgsl).\n //\n // ALWAYS-ON (no caps gate, unlike the point cube_array atlas at binding 5\n // which rides POINT_SHADOW_AVAILABLE): spot uses `texture_depth_2d` which is\n // compat-safe in every WebGPU profile, so the binding is unconditionally\n // declared. The matching WGSL declaration is `spotShadowMap` at @group(0)\n // binding 8 in common.wgsl (also unconditional) — the two must stay in\n // lock-step or WebGPU validation rejects the bind group at smoke time\n // (memory: BGL shape mismatch is a browser-path-only bug). No binding 9\n // sampler: spot reuses the comparison sampler at binding 4.\n // feat-20260625-spot-light-shadow-mapping M3 / w14 (D-5): spot shadow 2D\n // atlas, the LAST view-BG binding. The per-spot fragment-read perspective\n // lightViewProj matrices that w24 originally declared at a standalone\n // binding 9 uniform buffer were folded into the View UBO (binding 0,\n // `view.spotLightViewProj`) in w25 (scope-amend webkit-fallback): the\n // standalone binding pushed the WebGL2 fallback fragment uniform-buffer\n // count to 12, over GLES 3.0's `max_uniform_buffers_per_shader_stage = 11`,\n // crashing pipeline-layout creation on the compat path (this feat's target).\n {\n binding: 8,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n texture: { sampleType: 'depth', viewDimension: '2d' },\n },\n ];\n const extendedLighting = caps.extendedLighting ?? true;\n const lowLimitCloudBindings = extendedLighting === false && caps.projectorAvailable === false;\n if (extendedLighting) {\n entries.push(\n {\n binding: 9,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n sampler: { type: 'filtering' },\n },\n {\n binding: 11,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n texture: { sampleType: 'float', viewDimension: '2d-array' },\n },\n {\n binding: 12,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n texture: { sampleType: 'float', viewDimension: '2d-array' },\n },\n {\n binding: 13,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n texture: { sampleType: 'float', viewDimension: '2d' },\n },\n {\n binding: 14,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n texture: { sampleType: 'float', viewDimension: '2d' },\n },\n {\n binding: 15,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n buffer: { type: 'uniform' },\n },\n );\n } else if (caps.projectorAvailable !== false) {\n entries.push(\n {\n binding: 11,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n texture: { sampleType: 'float', viewDimension: '2d' },\n },\n {\n binding: 12,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n sampler: { type: 'filtering' },\n },\n );\n }\n entries.push({\n binding: 10,\n visibility: GPU_SHADER_STAGE_VERTEX,\n buffer: { type: 'uniform', hasDynamicOffset: true },\n });\n // Cloud direct-solar transport is a renderer-owned view resource. The\n // minimum 16-texture profile has no spare sampled texture lane; its shader\n // variant returns the direct-sun fallback without declaring this pair.\n if (!lowLimitCloudBindings) {\n entries.push(\n {\n binding: 16,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n texture: { sampleType: 'float', viewDimension: '2d' },\n },\n {\n binding: 17,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n sampler: { type: 'filtering' },\n },\n );\n }\n return entries;\n}\n\n// ─── PBR pipeline layout factory ────────────────────────────────────────────\n\n/**\n * Build the PBR pipeline layout under D-5 round-4: 4 slots `[view,\n * material, mesh-array, instances]`; the material BGL is derived from the\n * standard material schema and engine injection chain.\n *\n * `caps.storageBuffer===false` switches the mesh-array and instances entries\n * to `uniform`; local-light resources are never part of this view group.\n *\n * Throws on each `createBindGroupLayout` / `createPipelineLayout` Result\n * failure -- the engine bootstrap path (createRenderer) wraps the call in\n * `runShimSyncStep` to fold the throw into the structured error pipe.\n */\nexport function buildPbrPipelineLayouts(\n device: PbrPipelineDevice,\n caps: PbrCaps,\n): PbrPipelineLayoutBundle {\n // D-13 round-2: 4 BGLs route through buildBindGroupLayoutDescriptor.\n // The dispatcher reads kind + caps; spec content is unused without a\n // registry (no shader-axis reflection at this seam — the 4 BGLs are\n // caps-driven literals + the deterministic Skylight + transmission merge\n // sequence that has no dependency on shader.id).\n const viewBglRes = device.createBindGroupLayout(\n buildBindGroupLayoutDescriptor(BGL_ONLY_SPEC_STUB, { kind: 'pbr-view', caps }),\n );\n if (!viewBglRes.ok) throw viewBglRes.error;\n\n // Material BGL: derived user region + Skylight + transmission injection.\n // The transmission start binding is computed from the post-Skylight BGL\n // length (= 22 for the canonical Standard schema) by appendInjection.\n const materialBglRes = device.createBindGroupLayout(\n buildBindGroupLayoutDescriptor(BGL_ONLY_SPEC_STUB, {\n kind: 'pbr-material-merged',\n caps,\n }),\n );\n if (!materialBglRes.ok) throw materialBglRes.error;\n\n // mesh-array BGL.\n const meshArrayBglRes = device.createBindGroupLayout(\n buildBindGroupLayoutDescriptor(BGL_ONLY_SPEC_STUB, { kind: 'pbr-mesh-array', caps }),\n );\n if (!meshArrayBglRes.ok) throw meshArrayBglRes.error;\n\n // instances BGL.\n const instancesBglRes = device.createBindGroupLayout(\n buildBindGroupLayoutDescriptor(BGL_ONLY_SPEC_STUB, {\n kind: 'pbr-instances',\n caps: { ...caps, probeBlend: false },\n }),\n );\n if (!instancesBglRes.ok) throw instancesBglRes.error;\n // ProbeBlendRecord is a storage-buffer-only ABI extension. A uniform\n // fallback cannot afford the extra fragment-stage uniform binding on\n // WebGL2/GLES, so do not even construct the probe BGL on that capability\n // route. The record stage gates the matching variant and bind group with\n // the same storage capability; aliasing the ordinary BGL keeps the bundle\n // total and makes an accidental probe request fail closed at layout select.\n const probeInstancesBglRes = caps.storageBuffer\n ? device.createBindGroupLayout(\n buildBindGroupLayoutDescriptor(BGL_ONLY_SPEC_STUB, {\n kind: 'pbr-instances',\n caps: { ...caps, probeBlend: true },\n }),\n )\n : { ok: true as const, value: instancesBglRes.value };\n if (!probeInstancesBglRes.ok) throw probeInstancesBglRes.error;\n\n // Pipeline layout (4 slots).\n const layouts: readonly [BindGroupLayout, BindGroupLayout, BindGroupLayout, BindGroupLayout] = [\n viewBglRes.value,\n materialBglRes.value,\n meshArrayBglRes.value,\n instancesBglRes.value,\n ];\n const pipelineLayoutRes = device.createPipelineLayout({\n label: 'pbr-pl',\n bindGroupLayouts: layouts,\n });\n if (!pipelineLayoutRes.ok) throw pipelineLayoutRes.error;\n const probeLayouts: readonly [\n BindGroupLayout,\n BindGroupLayout,\n BindGroupLayout,\n BindGroupLayout,\n ] = [viewBglRes.value, materialBglRes.value, meshArrayBglRes.value, probeInstancesBglRes.value];\n let probePipelineLayout: PipelineLayout | null = null;\n if (caps.storageBuffer) {\n const probePipelineLayoutRes = device.createPipelineLayout({\n label: 'pbr-probe-pl',\n bindGroupLayouts: probeLayouts,\n });\n if (!probePipelineLayoutRes.ok) throw probePipelineLayoutRes.error;\n probePipelineLayout = probePipelineLayoutRes.value;\n }\n\n return {\n pipelineLayout: pipelineLayoutRes.value,\n viewBgl: viewBglRes.value,\n materialBgl: materialBglRes.value,\n meshArrayBgl: meshArrayBglRes.value,\n instancesBgl: instancesBglRes.value,\n probeInstancesBgl: probeInstancesBglRes.value,\n probePipelineLayout,\n bindGroupLayouts: layouts,\n };\n}\n\n// ─── PBR skin material-shader identifier (SSOT) ────────────────────────────\n\n/**\n * SSOT for the skin material shader's registered identifier. The shader\n * package registers under this string (see register-default-standard-pbr-skin.ts\n * `RESERVED_ID`); runtime dispatch sites import this constant rather than\n * carrying a literal so a future rename is a one-line change. AC-09 grep\n * gate: the body of `selectPipelineLayoutForVariant` MUST NOT contain a\n * literal `'forgeax::pbr-skin'` -- callers map this constant to\n * `LayoutKind = 'pbr-skin'` upstream.\n */\nexport const SKIN_MATERIAL_SHADER_ID = 'forgeax::pbr-skin' as const;\nexport const SHADOW_CASTER_SHADER_ID = 'forgeax::default-shadow-caster' as const;\n\n// Authored Standard templates are published under a unique module id for each\n// root contract. Keep the family marker in the id so every downstream render\n// owner (extract, layout, and record) can make the same Standard-vs-custom and\n// rigid-vs-skinned decision without a second registry or a runtime shader\n// inspection pass.\nconst AUTHORED_STANDARD_ID_RE = /::(?:standard|pbr-skin)(?:-|$)/;\n\nexport function isStandardPbrSkinMaterialShader(shaderId: string | undefined): boolean {\n return (\n shaderId === SKIN_MATERIAL_SHADER_ID ||\n shaderId === 'forgeax::default-standard-pbr-skin' ||\n (shaderId !== undefined && /::pbr-skin(?:-|$)/.test(shaderId))\n );\n}\n\nexport function shadowCasterVariantSet(\n storageBuffer: boolean,\n skinned: boolean,\n gpuDrivenSceneIndex = false,\n alphaMask = false,\n vertexColorAvailable = false,\n): string {\n const skinningDisabled = !skinned;\n const defines: Record<string, boolean> = {\n ALPHA_MASK: alphaMask,\n GPU_DRIVEN_SCENE_INDEX_AVAILABLE: gpuDrivenSceneIndex,\n GPU_DRIVEN_SCENE_INDEX_EXPLICIT: false,\n SKINNING_DISABLED: skinningDisabled,\n STORAGE_BUFFER_AVAILABLE: storageBuffer,\n };\n if (vertexColorAvailable) defines.VERTEX_COLOR_AVAILABLE = true;\n return Object.entries(defines)\n .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))\n .map(([name, value]) => `${name}=${String(value)}`)\n .join('+');\n}\n\nexport function isSkinnedShadowCasterVariant(\n materialShaderId: string | undefined,\n variantSet: string | undefined,\n): boolean {\n return (\n materialShaderId === SHADOW_CASTER_SHADER_ID &&\n variantSet?.includes('SKINNING_DISABLED=false') === true\n );\n}\n\nexport type PipelineGroup2Contract = 'mesh' | 'skin' | 'cluster' | 'skin-cluster';\n\n/** Resolve group(2) from the composed WGSL artifact used to build the PSO. */\nexport function resolvePipelineGroup2Contract(source: string): PipelineGroup2Contract {\n const withoutComments = source.replace(/\\/\\*[\\s\\S]*?\\*\\//gu, '').replace(/\\/\\/.*$/gmu, '');\n const bindings = [\n ...withoutComments.matchAll(/@group\\s*\\(\\s*2\\s*\\)\\s*@binding\\s*\\(\\s*(\\d+)\\s*\\)/gu),\n ].map((match) => Number(match[1]));\n const hasSkinBindings = bindings.includes(1) || bindings.includes(2);\n const hasClusterBindings = bindings.some((binding) => binding >= 3);\n if (hasSkinBindings && hasClusterBindings) return 'skin-cluster';\n if (hasSkinBindings) return 'skin';\n if (hasClusterBindings) return 'cluster';\n return 'mesh';\n}\n\n/** Returns true for the engine-shipped standard-PBR material shader family. */\nexport function isStandardPbrMaterialShader(shaderId: string | undefined): boolean {\n return (\n shaderId === 'forgeax::default-standard-pbr' ||\n shaderId === SKIN_MATERIAL_SHADER_ID ||\n shaderId === 'forgeax::default-standard-pbr-skin' ||\n (shaderId !== undefined && AUTHORED_STANDARD_ID_RE.test(shaderId))\n );\n}\n\n/**\n * Return true only for the two engine-owned Standard roots. Authored Standard\n * aliases intentionally remain outside this set: their cooked root schema may\n * omit transmission or other optional resources, so their compact user-region\n * layout must be derived from that artifact instead of borrowing the boot\n * layout's reserved slots.\n */\nexport function isCanonicalStandardPbrMaterialShader(shaderId: string | undefined): boolean {\n return (\n shaderId === 'forgeax::default-standard-pbr' ||\n shaderId === SKIN_MATERIAL_SHADER_ID ||\n shaderId === 'forgeax::default-standard-pbr-skin'\n );\n}\n\n// ─── PBR skin pipeline layout factory (bug-20260611) ───────────────────────\n//\n// The skin material shader (`forgeax::pbr-skin`, registered by\n// `register-default-standard-pbr-skin.ts`) needs the same 4-slot layout shape\n// as standard PBR EXCEPT for slot 2: its mesh-array BGL declares **2**\n// dynamic-offset entries (binding 0 = meshes, binding 1 = palette) versus\n// standard PBR's single binding 0. Without a dedicated pipeline layout the\n// skin shader's `@group(2) @binding(1) palette : array<mat4x4<f32>>` reference\n// trips a `Binding doesn't exist in [BindGroupLayoutInternal \"pbr-mesh-array-bgl\"]`\n// validation error in `device.createRenderPipeline`, surfaced as\n// `RhiError limit-exceeded` and an invalid command buffer (Playwright TDD trace\n// captured 2026-06-11 in apps/hello/skin).\n//\n// The factory **reuses** view / material / instances BGL handles produced by\n// `buildPbrPipelineLayouts` (charter P4: a single SSOT BGL for each slot the\n// shapes actually share) and only creates a new mesh-array BGL + new pipeline\n// layout. This keeps the per-binding-shape SSOT in one place and avoids an\n// alternate skin-only material BGL (the skin shader's group(0) and group(1)\n// are byte-for-byte the standard-PBR contract).\n\n/**\n * Build the PBR skin pipeline layout (4 slots `[view, material,\n * mesh-array(3-entry), instances]`). View / material / instances BGLs are\n * shared with the standard-PBR layout (passed in via `pbr` bundle); the only\n * new BGL is the 3-entry mesh-array slot for `meshes` + current/previous\n * `palette` buffers.\n *\n * Throws on each `createBindGroupLayout` / `createPipelineLayout` Result\n * failure -- the engine bootstrap path wraps the call in `runShimSyncStep`\n * to fold the throw into the structured error pipe.\n */\nexport function buildPbrSkinLayouts(\n device: PbrPipelineDevice,\n caps: PbrCaps,\n pbr: PbrPipelineLayoutBundle,\n): PbrPipelineLayoutBundle {\n // 3-entry mesh-array BGL: binding 0 meshes + binding 1 current palette\n // + binding 2 previous palette. All use dynamic offsets for the same\n // per-entity window contract.\n const skinMeshArrayBglRes = device.createBindGroupLayout(\n buildBindGroupLayoutDescriptor(BGL_ONLY_SPEC_STUB, {\n kind: 'pbr-skin-mesh-array',\n caps,\n }),\n );\n if (!skinMeshArrayBglRes.ok) throw skinMeshArrayBglRes.error;\n\n const layouts: readonly [BindGroupLayout, BindGroupLayout, BindGroupLayout, BindGroupLayout] = [\n pbr.viewBgl,\n pbr.materialBgl,\n skinMeshArrayBglRes.value,\n pbr.instancesBgl,\n ];\n const pipelineLayoutRes = device.createPipelineLayout({\n label: 'pbr-skin-pl',\n bindGroupLayouts: layouts,\n });\n if (!pipelineLayoutRes.ok) throw pipelineLayoutRes.error;\n const probeLayouts: readonly [\n BindGroupLayout,\n BindGroupLayout,\n BindGroupLayout,\n BindGroupLayout,\n ] = [pbr.viewBgl, pbr.materialBgl, skinMeshArrayBglRes.value, pbr.probeInstancesBgl];\n let probePipelineLayout: PipelineLayout | null = null;\n if (caps.storageBuffer) {\n const probePipelineLayoutRes = device.createPipelineLayout({\n label: 'pbr-skin-probe-pl',\n bindGroupLayouts: probeLayouts,\n });\n if (!probePipelineLayoutRes.ok) throw probePipelineLayoutRes.error;\n probePipelineLayout = probePipelineLayoutRes.value;\n }\n\n return {\n pipelineLayout: pipelineLayoutRes.value,\n viewBgl: pbr.viewBgl,\n materialBgl: pbr.materialBgl,\n meshArrayBgl: skinMeshArrayBglRes.value,\n instancesBgl: pbr.instancesBgl,\n probeInstancesBgl: pbr.probeInstancesBgl,\n probePipelineLayout,\n bindGroupLayouts: layouts,\n };\n}\n\n/**\n * Build the dedicated slot-3 layout used by scene-index GPU-driven draws.\n *\n * Direct material draws deliberately keep `pbr-instances-bgl` at binding(0),\n * and ProbeBlend deliberately owns binding(1). The scene-index stream is\n * therefore a separate BGL at binding(2), rather than an optional entry added\n * to the direct layout. This keeps every bind group complete for its shader\n * and prevents a direct draw from having to bind a dummy visible stream.\n */\nexport function buildGpuDrivenPbrInstancesBindGroupLayout(\n device: PbrPipelineDevice,\n caps: PbrCaps,\n): BindGroupLayout {\n if (!caps.storageBuffer) {\n throw new Error('GPU-driven PBR instances layout requires storage-buffer capability');\n }\n const result = device.createBindGroupLayout(\n buildBindGroupLayoutDescriptor(BGL_ONLY_SPEC_STUB, {\n kind: 'pbr-gpu-driven-instances',\n caps,\n }),\n );\n if (!result.ok) throw result.error;\n return result.value;\n}\n\n/**\n * Build the slot-3 layout used by direct single-layer-medium draws.\n *\n * Direct Surface draws retain their ordinary instance transforms at binding\n * zero, but consume the same producer-owned ProbeBlend, dynamic page, frame\n * rows, and shared time resources as the scene-index lane. Binding six is the\n * per-draw frame-row base; it keeps a local instance index independent from\n * the renderer's compact scene-index address.\n */\nexport function buildSurfaceDirectInstancesBindGroupLayout(\n device: PbrPipelineDevice,\n caps: PbrCaps,\n): BindGroupLayout {\n if (!caps.storageBuffer) {\n throw new Error('Direct Surface instances layout requires storage-buffer capability');\n }\n const result = device.createBindGroupLayout(\n buildBindGroupLayoutDescriptor(BGL_ONLY_SPEC_STUB, {\n kind: 'pbr-surface-direct-instances',\n caps,\n }),\n );\n if (!result.ok) throw result.error;\n return result.value;\n}\n\n/** Build the four-slot rigid scene-index pipeline layout. */\nexport function buildGpuDrivenPbrPipelineLayout(\n device: PbrPipelineDevice,\n pbr: PbrPipelineLayoutBundle,\n gpuDrivenInstancesBgl: BindGroupLayout,\n): PipelineLayout {\n const result = device.createPipelineLayout({\n label: 'pbr-gpu-driven-pl',\n bindGroupLayouts: [pbr.viewBgl, pbr.materialBgl, pbr.meshArrayBgl, gpuDrivenInstancesBgl],\n });\n if (!result.ok) throw result.error;\n return result.value;\n}\n\n/** Build the four-slot skinned scene-index pipeline layout. */\nexport function buildGpuDrivenPbrSkinPipelineLayout(\n device: PbrPipelineDevice,\n pbrSkin: PbrPipelineLayoutBundle,\n gpuDrivenInstancesBgl: BindGroupLayout,\n): PipelineLayout {\n const result = device.createPipelineLayout({\n label: 'pbr-skin-gpu-driven-pl',\n bindGroupLayouts: [\n pbrSkin.viewBgl,\n pbrSkin.materialBgl,\n pbrSkin.meshArrayBgl,\n gpuDrivenInstancesBgl,\n ],\n });\n if (!result.ok) throw result.error;\n return result.value;\n}\n\n/** Project the canonical group(2) resources for a PBR skin draw. */\nexport function createPbrSkinMeshBindGroupEntries(\n meshBuffer: Buffer,\n meshSize: number,\n paletteBuffer: Buffer,\n paletteWindowBytes: number,\n): BindGroupEntry[] {\n return [\n {\n binding: 0,\n resource: { kind: 'buffer', value: { buffer: meshBuffer, offset: 0, size: meshSize } },\n },\n ...[1, 2].map((binding) => ({\n binding,\n resource: {\n kind: 'buffer' as const,\n value: {\n buffer: paletteBuffer,\n offset: 0,\n size: paletteWindowBytes,\n },\n },\n })),\n ];\n}\n\n/** Project all dynamic offsets for the canonical PBR skin group(2) shape. */\nexport function pbrSkinMeshDynamicOffsets(\n meshOffset: number,\n paletteOffset: number,\n): readonly [number, number, number] {\n return [meshOffset, paletteOffset, paletteOffset];\n}\n\n// ─── Unlit material BGL factory ─────────────────────────────────────────────\n\n/**\n * Build a stand-alone 7-entry unlit material BGL. Round-4 D-5 keeps unlit\n * material BG isolated from Skylight binding 7..12 -- unlit demos do not\n * pay for IBL state. The unlit pipeline still binds material at slot 1,\n * just with a 7-entry layout.\n *\n * Note: at the moment the runtime still routes both unlit + standard\n * through a single 14-entry pipeline layout; the unlit material BG\n * carries fallback identity resources at binding 7..12. This factory is\n * exported as a future-proof seam for the moment when unlit demos own\n * their own pipeline layout (t57 (e) test pins the contract today so the\n * eventual split has a green target).\n */\nexport function buildUnlitMaterialBgl(device: PbrPipelineDevice): BindGroupLayout {\n const res = device.createBindGroupLayout(\n buildBindGroupLayoutDescriptor(BGL_ONLY_SPEC_STUB, { kind: 'unlit-material' }),\n );\n if (!res.ok) throw res.error;\n return res.value;\n}\n\n// ─── Material BG assembly helpers (unlit) ───────────────────────────────────\n\n/**\n * Inputs for `buildUnlitMaterialBindGroupEntries`. The fields mirror the\n * record-stage's local variables; isolating the assembler here lets t58\n * (e) test exercise the contract without recreating the entire record\n * stage.\n */\nexport interface UnlitMaterialBindGroupEntryInputs {\n readonly materialUniform: Buffer;\n readonly materialOffset: number;\n readonly materialSize: number;\n readonly defaultSampler: Sampler;\n readonly baseColorView: TextureView;\n readonly defaultWhiteView: TextureView;\n}\n\n/**\n * Build the 7 BindGroupEntry values for the unlit material BG (binding\n * 0..6). Output flows into `device.createBindGroup({ layout:\n * unlitMaterialBgl, entries })`.\n */\nexport function buildUnlitMaterialBindGroupEntries(\n inputs: UnlitMaterialBindGroupEntryInputs,\n): BindGroupEntry[] {\n return [\n {\n binding: 0,\n resource: {\n kind: 'buffer' as const,\n value: {\n buffer: inputs.materialUniform,\n offset: inputs.materialOffset,\n size: inputs.materialSize,\n },\n },\n },\n { binding: 1, resource: { kind: 'sampler' as const, value: inputs.defaultSampler } },\n { binding: 2, resource: { kind: 'textureView' as const, value: inputs.baseColorView } },\n { binding: 3, resource: { kind: 'sampler' as const, value: inputs.defaultSampler } },\n { binding: 4, resource: { kind: 'textureView' as const, value: inputs.defaultWhiteView } },\n { binding: 5, resource: { kind: 'sampler' as const, value: inputs.defaultSampler } },\n { binding: 6, resource: { kind: 'textureView' as const, value: inputs.defaultWhiteView } },\n ];\n}\n\n// Surface re-export so consumers can build a complete BindGroup pipeline\n// without reaching into multiple modules.\nexport type { BindGroup };\n\n// ─── feat-20260625 M3 / w10 — sprite-pass variantSet selector ────────────────\n//\n// Plan-strategy D-1 + D-4: when an entity carries `SpriteInstances` the\n// sprite-pass record stage must pick the `PER_INSTANCE_REGION=true` sprite\n// shader variant compiled in M2 (w7) so the WGSL `InstanceData` struct\n// includes the per-instance `region: vec4<f32>` field and reads region from\n// the interleaved 80B-per-instance buffer (not from the material UBO).\n//\n// Non-`SpriteInstances` sprite entities (e.g. the sprite-atlas demo) keep\n// the default variant where `PER_INSTANCE_REGION` is undefined and the\n// shader's `#else` branch reads region from material UBO — preserving\n// existing behaviour (plan-strategy D-4 \"pbr / unlit / sprite-atlas\n// behaviour unchanged\" / requirements Edge Cases).\n//\n// Variant set string format mirrors the Standard boot variant /\n// HDRP variant set string idiom in `pipeline-spec.ts` (`+`-separated kv\n// pairs); the record stage threads this string through the per-shader\n// pipeline-cache key + lazy-build `getMaterialShaderPipeline` lookup.\n\n/**\n * variantSet string fired into the sprite-pass pipeline cache when the\n * entity carries `SpriteInstances` (plan-strategy D-1 interleaved single\n * buffer + D-4 axis on `sprite.wgsl`).\n *\n * bug-20260708 M2 (c): aligned with the canonical all-true variant key\n * `''` — sprite's manifest emits `{PIR:true, SBA:true}` under the empty-\n * string key (all variant axes true → canonical). The runtime's\n * `getMaterialShaderPipeline` variant-substitution branch\n * (`createRenderer.ts:1730`) resolves this via\n * `findVariantByKey(msEntry, '')` returning the 5653B PIR=true variant.\n * Combined with the `cacheKeyOf` sentinel `~` (bug-20260708 M2 (b)) this\n * value produces a cache key distinct from the `variantSet=undefined`\n * character/default path (which now resolves to the PIR=false 5575B boot-\n * registered variant). Sprite pipeline layout routing is anchored via\n * `LayoutKind='sprite-urp'` so `variantSet=''` here does NOT trigger the\n * HDRP-layout branch of `selectPipelineLayoutForVariant` (research R-12\n * flow; plan-strategy §4 R-1' guard).\n */\nexport const SPRITE_PASS_PER_INSTANCE_REGION_VARIANT_SET = '';\n\n// BglKind dispatch (M3 / D-13) — closed union of BGL shapes the runtime ships\n// ══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Closed union of bind-group-layout shapes the runtime constructs.\n *\n * Each kind names one physically distinct BGL the runtime has historically\n * built by hand. {@link buildBindGroupLayoutDescriptor} dispatches on this\n * union so every `device.createBindGroupLayout(...)` call site shares one\n * SSOT for entries / labels (plan-strategy §3.2; D-13 round-2 decision).\n *\n * Three groups by derivation source:\n * 1. Shader-derived (paramSchema reflection + injection chain):\n * - `'pbr-material-merged'` — derived user region + Skylight 6 + transmission 2\n * - `'unlit-material'` — 7 entries: base PBR material only (no inject)\n * - `'hdrp-7-slot'` — 7 entries (binding 0 + 3..8): HDRP cluster + SSAO group(2) BGL\n * 2. Caps-driven literal shapes (no shader):\n * - `'pbr-view'` — camera/shadow bindings, optional projector\n * texture/sampler (11/12), and the Points/Lines UBO (10). Local lights\n * are carried exclusively by the Standard Cluster group(2).\n * (directional 3/4, point 5/6, cascade 7, spot atlas 8; the former\n * spot lightViewProj matrices moved into the View UBO)\n * - `'pbr-mesh-array'` — 1 entry: per-entity mesh SSBO (dynamic-offset)\n * - `'pbr-instances'` — 2 entries: per-instance SSBO plus the compact\n * visible-item index stream (the second entry is used only by the\n * scene-index vertex entry and shares the frame's instance bind group)\n * - `'pbr-skin-mesh-array'` — 3 entries: meshes + current/previous palette\n * 3. Attachment-driven (fullscreen post-process):\n * - `'fullscreen-post'` — 2 entries: input texture + sampler. The texture\n * `sampleType` is derived from `spec.attachments` (plan §R3 fix):\n * `'depth32float'` → `'depth'`; `'r32float'` → `'unfilterable-float'`;\n * else → `'float'`.\n * - `'fullscreen-post-with-params'` — 3 entries: the same texture@0 +\n * sampler@1 as `'fullscreen-post'`, plus a `buffer@2` uniform for the\n * per-frame params UBO (feat-20260621 D-2: `entry.params !== undefined`\n * passes route here; the layout stays group(1), q3=B). `'fullscreen-post'`\n * stays byte-identical so param-less consumers degrade with no change.\n * - `'fullscreen-post-with-scene-depth-msaa'` — the depth-read layout with\n * `texture.multisampled=true`, selected for a 4-sample scene depth target.\n */\nexport type BglKind =\n | 'pbr-view'\n | 'pbr-material-merged'\n | 'pbr-mesh-array'\n | 'pbr-instances'\n | 'pbr-gpu-driven-instances'\n | 'pbr-surface-direct-instances'\n | 'pbr-skin-mesh-array'\n | 'unlit-material'\n | 'hdrp-7-slot'\n | 'fullscreen-post'\n | 'fullscreen-post-with-params'\n | 'fullscreen-post-with-scene-depth'\n | 'fullscreen-post-with-scene-depth-msaa'\n | 'fullscreen-post-with-paired-msaa';\n\n/**\n * Output shape of {@link buildBindGroupLayoutDescriptor}: matches the RHI\n * `BindGroupLayoutDescriptor` (label + entries with `ExplicitUndefined`) so\n * the result can be passed directly to `device.createBindGroupLayout(...)`.\n *\n * `entries` is a mutable `Array` to match `GPUBindGroupLayoutDescriptor`\n * (WebGPU types declare it mutable). Callers MUST treat the array as\n * read-only — the dispatcher freezes neither the array nor its entries\n * for hot-path performance.\n */\nexport interface BindGroupLayoutDescriptorOutput {\n readonly label: string | undefined;\n readonly entries: GPUBindGroupLayoutEntry[];\n}\n\n/** Build the canonical HDRP group(2) bind-group layout. */\nexport function createHdrpBindGroupLayoutDescriptor(): BindGroupLayoutDescriptorOutput {\n const meshBufType: GPUBufferBindingType = 'read-only-storage';\n const clusterBufType: GPUBufferBindingType = 'read-only-storage';\n return {\n label: 'hdrp-unified-bgl-group2',\n entries: [\n {\n binding: 0,\n // Standard fragment lighting (transmission/refraction and clustered\n // evaluation) reads the same mesh transform window as the vertex\n // stage. Keep this visibility in the HDRP descriptor aligned with\n // the URP mesh-array descriptor; restricting it to vertex makes the\n // HDRP pipeline invalid when fs_main accesses `meshes[0]`.\n visibility: GPU_SHADER_STAGE_VERTEX | GPU_SHADER_STAGE_FRAGMENT,\n buffer: { type: meshBufType, hasDynamicOffset: true },\n },\n // Bindings 1 and 2 stay absent for the URP physical isolation gap.\n {\n binding: 3,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n buffer: { type: clusterBufType, hasDynamicOffset: false },\n },\n {\n binding: 4,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n buffer: { type: clusterBufType, hasDynamicOffset: false },\n },\n {\n binding: 5,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n buffer: { type: clusterBufType, hasDynamicOffset: false },\n },\n {\n binding: 6,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n buffer: { type: 'uniform', hasDynamicOffset: false },\n },\n {\n binding: 7,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n texture: { sampleType: 'float', viewDimension: '2d', multisampled: false },\n },\n {\n binding: 8,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n sampler: { type: 'filtering' },\n },\n ],\n };\n}\n\n/** Build the HDRP group(2) layout for the clustered skin variant. */\nexport function createHdrpSkinBindGroupLayoutDescriptor(): BindGroupLayoutDescriptorOutput {\n const base = createHdrpBindGroupLayoutDescriptor();\n const baseEntries = base.entries;\n if (baseEntries === undefined || baseEntries[0] === undefined) {\n throw new Error('HDRP base group(2) layout must declare mesh binding 0');\n }\n const paletteType: GPUBufferBindingType = 'read-only-storage';\n return {\n label: 'hdrp-skin-unified-bgl-group2',\n entries: [\n baseEntries[0],\n {\n binding: 1,\n visibility: GPU_SHADER_STAGE_VERTEX,\n buffer: { type: paletteType, hasDynamicOffset: true },\n },\n {\n binding: 2,\n visibility: GPU_SHADER_STAGE_VERTEX,\n buffer: { type: paletteType, hasDynamicOffset: true },\n },\n ...baseEntries.slice(1),\n ],\n };\n}\n\n/**\n * Build a `GPUBindGroupLayoutDescriptor` from a PipelineSpec, dispatching on\n * `options.kind` to one of 9 closed BGL shapes (D-13 round-2).\n *\n * Shader-derived kinds (`'pbr-material-merged'` / `'unlit-material'` /\n * `'hdrp-7-slot'`) require `options.registry` to look up the shader entry\n * and reflect its `paramSchema` via {@link deriveBglShapeFromShader}; they\n * compose the per-entry injection chain (Skylight + transmission for material;\n * HDRP variantSet for cluster-forward).\n *\n * Caps-driven kinds (`'pbr-view'` / `'pbr-mesh-array'` / `'pbr-instances'` /\n * `'pbr-skin-mesh-array'`) require `options.caps` for the storage-buffer\n * vs uniform-buffer fallback (RhiCaps.storageBuffer; PBR feat-20260526 M3 /\n * w9). They are wholly determined by the caps shape.\n *\n * Attachment-driven kind (`'fullscreen-post'`) reads\n * `spec.attachments.depthFormat` and `spec.attachments.colorFormats[0]` to\n * pick the texture binding's `sampleType` (R3 fix: `'depth32float'` → `'depth'`,\n * `'r32float'` → `'unfilterable-float'`, else → `'float'`).\n *\n * @param spec - the pipeline spec (axis source for reflection / caps fallback)\n * @param options.kind - which BGL shape to build (closed {@link BglKind} union)\n * @param options.registry - ShaderCatalog for shader-derived kinds\n * @param options.caps - caps shape for caps-driven kinds (storageBuffer)\n * @returns a WebGPU bind-group-layout descriptor (entries + label)\n * @see plan-strategy §3.2 · plan-decisions D-13 · requirements AC-02\n */\n/**\n * Resolve the material paramSchema for a per-shader user-region BGL derivation.\n *\n * Priority (D-1): explicit `options.materialParamSchema` > registry lookup of\n * `spec.shader.id` > `undefined` (the user-region builder then falls back to\n * the built-in standard-PBR 4-texture schema, whose user region is 9 entries).\n */\nfunction resolveMaterialParamSchema(\n spec: PipelineSpec,\n options: { registry?: ShaderCatalog; materialParamSchema?: readonly ParamSchemaEntry[] },\n): readonly ParamSchemaEntry[] | undefined {\n if (options.materialParamSchema !== undefined) return options.materialParamSchema;\n if (options.registry !== undefined) {\n const lookup = options.registry.findMaterialArtifact(spec.shader.id);\n if (lookup.ok) return lookup.value.paramSchema;\n }\n return undefined;\n}\n\nexport function buildBindGroupLayoutDescriptor(\n spec: PipelineSpec,\n options: {\n kind: BglKind;\n registry?: ShaderCatalog;\n caps?: PbrCaps;\n /**\n * Material paramSchema for the per-shader user-region derivation\n * (`'pbr-material-merged'` / `'unlit-material'`). When supplied it is the\n * authoritative source for the user-region BGL shape (D-1); when omitted,\n * `buildPbrMaterialUserRegionEntries` falls back to the built-in\n * standard-PBR 4-texture schema (user region is 9 entries), so\n * the caps-driven `buildPbrPipelineLayouts` seam keeps working unchanged.\n * A registry + resolvable shader id takes precedence over this field.\n */\n materialParamSchema?: readonly ParamSchemaEntry[];\n },\n): BindGroupLayoutDescriptorOutput {\n switch (options.kind) {\n case 'pbr-view': {\n const caps = options.caps ?? { storageBuffer: true };\n return {\n label: 'pbr-view-bgl',\n entries: buildPbrViewBglEntries(caps),\n };\n }\n case 'pbr-mesh-array': {\n const caps = options.caps ?? { storageBuffer: true };\n const meshBufType: GPUBufferBindingType = caps.storageBuffer\n ? 'read-only-storage'\n : 'uniform';\n // sprite-lit's fragment stage does not read the mesh SSBO -- worldPos\n // is carried through the VsOut interpolant. Visibility is kept widened\n // to VERTEX|FRAGMENT because the BGL JSON is compared byte-identically\n // across the sprite / sprite-lit / PBR pipelines that share this\n // descriptor; narrowing here would change every sibling pipeline's\n // BGL fingerprint. WebGPU rejects createRenderPipeline when a fragment\n // stage accesses a binding whose BGL visibility excludes FRAGMENT --\n // widening is permissive (validation-only, no perf cost).\n return {\n label: 'pbr-mesh-array-bgl',\n entries: [\n {\n binding: 0,\n visibility: GPU_SHADER_STAGE_VERTEX | GPU_SHADER_STAGE_FRAGMENT,\n buffer: { type: meshBufType, hasDynamicOffset: true },\n },\n ],\n };\n }\n case 'pbr-instances': {\n const caps = options.caps ?? { storageBuffer: true };\n const meshBufType: GPUBufferBindingType = caps.storageBuffer\n ? 'read-only-storage'\n : 'uniform';\n const entries: GPUBindGroupLayoutEntry[] = [\n {\n binding: 0,\n visibility: GPU_SHADER_STAGE_VERTEX,\n buffer: { type: meshBufType, hasDynamicOffset: false },\n },\n ...(caps.probeBlend === true\n ? [\n {\n // Per-object fragment lane; the record is always exactly 160B.\n binding: 1,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n buffer: { type: meshBufType, hasDynamicOffset: true },\n },\n ]\n : []),\n ];\n return {\n label: caps.probeBlend === true ? 'pbr-probe-instances-bgl' : 'pbr-instances-bgl',\n entries: entries.map((entry) =>\n entry.binding === 0\n ? {\n ...entry,\n // Standard transmission reads the same per-instance transform in\n // fs_main to convert glTF unit-space thickness into world metres.\n visibility: GPU_SHADER_STAGE_VERTEX | GPU_SHADER_STAGE_FRAGMENT,\n }\n : entry,\n ),\n };\n }\n case 'pbr-gpu-driven-instances': {\n const caps = options.caps ?? { storageBuffer: true };\n const meshBufType: GPUBufferBindingType = caps.storageBuffer\n ? 'read-only-storage'\n : 'uniform';\n // GPU-driven scene-index draws use a physically distinct slot-3 layout.\n // The ordinary instances BGL intentionally stays one-entry for direct\n // draws, while ProbeBlend owns binding(1). Keep the compact visible\n // `(meshRow, materialRow)` stream at binding(2) so a future probe-enabled\n // GPU variant can coexist without colliding with the probe record.\n return {\n label: 'pbr-gpu-driven-instances-bgl',\n entries: [\n {\n binding: 0,\n visibility: GPU_SHADER_STAGE_VERTEX,\n buffer: { type: meshBufType, hasDynamicOffset: false },\n },\n {\n // ShadowCaster's scene-index entry still reads the visible row\n // through binding(1). Keep this alias in the dedicated layout so\n // the shared visible bind group can serve both the Standard PBR\n // (binding(2)) and depth-only shadow (binding(1)) consumers.\n binding: 1,\n visibility: GPU_SHADER_STAGE_VERTEX | GPU_SHADER_STAGE_FRAGMENT,\n buffer: { type: meshBufType, hasDynamicOffset: false },\n },\n {\n binding: 2,\n visibility: GPU_SHADER_STAGE_VERTEX,\n buffer: { type: meshBufType, hasDynamicOffset: false },\n },\n {\n // Generic Surface dynamic pages are read by authored Surface\n // accessors. The binding is present for every scene-index group\n // so Standard and custom Surface batches share one owner shape.\n binding: 3,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n buffer: { type: meshBufType, hasDynamicOffset: false },\n },\n {\n // Frame time, explicit event ranges, and paired background/depth\n // facts use separate read-only pages. This keeps live state out\n // of the material row and leaves skin's address lane untouched.\n binding: 4,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n buffer: { type: meshBufType, hasDynamicOffset: false },\n },\n {\n // Frame time is one frame-global fact. Keeping it outside the\n // member row prevents a stable frame from issuing one 4-byte\n // queue write for every visible Surface member.\n binding: 5,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n buffer: { type: 'uniform', hasDynamicOffset: false },\n },\n ],\n };\n }\n case 'pbr-surface-direct-instances': {\n return {\n label: 'pbr-surface-direct-instances-bgl',\n entries: [\n {\n binding: 0,\n // Direct instance transforms are consumed only by vs_main. Keep\n // them out of the fragment-stage storage budget; Surface already\n // needs the retained ProbeBlend/page/frame records there and the\n // portable WebGPU limit is eight storage buffers per stage.\n visibility: GPU_SHADER_STAGE_VERTEX,\n buffer: { type: 'read-only-storage', hasDynamicOffset: false },\n },\n {\n binding: 1,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n buffer: { type: 'read-only-storage', hasDynamicOffset: true },\n },\n {\n binding: 3,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n buffer: { type: 'read-only-storage', hasDynamicOffset: false },\n },\n {\n binding: 4,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n buffer: { type: 'read-only-storage', hasDynamicOffset: false },\n },\n {\n binding: 5,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n buffer: { type: 'uniform', hasDynamicOffset: false },\n },\n {\n binding: 6,\n visibility: GPU_SHADER_STAGE_VERTEX,\n buffer: { type: 'uniform', hasDynamicOffset: false },\n },\n ],\n };\n }\n case 'pbr-skin-mesh-array': {\n const caps = options.caps ?? { storageBuffer: true };\n const meshBufType: GPUBufferBindingType = caps.storageBuffer\n ? 'read-only-storage'\n : 'uniform';\n return {\n label: 'pbr-skin-mesh-array-bgl',\n entries: [\n {\n binding: 0,\n visibility: GPU_SHADER_STAGE_VERTEX | GPU_SHADER_STAGE_FRAGMENT,\n buffer: { type: meshBufType, hasDynamicOffset: true },\n },\n {\n binding: 1,\n visibility: GPU_SHADER_STAGE_VERTEX,\n buffer: { type: meshBufType, hasDynamicOffset: true },\n },\n {\n binding: 2,\n visibility: GPU_SHADER_STAGE_VERTEX,\n buffer: { type: meshBufType, hasDynamicOffset: true },\n },\n ],\n };\n }\n case 'pbr-material-merged': {\n // Material BGL: per-shader user-region (derive(paramSchema).bglEntries)\n // + IBL injection (6) + transmission injection (2). The user-region\n // size is the only variable; injection start = userRegion.length so a\n // custom schema shifts IBL/transmission by its sampler/texture pairs.\n // The built-in standard-PBR user region has 15 entries;\n // scene rows follow injection, and physical texture pairs follow the effective root schema.\n //\n // Schema source priority (D-1): explicit materialParamSchema option >\n // registry lookup of spec.shader.id > built-in standard-PBR fallback.\n const resolvedSchema = resolveMaterialParamSchema(spec, options);\n const effectiveSchema = resolvedSchema ?? STANDARD_PIPELINE_PARAM_SCHEMA;\n const physicalFields = physicalTextureFields(effectiveSchema);\n // Standard's built-in shader keeps the transmission user-region slots\n // reserved even when a particular root omits those values. Physical\n // maps extend that canonical region; they must not compact the IBL\n // bindings to the smaller authored subset. A compact user region is\n // still correct for authored (non-engine) material shaders.\n const userRegionSchema = isCanonicalStandardPbrMaterialShader(spec.shader.id)\n ? STANDARD_PIPELINE_PARAM_SCHEMA\n : effectiveSchema;\n const userRegion = buildPbrMaterialUserRegionEntries(userRegionSchema);\n const afterIbl = [...userRegion, ...appendInjection(userRegion, 'ibl')];\n const afterTransmission = [...afterIbl, ...appendInjection(afterIbl, 'transmission')];\n const engineRegion =\n options.caps?.transmissionBackdrop === false &&\n spec.shader.id !== 'forgeax::single-layer-medium'\n ? afterIbl\n : afterTransmission;\n const afterSurfaceMedium =\n spec.shader.id === 'forgeax::single-layer-medium'\n ? [...engineRegion, ...appendSingleLayerMediumInjection(engineRegion)]\n : engineRegion;\n const merged = [\n ...afterSurfaceMedium,\n ...appendTextureInjection(afterSurfaceMedium, physicalFields),\n ];\n // Scene-index Standard variants consume one producer-owned material row\n // after the complete fixed physical range. Keeping it at binding 46\n // prevents any authored physical subset from aliasing the row.\n if (options.caps?.storageBuffer ?? true) {\n merged.push({\n binding: 46,\n visibility: GPU_SHADER_STAGE_VERTEX | GPU_SHADER_STAGE_FRAGMENT,\n buffer: { type: 'read-only-storage', hasDynamicOffset: false },\n });\n }\n const entries = [\n ...merged,\n ...(spec.shader.id === 'forgeax::single-layer-medium'\n ? []\n : [\n {\n binding: 47,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n texture: { sampleType: 'float' as const, viewDimension: 'cube' as const },\n },\n ]),\n ];\n return {\n label: 'pbr-material-skylight-bgl',\n entries,\n };\n }\n case 'unlit-material': {\n // Unlit material BGL: per-shader user-region only. No IBL/transmission\n // injection (D-5 round-4: unlit demos do not pay for IBL state).\n const resolvedSchema = resolveMaterialParamSchema(spec, options);\n return {\n label: 'unlit-material-bgl',\n entries: buildPbrMaterialUserRegionEntries(resolvedSchema),\n };\n }\n case 'hdrp-7-slot': {\n // Standard unified BGL for group(2): 9 entries (binding 0 + 3..8).\n // Cluster variants are admitted only when storage buffers are present;\n // there is no uniform-backed cluster shape.\n const desc = createHdrpBindGroupLayoutDescriptor();\n return {\n label: desc.label ?? 'hdrp-unified-bgl-group2',\n entries: [...(desc.entries ?? [])],\n };\n }\n case 'fullscreen-post': {\n // Fullscreen post-process BGL: 2 entries (input texture + sampler).\n // R3 fix: derive sampleType from spec.attachments. Depth attachments\n // (depth32float) need `sampleType: 'depth'`; r32float needs\n // `'unfilterable-float'`; everything else (rgba8unorm-srgb, rgba16float,\n // bgra8unorm, …) is filterable `'float'`.\n return {\n label: 'fullscreen-post-bgl',\n entries: buildFullscreenPostInputEntries(spec),\n };\n }\n case 'fullscreen-post-with-params': {\n // feat-20260621 D-2: the same input texture@0 + sampler@1 as\n // 'fullscreen-post', plus binding 2 = per-frame params UBO (uniform).\n // The first two entries reuse buildFullscreenPostInputEntries so the\n // sampleType derivation stays a single SSOT; 'fullscreen-post' is\n // untouched (param-less zero-regression, R-A7).\n return {\n label: 'fullscreen-post-with-params-bgl',\n entries: [\n ...buildFullscreenPostInputEntries(spec),\n {\n binding: 2,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n buffer: { type: 'uniform' },\n },\n ],\n };\n }\n case 'fullscreen-post-with-scene-depth': {\n // plan-strategy D-3: 5-entry BGL for post-process passes that read the\n // camera scene depth. color@0 + sampler@1 reuse buildFullscreenPostInputEntries\n // (float+filtering for color). depthTex@3 uses `sampleType: 'depth'` and\n // `dimension: '2d'`; depthSampler@4 uses `type: 'non-filtering'` (nearest\n // + clamp-to-edge, D-2 — NOT comparison). params@2 is always present\n // (uniform) to avoid a 2x2 kind explosion per D-3.\n return {\n label: 'fullscreen-post-with-scene-depth-bgl',\n entries: [\n ...buildFullscreenPostInputEntries(spec),\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 texture: { sampleType: 'depth', viewDimension: '2d' },\n },\n {\n binding: 4,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n sampler: { type: 'non-filtering' },\n },\n ],\n };\n }\n case 'fullscreen-post-with-scene-depth-msaa': {\n return {\n label: 'fullscreen-post-with-scene-depth-msaa-bgl',\n entries: [\n ...buildFullscreenPostInputEntries(spec),\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 texture: { sampleType: 'depth', viewDimension: '2d', multisampled: true },\n },\n {\n binding: 4,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n sampler: { type: 'non-filtering' },\n },\n ],\n };\n }\n case 'fullscreen-post-with-paired-msaa': {\n return {\n label: 'fullscreen-post-with-paired-msaa-bgl',\n entries: [\n {\n binding: 0,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n texture: {\n sampleType: 'unfilterable-float',\n viewDimension: '2d',\n multisampled: true,\n },\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 texture: { sampleType: 'depth', viewDimension: '2d', multisampled: true },\n },\n {\n binding: 4,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n sampler: { type: 'non-filtering' },\n },\n ],\n };\n }\n }\n}\n\n/**\n * The shared texture@0 + sampler@1 entries for fullscreen post-process BGLs.\n * sampleType is derived from `spec.attachments` (R3 fix): depth attachments →\n * `'depth'` + `'comparison'` sampler; `'r32float'` → `'unfilterable-float'`;\n * else → `'float'` + `'filtering'`. Both `'fullscreen-post'` and\n * `'fullscreen-post-with-params'` reuse this so the derivation is one SSOT.\n */\nfunction buildFullscreenPostInputEntries(spec: PipelineSpec): GPUBindGroupLayoutEntry[] {\n const inputFormat: GPUTextureFormat | undefined =\n spec.attachments.depthFormat ?? spec.attachments.colorFormats[0];\n const sampleType: GPUTextureSampleType =\n inputFormat === 'depth32float' ||\n inputFormat === 'depth24plus' ||\n inputFormat === 'depth24plus-stencil8' ||\n inputFormat === 'depth16unorm'\n ? 'depth'\n : inputFormat === 'r32float'\n ? 'unfilterable-float'\n : 'float';\n return [\n {\n binding: 0,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n texture: { sampleType, viewDimension: '2d' },\n },\n {\n binding: 1,\n visibility: GPU_SHADER_STAGE_FRAGMENT,\n sampler: {\n type: sampleType === 'depth' ? 'comparison' : 'filtering',\n },\n },\n ];\n}\n\n// ══════════════════════════════════════════════════════════════════════════════\n","// M3 / w19: PassSelector matching logic\n// (feat-20260526-material-asset-multipass-renderstate)\n//\n// Pure-function helpers for matching MaterialPass tags against\n// a PassSelector. Plan-strategy D-4: Tags free Record + PassSelector\n// Record<string, string[]>. Requirements AC-05.\n\nimport type { MaterialPass, PassSelector } from '@forgeax/engine-types';\n\n/**\n * Test whether a pass's tags match a {@link PassSelector}.\n *\n * Matching rule (AC-05): every key in the selector must exist in the pass's\n * `tags` and the pass's tag value must be in the selector's value list for\n * that key. An empty selector matches every pass.\n *\n * @param tags The pass-level tags (free key-value pairs)\n * @param selector The selector to match against\n */\nexport function matchPass(tags: Record<string, string>, selector: PassSelector): boolean {\n if (Object.keys(selector).length === 0) return true;\n for (const [key, allowedValues] of Object.entries(selector)) {\n const passValue = tags[key];\n if (passValue === undefined) return false;\n if ((allowedValues as readonly string[]).length === 0) return false;\n if (!(allowedValues as readonly string[]).includes(passValue)) return false;\n }\n return true;\n}\n\n/**\n * Filter passes whose tags match the given {@link PassSelector}.\n *\n * An empty selector matches all passes (returns the input array reference).\n * Otherwise each pass is checked via {@link matchPass}.\n *\n * @param passes The material's pass descriptors\n * @param selector The pass selector\n * @returns Filtered array of matching passes\n */\nexport function selectPasses(\n passes: readonly MaterialPass[],\n selector: PassSelector,\n): readonly MaterialPass[] {\n if (Object.keys(selector).length === 0) return passes;\n return passes.filter((p) =>\n matchPass((p.renderState?.tags as Record<string, string> | undefined) ?? {}, selector),\n );\n}\n","import type {\n MaterialShaderArtifact,\n MaterialShaderArtifactReceipt,\n MaterialShaderVertexInput,\n} from '@forgeax/engine-shader';\nimport type { PrimitiveTopology } from '@forgeax/engine-types';\nimport {\n GpuDrivenPreparationError,\n type GpuDrivenPreparationErrorDetail,\n} from '../errors/gpu-driven';\nimport type { RenderableSnapshot } from '../render-system-extract';\n\nexport interface GpuDrivenGeometryReceipt {\n readonly identity: string;\n readonly vertexInputs: readonly MaterialShaderVertexInput[];\n readonly topology: PrimitiveTopology;\n readonly indexed: boolean;\n}\n\nexport interface GpuDrivenSkinReceipt {\n readonly identity: string;\n readonly generation: number;\n readonly group: number;\n readonly binding: number;\n readonly byteOffset: number;\n}\n\nexport interface PreparedGpuDrivenDraw {\n readonly identity: {\n readonly material: string;\n readonly geometry: string;\n readonly deformation: 'rigid' | 'skin';\n };\n readonly receiptGeneration: number;\n /** Content/layout identity that separates ABI variants (for example COLOR_0). */\n readonly receiptIdentity?: string;\n readonly directEntry: string;\n readonly sceneIndexEntry: string;\n readonly materialRow: MaterialShaderArtifactReceipt['materialRow'];\n readonly resourceSlots: MaterialShaderArtifactReceipt['resourceSlots'];\n readonly uvSets: MaterialShaderArtifactReceipt['uvSets'];\n readonly vertexInputs: MaterialShaderArtifactReceipt['vertexInputs'];\n readonly alphaMask: MaterialShaderArtifactReceipt['alphaMask'];\n readonly skinPaletteAddress: MaterialShaderArtifactReceipt['skinPaletteAddress'];\n readonly topology: PrimitiveTopology;\n readonly indexed: boolean;\n readonly first: number;\n readonly count: number;\n readonly baseVertex: number;\n}\n\n/** Exact extracted draw range consumed by the preparation owner. */\nexport interface GpuDrivenDrawRange {\n readonly kind: 'indexed' | 'non-indexed';\n readonly first: number;\n readonly count: number;\n readonly baseVertex: number;\n readonly topology: PrimitiveTopology;\n}\n\nexport interface PrepareGpuDrivenDrawInput {\n readonly snapshot: RenderableSnapshot;\n readonly artifact: MaterialShaderArtifact;\n readonly geometry: GpuDrivenGeometryReceipt;\n readonly generation: number;\n /** The submesh draw currently being prepared; never infer draw zero. */\n readonly draw: GpuDrivenDrawRange;\n readonly skinReceipt?: GpuDrivenSkinReceipt;\n}\n\nfunction failure(\n code: ConstructorParameters<typeof GpuDrivenPreparationError>[0],\n detail: GpuDrivenPreparationErrorDetail,\n): { readonly ok: false; readonly error: GpuDrivenPreparationError } {\n return { ok: false, error: new GpuDrivenPreparationError(code, detail) };\n}\n\n/**\n * A material receipt declares the inputs its shader consumes. Geometry may\n * carry additional authored attributes (for example an unused TEXCOORD_1),\n * so admission checks required locations and formats without treating those\n * producer-owned extras as an ABI mismatch.\n */\nexport function hasRequiredVertexInputs(\n expected: readonly MaterialShaderVertexInput[],\n actual: readonly MaterialShaderVertexInput[],\n): boolean {\n return expected.every((input) =>\n actual.some(\n (candidate) =>\n candidate.semantic === input.semantic &&\n candidate.location === input.location &&\n candidate.format === input.format,\n ),\n );\n}\n\nfunction hasMaterialResources(\n snapshot: RenderableSnapshot,\n receipt: MaterialShaderArtifactReceipt,\n) {\n // Video frames and renderer-local target sources have no stable\n // scene-index binding in this feature. Extract keeps those draws on the\n // explicit CPU semantic lane; direct contract callers must fail closed too.\n if (\n (snapshot.material.textureSources?.size ?? 0) > 0 ||\n (snapshot.material.videoTextureFields?.size ?? 0) > 0\n ) {\n return false;\n }\n const textures = snapshot.material.textureHandles;\n const samplers = snapshot.material.samplerHandles;\n const authoredTextures = snapshot.material.authoredTextureFields;\n const authoredSamplers = snapshot.material.authoredSamplerFields;\n // Standard PBR declares optional texture slots whose missing values are\n // supplied by the existing frame material producer (white, flat-normal,\n // black, or the configured IBL defaults). Only an explicitly authored slot\n // is a readiness requirement; this keeps numeric-only PBR on the same GPU\n // lane while still rejecting an authored handle that failed to resolve.\n return receipt.resourceSlots.every((slot) => {\n // The renderer-owned Surface page is the one storage resource that is\n // intentionally available to a scene-index draw. Its address is\n // published in the Surface ABI; every other storage declaration still\n // fails closed because MaterialSnapshot has no generic storage handle.\n if (slot.kind === 'storage-buffer') {\n return (\n receipt.surface?.dynamicInput?.group === slot.group &&\n receipt.surface.dynamicInput.binding === slot.binding &&\n slot.group === 3 &&\n slot.binding === 3\n );\n }\n if (slot.kind === 'texture') {\n if (!authoredTextures?.has(slot.parameter)) return true;\n return (\n textures?.has(slot.parameter) === true ||\n snapshot.material.textureSources?.has(slot.parameter) === true ||\n snapshot.material.videoTextureFields?.has(slot.parameter) === true\n );\n }\n if (!authoredSamplers?.has(slot.parameter)) return true;\n return samplers?.has(slot.parameter) === true;\n });\n}\n\nexport function prepareGpuDrivenDraw(\n input: PrepareGpuDrivenDrawInput,\n):\n | { readonly ok: true; readonly value: PreparedGpuDrivenDraw }\n | { readonly ok: false; readonly error: GpuDrivenPreparationError } {\n const receipt = input.artifact.receipt;\n if (receipt === undefined) {\n return failure('missing-material-receipt', {\n reason: 'material-receipt-missing',\n owner: 'material',\n expected: 'MaterialShaderArtifact.receipt',\n });\n }\n if (receipt.generation !== input.generation) {\n return failure('stale-generation', {\n reason: 'generation-stale',\n owner: 'generation',\n expectedGeneration: input.generation,\n actualGeneration: receipt.generation,\n });\n }\n if (receipt.reflection.layoutIdentity !== input.artifact.layoutIdentity) {\n return failure('reflection-mismatch', {\n reason: 'reflection-receipt-mismatch',\n owner: 'material',\n expected: input.artifact.layoutIdentity,\n actual: receipt.reflection.layoutIdentity,\n });\n }\n if (receipt.uvSets.some((uv) => uv.set > 0) && input.geometry.vertexInputs.length < 3) {\n return failure('missing-uv', {\n reason: 'uv-set-missing',\n owner: 'geometry',\n expected: `${receipt.uvSets.length} material UV sets`,\n actual: `${input.geometry.vertexInputs.filter((vertex) => vertex.semantic.startsWith('uv')).length} geometry UV sets`,\n });\n }\n if (!hasRequiredVertexInputs(receipt.vertexInputs, input.geometry.vertexInputs)) {\n return failure('vertex-input-mismatch', {\n reason: 'vertex-semantic-mismatch',\n owner: 'geometry',\n expected: receipt.vertexInputs.map((input) => input.semantic).join(','),\n actual: input.geometry.vertexInputs.map((input) => input.semantic).join(','),\n });\n }\n const hasAlphaMask = receipt.alphaMask.cutoff.length > 0 || receipt.alphaMask.source.length > 0;\n if (\n hasAlphaMask &&\n (receipt.alphaMask.cutoff.length === 0 || receipt.alphaMask.source.length === 0)\n ) {\n return failure('alpha-mask-mismatch', {\n reason: 'alpha-mask-receipt-missing',\n owner: 'material',\n expected: 'alphaMask.cutoff and alphaMask.source for a masked Pass',\n });\n }\n if (!hasMaterialResources(input.snapshot, receipt)) {\n return failure('resource-not-ready', {\n reason: 'material-resource-missing',\n owner: 'material',\n expected: receipt.resourceSlots.map((slot) => slot.parameter).join(','),\n });\n }\n const deformation = input.snapshot.skin === undefined ? 'rigid' : 'skin';\n if (deformation === 'skin') {\n if (input.skinReceipt === undefined || receipt.skinPaletteAddress === undefined) {\n return failure('skin-receipt-mismatch', {\n reason: 'skin-address-missing',\n owner: 'skin',\n expected: 'skinPaletteAddress and skinReceipt',\n });\n }\n if (\n input.skinReceipt.identity !== input.snapshot.skin?.identity ||\n input.skinReceipt.generation !== input.snapshot.skin?.generation ||\n input.skinReceipt.group !== receipt.skinPaletteAddress.group ||\n input.skinReceipt.binding !== receipt.skinPaletteAddress.binding\n ) {\n return failure('skin-receipt-mismatch', {\n reason: 'skin-address-missing',\n owner: 'skin',\n expected: `${receipt.skinPaletteAddress.group}:${receipt.skinPaletteAddress.binding}@${input.snapshot.skin?.generation ?? '<missing>'}`,\n actual: `${input.skinReceipt.group}:${input.skinReceipt.binding}@${input.skinReceipt.generation}`,\n });\n }\n }\n return {\n ok: true,\n value: {\n identity: {\n material: input.artifact.material,\n geometry: input.geometry.identity,\n deformation,\n },\n receiptGeneration: receipt.generation,\n receiptIdentity: receipt.receiptIdentity,\n directEntry: receipt.directEntry,\n sceneIndexEntry: receipt.sceneIndexEntry,\n materialRow: receipt.materialRow,\n resourceSlots: receipt.resourceSlots,\n uvSets: receipt.uvSets,\n vertexInputs: receipt.vertexInputs,\n alphaMask: receipt.alphaMask,\n skinPaletteAddress: receipt.skinPaletteAddress,\n topology: input.draw.topology,\n indexed: input.draw.kind === 'indexed',\n first: input.draw.first,\n count: input.draw.count,\n baseVertex: input.draw.baseVertex,\n },\n };\n}\n","import { deriveVertexLayoutProjection } from '@forgeax/engine-geometry';\nimport type { MaterialShaderArtifact } from '@forgeax/engine-shader';\nimport type { MeshAsset } from '@forgeax/engine-types';\nimport { GpuDrivenPreparationError } from '../errors/gpu-driven';\nimport {\n type GpuDrivenDrawRange,\n type GpuDrivenGeometryReceipt,\n type GpuDrivenSkinReceipt,\n type PreparedGpuDrivenDraw,\n type PrepareGpuDrivenDrawInput,\n prepareGpuDrivenDraw,\n} from '../gpu-driven/prepared-draw';\nimport { isCanonicalStandardPbrMaterialShader } from '../pbr-pipeline';\nimport type { MaterialSnapshot, RenderableSnapshot } from '../render-system-extract';\n\nexport {\n GpuDrivenPreparationError,\n type GpuDrivenPreparationErrorCode,\n type GpuDrivenPreparationErrorDetail,\n type GpuDrivenPreparationReason,\n} from '../errors/gpu-driven';\nexport {\n type GpuDrivenDrawRange,\n type GpuDrivenGeometryReceipt,\n type GpuDrivenSkinReceipt,\n type PreparedGpuDrivenDraw,\n type PrepareGpuDrivenDrawInput,\n prepareGpuDrivenDraw,\n} from '../gpu-driven/prepared-draw';\n\nexport interface GpuDrivenDrawSnapshot {\n /** Stable source submesh identity; compact draw arrays must not renumber it. */\n readonly drawItemIndex?: number;\n readonly kind: GpuDrivenDrawRange['kind'];\n readonly first: GpuDrivenDrawRange['first'];\n readonly count: GpuDrivenDrawRange['count'];\n readonly baseVertex: GpuDrivenDrawRange['baseVertex'];\n readonly materialSlot: number;\n readonly topology: GpuDrivenDrawRange['topology'];\n readonly pipelineClass: string;\n readonly materialResourceClass: string;\n /** Producer-owned prepared ABI facts used by the PBR GPU lane. */\n readonly prepared?: PreparedGpuDrivenDraw;\n /** Structured producer failure; record never interprets an incomplete draw. */\n readonly preparationError?: GpuDrivenPreparationError;\n /** Optional lower-detail ranges aligned with the snapshot's LOD levels. */\n readonly lodRanges?: readonly {\n readonly first: number;\n readonly count: number;\n readonly baseVertex: number;\n }[];\n /** Optional camera-projected height supplied by direct GPU-view evidence. */\n readonly projectedHeight?: number;\n}\n\n/** Stable ownership key for one entity/material/concrete GPU draw item. */\nexport function gpuDrivenDrawKey(\n worldEntity: number,\n materialHandle: number,\n drawItemIndex: number,\n): string {\n return `${worldEntity}:${materialHandle}:${drawItemIndex}`;\n}\n\n/** Stable ShadowCaster ownership key: entity, concrete GPU draw item, and pass. */\nexport function gpuDrivenShadowDrawKey(\n worldEntity: number,\n materialHandle: number,\n drawItemIndex: number,\n passIndex: number,\n): string {\n return `${gpuDrivenDrawKey(worldEntity, materialHandle, drawItemIndex)}:${passIndex}`;\n}\n\n/**\n * Stable lookup key for the producer-published material artifact selected by\n * one prepared draw. The receipt identity is intentionally part of the key:\n * a COLOR_0 variant (or any later ABI variant) must never share a pipeline or\n * projection cache entry with its no-color sibling.\n */\nexport function gpuDrivenMaterialArtifactKey(input: {\n readonly material: string;\n readonly deformation: 'rigid' | 'skin';\n readonly receiptIdentity: string | undefined;\n readonly receiptGeneration: number;\n}): string {\n return [\n input.material,\n input.deformation,\n input.receiptIdentity ?? '<legacy-receipt>',\n input.receiptGeneration,\n ].join('|');\n}\n\n/** Resolve the producer-owned source identity for one compact draw snapshot. */\nexport function gpuDrivenSourceDrawItemIndex(\n draw: GpuDrivenDrawSnapshot,\n compactIndex: number,\n): number {\n return draw.drawItemIndex ?? compactIndex;\n}\n\n/**\n * Resolves prepared facts once at extract time; record never re-reads assets.\n * The resolver surfaces UV, reflection, vertex, alpha, resource, and\n * generation failures as GpuDrivenPreparationError before recording.\n */\nexport function resolvePreparedGpuDrivenDraw(input: PrepareGpuDrivenDrawInput):\n | { readonly ok: true; readonly value: PreparedGpuDrivenDraw }\n | {\n readonly ok: false;\n readonly error: import('../errors/gpu-driven').GpuDrivenPreparationError;\n } {\n return prepareGpuDrivenDraw(input);\n}\n\n/** Keeps the artifact type visible at this owner boundary for contract checks. */\nexport type PreparedGpuDrivenArtifact = MaterialShaderArtifact;\n\n/**\n * Derives the resource identity consumed by the existing GPU-driven batch\n * owner. The extract stage is the only place that resolves material values;\n * this helper keeps the batch adapter from re-reading assets later.\n */\nexport function gpuDrivenMaterialResourceClass(material: MaterialSnapshot): string {\n const textures = [...(material.textureHandles?.entries() ?? [])]\n .map(([name, handle]) => [name, Number(handle)] as const)\n .sort(([left], [right]) => left.localeCompare(right));\n const samplers = [...(material.samplerHandles?.entries() ?? [])]\n .map(([name, handle]) => [name, Number(handle)] as const)\n .sort(([left], [right]) => left.localeCompare(right));\n return JSON.stringify({\n textures,\n samplers,\n });\n}\n\n/**\n * Dynamic renderer-local targets and video frames are owned by their host\n * producers and do not have a stable scene-index binding in this feature.\n * Keep them on the explicit CPU semantic lane instead of inventing a\n * per-instance resource table or grouping opaque source objects by shape.\n */\nfunction hasCpuOnlyMaterialResources(material: MaterialSnapshot): boolean {\n return (material.textureSources?.size ?? 0) > 0 || (material.videoTextureFields?.size ?? 0) > 0;\n}\n\n/**\n * Projects already-resolved mesh facts into the existing GPU-driven draw\n * snapshot. No World or AssetRegistry access is permitted at this boundary.\n */\ninterface BuildGpuDrivenDrawsInput {\n readonly mesh: MeshAsset | undefined;\n readonly materials: readonly MaterialSnapshot[];\n readonly fallbackMaterial: MaterialSnapshot;\n readonly baseSnapshot: RenderableSnapshot;\n readonly getMaterialShaderArtifact?: (\n materialShaderId: string,\n request?: {\n readonly vertexColorAvailable?: boolean;\n readonly deformation?: 'rigid' | 'skin';\n readonly pass?: 'forward' | 'shadow' | 'depth';\n readonly address?: 'direct' | 'scene-index';\n },\n ) => MaterialShaderArtifact | undefined;\n /** Resolved lower-detail meshes, in the same order as baseSnapshot.lods. */\n readonly lodMeshes?: readonly (MeshAsset | undefined)[];\n}\n\ninterface LegacyBuildGpuDrivenDrawsInput {\n readonly submeshes: readonly MeshAsset['submeshes'][number][];\n readonly indexed: boolean;\n readonly materials: readonly MaterialSnapshot[];\n readonly fallbackMaterial: MaterialSnapshot;\n readonly prepare?: (\n draw: GpuDrivenDrawSnapshot,\n material: MaterialSnapshot,\n ) => PreparedGpuDrivenDraw | undefined;\n}\n\nexport function buildGpuDrivenDraws(input: BuildGpuDrivenDrawsInput): GpuDrivenDrawSnapshot[];\nexport function buildGpuDrivenDraws(input: LegacyBuildGpuDrivenDrawsInput): GpuDrivenDrawSnapshot[];\nexport function buildGpuDrivenDraws(\n input: BuildGpuDrivenDrawsInput | LegacyBuildGpuDrivenDrawsInput,\n): GpuDrivenDrawSnapshot[] {\n const legacy = 'submeshes' in input;\n if (!legacy && input.mesh === undefined) return [];\n const parsedMesh = legacy ? undefined : input.mesh;\n if (!legacy && parsedMesh === undefined) return [];\n const indexed = legacy ? input.indexed : parsedMesh?.indices !== undefined;\n const submeshes = legacy ? input.submeshes : (parsedMesh?.submeshes ?? []);\n const layoutProjection =\n parsedMesh === undefined ? undefined : deriveVertexLayoutProjection(parsedMesh.attributes);\n const geometry: GpuDrivenGeometryReceipt = {\n identity:\n parsedMesh === undefined\n ? '<no-mesh>'\n : `${(parsedMesh as { guid?: string }).guid ?? '<no-guid>'}:${layoutProjection?.digest ?? ''}`,\n vertexInputs: (layoutProjection?.attributes ?? []).map((attribute) => ({\n semantic: attribute.key,\n location: attribute.shaderLocation,\n format: attribute.format,\n })),\n topology: submeshes[0]?.topology ?? 'triangle-list',\n indexed,\n };\n let nonIndexedFirst = 0;\n return submeshes.flatMap((submesh, drawItemIndex) => {\n const drawMaterial = input.materials[submesh.materialSlot] ?? input.fallbackMaterial;\n const first = indexed ? submesh.indexOffset : nonIndexedFirst;\n nonIndexedFirst += submesh.vertexCount;\n if (drawMaterial.transparent === true) return [];\n const draw: GpuDrivenDrawSnapshot = {\n drawItemIndex,\n kind: indexed ? ('indexed' as const) : ('non-indexed' as const),\n first,\n count: indexed ? submesh.indexCount : submesh.vertexCount,\n baseVertex: 0,\n materialSlot: submesh.materialSlot,\n topology: submesh.topology,\n pipelineClass: `${drawMaterial.materialShaderId ?? 'forgeax::default-unlit'}|${submesh.topology}|${JSON.stringify(drawMaterial.renderState ?? null)}`,\n materialResourceClass: gpuDrivenMaterialResourceClass(drawMaterial),\n };\n const lodRanges = !legacy\n ? input.lodMeshes?.map((lodMesh) => {\n if (lodMesh === undefined) return undefined;\n const lower = lodMesh.submeshes[drawItemIndex];\n if (lower === undefined) return undefined;\n const lowerIndexed = lodMesh.indices !== undefined;\n const lowerFirst = lowerIndexed\n ? lower.indexOffset\n : lodMesh.submeshes\n .slice(0, drawItemIndex)\n .reduce((offset, entry) => offset + entry.vertexCount, 0);\n return {\n first: lowerFirst,\n count: lowerIndexed ? lower.indexCount : lower.vertexCount,\n baseVertex: 0,\n };\n })\n : undefined;\n const withLodRanges =\n lodRanges?.length !== 0 && lodRanges?.every((range) => range !== undefined)\n ? { lodRanges: lodRanges as { first: number; count: number; baseVertex: number }[] }\n : {};\n const prepared = legacy\n ? input.prepare?.(draw, drawMaterial)\n : hasCpuOnlyMaterialResources(drawMaterial)\n ? undefined\n : (() => {\n const materialShaderId = drawMaterial.materialShaderId;\n const vertexColorAvailable = geometry.vertexInputs.some(\n (input) => input.semantic === 'color',\n );\n // The snapshot keeps the direct program key as its logical\n // material identity. A published scene-index program has a\n // separate specialization key; resolve that concrete artifact\n // before preparing the draw so the indirect pipeline receives the\n // scene entry rather than silently reusing the direct shader.\n const sceneIndexProgramKey = Object.entries(\n drawMaterial.materialSceneIndexProgramKeys ?? {},\n ).find(\n ([passName, program]) =>\n program.pass === 'forward' &&\n drawMaterial.materialProgramKeys?.[passName] === materialShaderId,\n )?.[1]?.specializationKey;\n const artifact =\n materialShaderId === undefined\n ? undefined\n : input.getMaterialShaderArtifact?.(sceneIndexProgramKey ?? materialShaderId, {\n vertexColorAvailable,\n deformation: input.baseSnapshot.skin === undefined ? 'rigid' : 'skin',\n pass: 'forward',\n address: 'scene-index',\n });\n // Canonical roots and explicitly published scene-index programs\n // require their producer receipt. Legacy direct-only aliases do not.\n const requiresReceipt =\n isCanonicalStandardPbrMaterialShader(materialShaderId) ||\n sceneIndexProgramKey !== undefined;\n\n if (artifact === undefined) {\n return input.getMaterialShaderArtifact !== undefined && requiresReceipt\n ? new GpuDrivenPreparationError('missing-material-receipt', {\n reason: 'material-receipt-missing',\n owner: 'material',\n expected: `artifact for ${materialShaderId}`,\n })\n : undefined;\n }\n const receipt = artifact.receipt;\n if (receipt === undefined) {\n return new GpuDrivenPreparationError('missing-material-receipt', {\n reason: 'material-receipt-missing',\n owner: 'material',\n expected: `receipt for ${materialShaderId}`,\n });\n }\n const skinReceipt: GpuDrivenSkinReceipt | undefined =\n input.baseSnapshot.skin !== undefined && receipt.skinPaletteAddress !== undefined\n ? {\n identity: input.baseSnapshot.skin.identity,\n generation: input.baseSnapshot.skin.generation,\n group: receipt.skinPaletteAddress.group,\n binding: receipt.skinPaletteAddress.binding,\n byteOffset: input.baseSnapshot.skin.byteOffset,\n }\n : undefined;\n const selectedArtifact =\n artifact === undefined ||\n sceneIndexProgramKey === undefined ||\n materialShaderId === undefined\n ? artifact\n : {\n ...artifact,\n material: materialShaderId,\n specializationKey: sceneIndexProgramKey,\n };\n const result = resolvePreparedGpuDrivenDraw({\n snapshot: { ...input.baseSnapshot, material: drawMaterial },\n artifact: selectedArtifact ?? artifact,\n geometry: { ...geometry, topology: draw.topology, indexed: draw.kind === 'indexed' },\n generation: receipt.generation,\n draw,\n ...(skinReceipt === undefined ? {} : { skinReceipt }),\n });\n return result.ok ? result.value : result.error;\n })();\n if (prepared instanceof GpuDrivenPreparationError) {\n return [{ ...draw, preparationError: prepared, ...withLodRanges }];\n }\n return [\n prepared === undefined\n ? { ...draw, ...withLodRanges }\n : { ...draw, prepared, ...withLodRanges },\n ];\n });\n}\n","import type { Mat4Like } from '@forgeax/engine-math';\n\n// `fingerprintNumericArray` runs on every bounds-cache lookup. Keep the bit\n// reinterpretation scratch outside the hot path so a cache hit does not\n// allocate a pair of typed arrays for each retained render slot.\nconst fingerprintScalar = new Float32Array(1);\nconst fingerprintBits = new Uint32Array(fingerprintScalar.buffer);\n\n/**\n * Inputs owned by the render extract/persistent-scene boundary. Bounds are\n * deliberately derived here instead of being added to the author-facing\n * `Instances` component or written back to a Pack asset.\n */\nexport interface DerivedInstancesUnionBoundsInput {\n readonly meshAabb: ArrayLike<number> | undefined;\n readonly entityWorld: ArrayLike<number>;\n readonly transforms: ArrayLike<number> | undefined;\n}\n\n/**\n * Renderer-owned cache key. Each generation is supplied by the owner that can\n * observe that mutation: mesh/AABB publication, entity world transform, and\n * the packed instance matrix array respectively.\n */\nexport interface InstanceBoundsCacheKey {\n /** Optional scene/world scope for composite scenes; omitted for standalone tests. */\n readonly worldId?: number;\n readonly entityKey: number;\n readonly meshGeneration: number;\n readonly transformGeneration: number;\n readonly matrixGeneration: number;\n}\n\nexport type InstanceBoundsCacheInput = InstanceBoundsCacheKey & DerivedInstancesUnionBoundsInput;\n\n/**\n * Stable bitwise fingerprint for detached numeric facts used by the cache.\n * Float32 bits are hashed rather than decimal text so a real matrix/AABB\n * change invalidates the projection without keeping another mutable ledger.\n */\nexport function fingerprintNumericArray(values: ArrayLike<number>): number {\n let hash = 0x811c9dc5;\n for (let index = 0; index < values.length; index += 1) {\n fingerprintScalar[0] = Number(values[index]);\n hash = Math.imul(hash ^ (fingerprintBits[0] ?? 0), 0x01000193) >>> 0;\n }\n return hash >>> 0;\n}\n\nfunction finiteAabb(aabb: ArrayLike<number> | undefined): aabb is ArrayLike<number> {\n if (aabb === undefined || aabb.length < 6) return false;\n const minX = aabb[0] as number;\n const minY = aabb[1] as number;\n const minZ = aabb[2] as number;\n const maxX = aabb[3] as number;\n const maxY = aabb[4] as number;\n const maxZ = aabb[5] as number;\n return (\n Number.isFinite(minX) &&\n Number.isFinite(minY) &&\n Number.isFinite(minZ) &&\n Number.isFinite(maxX) &&\n Number.isFinite(maxY) &&\n Number.isFinite(maxZ) &&\n minX <= maxX &&\n minY <= maxY &&\n minZ <= maxZ\n );\n}\n\nfunction finiteMatrix(matrix: ArrayLike<number>): matrix is Mat4Like {\n if (matrix.length < 16) return false;\n for (let index = 0; index < 16; index += 1) {\n if (!Number.isFinite(matrix[index] as number)) return false;\n }\n return true;\n}\n\nfunction multiplyMat4(\n out: Float32Array,\n left: ArrayLike<number>,\n right: ArrayLike<number>,\n rightOffset = 0,\n): void {\n for (let column = 0; column < 4; column += 1) {\n const rightColumn = rightOffset + column * 4;\n const right0 = Number(right[rightColumn] ?? 0);\n const right1 = Number(right[rightColumn + 1] ?? 0);\n const right2 = Number(right[rightColumn + 2] ?? 0);\n const right3 = Number(right[rightColumn + 3] ?? 0);\n const outOffset = column * 4;\n out[outOffset] =\n Number(left[0] ?? 0) * right0 +\n Number(left[4] ?? 0) * right1 +\n Number(left[8] ?? 0) * right2 +\n Number(left[12] ?? 0) * right3;\n out[outOffset + 1] =\n Number(left[1] ?? 0) * right0 +\n Number(left[5] ?? 0) * right1 +\n Number(left[9] ?? 0) * right2 +\n Number(left[13] ?? 0) * right3;\n out[outOffset + 2] =\n Number(left[2] ?? 0) * right0 +\n Number(left[6] ?? 0) * right1 +\n Number(left[10] ?? 0) * right2 +\n Number(left[14] ?? 0) * right3;\n out[outOffset + 3] =\n Number(left[3] ?? 0) * right0 +\n Number(left[7] ?? 0) * right1 +\n Number(left[11] ?? 0) * right2 +\n Number(left[15] ?? 0) * right3;\n }\n}\n\nfunction finiteMatrixAt(values: ArrayLike<number>, offset: number): boolean {\n if (values.length - offset < 16) return false;\n for (let index = 0; index < 16; index += 1) {\n if (!Number.isFinite(values[offset + index] as number)) return false;\n }\n return true;\n}\n\nfunction isAffine(matrix: ArrayLike<number>): boolean {\n return (\n (matrix[3] as number) === 0 &&\n (matrix[7] as number) === 0 &&\n (matrix[11] as number) === 0 &&\n (matrix[15] as number) === 1\n );\n}\n\nfunction includeBox(\n out: Float32Array,\n candidate: ArrayLike<number>,\n initialized: boolean,\n): boolean {\n const minX = candidate[0] as number;\n const minY = candidate[1] as number;\n const minZ = candidate[2] as number;\n const maxX = candidate[3] as number;\n const maxY = candidate[4] as number;\n const maxZ = candidate[5] as number;\n if (!initialized) {\n out[0] = minX;\n out[1] = minY;\n out[2] = minZ;\n out[3] = maxX;\n out[4] = maxY;\n out[5] = maxZ;\n return true;\n }\n if (minX < (out[0] ?? Number.POSITIVE_INFINITY)) out[0] = minX;\n if (minY < (out[1] ?? Number.POSITIVE_INFINITY)) out[1] = minY;\n if (minZ < (out[2] ?? Number.POSITIVE_INFINITY)) out[2] = minZ;\n if (maxX > (out[3] ?? Number.NEGATIVE_INFINITY)) out[3] = maxX;\n if (maxY > (out[4] ?? Number.NEGATIVE_INFINITY)) out[4] = maxY;\n if (maxZ > (out[5] ?? Number.NEGATIVE_INFINITY)) out[5] = maxZ;\n return true;\n}\n\n/** Transform an AABB without per-instance arrays or corner tuples. */\nfunction transformAabb(\n out: Float32Array,\n local: ArrayLike<number>,\n matrix: ArrayLike<number>,\n): boolean {\n const minX = local[0] as number;\n const minY = local[1] as number;\n const minZ = local[2] as number;\n const maxX = local[3] as number;\n const maxY = local[4] as number;\n const maxZ = local[5] as number;\n const centerX = (minX + maxX) * 0.5;\n const centerY = (minY + maxY) * 0.5;\n const centerZ = (minZ + maxZ) * 0.5;\n const extentX = (maxX - minX) * 0.5;\n const extentY = (maxY - minY) * 0.5;\n const extentZ = (maxZ - minZ) * 0.5;\n\n if (isAffine(matrix)) {\n const centerWorldX =\n (matrix[0] as number) * centerX +\n (matrix[4] as number) * centerY +\n (matrix[8] as number) * centerZ +\n (matrix[12] as number);\n const centerWorldY =\n (matrix[1] as number) * centerX +\n (matrix[5] as number) * centerY +\n (matrix[9] as number) * centerZ +\n (matrix[13] as number);\n const centerWorldZ =\n (matrix[2] as number) * centerX +\n (matrix[6] as number) * centerY +\n (matrix[10] as number) * centerZ +\n (matrix[14] as number);\n const extentWorldX =\n Math.abs(matrix[0] as number) * extentX +\n Math.abs(matrix[4] as number) * extentY +\n Math.abs(matrix[8] as number) * extentZ;\n const extentWorldY =\n Math.abs(matrix[1] as number) * extentX +\n Math.abs(matrix[5] as number) * extentY +\n Math.abs(matrix[9] as number) * extentZ;\n const extentWorldZ =\n Math.abs(matrix[2] as number) * extentX +\n Math.abs(matrix[6] as number) * extentY +\n Math.abs(matrix[10] as number) * extentZ;\n out[0] = centerWorldX - extentWorldX;\n out[1] = centerWorldY - extentWorldY;\n out[2] = centerWorldZ - extentWorldZ;\n out[3] = centerWorldX + extentWorldX;\n out[4] = centerWorldY + extentWorldY;\n out[5] = centerWorldZ + extentWorldZ;\n return finiteAabb(out);\n }\n\n // Projective/non-affine matrices need the reference corner route. A w\n // interval crossing zero is unbounded, so explicitly return no-cull rather\n // than pretending the finite corner samples enclose the volume.\n let minimumW = Number.POSITIVE_INFINITY;\n let maximumW = Number.NEGATIVE_INFINITY;\n for (let corner = 0; corner < 8; corner += 1) {\n const x = (corner & 1) === 0 ? minX : maxX;\n const y = (corner & 2) === 0 ? minY : maxY;\n const z = (corner & 4) === 0 ? minZ : maxZ;\n const w =\n (matrix[3] as number) * x +\n (matrix[7] as number) * y +\n (matrix[11] as number) * z +\n (matrix[15] as number);\n if (!Number.isFinite(w)) return false;\n if (w < minimumW) minimumW = w;\n if (w > maximumW) maximumW = w;\n }\n if (minimumW <= 0 && maximumW >= 0) return false;\n\n let unionMinX = Number.POSITIVE_INFINITY;\n let unionMinY = Number.POSITIVE_INFINITY;\n let unionMinZ = Number.POSITIVE_INFINITY;\n let unionMaxX = Number.NEGATIVE_INFINITY;\n let unionMaxY = Number.NEGATIVE_INFINITY;\n let unionMaxZ = Number.NEGATIVE_INFINITY;\n for (let corner = 0; corner < 8; corner += 1) {\n const x = (corner & 1) === 0 ? minX : maxX;\n const y = (corner & 2) === 0 ? minY : maxY;\n const z = (corner & 4) === 0 ? minZ : maxZ;\n const rawX =\n (matrix[0] as number) * x +\n (matrix[4] as number) * y +\n (matrix[8] as number) * z +\n (matrix[12] as number);\n const rawY =\n (matrix[1] as number) * x +\n (matrix[5] as number) * y +\n (matrix[9] as number) * z +\n (matrix[13] as number);\n const rawZ =\n (matrix[2] as number) * x +\n (matrix[6] as number) * y +\n (matrix[10] as number) * z +\n (matrix[14] as number);\n const w =\n (matrix[3] as number) * x +\n (matrix[7] as number) * y +\n (matrix[11] as number) * z +\n (matrix[15] as number);\n const projectedX = rawX / w;\n const projectedY = rawY / w;\n const projectedZ = rawZ / w;\n if (\n !Number.isFinite(projectedX) ||\n !Number.isFinite(projectedY) ||\n !Number.isFinite(projectedZ)\n ) {\n return false;\n }\n if (projectedX < unionMinX) unionMinX = projectedX;\n if (projectedY < unionMinY) unionMinY = projectedY;\n if (projectedZ < unionMinZ) unionMinZ = projectedZ;\n if (projectedX > unionMaxX) unionMaxX = projectedX;\n if (projectedY > unionMaxY) unionMaxY = projectedY;\n if (projectedZ > unionMaxZ) unionMaxZ = projectedZ;\n }\n out[0] = unionMinX;\n out[1] = unionMinY;\n out[2] = unionMinZ;\n out[3] = unionMaxX;\n out[4] = unionMaxY;\n out[5] = unionMaxZ;\n return finiteAabb(out);\n}\n\n/**\n * Derive the world-space AABB enclosing every instance of a mesh.\n *\n * `undefined` is a conservative signal: the caller must skip CPU culling\n * when an input is missing, malformed, or empty. This prevents an empty\n * `Instances` row from becoming a synthetic identity draw/bounds candidate.\n */\nexport function deriveInstancesUnionBounds(\n input: DerivedInstancesUnionBoundsInput,\n): Float32Array | undefined {\n const { meshAabb, entityWorld, transforms } = input;\n if (!finiteAabb(meshAabb) || !finiteMatrix(entityWorld) || transforms === undefined) {\n return undefined;\n }\n if (transforms.length === 0 || transforms.length % 16 !== 0) return undefined;\n const local = meshAabb;\n const union = new Float32Array(6);\n const composed = new Float32Array(16);\n const transformed = new Float32Array(6);\n let initialized = false;\n for (let offset = 0; offset < transforms.length; offset += 16) {\n if (!finiteMatrixAt(transforms, offset)) return undefined;\n multiplyMat4(composed, entityWorld, transforms, offset);\n if (!finiteMatrix(composed) || !transformAabb(transformed, local, composed)) return undefined;\n initialized = includeBox(union, transformed, initialized);\n }\n return initialized && finiteAabb(union) ? union : undefined;\n}\n\ninterface InstanceBoundsCacheEntry extends InstanceBoundsCacheKey {\n readonly bounds: Float32Array | undefined;\n}\n\nexport interface InstanceBoundsCacheInspection {\n readonly hits: number;\n readonly misses: number;\n readonly derives: number;\n readonly invalidations: number;\n}\n\n/**\n * Small renderer-owned per-entity cache. A changed generation replaces the\n * entry atomically; packed-id reuse is safe when its owner supplies a new\n * generation (the normal RenderScene slot generation contract).\n */\nexport class InstanceBoundsCache {\n private readonly entries = new Map<string, InstanceBoundsCacheEntry>();\n private hits = 0;\n private misses = 0;\n private derives = 0;\n private invalidations = 0;\n\n private key(input: Pick<InstanceBoundsCacheKey, 'worldId' | 'entityKey'>): string {\n return `${input.worldId === undefined ? '' : `${input.worldId}:`}${input.entityKey}`;\n }\n\n get(input: InstanceBoundsCacheInput): Float32Array | undefined {\n const previous = this.entries.get(this.key(input));\n if (\n previous !== undefined &&\n previous.meshGeneration === input.meshGeneration &&\n previous.transformGeneration === input.transformGeneration &&\n previous.matrixGeneration === input.matrixGeneration\n ) {\n this.hits += 1;\n return previous.bounds;\n }\n this.misses += 1;\n this.derives += 1;\n const bounds = deriveInstancesUnionBounds(input);\n this.entries.set(this.key(input), {\n ...(input.worldId === undefined ? {} : { worldId: input.worldId }),\n entityKey: input.entityKey,\n meshGeneration: input.meshGeneration,\n transformGeneration: input.transformGeneration,\n matrixGeneration: input.matrixGeneration,\n bounds,\n });\n return bounds;\n }\n\n invalidate(entityKey?: number, worldId?: number): void {\n if (entityKey === undefined) {\n if (this.entries.size > 0) this.invalidations += this.entries.size;\n this.entries.clear();\n } else {\n if (\n this.entries.delete(this.key({ entityKey, ...(worldId === undefined ? {} : { worldId }) }))\n ) {\n this.invalidations += 1;\n }\n }\n }\n\n inspect(): InstanceBoundsCacheInspection {\n return {\n hits: this.hits,\n misses: this.misses,\n derives: this.derives,\n invalidations: this.invalidations,\n };\n }\n}\n"]}