@forgeax/engine-render 0.1.23 → 0.1.25

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 (322) hide show
  1. package/README.md +231 -10
  2. package/dist/assembly/bundler-contract.d.ts +9 -0
  3. package/dist/assembly/bundler-contract.d.ts.map +1 -0
  4. package/dist/assembly/device-feature-admission.d.ts +8 -0
  5. package/dist/assembly/device-feature-admission.d.ts.map +1 -1
  6. package/dist/assembly/extended-lighting-fallback.d.ts +13 -0
  7. package/dist/assembly/extended-lighting-fallback.d.ts.map +1 -0
  8. package/dist/assembly/factory.d.ts +7 -243
  9. package/dist/assembly/factory.d.ts.map +1 -1
  10. package/dist/assembly/material/assembly.d.ts +3 -2
  11. package/dist/assembly/material/assembly.d.ts.map +1 -1
  12. package/dist/assembly/material/standard-layer-projection.d.ts +10 -0
  13. package/dist/assembly/material/standard-layer-projection.d.ts.map +1 -0
  14. package/dist/assembly/material/surface-projection.d.ts +24 -0
  15. package/dist/assembly/material/surface-projection.d.ts.map +1 -0
  16. package/dist/assembly/material-shader-policy.d.ts +188 -0
  17. package/dist/assembly/material-shader-policy.d.ts.map +1 -0
  18. package/dist/assembly/material-shader-prewarm.d.ts +21 -0
  19. package/dist/assembly/material-shader-prewarm.d.ts.map +1 -0
  20. package/dist/assembly/mesh-ssbo-grow.d.ts +88 -0
  21. package/dist/assembly/mesh-ssbo-grow.d.ts.map +1 -0
  22. package/dist/assembly/recovery/device-loss-fanout.d.ts +14 -0
  23. package/dist/assembly/recovery/device-loss-fanout.d.ts.map +1 -0
  24. package/dist/assembly/recovery/generation.d.ts +46 -0
  25. package/dist/assembly/recovery/generation.d.ts.map +1 -0
  26. package/dist/assembly/recovery/recovery-attempt.d.ts +63 -0
  27. package/dist/assembly/recovery/recovery-attempt.d.ts.map +1 -0
  28. package/dist/assembly/recovery/renderer-recover.d.ts +115 -0
  29. package/dist/assembly/recovery/renderer-recover.d.ts.map +1 -0
  30. package/dist/assembly/renderer-facade.d.ts +10 -0
  31. package/dist/assembly/renderer-facade.d.ts.map +1 -0
  32. package/dist/assembly/renderer-frame-transaction.d.ts +17 -0
  33. package/dist/assembly/renderer-frame-transaction.d.ts.map +1 -1
  34. package/dist/assembly/renderer-helpers.d.ts +19 -0
  35. package/dist/assembly/renderer-helpers.d.ts.map +1 -0
  36. package/dist/assembly/renderer-lifecycle.d.ts +34 -0
  37. package/dist/assembly/renderer-lifecycle.d.ts.map +1 -1
  38. package/dist/assembly/shader-prewarm-policy.d.ts +15 -0
  39. package/dist/assembly/shader-prewarm-policy.d.ts.map +1 -0
  40. package/dist/assembly/webgpu-ready-contract.d.ts +9 -0
  41. package/dist/assembly/webgpu-ready-contract.d.ts.map +1 -0
  42. package/dist/assembly/webgpu-ready.d.ts +55 -0
  43. package/dist/assembly/webgpu-ready.d.ts.map +1 -0
  44. package/dist/assembly/webgpu-renderer.d.ts +152 -0
  45. package/dist/assembly/webgpu-renderer.d.ts.map +1 -0
  46. package/dist/assembly/webgpu-vertex-layouts.d.ts +89 -0
  47. package/dist/assembly/webgpu-vertex-layouts.d.ts.map +1 -0
  48. package/dist/assets/asset-decoders.d.ts.map +1 -1
  49. package/dist/authoring.mjs +1 -1
  50. package/dist/{chunk-FF7K3FSO.mjs → chunk-ADHHVYLW.mjs} +89 -89
  51. package/dist/chunk-ADHHVYLW.mjs.map +1 -0
  52. package/dist/{chunk-YALPS44A.mjs → chunk-E34VL5VI.mjs} +47 -47
  53. package/dist/chunk-E34VL5VI.mjs.map +1 -0
  54. package/dist/{chunk-4L3P6DT5.mjs → chunk-GE3SDD72.mjs} +37 -5
  55. package/dist/chunk-GE3SDD72.mjs.map +1 -0
  56. package/dist/{chunk-HZUPSYW7.mjs → chunk-HKXTW355.mjs} +105 -15
  57. package/dist/chunk-HKXTW355.mjs.map +1 -0
  58. package/dist/chunk-JSEDTZYS.mjs +413 -0
  59. package/dist/chunk-JSEDTZYS.mjs.map +1 -0
  60. package/dist/{chunk-FBC4R44J.mjs → chunk-KM2NOX2I.mjs} +57 -57
  61. package/dist/chunk-KM2NOX2I.mjs.map +1 -0
  62. package/dist/{chunk-DIYW3M5D.mjs → chunk-N3RT2EUR.mjs} +2288 -2238
  63. package/dist/chunk-N3RT2EUR.mjs.map +1 -0
  64. package/dist/{chunk-ZUWKAZ2I.mjs → chunk-TCLDX7SZ.mjs} +1167 -368
  65. package/dist/chunk-TCLDX7SZ.mjs.map +1 -0
  66. package/dist/{chunk-QODA5UKU.mjs → chunk-ZZ4YQ474.mjs} +2 -2
  67. package/dist/chunk-ZZ4YQ474.mjs.map +1 -0
  68. package/dist/components/instances.d.ts +13 -31
  69. package/dist/components/instances.d.ts.map +1 -1
  70. package/dist/construct-renderer.mjs +20688 -16314
  71. package/dist/construct-renderer.mjs.map +1 -1
  72. package/dist/device/device-scope.d.ts +2 -0
  73. package/dist/device/device-scope.d.ts.map +1 -1
  74. package/dist/device/gpu-residency.d.ts +24 -4
  75. package/dist/device/gpu-residency.d.ts.map +1 -1
  76. package/dist/environment/frame.d.ts +5 -0
  77. package/dist/environment/frame.d.ts.map +1 -1
  78. package/dist/environment/inspection.d.ts +7 -0
  79. package/dist/environment/inspection.d.ts.map +1 -1
  80. package/dist/environment/lifecycle.d.ts +20 -2
  81. package/dist/environment/lifecycle.d.ts.map +1 -1
  82. package/dist/errors/recover.d.ts +58 -2
  83. package/dist/errors/recover.d.ts.map +1 -1
  84. package/dist/errors/render.d.ts +13 -0
  85. package/dist/errors/render.d.ts.map +1 -1
  86. package/dist/extract/contracts.d.ts +899 -0
  87. package/dist/extract/contracts.d.ts.map +1 -0
  88. package/dist/features/host.d.ts +2 -0
  89. package/dist/features/host.d.ts.map +1 -1
  90. package/dist/features/prepared-gpu-work.d.ts +3 -0
  91. package/dist/features/prepared-gpu-work.d.ts.map +1 -1
  92. package/dist/features/prepared-graphics-store.d.ts +2 -0
  93. package/dist/features/prepared-graphics-store.d.ts.map +1 -1
  94. package/dist/gpu-driven/production-raster.d.ts +34 -1
  95. package/dist/gpu-driven/production-raster.d.ts.map +1 -1
  96. package/dist/gpu-scene.d.ts +5 -0
  97. package/dist/gpu-scene.d.ts.map +1 -1
  98. package/dist/ibl/IblPipelineCache.d.ts +7 -6
  99. package/dist/ibl/IblPipelineCache.d.ts.map +1 -1
  100. package/dist/ibl/skylight-bind-group.d.ts +7 -1
  101. package/dist/ibl/skylight-bind-group.d.ts.map +1 -1
  102. package/dist/index.d.ts +2 -1
  103. package/dist/index.d.ts.map +1 -1
  104. package/dist/index.mjs +27 -9
  105. package/dist/index.mjs.map +1 -1
  106. package/dist/instance-buffer-cache.d.ts +7 -1
  107. package/dist/instance-buffer-cache.d.ts.map +1 -1
  108. package/dist/instances.d.ts +101 -0
  109. package/dist/instances.d.ts.map +1 -0
  110. package/dist/internal.mjs +6 -6
  111. package/dist/light-buffer-layout.d.ts +3 -0
  112. package/dist/light-buffer-layout.d.ts.map +1 -1
  113. package/dist/materials.d.ts +96 -11
  114. package/dist/materials.d.ts.map +1 -1
  115. package/dist/mesh-material-bindings.d.ts +56 -0
  116. package/dist/mesh-material-bindings.d.ts.map +1 -1
  117. package/dist/occlusion-proxy.d.ts +4 -0
  118. package/dist/occlusion-proxy.d.ts.map +1 -0
  119. package/dist/pbr-pipeline.d.ts +32 -9
  120. package/dist/pbr-pipeline.d.ts.map +1 -1
  121. package/dist/pipeline-builder.d.ts.map +1 -1
  122. package/dist/pipeline-spec.d.ts.map +1 -1
  123. package/dist/points-lines/prepare.d.ts +3 -0
  124. package/dist/points-lines/prepare.d.ts.map +1 -1
  125. package/dist/points-lines/standard-owner.d.ts +33 -0
  126. package/dist/points-lines/standard-owner.d.ts.map +1 -0
  127. package/dist/record/frame-snapshot.d.ts +18 -2
  128. package/dist/record/frame-snapshot.d.ts.map +1 -1
  129. package/dist/record/frame-targets.d.ts.map +1 -1
  130. package/dist/record/frame.d.ts +14 -2
  131. package/dist/record/frame.d.ts.map +1 -1
  132. package/dist/record/main-pass-geometry.d.ts +36 -4
  133. package/dist/record/main-pass-geometry.d.ts.map +1 -1
  134. package/dist/record/main-pass-material.d.ts +7 -17
  135. package/dist/record/main-pass-material.d.ts.map +1 -1
  136. package/dist/record/main-pass.d.ts.map +1 -1
  137. package/dist/record/mesh-ssbo.d.ts +11 -3
  138. package/dist/record/mesh-ssbo.d.ts.map +1 -1
  139. package/dist/record/recovery-pipeline.d.ts +30 -0
  140. package/dist/record/recovery-pipeline.d.ts.map +1 -0
  141. package/dist/record/render-context.d.ts +28 -5
  142. package/dist/record/render-context.d.ts.map +1 -1
  143. package/dist/record/shadow-pass.d.ts +11 -1
  144. package/dist/record/shadow-pass.d.ts.map +1 -1
  145. package/dist/record/typed-frame-graph.d.ts +1 -1
  146. package/dist/record/typed-frame-graph.d.ts.map +1 -1
  147. package/dist/recovery/render-system-candidate.d.ts +65 -0
  148. package/dist/recovery/render-system-candidate.d.ts.map +1 -0
  149. package/dist/render-contract.d.ts +68 -7
  150. package/dist/render-contract.d.ts.map +1 -1
  151. package/dist/render-system-extract-tail.d.ts +16 -0
  152. package/dist/render-system-extract-tail.d.ts.map +1 -0
  153. package/dist/render-system-extract.d.ts +180 -22
  154. package/dist/render-system-extract.d.ts.map +1 -1
  155. package/dist/render-system.d.ts +131 -4
  156. package/dist/render-system.d.ts.map +1 -1
  157. package/dist/scene/render-scene-types.d.ts +2 -0
  158. package/dist/scene/render-scene-types.d.ts.map +1 -1
  159. package/dist/scene/render-scene.d.ts +31 -1
  160. package/dist/scene/render-scene.d.ts.map +1 -1
  161. package/dist/systems/skin-palette-allocator.d.ts +6 -0
  162. package/dist/systems/skin-palette-allocator.d.ts.map +1 -1
  163. package/dist/temporal/frame-coordinator.d.ts.map +1 -1
  164. package/dist/temporal/index.mjs +6 -6
  165. package/dist/temporal/taa-history-store.d.ts +15 -1
  166. package/dist/temporal/taa-history-store.d.ts.map +1 -1
  167. package/dist/temporal/transaction.d.ts +5 -0
  168. package/dist/temporal/transaction.d.ts.map +1 -1
  169. package/package.json +20 -20
  170. package/src/__tests__/device-feature-admission.unit.test.ts +6 -0
  171. package/src/__tests__/device-loss-fanout.unit.test.ts +107 -0
  172. package/src/__tests__/device-scope-lifecycle.unit.test.ts +21 -0
  173. package/src/__tests__/environment-generation.integration.test.ts +23 -0
  174. package/src/__tests__/expose-renderer-errors.unit.test.ts +34 -0
  175. package/src/__tests__/factory-contract.integration.test.ts +122 -7
  176. package/src/__tests__/fallback-row-stride-surface.unit.test.ts +4 -1
  177. package/src/__tests__/gpu-scene.unit.test.ts +38 -2
  178. package/src/__tests__/ibl/face-uniforms.unit.test.ts +2 -0
  179. package/src/__tests__/ibl-residency-publication.unit.test.ts +113 -0
  180. package/src/__tests__/instances-store.unit.test.ts +46 -0
  181. package/src/__tests__/instances-world-ownership.integration.test.ts +62 -0
  182. package/src/__tests__/material-contract-inventory.unit.test.ts +29 -22
  183. package/src/__tests__/material-cooked-projection.unit.test.ts +19 -1
  184. package/src/__tests__/material-pass-policy.unit.test.ts +69 -0
  185. package/src/__tests__/material-snapshot-mutation.integration.test.ts +69 -0
  186. package/src/__tests__/material-static-dynamic-route.unit.test.ts +29 -0
  187. package/src/__tests__/material-stride-surface.unit.test.ts +7 -3
  188. package/src/__tests__/material-surface-authoring.test-d.ts +62 -0
  189. package/src/__tests__/materials-standard-contract.unit.test.ts +104 -0
  190. package/src/__tests__/materials-transmission-validation.unit.test.ts +24 -0
  191. package/src/__tests__/mesh-buffer-usage-surface.unit.test.ts +1 -5
  192. package/src/__tests__/physical-clearcoat.integration.test.ts +89 -0
  193. package/src/__tests__/prepared-gpu-driven-pbr.integration.test.ts +1 -1
  194. package/src/__tests__/prepared-graphics-pipeline-warmup.unit.test.ts +1 -1
  195. package/src/__tests__/recover-error-policy-owner.unit.test.ts +6 -3
  196. package/src/__tests__/recovery-candidate-prepare.contract.test.ts +140 -0
  197. package/src/__tests__/renderer-factory-material-contract.unit.test.ts +127 -18
  198. package/src/__tests__/renderer-frame-generation-fence.integration.test.ts +47 -0
  199. package/src/__tests__/renderer-generation-assembly.unit.test.ts +77 -0
  200. package/src/__tests__/renderer-generation-failure.unit.test.ts +108 -0
  201. package/src/__tests__/renderer-producer-root-matrix.integration.test.ts +33 -0
  202. package/src/__tests__/renderer-recovery-capability-matrix.unit.test.ts +59 -0
  203. package/src/__tests__/renderer-recovery-contract.unit.test.ts +73 -0
  204. package/src/__tests__/renderer-recovery-lifecycle.unit.test.ts +216 -0
  205. package/src/__tests__/renderer-target-history-recovery.integration.test.ts +80 -0
  206. package/src/__tests__/shader-manifest-fixture.ts +13 -16
  207. package/src/__tests__/shader-stage-surface.unit.test.ts +1 -1
  208. package/src/__tests__/skin-motion-regression.unit.test.ts +33 -0
  209. package/src/__tests__/skinned-shadow-caster.test.ts +30 -2
  210. package/src/__tests__/standard-layer-projection.unit.test.ts +23 -0
  211. package/src/__tests__/surface-adjacent-regressions.integration.test.ts +60 -0
  212. package/src/__tests__/surface-standard-pipeline.browser.test.ts +20 -0
  213. package/src/__tests__/surface-standard-pipeline.dawn.test.ts +20 -0
  214. package/src/__tests__/surface-standard-pipeline.fixture.ts +132 -0
  215. package/src/__tests__/surface-variant-provenance.integration.test.ts +33 -0
  216. package/src/__tests__/transmission-prewarm.unit.test.ts +95 -85
  217. package/src/__tests__/volumetric-fog-budget-recovery.integration.test.ts +1 -1
  218. package/src/__tests__/volumetric-fog-topology.unit.test.ts +3 -1
  219. package/src/assembly/bundler-contract.ts +9 -0
  220. package/src/assembly/device-feature-admission.ts +15 -5
  221. package/src/assembly/extended-lighting-fallback.ts +216 -0
  222. package/src/assembly/factory.ts +83 -10088
  223. package/src/assembly/material/__tests__/standard-layer-plan-projection.integration.test.ts +18 -0
  224. package/src/assembly/material/__tests__/surface-pass-projection.integration.test.ts +62 -0
  225. package/src/assembly/material/assembly.ts +18 -2
  226. package/src/assembly/material/standard-layer-projection.ts +16 -0
  227. package/src/assembly/material/surface-projection.ts +90 -0
  228. package/src/assembly/material-shader-policy.ts +932 -0
  229. package/src/assembly/material-shader-prewarm.ts +88 -0
  230. package/src/assembly/mesh-ssbo-grow.ts +270 -0
  231. package/src/assembly/recovery/device-loss-fanout.ts +89 -0
  232. package/src/assembly/recovery/generation.ts +141 -0
  233. package/src/assembly/recovery/recovery-attempt.ts +800 -0
  234. package/src/assembly/recovery/renderer-recover.ts +906 -0
  235. package/src/assembly/renderer-facade.ts +342 -0
  236. package/src/assembly/renderer-frame-transaction.ts +45 -0
  237. package/src/assembly/renderer-helpers.ts +99 -0
  238. package/src/assembly/renderer-lifecycle.ts +159 -0
  239. package/src/assembly/shader-prewarm-policy.ts +157 -0
  240. package/src/assembly/webgpu-ready-contract.ts +14 -0
  241. package/src/assembly/webgpu-ready.ts +4066 -0
  242. package/src/assembly/webgpu-renderer.ts +4027 -0
  243. package/src/assembly/webgpu-vertex-layouts.ts +132 -0
  244. package/src/assets/asset-decoders.ts +27 -4
  245. package/src/components/camera.ts +1 -1
  246. package/src/components/instances.ts +14 -197
  247. package/src/debug-draw-glue.ts +1 -1
  248. package/src/device/device-scope.ts +35 -6
  249. package/src/device/gpu-residency.ts +194 -26
  250. package/src/environment/frame.ts +6 -0
  251. package/src/environment/inspection.ts +10 -0
  252. package/src/environment/lifecycle.ts +114 -8
  253. package/src/errors/recover.ts +76 -5
  254. package/src/errors/render.ts +17 -0
  255. package/src/extract/contracts.ts +974 -0
  256. package/src/features/host.ts +16 -0
  257. package/src/features/prepared-gpu-work.ts +20 -2
  258. package/src/features/prepared-graphics-store.ts +17 -0
  259. package/src/gpu-driven/production-raster.ts +131 -3
  260. package/src/gpu-scene.ts +87 -31
  261. package/src/ibl/IblPipelineCache.ts +134 -50
  262. package/src/ibl/skylight-bind-group.ts +26 -0
  263. package/src/index.ts +10 -1
  264. package/src/instance-buffer-cache.ts +14 -1
  265. package/src/instances.ts +288 -0
  266. package/src/light-buffer-layout.ts +3 -0
  267. package/src/materials.ts +365 -53
  268. package/src/mesh-material-bindings.ts +59 -0
  269. package/src/occlusion-proxy.ts +64 -0
  270. package/src/pbr-pipeline.ts +139 -15
  271. package/src/pipeline-builder.ts +14 -10
  272. package/src/pipeline-spec.ts +6 -14
  273. package/src/points-lines/__tests__/cache-recovery.unit.test.ts +22 -0
  274. package/src/points-lines/prepare.ts +9 -0
  275. package/src/points-lines/standard-owner.ts +403 -0
  276. package/src/record/__tests__/frame-targets-recovery.unit.test.ts +60 -0
  277. package/src/record/__tests__/main-pass-geometry.unit.test.ts +26 -1
  278. package/src/record/__tests__/mesh-ssbo.unit.test.ts +38 -0
  279. package/src/record/__tests__/recovery-pipeline.unit.test.ts +124 -0
  280. package/src/record/__tests__/sprite-material-abi.unit.test.ts +28 -13
  281. package/src/record/__tests__/standard-pbr-ubo-layout.unit.test.ts +47 -4
  282. package/src/record/__tests__/temporal-payload.unit.test.ts +22 -43
  283. package/src/record/__tests__/typed-frame-graph-plan.unit.test.ts +1 -1
  284. package/src/record/frame-snapshot.ts +34 -2
  285. package/src/record/frame-targets.ts +11 -1
  286. package/src/record/frame.ts +37 -4
  287. package/src/record/helpers.ts +1 -1
  288. package/src/record/main-pass-geometry.ts +727 -63
  289. package/src/record/main-pass-material.ts +316 -209
  290. package/src/record/main-pass-sprite-draws.ts +7 -8
  291. package/src/record/main-pass.ts +94 -6
  292. package/src/record/mesh-ssbo.ts +32 -10
  293. package/src/record/recovery-pipeline.ts +695 -0
  294. package/src/record/render-context.ts +39 -4
  295. package/src/record/shadow-pass.ts +46 -99
  296. package/src/record/typed-frame-graph.ts +45 -1
  297. package/src/record/view-ubo.ts +3 -3
  298. package/src/recovery/render-system-candidate.ts +876 -0
  299. package/src/render-contract.ts +69 -7
  300. package/src/render-system-extract-tail.ts +3039 -0
  301. package/src/render-system-extract.ts +177 -3003
  302. package/src/render-system.ts +906 -662
  303. package/src/scene/render-scene-types.ts +2 -0
  304. package/src/scene/render-scene.ts +703 -37
  305. package/src/systems/skin-palette-allocator.ts +129 -7
  306. package/src/temporal/frame-coordinator.ts +4 -1
  307. package/src/temporal/taa-history-store.ts +46 -2
  308. package/src/temporal/temporal-view.ts +1 -1
  309. package/src/temporal/transaction.ts +9 -0
  310. package/src/tilemap-chunk-extract-system.ts +1 -1
  311. package/src/transmission/__tests__/standard-transmission.dawn.test.ts +19 -12
  312. package/src/transmission/__tests__/surface-compatibility.integration.test.ts +32 -0
  313. package/dist/chunk-4L3P6DT5.mjs.map +0 -1
  314. package/dist/chunk-4NPUASZR.mjs +0 -203
  315. package/dist/chunk-4NPUASZR.mjs.map +0 -1
  316. package/dist/chunk-DIYW3M5D.mjs.map +0 -1
  317. package/dist/chunk-FBC4R44J.mjs.map +0 -1
  318. package/dist/chunk-FF7K3FSO.mjs.map +0 -1
  319. package/dist/chunk-HZUPSYW7.mjs.map +0 -1
  320. package/dist/chunk-QODA5UKU.mjs.map +0 -1
  321. package/dist/chunk-YALPS44A.mjs.map +0 -1
  322. package/dist/chunk-ZUWKAZ2I.mjs.map +0 -1
@@ -0,0 +1,3039 @@
1
+ import type { AssetRegistry } from '@forgeax/engine-assets-runtime';
2
+ import {
3
+ resolveAssetHandle,
4
+ walkMaterialPassesOverSharedRefs,
5
+ } from '@forgeax/engine-assets-runtime';
6
+ import type { EntityHandle, World } from '@forgeax/engine-ecs';
7
+ import {
8
+ InstanceTransformsStrideMismatchError,
9
+ routeWorldError,
10
+ SpawnLightInvalidBoundsError,
11
+ SpriteInstancesCountMismatchError,
12
+ SpriteInstancesMutuallyExclusiveWithInstancesError,
13
+ SpriteInstancesRequiresSpriteShaderError,
14
+ } from '@forgeax/engine-ecs/projection';
15
+ import { deriveVertexLayoutProjection } from '@forgeax/engine-geometry';
16
+ import { box3, frustum, type Mat4, mat4, type Vec3, vec3 } from '@forgeax/engine-math';
17
+ import { AssetGuid } from '@forgeax/engine-pack/guid';
18
+ import { RhiError } from '@forgeax/engine-rhi';
19
+ import { GlobalTransform, MorphWeights, Transform } from '@forgeax/engine-scene';
20
+ import type { MaterialShaderArtifact } from '@forgeax/engine-shader';
21
+ import {
22
+ JointCountMismatchError,
23
+ JointEntityDanglingError,
24
+ SkeletonResolveFailedError,
25
+ Skin,
26
+ SkinInstancesCoexistForbiddenError,
27
+ } from '@forgeax/engine-skinning';
28
+ import type {
29
+ Asset,
30
+ Handle,
31
+ IesProfileAsset,
32
+ MeshAsset,
33
+ MeshLodLevel,
34
+ SkeletonAsset,
35
+ TextureAsset,
36
+ } from '@forgeax/engine-types';
37
+ import {
38
+ ASSET_ERROR_HINTS,
39
+ AssetError,
40
+ derive,
41
+ handleSlot,
42
+ materialValuesToLinearRuntime,
43
+ toShared,
44
+ } from '@forgeax/engine-types';
45
+ import {
46
+ Atmosphere,
47
+ DirectionalLight,
48
+ Instances,
49
+ Layer,
50
+ LightProbe,
51
+ Lines,
52
+ MeshFilter,
53
+ MeshRenderer,
54
+ PointLight,
55
+ PointLightShadow,
56
+ Points,
57
+ PostProcessParams,
58
+ pointShapeFromU32,
59
+ RectAreaLight,
60
+ SkyboxBackground,
61
+ Skylight,
62
+ SortKey,
63
+ SpotLight,
64
+ SpriteInstances,
65
+ SpriteRegionOverride,
66
+ } from './components';
67
+ import {
68
+ type DirectionalShadowQuality,
69
+ directionalShadowQualityFromF32,
70
+ } from './components/directional-shadow-filter';
71
+ import { GlyphText } from './components/glyph-text';
72
+ import {
73
+ computeInvRangeSquared,
74
+ degToCos,
75
+ type LightValidationError,
76
+ validateDirectionalLightData,
77
+ validateLightProbeData,
78
+ validateRectAreaLightData,
79
+ } from './components/light-helpers';
80
+ import { selectEnvironment } from './environment/frame';
81
+ import { MaterialSkinAttrMissingError, SkinMaterialMismatchError } from './errors/render';
82
+ import type { EnvironmentCandidate, EnvironmentFrame } from './extract/environment';
83
+ import { buildGpuDrivenDraws, resolvePreparedGpuDrivenDraw } from './extract/gpu-driven';
84
+ import type { VisibilitySnapshot } from './extract/visibility';
85
+ import type {
86
+ RenderFeatureHiddenEntityReport,
87
+ RenderFeatureWorldVisibilitySnapshot,
88
+ } from './features/types';
89
+ import { ensureGlyphMeshMaterialSlots } from './glyph-text-layout-system';
90
+ import type { GpuDrivenGeometryReceipt } from './gpu-driven/prepared-draw';
91
+ import type { InstanceProjectionStore } from './instances';
92
+ import { deriveInstancesUnionBounds, fingerprintNumericArray } from './instances-derived-bounds';
93
+ import {
94
+ type MeshMaterialBindingDiagnostic,
95
+ type MeshMaterialBindingSource,
96
+ resolveMeshMaterialBindings,
97
+ } from './mesh-material-bindings';
98
+ import { isStandardPbrSkinMaterialShader } from './pbr-pipeline';
99
+ import { expandPointsLinesBounds } from './points-lines/bounds';
100
+ import type { PointsLinesRetainedSnapshot, PointsLinesStyle } from './points-lines/snapshot';
101
+ import { COOKIE_SLICE_CAPACITY, IES_SLICE_CAPACITY } from './prepare/extended-lighting/resources';
102
+ import { prepareCookieProjection } from './prepare/extended-lighting/spot-modifiers';
103
+ import { STANDARD_OUTPUT_TRANSFORM_FEATURE_ID } from './render-contract';
104
+ import type {
105
+ CsmCameraData,
106
+ DirectionalCsmConfig,
107
+ DirectionalLightSnapshot,
108
+ DispatchEntry,
109
+ ExtractedFrame,
110
+ ExtractedLights,
111
+ ExtractFramesOwner,
112
+ ExtractPipelineSurface,
113
+ InstancesSnapshot,
114
+ LightProbeSnapshot,
115
+ MaterialSnapshot,
116
+ MaterialSnapshotCache,
117
+ MaterialSnapshotCachesByWorld,
118
+ MorphSnapshot,
119
+ PointLightSnapshot,
120
+ PointShadowSnapshot,
121
+ PreparedExtractContext,
122
+ RectAreaDirectLightSnapshot,
123
+ RenderableSnapshot,
124
+ SkyboxSnapshot,
125
+ SkylightSnapshot,
126
+ SpotLightSnapshot,
127
+ SpriteInstancesSnapshot,
128
+ TransformSnapshot,
129
+ } from './render-system-extract';
130
+ import {
131
+ appendMaterialDispatchEntries,
132
+ assetReferenceText,
133
+ BUILTIN_USER_REGION_TEXTURE_FIELDS,
134
+ buildPointShadowMatrices,
135
+ buildRectAreaWorldFrame,
136
+ collectCubeCameraSnapshots,
137
+ collectMaterialTextureCoordinates,
138
+ collectMaterialTextureSamplers,
139
+ collectMaterialTextureSources,
140
+ collectReflectionProbeFacts,
141
+ computeDirectionalCsm,
142
+ createWorldInternalView,
143
+ DEFAULT_FORWARD_PASS,
144
+ extractVolumeSnapshot,
145
+ fogState,
146
+ internSharedRefFromGuid,
147
+ isEngineInjectedTextureField,
148
+ materialColorParameterSchema,
149
+ materialNormalScale,
150
+ materialParametersToParamSchema,
151
+ materialTextureFields,
152
+ materialTextureRef,
153
+ pipelineRenderState,
154
+ prepareExtractContext,
155
+ pssmSplit,
156
+ readPersistentMaterialSnapshot,
157
+ readStablePersistentMaterialSnapshot,
158
+ resolveMaterialSnapshot,
159
+ resolveVideoFieldHandle,
160
+ runtimeMaterialShaderIdForMaterial,
161
+ Severity,
162
+ selectCameraRoles,
163
+ selectFogFrame,
164
+ sortDispatchByQueue,
165
+ storeMaterialSnapshot,
166
+ tonemapParams,
167
+ } from './render-system-extract';
168
+ import { SHADOW_ATLAS_DEFAULT_LAYERS } from './shadow-atlas';
169
+ import type { SkinPaletteSlice } from './systems/skin-palette-types';
170
+ export function extractFrames(
171
+ worlds: readonly World[],
172
+ owner: number | ExtractFramesOwner,
173
+ assets?: AssetRegistry | null,
174
+ pipelineState?: ExtractPipelineSurface | null,
175
+ materialSnapshotCachesByWorld?: MaterialSnapshotCachesByWorld,
176
+ options: {
177
+ readonly cull?: 'normal' | 'none';
178
+ readonly renderables?: 'full' | 'none';
179
+ readonly renderableEntitiesByWorld?: readonly (ReadonlySet<number> | undefined)[];
180
+ readonly retainHidden?: boolean;
181
+ readonly getMaterialShaderArtifact?: (
182
+ materialShaderId: string,
183
+ ) => MaterialShaderArtifact | undefined;
184
+ readonly instanceCollections?: InstanceProjectionStore;
185
+ } = {},
186
+ ): ExtractedFrame {
187
+ // w4: normalize the owner argument. A bare number is the legacy single-owner
188
+ // form (cameraOwner === resourceOwner); an object carries the two split
189
+ // indices. When they coincide the code path is byte-identical to the pre-w4
190
+ // single-owner behaviour (w1 contract combination 2).
191
+ const cameraOwner = typeof owner === 'number' ? owner : owner.cameraOwner;
192
+ const resourceOwner = typeof owner === 'number' ? owner : owner.resourceOwner;
193
+
194
+ // ── D-2: frame-level side effects live here ────────────────────────────
195
+ //
196
+ // resetForFrame is called exactly once per frame, at the extractFrames
197
+ // entry. The skinPaletteAllocator cursor is reset before each per-world
198
+ // extract runs, so sequential per-world allocation yields non-overlapping
199
+ // palette slices (AC-08).
200
+ const skinPaletteAllocator = pipelineState?.skinPaletteAllocator ?? null;
201
+ if (skinPaletteAllocator !== null) {
202
+ skinPaletteAllocator.resetForFrame();
203
+ }
204
+
205
+ const failedWorlds = new Set<World>();
206
+ // Resource-owner selection is a frame-level concern. Select Fog once before
207
+ // per-world extraction so non-owner worlds do not scan their ECS tables for
208
+ // a value that the merge layer will discard.
209
+ const resourceOwnerWorld = worlds[resourceOwner];
210
+ const resourceOwnerFog =
211
+ resourceOwnerWorld === undefined ? null : (selectFogFrame(resourceOwnerWorld) ?? null);
212
+ // ── D-2: per-world extract with error isolation ────────────────────────
213
+ //
214
+ // Each world runs extractFrame over the final state published by
215
+ // world.update(). Failure in one world is caught, routed to that world's
216
+ // _routeError (systemName carries worldId for source identification),
217
+ // and the world's contribution is skipped (AC-09 graceful degradation).
218
+
219
+ // The camera-owner frame must be extracted first: non-owner worlds do not
220
+ // carry the surfaced camera, but their renderables still need to be tested
221
+ // against that camera's frustum. Frames are placed back into worlds[] order
222
+ // before merge so queue / directional-light / worldId semantics stay stable.
223
+ const succeededFrames: ExtractedFrame[] = [];
224
+ const succeededIndices: number[] = [];
225
+
226
+ const extractionOrder = Array.from({ length: worlds.length }, (_, wi) => wi).sort((a, b) => {
227
+ if (a === cameraOwner) return -1;
228
+ if (b === cameraOwner) return 1;
229
+ return a - b;
230
+ });
231
+ const framesByWorld = new Map<number, ExtractedFrame>();
232
+
233
+ for (const wi of extractionOrder) {
234
+ const world = worlds[wi];
235
+ if (world === undefined || failedWorlds.has(world)) continue;
236
+ try {
237
+ const isCameraOwner = wi === cameraOwner;
238
+ const cameraOwnerFrame = framesByWorld.get(cameraOwner);
239
+ const prepared = prepareExtractContext(world, {
240
+ ...(assets !== undefined ? { assets } : {}),
241
+ ...(pipelineState !== undefined ? { pipelineState } : {}),
242
+ resourceOwnerFog: wi === resourceOwner ? resourceOwnerFog : null,
243
+ ...(materialSnapshotCachesByWorld === undefined
244
+ ? {}
245
+ : {
246
+ materialSnapshotCache:
247
+ materialSnapshotCachesByWorld.get(world) ??
248
+ (() => {
249
+ const cache: MaterialSnapshotCache = new Map();
250
+ materialSnapshotCachesByWorld.set(world, cache);
251
+ return cache;
252
+ })(),
253
+ }),
254
+ cull: options.cull === 'none' ? 'none' : isCameraOwner ? 'self' : 'external',
255
+ renderables: options.renderables ?? 'full',
256
+ ...(options.renderableEntitiesByWorld?.[wi] === undefined
257
+ ? {}
258
+ : { renderableEntities: options.renderableEntitiesByWorld[wi] }),
259
+ retainHidden: options.retainHidden ?? false,
260
+ ...(options.getMaterialShaderArtifact === undefined
261
+ ? {}
262
+ : { getMaterialShaderArtifact: options.getMaterialShaderArtifact }),
263
+ ...(options.instanceCollections === undefined
264
+ ? {}
265
+ : { instanceCollections: options.instanceCollections }),
266
+ ...(cameraOwnerFrame === undefined ? {} : { cullCameras: cameraOwnerFrame.cameras }),
267
+ });
268
+ const frame = extractFrame(world, prepared);
269
+
270
+ framesByWorld.set(wi, frame);
271
+ } catch (err) {
272
+ // Per-world failure: route to world's own error handler, skip contribution.
273
+ try {
274
+ createWorldInternalView(world)._routeError(err, {
275
+ severity: Severity.Error,
276
+ systemName: `RenderSystem.extractFrames(world[${wi}])`,
277
+ });
278
+ } catch {
279
+ // If _routeError itself throws, the world already failed — skip silently.
280
+ }
281
+ }
282
+ }
283
+
284
+ // Restore the caller's world order after the camera-owner-first extraction.
285
+ for (let wi = 0; wi < worlds.length; wi++) {
286
+ const frame = framesByWorld.get(wi);
287
+ if (frame === undefined) continue;
288
+ succeededFrames.push(frame);
289
+ succeededIndices.push(wi);
290
+ }
291
+
292
+ // ── D-3: merge semantics ───────────────────────────────────────────────
293
+
294
+ // AC-04: renderables — concat by worlds[] order, stamp worldId.
295
+ const renderables: RenderableSnapshot[] = [];
296
+ const dispatchEntries: DispatchEntry[] = [];
297
+ const visibilitySnapshots: VisibilitySnapshot[] = [];
298
+ const featureVisibilitySnapshots: RenderFeatureWorldVisibilitySnapshot[] = [];
299
+ const hiddenEntityReports: RenderFeatureHiddenEntityReport[] = [];
300
+
301
+ for (let fi = 0; fi < succeededFrames.length; fi++) {
302
+ const f = succeededFrames[fi];
303
+ const wId = succeededIndices[fi];
304
+ if (f === undefined || wId === undefined) continue;
305
+
306
+ const base = renderables.length;
307
+ const visibilitySnapshot = f.visibilitySnapshots[0];
308
+ const world = worlds[wId];
309
+ if (visibilitySnapshot !== undefined) {
310
+ visibilitySnapshots.push(visibilitySnapshot);
311
+ if (world !== undefined)
312
+ featureVisibilitySnapshots.push({ world, snapshot: visibilitySnapshot });
313
+ }
314
+ hiddenEntityReports.push(...f.hiddenEntityReports);
315
+ for (const r of f.renderables) {
316
+ renderables.push({
317
+ ...r,
318
+ worldId: wId,
319
+ ...(r.pointsLines === undefined ? {} : { pointsLines: { ...r.pointsLines, worldId: wId } }),
320
+ });
321
+ }
322
+
323
+ // D-3: dispatch — per-world renderableIndex rebased by base offset.
324
+ for (const d of f.dispatch) {
325
+ dispatchEntries.push({ ...d, renderableIndex: (d.renderableIndex ?? 0) + base });
326
+ }
327
+ }
328
+
329
+ // Stable sort dispatch by queue value.
330
+ dispatchEntries.sort((a, b) => (a.queue ?? 0) - (b.queue ?? 0));
331
+
332
+ // AC-04: lights — point[]/spot[] concat; directional first-hit in
333
+ // succeededFrames order (which preserves worlds[] order for successful
334
+ // frames); directionalCount sum.
335
+ const point: PointLightSnapshot[] = [];
336
+ const spot: SpotLightSnapshot[] = [];
337
+ const rect: RectAreaDirectLightSnapshot[] = [];
338
+ let directional: DirectionalLightSnapshot | undefined;
339
+ let directionalCount = 0;
340
+ let lightViewProj: readonly Float32Array[] | undefined;
341
+ let splitPlanes: Float32Array | undefined;
342
+ let cascadeCount: number | undefined;
343
+ let cascadeBlend: number | undefined;
344
+ let shadowMapSize: number | undefined;
345
+ let depthBias: number | undefined;
346
+ let normalBias: number | undefined;
347
+ let directionalShadowQuality: DirectionalShadowQuality | undefined;
348
+ let directionalShadowError: LightValidationError | undefined;
349
+ const pointShadow: PointShadowSnapshot[] = [];
350
+ // bug-20260710-editor-cross-world-shadow: carry the raw CSM config +
351
+ // direction of the first-hit directional so the merge layer can recompute
352
+ // matrices against the SURFACED (cameraOwner) camera — the light and the
353
+ // camera may live in different worlds (editor super-composite).
354
+ let directionalCsmConfig: DirectionalCsmConfig | undefined;
355
+ let directionalCsmDirection: Vec3 | undefined;
356
+ for (const f of succeededFrames) {
357
+ for (const p of f.lights.point) point.push(p);
358
+ for (const s of f.lights.spot) spot.push(s);
359
+ for (const r of f.lights.rect) rect.push(r);
360
+ for (const ps of f.lights.pointShadow) pointShadow.push(ps);
361
+ if (directional === undefined && f.lights.directional !== undefined) {
362
+ directional = f.lights.directional;
363
+ // Carry CSM shadow fields from the first-hit directional's world.
364
+ lightViewProj = f.lights.lightViewProj;
365
+ splitPlanes = f.lights.splitPlanes;
366
+ cascadeCount = f.lights.cascadeCount;
367
+ cascadeBlend = f.lights.cascadeBlend;
368
+ shadowMapSize = f.lights.shadowMapSize;
369
+ depthBias = f.lights.depthBias;
370
+ normalBias = f.lights.normalBias;
371
+ directionalShadowQuality = f.lights.directionalShadowQuality;
372
+ directionalShadowError = f.lights.directionalShadowError;
373
+ directionalCsmConfig = f.lights.directionalCsmConfig;
374
+ directionalCsmDirection = f.lights.directionalCsmDirection;
375
+ }
376
+ directionalCount += f.lights.directionalCount;
377
+ }
378
+
379
+ // AC-05/06 + w4 owner split (D-3 / R-6): cameras come from the cameraOwner
380
+ // world; skylight / skybox / postProcessParams come from the resourceOwner
381
+ // world (holistic snapshot selection). Scan succeededIndices once to locate
382
+ // each owner's surviving frame. When cameraOwner === resourceOwner both
383
+ // resolve to the same frame — byte-identical to the pre-w4 single-owner path.
384
+ let cameraOwnerFrame: ExtractedFrame | undefined;
385
+ let resourceOwnerFrame: ExtractedFrame | undefined;
386
+ for (let fi = 0; fi < succeededFrames.length; fi++) {
387
+ if (succeededIndices[fi] === cameraOwner) cameraOwnerFrame = succeededFrames[fi];
388
+ if (succeededIndices[fi] === resourceOwner) resourceOwnerFrame = succeededFrames[fi];
389
+ }
390
+ const cameras = cameraOwnerFrame !== undefined ? [...cameraOwnerFrame.cameras] : [];
391
+ const auxiliaryCameras =
392
+ cameraOwnerFrame !== undefined ? [...cameraOwnerFrame.auxiliaryCameras] : [];
393
+ const cubeCameras = cameraOwnerFrame !== undefined ? [...cameraOwnerFrame.cubeCameras] : [];
394
+
395
+ // bug-20260710-editor-cross-world-shadow: RECOMPUTE directional CSM matrices
396
+ // against the surfaced camera. In a single-world app the per-world extract
397
+ // already produced correct matrices (light+camera share the world), and this
398
+ // recompute reproduces them byte-identically (same config, same camera). In
399
+ // the editor super-composite the directional light's world has NO camera, so
400
+ // its per-world `lightViewProj` is undefined/degenerate; the surfaced camera
401
+ // lives in the cameraOwner world. Pairing them here is the ONLY place both
402
+ // are visible. Point/spot shadows are camera-independent (light-space only)
403
+ // and need no merge-layer fix-up.
404
+ const mergeCam = cameras[0];
405
+ if (directionalCsmConfig !== undefined && directionalCsmDirection !== undefined) {
406
+ const mergeCameraData: CsmCameraData | undefined =
407
+ mergeCam !== undefined
408
+ ? {
409
+ world: mergeCam.world,
410
+ fov: mergeCam.fov,
411
+ aspect: mergeCam.aspect,
412
+ near: mergeCam.near,
413
+ far: mergeCam.far,
414
+ projection: mergeCam.projection,
415
+ orthoLeft: mergeCam.orthoLeft,
416
+ orthoRight: mergeCam.orthoRight,
417
+ orthoBottom: mergeCam.orthoBottom,
418
+ orthoTop: mergeCam.orthoTop,
419
+ }
420
+ : undefined;
421
+ const csm = computeDirectionalCsm(
422
+ directionalCsmDirection,
423
+ directionalCsmConfig,
424
+ mergeCameraData,
425
+ );
426
+ if (csm !== null) {
427
+ lightViewProj = csm.lightViewProj;
428
+ splitPlanes = csm.splitPlanes;
429
+ cascadeCount = csm.cascadeCount;
430
+ cascadeBlend = csm.cascadeBlend;
431
+ shadowMapSize = csm.shadowMapSize;
432
+ directionalShadowQuality = csm.directionalShadowQuality;
433
+ }
434
+ // csm === null (no surfaced camera at all): keep the per-world carry —
435
+ // there is no better data, and a cameraless frame renders nothing anyway.
436
+ }
437
+
438
+ const lights: ExtractedLights = {
439
+ directional,
440
+ directionalCount,
441
+ point,
442
+ spot,
443
+ rect,
444
+ lightViewProj,
445
+ splitPlanes,
446
+ cascadeCount,
447
+ cascadeBlend,
448
+ shadowMapSize,
449
+ depthBias,
450
+ normalBias,
451
+ directionalShadowQuality,
452
+ directionalShadowError,
453
+ pointShadow,
454
+ directionalCsmConfig,
455
+ directionalCsmDirection,
456
+ };
457
+ const volumetricFog = resourceOwnerFrame?.volumetricFog;
458
+ const skylight = resourceOwnerFrame?.skylight;
459
+ const skylightCount = resourceOwnerFrame?.skylightCount ?? 0;
460
+ const skybox = resourceOwnerFrame?.skybox;
461
+ const skyboxCount = resourceOwnerFrame?.skyboxCount ?? 0;
462
+ const fog = resourceOwnerFrame?.fog;
463
+ const fogFailure = resourceOwnerFrame?.fogFailure;
464
+ const environment = resourceOwnerFrame?.environment;
465
+ const lightProbes = succeededFrames.flatMap((frame) => frame.lightProbes ?? []);
466
+ // User-authored PostProcessParams entities are singleton scene resources, so
467
+ // they come from the resourceOwner world (holistic snapshot selection).
468
+ const postProcessParams = new Map(resourceOwnerFrame?.postProcessParams);
469
+ // feat-20260709-editor-world-partition ENGINE-fix-round2 (defect 1): the
470
+ // engine built-in Standard tonemap param is NOT a scene resource — the
471
+ // per-world extractFrame bridges it from that world's own `cameras[0]`
472
+ // (Camera.exposure / whitePoint / tonemap is the SSOT). It therefore lives on
473
+ // the CAMERA-owner frame, not the resource-owner frame. In the split-owner
474
+ // editor topology the resourceOwner world has no Camera, so its frame carries
475
+ // no Standard tonemap entry; taking postProcessParams from resourceOwner
476
+ // alone drops it, the tonemap pass's params UBO stays zero-filled
477
+ // (exposure=0 => tonemapped output is uniformly black), and the whole frame
478
+ // reads black even though geometry drew into the HDR target. Overlay the
479
+ // camera-owner frame's tonemap param (its SSOT source) so the surfaced
480
+ // camera's exposure/whitePoint/mode reach the tonemap pass. When
481
+ // cameraOwner === resourceOwner this is a no-op (identical entry). The 'na'
482
+ // Standard tonemap identity mirrors the engine provider key set at the
483
+ // bottom of extractFrame (SSOT: same identity, same 16B layout).
484
+ const OUTPUT_TRANSFORM_PARAM_KEY = STANDARD_OUTPUT_TRANSFORM_FEATURE_ID;
485
+ const cameraTonemapParam = cameraOwnerFrame?.postProcessParams.get(OUTPUT_TRANSFORM_PARAM_KEY);
486
+ if (cameraTonemapParam !== undefined) {
487
+ postProcessParams.set(OUTPUT_TRANSFORM_PARAM_KEY, cameraTonemapParam);
488
+ } else {
489
+ // The camera-owner world produced no tonemap param (no Camera surfaced
490
+ // there this frame); do not leave a stale resource-owner entry that would
491
+ // apply a foreign camera's exposure. Removing it lets the tonemap pass fall
492
+ // back to its param-less zero path only when genuinely no camera exists.
493
+ postProcessParams.delete(OUTPUT_TRANSFORM_PARAM_KEY);
494
+ }
495
+
496
+ // D-3: frustumStats — culled/total summed across worlds.
497
+ const frustumStats = {
498
+ culled: succeededFrames.reduce((s, f) => s + f.frustumStats.culled, 0),
499
+ total: succeededFrames.reduce((s, f) => s + f.frustumStats.total, 0),
500
+ };
501
+ const visibilityStats = {
502
+ explicitlyHidden: succeededFrames.reduce((s, f) => s + f.visibilityStats.explicitlyHidden, 0),
503
+ };
504
+ const reflectionProbes = succeededFrames.flatMap((f, index) => {
505
+ const worldId = succeededIndices[index] ?? 0;
506
+ return (f.reflectionProbes ?? []).map((probe) => ({ ...probe, worldId }));
507
+ });
508
+
509
+ if (options.renderables !== 'none' && options.renderableEntitiesByWorld === undefined) {
510
+ options.instanceCollections?.retain(
511
+ new Set(
512
+ renderables.flatMap((row) =>
513
+ row.instances?.collectionId === undefined ? [] : [row.instances.collectionId],
514
+ ),
515
+ ),
516
+ );
517
+ if (
518
+ skinPaletteAllocator !== null &&
519
+ typeof skinPaletteAllocator.retainSliceKeys === 'function'
520
+ ) {
521
+ skinPaletteAllocator.retainSliceKeys(
522
+ new Set(
523
+ renderables.flatMap((row) =>
524
+ row.skin === undefined
525
+ ? []
526
+ : [`${worlds[row.worldId]?.identity ?? row.worldId}:${row.entityKey}`],
527
+ ),
528
+ ),
529
+ );
530
+ }
531
+ }
532
+
533
+ return {
534
+ cameras,
535
+ auxiliaryCameras,
536
+ cubeCameras,
537
+ reflectionProbes,
538
+ lights,
539
+ ...(volumetricFog === undefined
540
+ ? {}
541
+ : { volumetricFog: { ...volumetricFog, worldId: resourceOwner } }),
542
+ renderables,
543
+ dispatch: dispatchEntries,
544
+ skylight,
545
+ skylightCount,
546
+ lightProbes,
547
+ skybox,
548
+ skyboxCount,
549
+ fog,
550
+ ...(fogFailure === undefined ? {} : { fogFailure }),
551
+ environment,
552
+ environmentReady: resourceOwnerFrame !== undefined && environment !== undefined,
553
+ frustumStats,
554
+ visibilityStats,
555
+ postProcessParams,
556
+ visibilitySnapshots,
557
+ featureVisibilitySnapshots,
558
+ hiddenEntityReports,
559
+ };
560
+ }
561
+
562
+ /**
563
+ * A MeshAsset participates in frustum culling only when its producer supplied
564
+ * the complete finite local-space bounds promised by the asset contract.
565
+ * Missing, malformed, and inverted-infinity empty bounds remain conservative
566
+ * (always visible) so a bad asset cannot turn into a false-negative render;
567
+ * they are not cull candidates and therefore do not inflate frustumStats.
568
+ */
569
+ function hasFiniteOrderedLocalAabb(aabb: Float32Array | undefined): aabb is Float32Array {
570
+ if (aabb === undefined || aabb.length !== 6) return false;
571
+ const minX = aabb[0];
572
+ const minY = aabb[1];
573
+ const minZ = aabb[2];
574
+ const maxX = aabb[3];
575
+ const maxY = aabb[4];
576
+ const maxZ = aabb[5];
577
+ if (
578
+ minX === undefined ||
579
+ minY === undefined ||
580
+ minZ === undefined ||
581
+ maxX === undefined ||
582
+ maxY === undefined ||
583
+ maxZ === undefined
584
+ ) {
585
+ return false;
586
+ }
587
+ if (
588
+ !Number.isFinite(minX) ||
589
+ !Number.isFinite(minY) ||
590
+ !Number.isFinite(minZ) ||
591
+ !Number.isFinite(maxX) ||
592
+ !Number.isFinite(maxY) ||
593
+ !Number.isFinite(maxZ)
594
+ ) {
595
+ return false;
596
+ }
597
+ return minX <= maxX && minY <= maxY && minZ <= maxZ;
598
+ }
599
+
600
+ function morphSnapshotFor(
601
+ mesh: MeshAsset,
602
+ weights: ArrayLike<number> | undefined,
603
+ ): MorphSnapshot | undefined {
604
+ const targets = mesh.morphTargets;
605
+ if (targets === undefined || targets.length === 0 || weights === undefined) return undefined;
606
+ if (weights.length !== targets.length) return undefined;
607
+ const firstPositions = targets[0]?.position;
608
+ if (
609
+ firstPositions === undefined ||
610
+ firstPositions.length === 0 ||
611
+ firstPositions.length % 3 !== 0
612
+ ) {
613
+ return undefined;
614
+ }
615
+ const vertexCount = firstPositions.length / 3;
616
+ if (mesh.vertices.length % vertexCount !== 0) return undefined;
617
+ for (let targetIndex = 0; targetIndex < targets.length; targetIndex += 1) {
618
+ const target = targets[targetIndex];
619
+ if (target?.position?.length !== firstPositions.length) return undefined;
620
+ }
621
+ const copied = new Float32Array(weights.length);
622
+ for (let index = 0; index < weights.length; index += 1) {
623
+ const weight = weights[index] ?? Number.NaN;
624
+ if (!Number.isFinite(weight)) return undefined;
625
+ copied[index] = weight;
626
+ }
627
+ return { weights: copied, targetCount: targets.length };
628
+ }
629
+
630
+ export function extractFrame(world: World, context: PreparedExtractContext): ExtractedFrame {
631
+ // feat-20260708-composited-multi-world-rendering M2 / D-2: resetForFrame
632
+ // has been lifted to extractFrames (the frame-level entry point).
633
+ // extractFrame is now a pure world->snapshot function with no frame-level
634
+ // side effects. See plan-decisions PD2 for the reviewer ruling.
635
+ const {
636
+ assets,
637
+ pipelineState,
638
+ materialSnapshotCache: persistentMaterialSnapshotCache,
639
+ cull: cullMode,
640
+ resourceOwnerFog,
641
+ getMaterialShaderArtifact,
642
+ instanceCollections,
643
+ renderableEntities,
644
+ retainHidden,
645
+ } = context;
646
+ // Environment reads are owned by the retained resource projection and are
647
+ // established at the frame boundary; record never revisits World state.
648
+ const fog =
649
+ resourceOwnerFog === undefined ? selectFogFrame(world) : (resourceOwnerFog ?? undefined);
650
+ const fogFailure = fogState(world).failure;
651
+ const visibility = context.visibility.hasAnyHiddenIntent ? context.visibility : undefined;
652
+ const skinPaletteAllocator = pipelineState?.skinPaletteAllocator ?? null;
653
+
654
+ const directionalLightQuery = world.query({ read: [DirectionalLight] }).unwrap();
655
+
656
+ // feat-20260601 D-3: camera / point / spot light world transforms are read
657
+ // through the single resolved `GlobalTransform.world` mat4 (written by
658
+ // propagateTransforms).
659
+ //
660
+ // Each segment routes through a World-owned Query with explicit read and
661
+ // optional roles. The packed entity handle for `readWorldMat4Copy` /
662
+ // `_getArrayView` reads comes from `row.entity` -- the
663
+ // archetype-graph back-door (`graph.archetypes` / `arch.components.some`) is gone.
664
+ // Plan-decisions K-2 sniffing scheme B (archetype-edge sniff once via
665
+ // `row.get(X) !== undefined`); K-3 invariant preserved (`_getArrayView`
666
+ // calls survive untouched, only the entity source changes).
667
+ const worldInternal = createWorldInternalView(world);
668
+ let volumetricFog = extractVolumeSnapshot(world, assets, worldInternal);
669
+
670
+ const cameraRoles = selectCameraRoles(world);
671
+ const cameras = [...cameraRoles.display];
672
+ const auxiliaryCameras = cameraRoles.auxiliary;
673
+ const cubeCameras = collectCubeCameraSnapshots(world);
674
+ const reflectionProbes = collectReflectionProbeFacts(world);
675
+
676
+ // Three-query union (M2 / w16 / AC-03): directional has no Transform
677
+ // dependency (sun-like infinite-source semantics); point + spot pull
678
+ // position from the companion Transform via the joined queries.
679
+ // Host-side pre-multiplication: color *= intensity (charter P4); cone
680
+ // deg -> cos (D-S2); range -> 1/range^2 (D-S5).
681
+ let directional: DirectionalLightSnapshot | undefined;
682
+ let directionalCount = 0;
683
+ // feat-20260621 M2: capture shadow fields from the first-hit DirectionalLight.
684
+ // castShadow defaults to true; the CSM path is gated on firstHitCastShadow !== false.
685
+ let firstHitCastShadow: boolean | undefined;
686
+ let firstHitShadowFields:
687
+ | {
688
+ cascadeCount: number;
689
+ splitLambda: number;
690
+ cascadeBlend: number;
691
+ mapSize: number;
692
+ depthBias: number;
693
+ normalBias: number;
694
+ shadowDistance: number;
695
+ shadowFilter: number;
696
+ shadowAngularRadius: number;
697
+ maxPenumbraTexels: number;
698
+ }
699
+ | undefined;
700
+ for (const row of directionalLightQuery) {
701
+ const l = row.get(DirectionalLight);
702
+ directionalCount += 1;
703
+ const intensity = l.intensity;
704
+ const snapshot: DirectionalLightSnapshot = {
705
+ kind: 'directional',
706
+ entity: row.entity,
707
+ direction: vec3.create(l.direction[0] ?? 0, l.direction[1] ?? -1, l.direction[2] ?? 0),
708
+ color: vec3.create(
709
+ (l.color[0] ?? 1) * intensity,
710
+ (l.color[1] ?? 1) * intensity,
711
+ (l.color[2] ?? 1) * intensity,
712
+ ),
713
+ intensity,
714
+ };
715
+ if (directional === undefined) {
716
+ // First hit wins; record-stage N>1 fail-fast (M3 / w19) flags duplicates.
717
+ directional = snapshot;
718
+ firstHitCastShadow = l.castShadow;
719
+ firstHitShadowFields = {
720
+ cascadeCount: l.cascadeCount,
721
+ splitLambda: l.splitLambda,
722
+ cascadeBlend: l.cascadeBlend,
723
+ mapSize: l.mapSize,
724
+ depthBias: l.depthBias,
725
+ normalBias: l.normalBias,
726
+ shadowDistance: l.shadowDistance,
727
+ shadowFilter: l.shadowFilter,
728
+ shadowAngularRadius: l.shadowAngularRadius,
729
+ maxPenumbraTexels: l.maxPenumbraTexels,
730
+ };
731
+ }
732
+ }
733
+
734
+ let directionalShadowError: LightValidationError | undefined;
735
+ if (directional !== undefined && firstHitShadowFields !== undefined) {
736
+ const validation = validateDirectionalLightData({
737
+ direction: directional.direction,
738
+ castShadow: firstHitCastShadow,
739
+ ...firstHitShadowFields,
740
+ });
741
+ if (!validation.ok) {
742
+ directionalShadowError = validation.error;
743
+ worldInternal._routeError(directionalShadowError, {
744
+ severity: Severity.Error,
745
+ systemName: 'RenderSystem.extract (directional-shadow)',
746
+ });
747
+ }
748
+ }
749
+
750
+ const pointSnapshots: PointLightSnapshot[] = [];
751
+ // feat-20260612-point-light-shadows-urp-hdrp M4 / T-M4-4: track entity per
752
+ // pointSnapshots index so the post-extract pointShadow join can stamp
753
+ // `shadowAtlasLayer + shadowNear + shadowFar` onto the matching PointLight.
754
+ const pointSnapshotEntities: number[] = [];
755
+ const pointLightQuery = world
756
+ .query({
757
+ read: [PointLight],
758
+ optional: [Transform, GlobalTransform],
759
+ })
760
+ .unwrap();
761
+ for (const row of pointLightQuery) {
762
+ const p = row.get(PointLight);
763
+ // K-2 scheme B: archetype-edge sniff -- `bundle.Transform` key is absent
764
+ // when the archetype does not carry the Transform column.
765
+ const hasTransform = row.get(GlobalTransform) !== undefined;
766
+ const intensity = p.intensity;
767
+ const range = p.range;
768
+ const entityId = row.entity;
769
+ // Position = world-space translation extracted from GlobalTransform.world.
770
+ // A point light archetype without a Transform column sits at the origin.
771
+ let worldMat: Float32Array | undefined;
772
+ if (hasTransform) {
773
+ const view = worldInternal._getArrayView(entityId, GlobalTransform, 'world');
774
+ if (view !== undefined) worldMat = new Float32Array(view);
775
+ }
776
+ const position =
777
+ worldMat !== undefined ? mat4.getTranslation(vec3.create(), worldMat) : vec3.create(0, 0, 0);
778
+ pointSnapshots.push({
779
+ kind: 'point',
780
+ entity: entityId,
781
+ position,
782
+ color: vec3.create(
783
+ (p.color[0] ?? 1) * intensity,
784
+ (p.color[1] ?? 1) * intensity,
785
+ (p.color[2] ?? 1) * intensity,
786
+ ),
787
+ intensity,
788
+ invRangeSquared: computeInvRangeSquared(range),
789
+ });
790
+ pointSnapshotEntities.push(entityId);
791
+ }
792
+
793
+ const spotSnapshots: SpotLightSnapshot[] = [];
794
+ const spotLightQuery = world
795
+ .query({
796
+ read: [SpotLight],
797
+ optional: [Transform, GlobalTransform],
798
+ })
799
+ .unwrap();
800
+ // feat-20260625-spot-light-shadow-mapping M1 w5: tile allocation for castShadow spots.
801
+ // Cap = 4 (OOS-5), sentinel -1 = unassigned (plan-strategy D-4).
802
+ // Direction degeneration (near-zero) also skips shadow (requirements $112).
803
+ let spotTileNext = 0;
804
+ const iesSlices = new Map<number, number>();
805
+ const cookieSlices = new Map<number, number>();
806
+ const projectorSlices = new Map<number, number>();
807
+ for (const row of spotLightQuery) {
808
+ const s = row.get(SpotLight);
809
+ const hasTransform = row.get(GlobalTransform) !== undefined;
810
+ const intensity = s.intensity;
811
+ const range = s.range;
812
+ const innerConeDeg = s.innerConeDeg;
813
+ const outerConeDeg = s.outerConeDeg;
814
+ let worldMat: Float32Array | undefined;
815
+ if (hasTransform) {
816
+ const entity = row.entity;
817
+ const view = worldInternal._getArrayView(entity, GlobalTransform, 'world');
818
+ if (view !== undefined) worldMat = new Float32Array(view);
819
+ }
820
+ const position =
821
+ worldMat !== undefined ? mat4.getTranslation(vec3.create(), worldMat) : vec3.create(0, 0, 0);
822
+ const dir = vec3.create(s.direction[0] ?? 0, s.direction[1] ?? -1, s.direction[2] ?? 0);
823
+
824
+ // Extract is the single direction-normalization owner for direct-light
825
+ // snapshots. URP and HDRP preserve this value downstream.
826
+ const dirLen = Math.sqrt(
827
+ (dir[0] ?? 0) * (dir[0] ?? 0) + (dir[1] ?? 0) * (dir[1] ?? 0) + (dir[2] ?? 0) * (dir[2] ?? 0),
828
+ );
829
+ const EPSILON = 1e-6;
830
+ const hasValidDirection = dirLen > EPSILON;
831
+ if (!hasValidDirection) {
832
+ worldInternal._routeError(
833
+ new SpawnLightInvalidBoundsError('SpotLight', 'direction', [
834
+ dir[0] ?? 0,
835
+ dir[1] ?? 0,
836
+ dir[2] ?? 0,
837
+ ]),
838
+ {
839
+ severity: Severity.Error,
840
+ systemName: 'RenderSystem.extract (spot-direction)',
841
+ },
842
+ );
843
+ }
844
+ const dirN = vec3.create(
845
+ hasValidDirection ? (dir[0] ?? 0) / dirLen : (dir[0] ?? 0),
846
+ hasValidDirection ? (dir[1] ?? 0) / dirLen : (dir[1] ?? 0),
847
+ hasValidDirection ? (dir[2] ?? 0) / dirLen : (dir[2] ?? 0),
848
+ );
849
+
850
+ // ── shadow fields (feat-20260625-spot-light-shadow-mapping M1) ──
851
+ const castShadow = s.castShadow;
852
+ const sMapSize = s.mapSize;
853
+ const sNearPlane = s.nearPlane;
854
+ const sFarPlane = s.farPlane;
855
+ const iesProfileAsset =
856
+ s.iesProfile === undefined
857
+ ? undefined
858
+ : resolveAssetHandle<IesProfileAsset>(world, s.iesProfile);
859
+ const cookieAsset =
860
+ s.cookie === undefined ? undefined : resolveAssetHandle<TextureAsset>(world, s.cookie);
861
+ // Resolve the legacy projector before assigning array slices so the
862
+ // extended-lighting path can reuse its texture transport without losing
863
+ // the old lightViewProj projection semantics.
864
+ const hasProjector = Number(s.projector) > 0;
865
+ let projectorHandle: Handle<'TextureAsset', 'shared'> | undefined;
866
+ let projectorAsset: TextureAsset | undefined;
867
+ let projectorGuid: string | undefined;
868
+ if (hasProjector) {
869
+ const candidate = toShared<'TextureAsset'>(Math.round(Number(s.projector)));
870
+ const resolvedProjector = resolveAssetHandle<TextureAsset>(world, candidate);
871
+ if (!resolvedProjector.ok || resolvedProjector.value.kind !== 'texture') {
872
+ worldInternal._routeError(
873
+ resolvedProjector.ok
874
+ ? new RhiError({
875
+ code: 'asset-not-registered',
876
+ expected: 'SpotLight.projector resolves to a TextureAsset',
877
+ hint: 'load the authored projector TextureAsset before assigning SpotLight.projector',
878
+ detail: { assetHandle: Number(candidate) },
879
+ })
880
+ : resolvedProjector.error,
881
+ { severity: Severity.Error, systemName: 'RenderSystem.extract (spot-projector)' },
882
+ );
883
+ } else {
884
+ projectorHandle = candidate;
885
+ projectorAsset = resolvedProjector.value;
886
+ projectorGuid = assets?.guidOf(projectorAsset) ?? `handle:${Number(candidate)}`;
887
+ }
888
+ }
889
+ const iesProfileData =
890
+ iesProfileAsset?.ok && iesProfileAsset.value.kind === 'ies-profile'
891
+ ? new Uint8Array(iesProfileAsset.value.data)
892
+ : undefined;
893
+ const cookieProjection =
894
+ cookieAsset?.ok && cookieAsset.value.kind === 'texture'
895
+ ? prepareCookieProjection(cookieAsset.value)
896
+ : undefined;
897
+ const cookieData = cookieProjection?.data;
898
+ const projectorProjection =
899
+ projectorAsset === undefined ? undefined : prepareCookieProjection(projectorAsset);
900
+ const projectorData = projectorProjection?.data;
901
+ const iesProfileHandle = s.iesProfile === undefined ? undefined : handleSlot(s.iesProfile);
902
+ const cookieHandle = s.cookie === undefined ? undefined : handleSlot(s.cookie);
903
+ let iesProfileSlice =
904
+ iesProfileHandle === undefined ? undefined : iesSlices.get(iesProfileHandle);
905
+ if (
906
+ iesProfileSlice === undefined &&
907
+ iesProfileHandle !== undefined &&
908
+ iesProfileData !== undefined &&
909
+ iesSlices.size < IES_SLICE_CAPACITY
910
+ ) {
911
+ iesProfileSlice = iesSlices.size;
912
+ iesSlices.set(iesProfileHandle, iesProfileSlice);
913
+ }
914
+ let cookieSlice = cookieHandle === undefined ? undefined : cookieSlices.get(cookieHandle);
915
+ if (
916
+ cookieSlice === undefined &&
917
+ cookieHandle !== undefined &&
918
+ cookieData !== undefined &&
919
+ cookieSlices.size < COOKIE_SLICE_CAPACITY
920
+ ) {
921
+ cookieSlice = cookieSlices.size;
922
+ cookieSlices.set(cookieHandle, cookieSlice);
923
+ }
924
+ let projectorSlice =
925
+ projectorHandle === undefined
926
+ ? undefined
927
+ : (projectorSlices.get(projectorHandle) ?? cookieSlices.get(projectorHandle));
928
+ if (
929
+ projectorSlice === undefined &&
930
+ projectorHandle !== undefined &&
931
+ projectorData !== undefined &&
932
+ cookieSlices.size + projectorSlices.size < COOKIE_SLICE_CAPACITY
933
+ ) {
934
+ projectorSlice = cookieSlices.size + projectorSlices.size;
935
+ projectorSlices.set(projectorHandle, projectorSlice);
936
+ }
937
+ const shadowIntensity = s.shadowIntensity;
938
+ // `shared<T>` columns are u32-backed and zero-filled when the optional
939
+ // field is absent. Treat only a positive handle as an authored projector;
940
+ // checking nullish values alone would turn the zero sentinel into a
941
+ // phantom projector matrix and an avoidable asset-not-found diagnostic.
942
+ let lightViewProj: Float32Array | undefined;
943
+ let shadowAtlasTile = -1;
944
+
945
+ // A projector needs the same perspective transform even when its SpotLight
946
+ // has no shadow atlas tile. The matrix remains a derived light fact; the
947
+ // shadow tile stays -1 so shadow visibility is still independently gated.
948
+ if ((castShadow || hasProjector) && hasValidDirection) {
949
+ const target = vec3.create(
950
+ (position[0] ?? 0) + (dirN[0] ?? 0),
951
+ (position[1] ?? 0) + (dirN[1] ?? 0),
952
+ (position[2] ?? 0) + (dirN[2] ?? 0),
953
+ );
954
+ // D-1: perspective(outerConeDeg*2, aspect=1, near, far) x lookAt(pos, pos+dir).
955
+ // FOV = outerConeDeg * 2 in degrees; mat4.perspective takes fov in radians.
956
+ const fov = outerConeDeg * 2 * (Math.PI / 180);
957
+ const proj = mat4.create();
958
+ mat4.perspective(proj, fov, 1, sNearPlane, sFarPlane);
959
+ const view = mat4.create();
960
+ mat4.lookAt(view, position, target, vec3.create(0, 1, 0));
961
+ lightViewProj = new Float32Array(16);
962
+ // Reinterpret the Float32Array surface field as a Mat4 out-param; a
963
+ // factory would force a needless alloc+copy. brand-cast-ok
964
+ mat4.multiply(lightViewProj as Mat4, proj, view);
965
+
966
+ // D-4: allocate tile 0..3; 5th+ = -1 sentinel.
967
+ if (castShadow && spotTileNext < 4) {
968
+ shadowAtlasTile = spotTileNext;
969
+ spotTileNext += 1;
970
+ }
971
+ }
972
+
973
+ spotSnapshots.push({
974
+ kind: 'spot',
975
+ entity: row.entity,
976
+ // D-6: position reflects world transform; direction stays sourced
977
+ // from SpotLight.direction (NOT rotated by the parent).
978
+ position,
979
+ direction: dirN,
980
+ color: vec3.create(
981
+ (s.color[0] ?? 1) * intensity,
982
+ (s.color[1] ?? 1) * intensity,
983
+ (s.color[2] ?? 1) * intensity,
984
+ ),
985
+ intensity,
986
+ invRangeSquared: computeInvRangeSquared(range),
987
+ cosInner: degToCos(innerConeDeg),
988
+ cosOuter: degToCos(outerConeDeg),
989
+ ...(s.iesProfile === undefined
990
+ ? {}
991
+ : {
992
+ iesProfileHandle: handleSlot(s.iesProfile),
993
+ ...(iesProfileSlice === undefined ? {} : { iesProfileSlice }),
994
+ }),
995
+ ...(s.cookie === undefined
996
+ ? {}
997
+ : {
998
+ cookieHandle: handleSlot(s.cookie),
999
+ ...(cookieSlice === undefined ? {} : { cookieSlice }),
1000
+ }),
1001
+ ...(iesProfileData === undefined ? {} : { iesProfileData }),
1002
+ ...(cookieData === undefined ? {} : { cookieData }),
1003
+ ...(cookieProjection === undefined ? {} : { cookieMatrix: cookieProjection.matrix }),
1004
+ ...(projectorSlice === undefined ? {} : { projectorSlice }),
1005
+ ...(projectorData === undefined ? {} : { projectorData }),
1006
+ ...(projectorProjection === undefined ? {} : { projectorMatrix: projectorProjection.matrix }),
1007
+ rollDeg: s.rollDeg,
1008
+ // ── shadow fields ──
1009
+ castShadow,
1010
+ lightViewProj,
1011
+ mapSize: sMapSize,
1012
+ nearPlane: sNearPlane,
1013
+ farPlane: sFarPlane,
1014
+ shadowAtlasTile,
1015
+ shadowIntensity,
1016
+ depthBias: s.depthBias,
1017
+ normalBias: s.normalBias,
1018
+ pcfKernelSize: s.pcfKernelSize,
1019
+ ...(projectorHandle === undefined ||
1020
+ projectorAsset === undefined ||
1021
+ projectorGuid === undefined
1022
+ ? {}
1023
+ : {
1024
+ projectorHandle,
1025
+ projectorAsset,
1026
+ projectorGuid,
1027
+ projectorGeneration: 1,
1028
+ projectorRevision: 1,
1029
+ }),
1030
+ });
1031
+ }
1032
+
1033
+ const rectSnapshots: RectAreaDirectLightSnapshot[] = [];
1034
+ const rectLightQuery = world
1035
+ .query({
1036
+ read: [RectAreaLight],
1037
+ optional: [Transform, GlobalTransform],
1038
+ })
1039
+ .unwrap();
1040
+ for (const row of rectLightQuery) {
1041
+ const light = row.get(RectAreaLight);
1042
+ const validation = validateRectAreaLightData({
1043
+ intensity: light.intensity,
1044
+ color: light.color,
1045
+ width: light.width,
1046
+ height: light.height,
1047
+ range: light.range,
1048
+ });
1049
+ if (!validation.ok) {
1050
+ worldInternal._routeError(validation.error, {
1051
+ severity: Severity.Error,
1052
+ systemName: 'RenderSystem.extract (rect-area-light)',
1053
+ });
1054
+ continue;
1055
+ }
1056
+ const worldView = row.get(GlobalTransform);
1057
+ const worldMat =
1058
+ worldView === undefined
1059
+ ? undefined
1060
+ : new Float32Array(worldInternal._getArrayView(row.entity, GlobalTransform, 'world') ?? []);
1061
+ const position =
1062
+ worldMat !== undefined ? mat4.getTranslation(vec3.create(), worldMat) : vec3.create(0, 0, 0);
1063
+ const frame = buildRectAreaWorldFrame({
1064
+ center: position,
1065
+ axisX: [worldMat?.[0] ?? 1, worldMat?.[1] ?? 0, worldMat?.[2] ?? 0],
1066
+ axisY: [worldMat?.[4] ?? 0, worldMat?.[5] ?? 1, worldMat?.[6] ?? 0],
1067
+ width: light.width,
1068
+ height: light.height,
1069
+ });
1070
+ rectSnapshots.push({
1071
+ kind: 'rect-area',
1072
+ position,
1073
+ color: vec3.create(
1074
+ (light.color[0] ?? 1) * light.intensity,
1075
+ (light.color[1] ?? 1) * light.intensity,
1076
+ (light.color[2] ?? 1) * light.intensity,
1077
+ ),
1078
+ intensity: light.intensity,
1079
+ invRangeSquared: computeInvRangeSquared(light.range),
1080
+ halfWidth: frame.halfWidth,
1081
+ halfHeight: frame.halfHeight,
1082
+ axisX: frame.axisX,
1083
+ axisY: frame.axisY,
1084
+ });
1085
+ }
1086
+ // The SpotLight is the sole projector owner. Once all light snapshots have
1087
+ // been extracted, publish its accepted TextureAsset tuple on the volume
1088
+ // snapshot so surface and volume consume the same identity and revision.
1089
+ let volumeSpot: SpotLightSnapshot | undefined;
1090
+ const extractedFog = volumetricFog;
1091
+ if (extractedFog !== undefined) {
1092
+ if (extractedFog.spotLightEntity !== undefined) {
1093
+ volumeSpot = spotSnapshots.find((light) => light.entity === extractedFog.spotLightEntity);
1094
+ } else if (extractedFog.lightKind === 'spot') {
1095
+ volumeSpot = spotSnapshots.find((light) => light.entity === extractedFog.lightEntity);
1096
+ }
1097
+ }
1098
+ if (
1099
+ volumetricFog !== undefined &&
1100
+ volumetricFog.status === 'available' &&
1101
+ volumeSpot?.projectorAsset !== undefined &&
1102
+ volumeSpot.projectorHandle !== undefined
1103
+ ) {
1104
+ const projectorHandle = volumeSpot.projectorHandle;
1105
+ const projectorAsset = volumeSpot.projectorAsset;
1106
+ volumetricFog = {
1107
+ ...volumetricFog,
1108
+ projector: {
1109
+ guid: volumeSpot.projectorGuid ?? `handle:${Number(volumeSpot.projectorHandle)}`,
1110
+ generation: volumeSpot.projectorGeneration ?? 1,
1111
+ view: '2d',
1112
+ sampler: 'linear-clamp-to-edge',
1113
+ projection: 'spot-projection',
1114
+ revision: volumeSpot.projectorRevision ?? 1,
1115
+ },
1116
+ projectorHandle,
1117
+ projectorAsset,
1118
+ };
1119
+ }
1120
+
1121
+ // bug-20260710-editor-cross-world-shadow: CSM matrices are computed by the
1122
+ // shared pure {@link computeDirectionalCsm}, called here per-world with THIS
1123
+ // world's own `cameras[0]`. In a single-world app the light and camera share
1124
+ // the world, so this per-world result is final (byte-identical to the prior
1125
+ // inline block). In the editor super-composite the light's world may have no
1126
+ // camera → this yields no matrices; {@link extractFrames} then RECOMPUTES at
1127
+ // the merge layer using the surfaced (cameraOwner) camera + the raw config
1128
+ // carried on ExtractedLights. The raw config + direction are surfaced
1129
+ // unconditionally so the merge layer can re-run the builder.
1130
+ let lightViewProj: Float32Array[] | undefined;
1131
+ let splitPlanes: Float32Array | undefined;
1132
+ let cascadeCount: number | undefined;
1133
+ let cascadeBlend: number | undefined;
1134
+ let shadowMapSize: number | undefined;
1135
+ let directionalShadowQuality: DirectionalShadowQuality | undefined;
1136
+ let directionalCsmConfig: DirectionalCsmConfig | undefined;
1137
+ let directionalCsmDirection: Vec3 | undefined;
1138
+
1139
+ // Camera data needed for frustum corner computation (first camera only;
1140
+ // multi-camera CSM is OOS-1). Undefined in a cameraless world.
1141
+ const cam0 = cameras[0];
1142
+ const cameraData: CsmCameraData | undefined =
1143
+ cam0 !== undefined
1144
+ ? {
1145
+ world: cam0.world,
1146
+ fov: cam0.fov,
1147
+ aspect: cam0.aspect,
1148
+ near: cam0.near,
1149
+ far: cam0.far,
1150
+ projection: cam0.projection,
1151
+ orthoLeft: cam0.orthoLeft,
1152
+ orthoRight: cam0.orthoRight,
1153
+ orthoBottom: cam0.orthoBottom,
1154
+ orthoTop: cam0.orthoTop,
1155
+ }
1156
+ : undefined;
1157
+
1158
+ // feat-20260621 M2: CSM computation gated on castShadow from the
1159
+ // merged DirectionalLight. castShadow defaults to true (first-hit-wins
1160
+ // semantics, D-6 no cardinality cap).
1161
+ if (
1162
+ directional !== undefined &&
1163
+ firstHitCastShadow !== false &&
1164
+ directionalShadowError === undefined
1165
+ ) {
1166
+ const dirSnapshot = directional;
1167
+ const sf = firstHitShadowFields;
1168
+ if (sf !== undefined) {
1169
+ directionalCsmConfig = {
1170
+ cascadeCount: sf.cascadeCount,
1171
+ splitLambda: sf.splitLambda,
1172
+ cascadeBlend: sf.cascadeBlend,
1173
+ mapSize: sf.mapSize,
1174
+ shadowDistance: sf.shadowDistance,
1175
+ shadowFilter: sf.shadowFilter,
1176
+ shadowAngularRadius: sf.shadowAngularRadius,
1177
+ maxPenumbraTexels: sf.maxPenumbraTexels,
1178
+ };
1179
+ directionalCsmDirection = dirSnapshot.direction;
1180
+ const csm = computeDirectionalCsm(dirSnapshot.direction, directionalCsmConfig, cameraData);
1181
+ // Cascade metadata (splitPlanes / count / blend / mapSize) is available
1182
+ // even without a camera (splitPlanes needs only near/far); the matrices
1183
+ // need the camera. When csm is null (no camera) leave lightViewProj
1184
+ // undefined — the merge layer recomputes. Still surface the split/count
1185
+ // metadata so a single-world path keeps its prior fields.
1186
+ cascadeCount = Math.round(sf.cascadeCount);
1187
+ cascadeBlend = sf.cascadeBlend;
1188
+ shadowMapSize = sf.mapSize;
1189
+ if (csm !== null) {
1190
+ lightViewProj = csm.lightViewProj;
1191
+ splitPlanes = csm.splitPlanes;
1192
+ directionalShadowQuality = csm.directionalShadowQuality;
1193
+ } else {
1194
+ const sNear = cameraData?.near ?? 0.1;
1195
+ const splits = pssmSplit(sNear, sf.shadowDistance, cascadeCount, sf.splitLambda);
1196
+ const padded = new Float32Array(16);
1197
+ for (let i = 0; i < splits.length; i++) padded[i * 4] = splits[i] ?? 0;
1198
+ splitPlanes = padded;
1199
+ }
1200
+ directionalShadowQuality = directionalShadowQualityFromF32(
1201
+ sf.shadowFilter,
1202
+ sf.shadowAngularRadius,
1203
+ sf.maxPenumbraTexels,
1204
+ );
1205
+ }
1206
+ }
1207
+
1208
+ // feat-20260613-csm M3 / w14 (plan-strategy §D-7): pad the up-to-4
1209
+ // splitPlanes into a fixed length-4 Float32Array (unused slots = 0) so
1210
+ // the View UBO tail keeps a stable layout regardless of the runtime
1211
+ // cascadeCount. Host-side correctness invariant: only the first
1212
+ // cascadeCount slots are ever read by the WGSL kernel.
1213
+ const paddedSplitPlanes = new Float32Array(16);
1214
+ if (splitPlanes !== undefined) {
1215
+ for (let i = 0; i < splitPlanes.length; i++) {
1216
+ paddedSplitPlanes[i] = splitPlanes[i] ?? 0;
1217
+ }
1218
+ }
1219
+
1220
+ // feat-20260612-point-light-shadows-urp-hdrp M1 / T-M1-7 (plan-strategy §D-3,
1221
+ // requirements §5.3): query (PointLight + PointLightShadow + Transform)
1222
+ // archetype join. For each shadow caster, build 6 face VP matrices and pack
1223
+ // into Float32Array(96). Atlas layer is assigned in spawn order while the
1224
+ // renderer-owned atlas has capacity; the sentinel -1 is shader-side and
1225
+ // applies to non-admitted PointLightShadow requests as well.
1226
+ const pointShadowSnapshots: PointShadowSnapshot[] = [];
1227
+ {
1228
+ const pointShadowQuery = world
1229
+ .query({ read: [Transform, GlobalTransform, PointLightShadow], with: [PointLight] })
1230
+ .unwrap();
1231
+ for (const row of pointShadowQuery) {
1232
+ const ps = row.get(PointLightShadow);
1233
+ // Read world-space position from GlobalTransform.world (mat4 column-major;
1234
+ // translation lives at indices 12..14, mirroring CameraSnapshot.world
1235
+ // semantics in this file).
1236
+ // feat-20260614 M4 / w13: TypedArrayFor for `array<f32, 16>` now
1237
+ // resolves to a concrete `Float32Array` (was `never` pre-w11), which
1238
+ // surfaces the row-window slicing -- `t.world` is the stride-16 flat
1239
+ // column view; row i lives at `[i*16, (i+1)*16)`. The prior
1240
+ // `t.world?.[i]` form silently returned a single element under the
1241
+ // `never`-typed bundle path and `wRow[12]` widened to `undefined ?? 0`
1242
+ // so light positions clamped to the origin.
1243
+ const wRow = row.get(GlobalTransform).world;
1244
+ if (wRow === undefined) continue;
1245
+ const px = wRow[12] ?? 0;
1246
+ const py = wRow[13] ?? 0;
1247
+ const pz = wRow[14] ?? 0;
1248
+ const lightPos = vec3.create(px, py, pz);
1249
+ const mapSize = ps.mapSize;
1250
+ const nearPlane = ps.nearPlane;
1251
+ const farPlane = ps.farPlane;
1252
+ // The renderer, not ECS, owns the atlas budget. Preserve every request
1253
+ // for inspection, but emit the shader sentinel for entries that cannot
1254
+ // acquire a layer so record never calls faceView outside the atlas.
1255
+ const layer =
1256
+ pointShadowSnapshots.length < SHADOW_ATLAS_DEFAULT_LAYERS
1257
+ ? pointShadowSnapshots.length
1258
+ : -1;
1259
+
1260
+ const matrices = buildPointShadowMatrices(lightPos, nearPlane, farPlane);
1261
+ const packed = new Float32Array(96);
1262
+ for (let f = 0; f < 6; f++) {
1263
+ const m = matrices[f];
1264
+ if (m === undefined) continue;
1265
+ for (let k = 0; k < 16; k++) {
1266
+ packed[f * 16 + k] = m[k] ?? 0;
1267
+ }
1268
+ }
1269
+ pointShadowSnapshots.push({
1270
+ entity: row.entity,
1271
+ position: lightPos,
1272
+ mapSize,
1273
+ nearPlane,
1274
+ farPlane,
1275
+ shadowAtlasLayer: layer,
1276
+ shadowMatrices: packed,
1277
+ });
1278
+ }
1279
+ }
1280
+
1281
+ // feat-20260612-point-light-shadows-urp-hdrp M4 / T-M4-4 (plan-strategy §D-8):
1282
+ // join pointShadow snapshots into the matching PointLightSnapshot so the
1283
+ // record stage threads `shadowAtlasLayer + shadowNear + shadowFar` through
1284
+ // the unified direct-light metadata payload.
1285
+ // Mutates the freshly-built PointLightSnapshot in place; the snapshot is
1286
+ // not exposed elsewhere this frame yet (consumed only by lights.point[]).
1287
+ if (pointShadowSnapshots.length > 0) {
1288
+ const shadowByEntity = new Map<number, PointShadowSnapshot>();
1289
+ for (const ps of pointShadowSnapshots) shadowByEntity.set(ps.entity, ps);
1290
+ for (let i = 0; i < pointSnapshots.length; i++) {
1291
+ const entityId = pointSnapshotEntities[i] ?? 0;
1292
+ const ps = shadowByEntity.get(entityId);
1293
+ if (ps !== undefined) {
1294
+ pointSnapshots[i] = {
1295
+ ...(pointSnapshots[i] as PointLightSnapshot),
1296
+ shadowAtlasLayer: ps.shadowAtlasLayer,
1297
+ shadowNear: ps.nearPlane,
1298
+ shadowFar: ps.farPlane,
1299
+ };
1300
+ }
1301
+ }
1302
+ }
1303
+
1304
+ const lights: ExtractedLights = {
1305
+ directional,
1306
+ directionalCount,
1307
+ point: pointSnapshots,
1308
+ spot: spotSnapshots,
1309
+ rect: rectSnapshots,
1310
+ lightViewProj,
1311
+ splitPlanes: splitPlanes !== undefined ? paddedSplitPlanes : undefined,
1312
+ cascadeCount,
1313
+ cascadeBlend,
1314
+ shadowMapSize,
1315
+ depthBias: firstHitCastShadow !== false ? firstHitShadowFields?.depthBias : undefined,
1316
+ normalBias: firstHitCastShadow !== false ? firstHitShadowFields?.normalBias : undefined,
1317
+ directionalShadowQuality,
1318
+ directionalShadowError,
1319
+ pointShadow: pointShadowSnapshots,
1320
+ // bug-20260710-editor-cross-world-shadow: raw CSM config + light direction
1321
+ // so the merge layer can recompute matrices against the surfaced camera.
1322
+ directionalCsmConfig,
1323
+ directionalCsmDirection,
1324
+ };
1325
+
1326
+ // feat-20260520-skylight-ibl-cubemap M4 / t26+t27: query Skylight entities.
1327
+ // First archetype hit wins (mirrors DirectionalLight pattern); multi-Skylight
1328
+ // warn in record stage (t27) uses skylightCount.
1329
+ const skylightQuery = world.query({ read: [Skylight] }).unwrap();
1330
+ let skylight: SkylightSnapshot | undefined;
1331
+ let skylightCount = 0;
1332
+ for (const row of skylightQuery) {
1333
+ const s = row.get(Skylight);
1334
+ // equirect is OPTIONAL: an omitted field zero-inits to handle 0, which
1335
+ // record treats as "no equirect" -> solid-color ambient via the white
1336
+ // fallback cube. A Skylight WITHOUT an equirect is still a valid snapshot
1337
+ // (the prior `equirectRaw !== undefined` gate dropped color-only
1338
+ // skylights, leaving the scene black -- the downstream gap #4).
1339
+ const equirectRaw = s.equirect;
1340
+ const intensity = s.intensity;
1341
+ const colorR = s.color[0] ?? 1.0;
1342
+ const colorG = s.color[1] ?? 1.0;
1343
+ const colorB = s.color[2] ?? 1.0;
1344
+ const rotation: [number, number, number, number] = [
1345
+ s.rotation[0] ?? 0,
1346
+ s.rotation[1] ?? 0,
1347
+ s.rotation[2] ?? 0,
1348
+ s.rotation[3] ?? 1,
1349
+ ];
1350
+ skylightCount += 1;
1351
+ if (skylight === undefined) {
1352
+ skylight = {
1353
+ equirectHandle: equirectRaw !== undefined ? Math.round(equirectRaw) : 0,
1354
+ color: [colorR, colorG, colorB],
1355
+ intensity,
1356
+ rotation,
1357
+ // w19: winning entity handle for the multi-Skylight once-warn (F-8).
1358
+ entityHandle: row.entity,
1359
+ };
1360
+ }
1361
+ }
1362
+
1363
+ const lightProbeQuery = world.query({ read: [LightProbe, GlobalTransform] }).unwrap();
1364
+ const lightProbes: LightProbeSnapshot[] = [];
1365
+ for (const row of lightProbeQuery) {
1366
+ const probe = row.get(LightProbe);
1367
+ const validation = validateLightProbeData({
1368
+ irradiance: probe.irradiance,
1369
+ radius: probe.radius,
1370
+ });
1371
+ if (!validation.ok) {
1372
+ worldInternal._routeError(validation.error, {
1373
+ severity: Severity.Error,
1374
+ systemName: 'RenderSystem.extract (light-probe)',
1375
+ });
1376
+ continue;
1377
+ }
1378
+ const transform = row.get(GlobalTransform);
1379
+ lightProbes.push({
1380
+ identity: String(row.entity),
1381
+ position: [transform.world[12] ?? 0, transform.world[13] ?? 0, transform.world[14] ?? 0],
1382
+ radius: probe.radius,
1383
+ irradiance: new Float32Array(probe.irradiance),
1384
+ admitted: true,
1385
+ });
1386
+ }
1387
+
1388
+ // feat-20260531-skybox-env-background M2 / w5: query SkyboxBackground entities.
1389
+ // First archetype hit wins (mirrors Skylight pattern); multi-entity
1390
+ // once-warn in record stage uses skyboxCount.
1391
+ const skyboxQuery = world.query({ read: [SkyboxBackground] }).unwrap();
1392
+ let skybox: SkyboxSnapshot | undefined;
1393
+ let skyboxCount = 0;
1394
+ for (const row of skyboxQuery) {
1395
+ const s = row.get(SkyboxBackground);
1396
+ const equirectRaw = s.equirect;
1397
+ const modeRaw = s.mode;
1398
+ const rotation: [number, number, number, number] = [
1399
+ s.rotation[0] ?? 0,
1400
+ s.rotation[1] ?? 0,
1401
+ s.rotation[2] ?? 0,
1402
+ s.rotation[3] ?? 1,
1403
+ ];
1404
+ skyboxCount += 1;
1405
+ if (skybox === undefined && equirectRaw !== undefined) {
1406
+ skybox = {
1407
+ equirectHandle: Math.round(equirectRaw),
1408
+ mode: modeRaw,
1409
+ rotation,
1410
+ // w19: winning entity handle for the multi-SkyboxBackground warn (F-8).
1411
+ entityHandle: row.entity,
1412
+ };
1413
+ }
1414
+ }
1415
+
1416
+ const environmentCandidates: EnvironmentCandidate[] = [];
1417
+ const imageEnvironment =
1418
+ skylight?.equirectHandle !== undefined && skylight.equirectHandle > 0
1419
+ ? skylight
1420
+ : skybox?.equirectHandle !== undefined && skybox.equirectHandle > 0
1421
+ ? skybox
1422
+ : undefined;
1423
+ if (imageEnvironment !== undefined) {
1424
+ environmentCandidates.push({
1425
+ kind: 'image',
1426
+ entityKey: imageEnvironment.entityHandle,
1427
+ sourceKey: `equirect:${imageEnvironment.equirectHandle}`,
1428
+ });
1429
+ }
1430
+ const atmosphereQuery = world.query({ read: [Atmosphere] }).unwrap();
1431
+ for (const row of atmosphereQuery) {
1432
+ const value = row.get(Atmosphere);
1433
+ const atmosphere = {
1434
+ turbidity: value.turbidity,
1435
+ rayleigh: value.rayleigh,
1436
+ mieCoefficient: value.mieCoefficient,
1437
+ mieDirectionalG: value.mieDirectionalG,
1438
+ sunAngularRadius: value.sunAngularRadius,
1439
+ } as const;
1440
+ environmentCandidates.push({
1441
+ kind: 'atmosphere',
1442
+ entityKey: row.entity,
1443
+ sourceKey: `atmosphere:${row.entity}`,
1444
+ atmosphere,
1445
+ });
1446
+ }
1447
+ const directionalDirection = directional?.direction;
1448
+ const directionalLength =
1449
+ directionalDirection === undefined
1450
+ ? 0
1451
+ : Math.hypot(
1452
+ directionalDirection[0] ?? 0,
1453
+ directionalDirection[1] ?? 0,
1454
+ directionalDirection[2] ?? 0,
1455
+ );
1456
+ const sun =
1457
+ directional === undefined || directionalLength <= 1e-6
1458
+ ? []
1459
+ : [
1460
+ {
1461
+ entityKey: 0,
1462
+ direction: [
1463
+ -(directionalDirection?.[0] ?? 0) / directionalLength,
1464
+ -(directionalDirection?.[1] ?? 0) / directionalLength,
1465
+ -(directionalDirection?.[2] ?? 0) / directionalLength,
1466
+ ] as [number, number, number],
1467
+ color: [
1468
+ directional.color[0] ?? 0,
1469
+ directional.color[1] ?? 0,
1470
+ directional.color[2] ?? 0,
1471
+ ] as [number, number, number],
1472
+ intensity: directional.intensity,
1473
+ },
1474
+ ];
1475
+ const environmentSelection = selectEnvironment({
1476
+ environments: environmentCandidates,
1477
+ fogs: fog === undefined ? [] : [fog],
1478
+ suns: sun,
1479
+ lane: 'direct',
1480
+ });
1481
+ if (!environmentSelection.ok) {
1482
+ routeWorldError(world, environmentSelection.error, {
1483
+ systemName: 'RenderSystem.extract (environment-selection)',
1484
+ });
1485
+ throw environmentSelection.error;
1486
+ }
1487
+ const environment: EnvironmentFrame = environmentSelection.value;
1488
+
1489
+ // feat-20260528-frustum-culling M3 / w10: precompute per-camera frustum
1490
+ // planes so entities can be tested against all cameras in the inner loop.
1491
+ // Cameras with degenerate projection parameters (e.g. zero fov, zero aspect)
1492
+ // are skipped — entities are always-visible for those. Frustum plane cache
1493
+ // stored as Float32Array[] parallel to the cameras[] array.
1494
+ //
1495
+ // feat-20260708-composited-multi-world-rendering M2 / D-4: a composite
1496
+ // non-owner world uses the camera-owner snapshots, not its own cameras.
1497
+ // This keeps culling correct when the surfaced camera and renderables live
1498
+ // in different worlds. The explicit 'none' mode remains the always-visible
1499
+ // escape hatch for callers that genuinely need it.
1500
+ const frustumPlanes: Float32Array[] = [];
1501
+ const cullingCameras = cullMode === 'external' ? (context.cullCameras ?? []) : cameras;
1502
+ if (cullMode !== 'none') {
1503
+ for (const cam of cullingCameras) {
1504
+ // feat-20260613 M6 / w20: orthographic cameras have fov=0 by design;
1505
+ // the previous degeneracy guard (`fov <= 0`) was rejecting valid ortho
1506
+ // cameras and returning the always-visible escape hatch. Only the
1507
+ // perspective path needs the fov check.
1508
+ if (cam.projection === 'perspective' && (cam.fov <= 0 || cam.aspect <= 0)) {
1509
+ frustumPlanes.push(new Float32Array(0)); // degenerate → always-visible
1510
+ continue;
1511
+ }
1512
+ if (cam.near >= cam.far) {
1513
+ frustumPlanes.push(new Float32Array(0));
1514
+ continue;
1515
+ }
1516
+ const proj = mat4.create();
1517
+ if (cam.projection === 'orthographic') {
1518
+ mat4.orthographic(
1519
+ proj,
1520
+ cam.orthoLeft,
1521
+ cam.orthoRight,
1522
+ cam.orthoTop,
1523
+ cam.orthoBottom,
1524
+ cam.near,
1525
+ cam.far,
1526
+ );
1527
+ } else {
1528
+ mat4.perspective(proj, cam.fov, cam.aspect, cam.near, cam.far);
1529
+ }
1530
+ // feat-20260601 D-3: view = invert(camera world mat4). The camera scale is
1531
+ // carried in the world basis columns; the cull frustum uses the same view
1532
+ // the record stage derives, so cull stays same-source with render (AC-05).
1533
+ const view = mat4.create();
1534
+ mat4.invert(view, cam.world);
1535
+ const vp = mat4.create();
1536
+ mat4.multiply(vp, proj, view);
1537
+ const f = frustum.create();
1538
+ frustum.fromViewProjection(f, vp);
1539
+ frustumPlanes.push(f);
1540
+ }
1541
+ }
1542
+
1543
+ const renderables: RenderableSnapshot[] = [];
1544
+ // feat-20260528-frustum-culling M3 / w11: frustum culling counters.
1545
+ let frustumCulled = 0;
1546
+ let frustumTotal = 0;
1547
+ const explicitlyHidden = new Set<EntityHandle>();
1548
+ // feat-20260520-2d-sprite-layer-mvp M-3 / w22 (@new-surface): three-
1549
+ // bucket dispatch arrays. The legacy `materialDispatch` field stays as
1550
+ // a back-compat union (opaque + transparent + overlay back-compat
1551
+ // entries) so the pre-w25 RenderSystem.draw consumer loop keeps
1552
+ // working until M-3 / w25 lands the bucket-aware record. Plan-strategy
1553
+ // §6.1 (back-compat field stays until M-4 acceptance round green).
1554
+ // M3 / w26: single dispatch list replaces old three-bucket model
1555
+ // (plan-strategy D-3). Entries built per-entity per-pass inside the
1556
+ // archetype walk, then sorted by queue at the end.
1557
+ let dispatch: DispatchEntry[] = [];
1558
+ // Keep the derived material snapshot and its resolved passes local to this
1559
+ // extraction. Shared handles are immutable inputs for the frame, while
1560
+ // dispatch entries still need to be rebuilt for each entity.
1561
+ const materialSnapshotCache: MaterialSnapshotCache = new Map();
1562
+ // tweak-20260611 M1: MeshRenderer renderable archetype walk routes
1563
+ // through one World-owned Query. K-2 sniffing scheme B
1564
+ // (`row.get(X) !== undefined` edge sniff) replaces the prior
1565
+ // `arch.components.some` row-internal back-door. K-3 invariant: the
1566
+ // variable-length array reads (`MeshRenderer.materials`, SpriteInstances
1567
+ // arrays) still flow through `_getArrayView`; explicit Instances bytes also come
1568
+ // from World, before projection into renderer-owned snapshots.
1569
+ //
1570
+ // archVersion remains the content fingerprint for SpriteInstances' managed
1571
+ // arrays; explicit Instances use the collection revision below and never
1572
+ // need an archetype graph access for their matrix bytes.
1573
+ // feat-20260521-sprite-atlas-animation M3 / T-16: SpriteRegionOverride
1574
+ // column id for the sprite-bucket per-entity region override read
1575
+ void SpriteRegionOverride;
1576
+
1577
+ const meshRendererQuery =
1578
+ context.renderables === 'none'
1579
+ ? []
1580
+ : world
1581
+ .query({
1582
+ read: [MeshRenderer],
1583
+ optional: [
1584
+ Transform,
1585
+ GlobalTransform,
1586
+ MeshFilter,
1587
+ Instances,
1588
+ Skin,
1589
+ Layer,
1590
+ MorphWeights,
1591
+ SpriteRegionOverride,
1592
+ SpriteInstances,
1593
+ Points,
1594
+ Lines,
1595
+ SortKey,
1596
+ ],
1597
+ })
1598
+ .unwrap();
1599
+ // QueryRow deliberately exposes component data, not an archetype version.
1600
+ // SpriteInstances still uses a content fingerprint for its managed arrays;
1601
+ // explicit Instances use the renderer-owned collection revision below.
1602
+ const resolveArchVersion = (entity: EntityHandle): number => {
1603
+ const values = [
1604
+ worldInternal._getArrayView(entity, SpriteInstances, 'transforms'),
1605
+ worldInternal._getArrayView(entity, SpriteInstances, 'regions'),
1606
+ ];
1607
+ let hash = 2166136261;
1608
+ for (const value of values) {
1609
+ hash = Math.imul(hash ^ (value?.length ?? 0), 16777619) >>> 0;
1610
+ if (value === undefined) continue;
1611
+ for (let index = 0; index < value.length; index += 1) {
1612
+ hash = Math.imul(hash ^ Math.fround(value[index] ?? 0), 16777619) >>> 0;
1613
+ }
1614
+ }
1615
+ return hash;
1616
+ };
1617
+ // Pending entries are created with the current renderables.length, which is
1618
+ // exactly the slot this entity receives if it survives culling. No other
1619
+ // renderable can be pushed between staging and this entity's push, so publish
1620
+ // the original fresh entries instead of cloning every submesh descriptor.
1621
+ // A culled entity still discards its private pending array unchanged.
1622
+ const flushPendingDispatch = (pending: readonly DispatchEntry[]): void => {
1623
+ for (const entry of pending) dispatch.push(entry);
1624
+ };
1625
+ for (const row of meshRendererQuery) {
1626
+ if (
1627
+ context.renderables === 'full' &&
1628
+ renderableEntities !== undefined &&
1629
+ !renderableEntities.has(row.entity)
1630
+ ) {
1631
+ continue;
1632
+ }
1633
+ // K-2 archetype-edge sniff (scheme B): a missing optional component
1634
+ // surfaces as an absent bundle key, not a row-internal optional chain.
1635
+ // Presence-only checks use QueryRow.has so large array-bearing components
1636
+ // are not materialised merely to answer a boolean question.
1637
+ const hasTransform = row.has(Transform);
1638
+ const meshFilter = row.get(MeshFilter);
1639
+ const hasInstances = row.has(Instances);
1640
+ const skin = row.get(Skin);
1641
+ const morphWeightsView = worldInternal._getArrayView(row.entity, MorphWeights, 'weights');
1642
+ const hasMeshFilter = meshFilter !== undefined;
1643
+ const hasSkin = skin !== undefined;
1644
+ // feat-20260625-sprite-instances-and-tilemap-terrain-static-batch M3 / w10:
1645
+ // SpriteInstances optional component archetype-edge sniff. Three structured
1646
+ // EcsError codes fire at the row-loop entry (D-6 fail-fast at extract):
1647
+ // - 'sprite-instances-mutually-exclusive-with-instances'
1648
+ // (hasInstances && hasSpriteInstances) — Instances + SpriteInstances peers.
1649
+ // - 'sprite-instances-requires-sprite-shading-model'
1650
+ // (materialSnap.materialShaderId !== 'forgeax::sprite') — non-sprite material.
1651
+ // - 'sprite-instances-count-mismatch'
1652
+ // (transforms.length / 16 !== regions.length / 4) — stride pair desync.
1653
+ const hasSpriteInstances = row.has(SpriteInstances);
1654
+ const points = row.get(Points);
1655
+ const lines = row.get(Lines);
1656
+ const sortKey = row.get(SortKey)?.value;
1657
+ const pointsLinesComponent =
1658
+ points !== undefined ? 'Points' : lines !== undefined ? 'Lines' : undefined;
1659
+ const isRenderable = hasTransform && hasMeshFilter;
1660
+
1661
+ // The resolved world transform is read per-entity from the single
1662
+ // `GlobalTransform.world` mat4 (propagateTransforms output) inside the row
1663
+ // loop below. Normal structural paths materialize this carrier through
1664
+ // Transform's generic ECS requirement; keep the defensive row check because
1665
+ // an owner can explicitly remove a required component during recovery.
1666
+ const fAssetHandle = meshFilter?.assetHandle;
1667
+ // feat-20260520-2d-sprite-layer-mvp M-3 / w22: Layer column read here;
1668
+ // value folded into each DispatchEntry so the render-system sort can use
1669
+ // it as the primary transparent-sort key without a second ECS round-trip.
1670
+ const fLayerValue = row.get(Layer)?.value;
1671
+ // feat-20260608-tilemap-object-layer-rendering M3 / m3-t5: tilemap-spawned
1672
+ // per-cell render entities (the ones `tilemap-chunk-extract-system`
1673
+ // pushes via `spawnDerivedRenderEntities`) reach this loop via the same
1674
+ // archetype edge that carries a sprite entity -- they all wear
1675
+ // `MeshFilter.assetHandle === HANDLE_QUAD` + a `forgeax::sprite`-shaded
1676
+ // material asset + the sprite-bucket `values.region` rectangle.
1677
+ // For the per-entity Y-sort path (requirements §AC-12 / §AC-13):
1678
+ //
1679
+ // sortKey = -(Transform.posY - effectivePivotY * |Transform.scaleY|)
1680
+ //
1681
+ // with `effectivePivotY = effectivePivotYForTilemapFlip(pivotY, pivotX,
1682
+ // flipV, flipDiagonal)` from `tilemap-chunk-extract-system` (the SAME
1683
+ // helper drives `spawnDerivedRenderEntities`, so the value the sort
1684
+ // uses matches the value baked into `Transform.posY` -- charter P4
1685
+ // single SSOT for the post-flip pivot). Sprite entities reuse the same
1686
+ // formula but skip the flip composition (their pivot stays raw); both
1687
+ // bucket types therefore feed one `transparentSortEntries` argsort
1688
+ // step + share the `argsortInPlace` radix LSD primitive (plan-strategy
1689
+ // §D-1 / §D-3). The detection lives on the material side -- detect a
1690
+ // tilemap-spawned entity by `MeshFilter.assetHandle === HANDLE_QUAD`
1691
+ // plus the `forgeax::sprite` shader id on `MeshRenderer.material`'s
1692
+ // first pass + non-empty `values.region`; no new public ECS
1693
+ // marker component lands (charter F1 minimum surface).
1694
+ //
1695
+ // Layer.value is now folded into each DispatchEntry.layer (fLayerValue
1696
+ // column, read once per archetype pass above). render-system.ts
1697
+ // `sortTransparentDispatch` applies (layer ASC, sortValue ASC) for all
1698
+ // transparent-sort modes (0/1/2) using posY/pivotY/sizeY from the
1699
+ // parallel renderables[] snapshot -- no second ECS round-trip needed.
1700
+ // feat-20260527-sprite-nineslice M4 / w17 (AC-14): SpriteRegionOverride
1701
+ // per-entity UV sub-rectangle. When the entity carries this component the
1702
+ // 4-float `[uMin, vMin, uW, vH]` override displaces the asset-side
1703
+ // `values.region` for this entity only — downstream 9-slice logic
1704
+ // measures slices against this effective region.zw, so a half-width sub-
1705
+ // sprite reduces the anchor budget to 0.5 rather than the asset's 1.0.
1706
+ //
1707
+ // SpriteRegionOverride.region is a fixed stride-4 value. Per-row reads
1708
+ // route through `_getArrayView` for the zero-copy row window
1709
+ // row-window slice (consistent with the variable-length array column
1710
+ // reads -- K-3 carve-out keeps `_getArrayView` as the row-accessor of
1711
+ // record for each non-scalar column).
1712
+ const hasSpriteRegionOverride = row.has(SpriteRegionOverride);
1713
+ // feat-20260523-skin-skeleton-animation M2 / T-21: Skin component
1714
+ // column views for coexistence check + joint despawn fail-fast.
1715
+ // `skeleton` holds the packed Handle<SkeletonAsset>; `joints` holds
1716
+ // the packed Entity u32 array (N x one u32 each).
1717
+ const skinSkeletonView = skin?.skeleton;
1718
+
1719
+ let archVersion = 0;
1720
+ if (hasInstances || hasSpriteInstances) {
1721
+ // All rows in this callback share one archetype. Only these two
1722
+ // instance-bearing paths consume the version in their cache key.
1723
+ archVersion = resolveArchVersion(row.entity);
1724
+ }
1725
+
1726
+ {
1727
+ // feat-20260608 M2 / w11: read materials array via _getArrayView
1728
+ const entity = row.entity;
1729
+ const authorVisible = !(isRenderable && visibility?.effective(entity) === 'hidden');
1730
+ if (!authorVisible) explicitlyHidden.add(entity);
1731
+ if (!authorVisible && !retainHidden) {
1732
+ continue;
1733
+ }
1734
+ const layerVal = fLayerValue ?? 0;
1735
+ // bug-20260709-builtin-quad-withoutaabb-disables-sprite-frustum-cu M2.5
1736
+ // (carries PR #598 feat-20260703 D-7): dispatch entries for this entity
1737
+ // are staged locally and flushed into the shared `dispatch[]` array
1738
+ // ONLY when the entity survives the frustum-cull `continue` below —
1739
+ // same cull-passed branch as the paired `renderables.push`. Prior to
1740
+ // this fix the three `dispatch.push` sites ran before the cull check,
1741
+ // so a culled entity left dangling entries whose `renderableIndex`
1742
+ // aliased the slot a LATER visible entity occupied — surfacing as the
1743
+ // pbr-mesh-array-bgl vs hdrp-unified-bgl-group2 BGL/PL mismatch on
1744
+ // the deferred-shading smoke (PR #598 CI). Pure ordering fix; cull
1745
+ // logic and MeshRenderer contract unchanged.
1746
+ const pendingDispatch: DispatchEntry[] = [];
1747
+ const materialsView = worldInternal._getArrayView(entity, MeshRenderer, 'materials') as
1748
+ | Uint32Array
1749
+ | undefined;
1750
+ const materialCount = materialsView?.length ?? 0;
1751
+ let materialHandles = Array.from(materialsView ?? []);
1752
+ let materialBindingSources: MeshMaterialBindingSource[] = materialHandles.map(
1753
+ () => 'renderer-override',
1754
+ );
1755
+ let materialBindingDiagnostics: MeshMaterialBindingDiagnostic[] = [];
1756
+ let gpuDrivenSubmeshes: readonly MeshAsset['submeshes'][number][] = [];
1757
+ let gpuDrivenIndexed = false;
1758
+ let gpuDrivenGeometry: GpuDrivenGeometryReceipt | undefined;
1759
+
1760
+ // Resolve instance overrides against mesh-owned slot defaults once.
1761
+ const fAssetHandleVal = fAssetHandle;
1762
+ if (
1763
+ fAssetHandleVal !== undefined &&
1764
+ fAssetHandleVal !== 0 &&
1765
+ assets !== undefined &&
1766
+ assets !== null
1767
+ ) {
1768
+ const meshHandle = toShared<'MeshAsset'>(fAssetHandleVal);
1769
+ const meshRes = resolveAssetHandle<Asset>(world, meshHandle);
1770
+ if (meshRes.ok && meshRes.value.kind === 'mesh') {
1771
+ const meshAsset = meshRes.value as MeshAsset;
1772
+ const guid = (meshRes.value as { guid?: string }).guid ?? '<no-guid>';
1773
+ gpuDrivenSubmeshes = meshAsset.submeshes;
1774
+ gpuDrivenIndexed = meshAsset.indices !== undefined;
1775
+ const layoutProjection = deriveVertexLayoutProjection(meshAsset.attributes);
1776
+ gpuDrivenGeometry = {
1777
+ identity: `${guid}:${layoutProjection.digest}`,
1778
+ vertexInputs: layoutProjection.attributes.map((attribute) => ({
1779
+ semantic: attribute.key,
1780
+ location: attribute.shaderLocation,
1781
+ format: attribute.format,
1782
+ })),
1783
+ topology: meshAsset.submeshes[0]?.topology ?? 'triangle-list',
1784
+ indexed: gpuDrivenIndexed,
1785
+ };
1786
+ // extractFrames is also a public read path and can run before the
1787
+ // Renderer.draw pre-render stage. GlyphText proves the derived mesh
1788
+ // owns exactly one Default slot; arbitrary meshes still fail closed
1789
+ // and never infer slot topology from their submeshes.
1790
+ if (!Array.isArray(meshAsset.materialSlots) && world.get(entity, GlyphText).ok) {
1791
+ ensureGlyphMeshMaterialSlots(world, meshHandle);
1792
+ }
1793
+ const resolvedBindings = resolveMeshMaterialBindings(meshAsset, materialsView ?? [], {
1794
+ isValidOverride(handle) {
1795
+ const resolved = resolveAssetHandle(world, toShared<'MaterialAsset'>(handle));
1796
+ return resolved.ok && resolved.value.kind === 'material';
1797
+ },
1798
+ resolveMeshDefault(defaultGuid) {
1799
+ const guidText = AssetGuid.format(defaultGuid);
1800
+ if (assets.lookup<Asset>(guidText)?.kind !== 'material') return undefined;
1801
+ return internSharedRefFromGuid(world, assets, guidText, 'MaterialAsset') as
1802
+ | number
1803
+ | undefined;
1804
+ },
1805
+ });
1806
+ if (!resolvedBindings.ok) {
1807
+ if (resolvedBindings.code === 'mesh-material-slots-missing') {
1808
+ worldInternal._routeError(
1809
+ new AssetError({
1810
+ code: 'load-failed',
1811
+ expected: 'every MeshAsset producer supplies materialSlots[]',
1812
+ hint: `fix the MeshAsset producer; renderer inheritance never guesses slot topology (mesh=${guid}, entity=${entity}, vertices=${meshAsset.vertices.length}, indices=${meshAsset.indices?.length ?? 0})`,
1813
+ detail: {
1814
+ referencedByGuid: guid,
1815
+ referencedByKind: 'mesh',
1816
+ subAssetGuid: '<material-slots-missing>',
1817
+ sourceField: { fieldName: 'materialSlots' },
1818
+ },
1819
+ }),
1820
+ {
1821
+ severity: Severity.Error,
1822
+ systemName: 'RenderSystem.extract (mesh-material-slots-missing)',
1823
+ },
1824
+ );
1825
+ continue;
1826
+ }
1827
+ const materialGuid = AssetGuid.format(resolvedBindings.defaultMaterial);
1828
+ worldInternal._routeError(
1829
+ new AssetError({
1830
+ code: 'load-failed',
1831
+ expected: `MeshAsset materialSlots[${resolvedBindings.slotIndex}] default ${materialGuid} is ready and a MaterialAsset`,
1832
+ hint: `loadByGuid(meshGuid) must recursively load the declared default material; mesh=${guid}, slot=${resolvedBindings.slotIndex}, material=${materialGuid}`,
1833
+ detail: {
1834
+ referencedByGuid: guid,
1835
+ referencedByKind: 'mesh',
1836
+ subAssetGuid: materialGuid,
1837
+ sourceField: {
1838
+ fieldName: 'materialSlots',
1839
+ arrayIndex: resolvedBindings.slotIndex,
1840
+ },
1841
+ },
1842
+ }),
1843
+ {
1844
+ severity: Severity.Error,
1845
+ systemName: 'RenderSystem.extract (mesh-default-not-ready)',
1846
+ },
1847
+ );
1848
+ continue;
1849
+ }
1850
+ materialHandles = resolvedBindings.bindings.map((binding) => binding.handle);
1851
+ materialBindingSources = resolvedBindings.bindings.map((binding) => binding.source);
1852
+ materialBindingDiagnostics = resolvedBindings.diagnostics.map((diagnostic) => ({
1853
+ ...diagnostic,
1854
+ detail:
1855
+ diagnostic.code === 'mesh-renderer-material-override-overflow'
1856
+ ? {
1857
+ expectedCount: meshAsset.materialSlots.length,
1858
+ actualCount: materialCount,
1859
+ meshAssetGuid: guid,
1860
+ }
1861
+ : {
1862
+ meshAssetGuid: guid,
1863
+ slotIndex: diagnostic.slotIndex,
1864
+ handle: diagnostic.handle ?? 0,
1865
+ },
1866
+ }));
1867
+ for (const diagnostic of resolvedBindings.diagnostics) {
1868
+ worldInternal._routeError(
1869
+ new AssetError({
1870
+ code: diagnostic.code,
1871
+ expected:
1872
+ diagnostic.code === 'mesh-renderer-material-override-overflow'
1873
+ ? `materials.length <= materialSlots.length (${meshAsset.materialSlots.length})`
1874
+ : `materials[${diagnostic.slotIndex}] resolves to a live MaterialAsset`,
1875
+ hint: ASSET_ERROR_HINTS[diagnostic.code],
1876
+ detail:
1877
+ diagnostic.code === 'mesh-renderer-material-override-overflow'
1878
+ ? {
1879
+ expectedCount: meshAsset.materialSlots.length,
1880
+ actualCount: materialCount,
1881
+ meshAssetGuid: guid,
1882
+ }
1883
+ : {
1884
+ meshAssetGuid: guid,
1885
+ slotIndex: diagnostic.slotIndex,
1886
+ handle: diagnostic.handle ?? 0,
1887
+ },
1888
+ }),
1889
+ {
1890
+ severity: Severity.Warning,
1891
+ systemName: `RenderSystem.extract (${diagnostic.code})`,
1892
+ },
1893
+ );
1894
+ }
1895
+ }
1896
+ }
1897
+
1898
+ if (materialHandles.length === 0) {
1899
+ materialHandles = [0];
1900
+ materialBindingSources = ['engine-default'];
1901
+ }
1902
+
1903
+ // Use the first material handle for the entity-level snapshot
1904
+ // (shading-model dispatch routing + multi-pass DispatchEntry. Per-
1905
+ // submesh materials[i>=1] are resolved by `resolveMaterialSnapshot`
1906
+ // below into the `materials[]` array, used by the record stage to
1907
+ // upload N material UBO slots and bind the i-th slot before the
1908
+ // i-th submesh draw.) -- feat-20260608 M5 amend / w11-a.
1909
+ const handleRaw = materialHandles[0] ?? 0;
1910
+
1911
+ const cachedMaterial =
1912
+ handleRaw !== 0 && !hasSpriteRegionOverride && !hasSkin
1913
+ ? materialSnapshotCache.get(handleRaw)
1914
+ : undefined;
1915
+
1916
+ let materialSnap: MaterialSnapshot;
1917
+
1918
+ if (cachedMaterial !== undefined) {
1919
+ materialSnap = cachedMaterial.snapshot;
1920
+ if (isRenderable) {
1921
+ appendMaterialDispatchEntries(
1922
+ pendingDispatch,
1923
+ cachedMaterial.passes,
1924
+ entity,
1925
+ handleRaw,
1926
+ renderables.length,
1927
+ layerVal,
1928
+ materialSnap.paramSnapshot,
1929
+ 0,
1930
+ materialSnap.materialShaderId,
1931
+ );
1932
+ }
1933
+ } else if (handleRaw === 0 || assets === undefined || assets === null) {
1934
+ // case B: missing-spec sentinel -> mid-grey defaultMaterialSnapshot.
1935
+ materialSnap = defaultMaterialSnapshot(handleRaw);
1936
+ } else {
1937
+ const tagged = toShared<'MaterialAsset'>(handleRaw);
1938
+ const stablePersistentCached =
1939
+ !hasSpriteRegionOverride && !hasSkin
1940
+ ? readStablePersistentMaterialSnapshot(
1941
+ persistentMaterialSnapshotCache,
1942
+ handleRaw,
1943
+ assets,
1944
+ )
1945
+ : undefined;
1946
+ if (stablePersistentCached !== undefined) {
1947
+ materialSnapshotCache.set(handleRaw, stablePersistentCached);
1948
+ materialSnap = stablePersistentCached.snapshot;
1949
+ if (isRenderable) {
1950
+ appendMaterialDispatchEntries(
1951
+ pendingDispatch,
1952
+ stablePersistentCached.passes,
1953
+ entity,
1954
+ handleRaw,
1955
+ renderables.length,
1956
+ layerVal,
1957
+ materialSnap.paramSnapshot,
1958
+ 0,
1959
+ materialSnap.materialShaderId,
1960
+ );
1961
+ }
1962
+ } else {
1963
+ const res = resolveAssetHandle(world, tagged);
1964
+ if (!res.ok) {
1965
+ if (isRenderable) {
1966
+ const rhiErr = new RhiError({
1967
+ code: 'asset-not-registered',
1968
+ expected: 'MeshRenderer.material in AssetRegistry',
1969
+ hint: 'catalog the material via assetRegistry.catalog(guid, asset) + world.allocSharedRef before spawn, or remove the material field to fall back to default',
1970
+ detail: { assetHandle: handleRaw },
1971
+ });
1972
+ worldInternal._routeError(rhiErr, {
1973
+ severity: Severity.Error,
1974
+ systemName: 'RenderSystem.extract (material asset-not-registered)',
1975
+ });
1976
+ }
1977
+ continue;
1978
+ }
1979
+ const asset = res.value;
1980
+ if (asset.kind !== 'material') {
1981
+ materialSnap = defaultMaterialSnapshot(handleRaw);
1982
+ } else {
1983
+ // feat-20260529 M3 / w11: material parent chain inheritance via
1984
+ // read-through _materialWalk accessor (plan-strategy D-6).
1985
+ // The old direct asset.passes / asset.values read never
1986
+ // walked the parent chain, causing broken-inheritance (root cause).
1987
+ const resolvedResult = walkMaterialPassesOverSharedRefs(world, tagged, assets);
1988
+ if (!resolvedResult.ok) {
1989
+ // AC-09 / S-7 / q8=A: passes-empty or cycle must fire structured
1990
+ // error through _routeError (same routing as asset-not-registered
1991
+ // branch above). Silent continue is forbidden because it produces
1992
+ // a black screen indistinguishable from a content bug.
1993
+ const err = resolvedResult.error;
1994
+ switch (err.code) {
1995
+ case 'material-parent-not-found':
1996
+ case 'material-no-effective-pass':
1997
+ case 'material-value-unknown':
1998
+ case 'material-value-type-mismatch':
1999
+ case 'material-contract-program-mismatch':
2000
+ worldInternal._routeError(err, {
2001
+ severity: Severity.Error,
2002
+ systemName: `RenderSystem.extract (${err.code})`,
2003
+ });
2004
+ break;
2005
+ case 'material-circular-inheritance':
2006
+ worldInternal._routeError(err, {
2007
+ severity: Severity.Error,
2008
+ systemName: 'RenderSystem.extract (material-circular-inheritance)',
2009
+ });
2010
+ break;
2011
+ default:
2012
+ // Exhaustive guard: unhandled error codes from _materialWalk
2013
+ // surface an internal assertion to avoid silent continuation.
2014
+ worldInternal._routeError(err, {
2015
+ severity: Severity.Error,
2016
+ systemName: `RenderSystem.extract (_materialWalk: ${err.code})`,
2017
+ });
2018
+ }
2019
+ continue;
2020
+ }
2021
+ const resolved = resolvedResult.value;
2022
+ const allPasses = resolved.passes;
2023
+ const firstPassShader = runtimeMaterialShaderIdForMaterial(asset, allPasses, assets);
2024
+ const pv = materialValuesToLinearRuntime(
2025
+ resolved.values,
2026
+ materialColorParameterSchema(resolved.parameters ?? [], firstPassShader, assets),
2027
+ resolved.colorSpace,
2028
+ ) as Readonly<Record<string, unknown>>;
2029
+
2030
+ const baseColorPv = pv.baseColor as readonly number[] | undefined;
2031
+ const baseColor = vec3.create(
2032
+ baseColorPv?.[0] ?? 1,
2033
+ baseColorPv?.[1] ?? 1,
2034
+ baseColorPv?.[2] ?? 1,
2035
+ );
2036
+ const metallicPv = typeof pv.metallic === 'number' ? pv.metallic : 0;
2037
+ const roughnessPv = typeof pv.roughness === 'number' ? pv.roughness : 0.5;
2038
+ const specularColorPv = pv.specularColor as readonly number[] | undefined;
2039
+ const normalScalePv = materialNormalScale(pv);
2040
+
2041
+ const paramSnap: Record<string, number | number[] | string> = {};
2042
+ for (const [k, v] of Object.entries(pv)) {
2043
+ if (typeof v === 'number') paramSnap[k] = v;
2044
+ else if (typeof v === 'string') paramSnap[k] = v;
2045
+ else if (Array.isArray(v) && v.every((x) => typeof x === 'number')) {
2046
+ paramSnap[k] = v as number[];
2047
+ }
2048
+ }
2049
+
2050
+ const materialParamSchema = materialParametersToParamSchema(
2051
+ resolved.parameters ?? [],
2052
+ firstPassShader,
2053
+ );
2054
+ // feat-20260611-fox-skinning-vertex-attribute-chain M4 / w17 (D-5):
2055
+ // bidirectional Skin <-> pbr-skin material fail-fast at extract.
2056
+ // Skin component without a forgeax::pbr-skin first-pass material
2057
+ // would draw with a non-skin shader against the 18-float vertex
2058
+ // buffer (joints/weights bytes interpreted as garbage). Conversely
2059
+ // a forgeax::pbr-skin material against a 12-float (unskinned) mesh
2060
+ // would have @location(4)/@location(5) read uninitialized memory.
2061
+ // Both cases route through `_routeError` + `continue` so a single
2062
+ // misconfigured entity does NOT abort the whole frame's draw list
2063
+ // (charter P3 explicit failure + plan-decisions D-5 over `return err`).
2064
+ {
2065
+ const hasSkinSkel =
2066
+ hasSkin &&
2067
+ skinSkeletonView !== undefined &&
2068
+ skinSkeletonView !== undefined &&
2069
+ skinSkeletonView !== 0;
2070
+ const isPbrSkinMaterial = isStandardPbrSkinMaterialShader(firstPassShader);
2071
+ if (hasSkinSkel && !isPbrSkinMaterial) {
2072
+ worldInternal._routeError(new SkinMaterialMismatchError(entity, firstPassShader), {
2073
+ severity: Severity.Error,
2074
+ systemName: 'RenderSystem.extract (skin-material-mismatch)',
2075
+ });
2076
+ continue;
2077
+ }
2078
+ if (isPbrSkinMaterial && fAssetHandleVal !== undefined && fAssetHandleVal !== 0) {
2079
+ const meshHandleForSkinCheck = toShared<'MeshAsset'>(fAssetHandleVal);
2080
+ const meshResForSkinCheck = resolveAssetHandle<MeshAsset>(
2081
+ world,
2082
+ meshHandleForSkinCheck,
2083
+ );
2084
+ if (meshResForSkinCheck.ok) {
2085
+ const meshAttrs = meshResForSkinCheck.value.attributes;
2086
+ const hasSkinIdx = meshAttrs.skinIndex !== undefined;
2087
+ const hasSkinWt = meshAttrs.skinWeight !== undefined;
2088
+ if (!hasSkinIdx || !hasSkinWt) {
2089
+ const missing: 'skinIndex' | 'skinWeight' | 'both' =
2090
+ !hasSkinIdx && !hasSkinWt ? 'both' : !hasSkinIdx ? 'skinIndex' : 'skinWeight';
2091
+ worldInternal._routeError(new MaterialSkinAttrMissingError(entity, missing), {
2092
+ severity: Severity.Error,
2093
+ systemName: 'RenderSystem.extract (material-skin-attr-missing)',
2094
+ });
2095
+ continue;
2096
+ }
2097
+ }
2098
+ }
2099
+ }
2100
+ // feat-20260625-refactor-sprite-as-transparent-mesh M3 / w12 (D-3):
2101
+ // sprite materials now flow through the same generic paramSchema-
2102
+ // driven extract path PBR / unlit use. The narrow `forgeax::sprite`
2103
+ // exception block below covers exactly 2 plan-authorised cases:
2104
+ // 1. SpriteRegionOverride per-entity region displacement (Q4=a)
2105
+ // 2. flipX / flipY -> region fold (plan-strategy D-8)
2106
+ // No legacy values field-name shim; demos and SpriteParamValues
2107
+ // are UBO-aligned (no `texture` / `baseColor` / `pivot` / `slices`
2108
+ // / `sliceMode` keys reaching this code path). AGENTS.md §Change
2109
+ // stance: "no shim layer, no v1/v2 dual-path".
2110
+ //
2111
+ // feat-20260624 M1' / t6: `'forgeax::sprite-lit'` walks the same
2112
+ // sprite-family vertex path (VsOut byte-identical, paramSchema
2113
+ // mirror) so the SAME 2 folds apply — extending `isSprite` to
2114
+ // cover both shader ids keeps the narrowing-point count at 1
2115
+ // (plan-strategy §1.6 + D-1: mirror sprite, no new branch).
2116
+ const isSprite =
2117
+ firstPassShader === 'forgeax::sprite' || firstPassShader === 'forgeax::sprite-lit';
2118
+
2119
+ // feat-20260613-material-paramschema-driven-binding M4 / w23
2120
+ // (D-5 graceful): paramSchema-driven texture-field validation.
2121
+ // For each handle-shaped paramValue (typeof === 'number'),
2122
+ // verify it actually points at a registered texture asset
2123
+ // when the field is declared as a texture in the shader's
2124
+ // paramSchema; mis-typed handles (e.g. a scalar f32 stored as
2125
+ // int 0 the M4 / w22 graceful fallback resolved to a wrong
2126
+ // sub-asset) are dropped here so the record stage falls back
2127
+ // to MISSING_TEXTURE_HANDLE (default white) without raising.
2128
+ const validateTextureHandle = (
2129
+ fieldName: string,
2130
+ raw: unknown,
2131
+ ): Handle<'TextureAsset', 'shared'> | undefined => {
2132
+ // feat-20260614 M8 (D-19): a string value is an embedded texture
2133
+ // GUID; resolve it to a column handle via catalog + allocSharedRef
2134
+ // before validation. A number is an already-minted column handle.
2135
+ let handle: Handle<'TextureAsset', 'shared'>;
2136
+ const textureRef = materialTextureRef(raw);
2137
+ const textureGuid = assetReferenceText(textureRef);
2138
+ if (textureGuid !== undefined) {
2139
+ if (assets === null || assets === undefined) return undefined;
2140
+ // M4: intern so the GUID mints one stable handle per World
2141
+ // instead of a fresh slot every frame (GPU residency relies on
2142
+ // a stable handleSlot). onLastRelease -> gpuStore.evictTexture.
2143
+ const interned = internSharedRefFromGuid(
2144
+ world,
2145
+ assets,
2146
+ textureGuid,
2147
+ 'TextureAsset',
2148
+ );
2149
+ if (interned === undefined) return undefined;
2150
+ handle = interned;
2151
+ } else if (typeof textureRef === 'number') {
2152
+ handle = toShared<'TextureAsset'>(textureRef);
2153
+ } else {
2154
+ return undefined;
2155
+ }
2156
+ if (assets === null || assets === undefined) return handle;
2157
+ const declaredFields = materialTextureFields(
2158
+ firstPassShader,
2159
+ materialParamSchema.length > 0
2160
+ ? derive(materialParamSchema).textureFieldNames
2161
+ : firstPassShader !== undefined
2162
+ ? assets.materialShaderTextureFieldNames(firstPassShader)
2163
+ : undefined,
2164
+ );
2165
+ // Shader not registered (R-4 cross-worktree path) -> trust the
2166
+ // raw handle and let the record stage / GPU layer surface each
2167
+ // mismatch via MISSING_TEXTURE_HANDLE.
2168
+ if (declaredFields === undefined) return handle;
2169
+ // Field is not declared as a texture by the shader -> the
2170
+ // loader's "try every int" fallback misclassified a scalar;
2171
+ // drop the slot so the record stage uses the default white.
2172
+ if (
2173
+ !declaredFields.has(fieldName) &&
2174
+ !isEngineInjectedTextureField(firstPassShader, fieldName)
2175
+ ) {
2176
+ return undefined;
2177
+ }
2178
+ // Field declared as texture: verify the handle's asset kind.
2179
+ const assetRes = resolveAssetHandle(world, handle);
2180
+ if (!assetRes.ok) return undefined;
2181
+ const kind = (assetRes.value as { kind?: string }).kind;
2182
+ if (kind !== 'texture') return undefined;
2183
+ return handle;
2184
+ };
2185
+ // feat-20260614 M8 (D-19): resolve a sampler / texture paramValue
2186
+ // that may be an embedded GUID string (catalog + allocSharedRef) or
2187
+ // an already-minted column handle (number passthrough).
2188
+ const resolveParamHandle = <B extends string>(
2189
+ raw: unknown,
2190
+ brand: B,
2191
+ ): Handle<B, 'shared'> | undefined => {
2192
+ const value = materialTextureRef(raw);
2193
+ if (typeof value === 'number') return toShared<B>(value);
2194
+ const guid = assetReferenceText(value);
2195
+ if (guid !== undefined) {
2196
+ if (assets === null || assets === undefined) return undefined;
2197
+ // M4: intern the GUID -> column-handle resolution (one stable
2198
+ // handle per (world, guid, brand), reused across frames).
2199
+ return internSharedRefFromGuid(world, assets, guid, brand);
2200
+ }
2201
+ return undefined;
2202
+ };
2203
+ // feat-20260621-learn-render-5-5-parallax M2 / w7 (D-3): iterate the
2204
+ // shader's derive(paramSchema).textureFieldNames SSOT so the Nth
2205
+ // user-region texture (e.g. parallax heightTexture) is validated +
2206
+ // carried, replacing the hardcoded 3-field list. validateTextureHandle
2207
+ // already drops fields a shader doesn't declare as a texture.
2208
+ const userRegionFields =
2209
+ materialTextureFields(
2210
+ firstPassShader,
2211
+ materialParamSchema.length > 0
2212
+ ? derive(materialParamSchema).textureFieldNames
2213
+ : firstPassShader !== undefined && assets !== null && assets !== undefined
2214
+ ? assets.materialShaderTextureFieldNames(firstPassShader)
2215
+ : undefined,
2216
+ ) ?? BUILTIN_USER_REGION_TEXTURE_FIELDS;
2217
+ const textureHandles = new Map<string, Handle<'TextureAsset', 'shared'>>();
2218
+ const videoTextureFields = new Map<string, Handle<'VideoAsset', 'shared'>>();
2219
+ for (const field of userRegionFields) {
2220
+ // D-5: a video-kind paramValue routes to the transient path
2221
+ // (videoTextureFields), NOT validateTextureHandle (which drops
2222
+ // kind!=='texture', the R-7 silent-fail path). Static fields fall
2223
+ // through to validateTextureHandle unchanged.
2224
+ const videoHandle =
2225
+ assets !== null && assets !== undefined
2226
+ ? resolveVideoFieldHandle(pv[field], world, assets)
2227
+ : undefined;
2228
+ if (videoHandle !== undefined) {
2229
+ videoTextureFields.set(field, videoHandle);
2230
+ continue;
2231
+ }
2232
+ const handle = validateTextureHandle(field, pv[field]);
2233
+ if (handle !== undefined) textureHandles.set(field, handle);
2234
+ }
2235
+ const baseColorTextureHandle = textureHandles.get('baseColorTexture');
2236
+ const metallicRoughnessTextureHandle = textureHandles.get('metallicRoughnessTexture');
2237
+ const normalTextureHandle = textureHandles.get('normalTexture');
2238
+ const samplerHandles = collectMaterialTextureSamplers(pv, (value) =>
2239
+ resolveParamHandle(materialTextureRef(value), 'SamplerAsset'),
2240
+ );
2241
+ const emissiveTextureHandle = validateTextureHandle(
2242
+ 'emissiveTexture',
2243
+ pv.emissiveTexture,
2244
+ );
2245
+ const occlusionTextureHandle = validateTextureHandle(
2246
+ 'occlusionTexture',
2247
+ pv.occlusionTexture,
2248
+ );
2249
+ const textureCoordinates = collectMaterialTextureCoordinates(pv);
2250
+ const textureSources = collectMaterialTextureSources(pv, world);
2251
+ const emissivePv = pv.emissive as readonly number[] | undefined;
2252
+ // feat-20260625 M2 / w6: first-pass transparency flag folds into
2253
+ // MaterialSnapshot.transparent so the record stage can drive the
2254
+ // LDR split + premultiplied-alpha blend decision without
2255
+ // re-reading passes[]. feat-20260626-collapse M2: derive from
2256
+ // `passes[0].renderState.blend !== undefined` (blend presence is
2257
+ // the SSOT after MaterialPass.transparent was dropped).
2258
+ // Result is plain boolean (always defined here) — written as-is
2259
+ // into the snapshot (`boolean | undefined` field, see L759).
2260
+ const firstPassTransparent: boolean = allPasses[0]?.renderState?.blend !== undefined;
2261
+
2262
+ // feat-20260625-refactor-sprite-as-transparent-mesh M3 / w12 (D-8):
2263
+ // narrow `forgeax::sprite` extract block --- folds the legacy user
2264
+ // values format (flipX / flipY / slices / sliceMode + free
2265
+ // region / pivot) into the UBO-aligned paramSnapshot vec4 fields
2266
+ // (region / pivotAndSize / slicesAndMode + colorTint). Also folds
2267
+ // per-entity SpriteRegionOverride (Q4=a). After this block the
2268
+ // generic else branch picks up the snapshot via the same writer
2269
+ // path PBR / unlit use; no more shadingModel='sprite' arm, no
2270
+ // spriteFields POD (AC-02 / AC-07: extract has exactly 2 hard
2271
+ // `forgeax::sprite` checks --- this fold + the slices mesh swap on
2272
+ // the record side).
2273
+ if (isSprite) {
2274
+ // SpriteRegionOverride: per-entity per-frame region displacement.
2275
+ let overrideRegion: readonly [number, number, number, number] | undefined;
2276
+ if (hasSpriteRegionOverride) {
2277
+ const overrideView = worldInternal._getArrayView(
2278
+ entity,
2279
+ SpriteRegionOverride,
2280
+ 'region',
2281
+ ) as Float32Array | undefined;
2282
+ if (overrideView !== undefined && overrideView.length >= 4) {
2283
+ overrideRegion = [
2284
+ overrideView[0] ?? 0,
2285
+ overrideView[1] ?? 0,
2286
+ overrideView[2] ?? 1,
2287
+ overrideView[3] ?? 1,
2288
+ ];
2289
+ }
2290
+ }
2291
+ // Region resolution priority: SpriteRegionOverride > paramSnapshot.
2292
+ // region (UBO-aligned user input) > [0,0,1,1] identity.
2293
+ const regionPv = paramSnap.region as readonly number[] | undefined;
2294
+ let regionX = overrideRegion?.[0] ?? regionPv?.[0] ?? 0;
2295
+ let regionY = overrideRegion?.[1] ?? regionPv?.[1] ?? 0;
2296
+ let regionZ = overrideRegion?.[2] ?? regionPv?.[2] ?? 1;
2297
+ let regionW = overrideRegion?.[3] ?? regionPv?.[3] ?? 1;
2298
+ // flipX / flipY fold into region (D-8): the shader does
2299
+ // `uv * region.zw + region.xy`, so flipping along U is a sign
2300
+ // negation of region.z plus an origin offset.
2301
+ const flipXPv = typeof pv.flipX === 'number' ? pv.flipX : 0;
2302
+ const flipYPv = typeof pv.flipY === 'number' ? pv.flipY : 0;
2303
+ if (flipXPv !== 0) {
2304
+ regionX += regionZ;
2305
+ regionZ = -regionZ;
2306
+ }
2307
+ if (flipYPv !== 0) {
2308
+ regionY += regionW;
2309
+ regionW = -regionW;
2310
+ }
2311
+ paramSnap.region = [regionX, regionY, regionZ, regionW];
2312
+ // Guard: slicesAndMode must be present and zero for non-9-slice
2313
+ // sprites so the record-stage UBO writer (applyParamSnapshotToUbo)
2314
+ // writes [0,0,0,0] at offset 48 instead of leaving the
2315
+ // buildPbrMaterialUboPayload PBR baseline (e.g. occlusionStrength=1
2316
+ // at that slot). A non-zero slicesAndMode trips `useSlices=true`
2317
+ // in sprite.wgsl, which degenerates HANDLE_QUAD geometry → invisible.
2318
+ if (!('slicesAndMode' in paramSnap)) {
2319
+ (paramSnap as Record<string, unknown>).slicesAndMode = [0, 0, 0, 0];
2320
+ }
2321
+ }
2322
+
2323
+ // Generic materialShaderId snapshot --- sprite included now flows
2324
+ // through this single branch (plan-strategy D-3 / AC-01 / AC-02 /
2325
+ // AC-07). The sprite block above only writes paramSnap.region (D-8
2326
+ // SpriteRegionOverride + flip fold); the rest of the UBO is filled
2327
+ // by the same paramSchema-driven path PBR / unlit use.
2328
+ materialSnap = {
2329
+ baseColor,
2330
+ metallic: metallicPv,
2331
+ roughness: roughnessPv,
2332
+ ...(specularColorPv !== undefined && {
2333
+ specularColor: [
2334
+ specularColorPv[0] ?? 1,
2335
+ specularColorPv[1] ?? 1,
2336
+ specularColorPv[2] ?? 1,
2337
+ ] as readonly [number, number, number],
2338
+ }),
2339
+ normalScale: normalScalePv,
2340
+ materialShaderId: firstPassShader,
2341
+ materialHandle: handleRaw,
2342
+ renderState: pipelineRenderState(allPasses[0]?.renderState),
2343
+ paramSnapshot: paramSnap,
2344
+ ...(materialParamSchema.length > 0 && { materialParamSchema }),
2345
+ ...(textureCoordinates.size > 0 && { textureCoordinates }),
2346
+ ...(samplerHandles.size > 0 && { samplerHandles }),
2347
+ ...(textureHandles.size > 0 && { textureHandles }),
2348
+ ...(textureSources.size > 0 && { textureSources }),
2349
+ ...(videoTextureFields.size > 0 && { videoTextureFields }),
2350
+ ...(baseColorTextureHandle !== undefined && {
2351
+ baseColorTexture: baseColorTextureHandle,
2352
+ }),
2353
+ ...(metallicRoughnessTextureHandle !== undefined && {
2354
+ metallicRoughnessTexture: metallicRoughnessTextureHandle,
2355
+ }),
2356
+ ...(normalTextureHandle !== undefined && { normalTexture: normalTextureHandle }),
2357
+ ...(emissivePv !== undefined && {
2358
+ emissive: [emissivePv[0] ?? 0, emissivePv[1] ?? 0, emissivePv[2] ?? 0] as readonly [
2359
+ number,
2360
+ number,
2361
+ number,
2362
+ ],
2363
+ }),
2364
+ ...(typeof pv.emissiveIntensity === 'number' && {
2365
+ emissiveIntensity: pv.emissiveIntensity,
2366
+ }),
2367
+ ...(emissiveTextureHandle !== undefined && {
2368
+ emissiveTexture: emissiveTextureHandle,
2369
+ }),
2370
+ ...(occlusionTextureHandle !== undefined && {
2371
+ occlusionTexture: occlusionTextureHandle,
2372
+ }),
2373
+ ...(typeof pv.occlusionStrength === 'number' && {
2374
+ occlusionStrength: pv.occlusionStrength,
2375
+ }),
2376
+ transparent: firstPassTransparent,
2377
+ };
2378
+
2379
+ if (!hasSpriteRegionOverride && !hasSkin) {
2380
+ const stored = storeMaterialSnapshot(
2381
+ materialSnapshotCache,
2382
+ handleRaw,
2383
+ materialSnap,
2384
+ allPasses,
2385
+ asset,
2386
+ assets,
2387
+ );
2388
+ if (stored.crossFrameSafe) persistentMaterialSnapshotCache?.set(handleRaw, stored);
2389
+ }
2390
+
2391
+ // Build dispatch entries from resolved passes.
2392
+ if (isRenderable) {
2393
+ appendMaterialDispatchEntries(
2394
+ pendingDispatch,
2395
+ allPasses,
2396
+ entity,
2397
+ handleRaw,
2398
+ renderables.length,
2399
+ layerVal,
2400
+ paramSnap,
2401
+ 0,
2402
+ firstPassShader,
2403
+ );
2404
+ }
2405
+ }
2406
+ }
2407
+ }
2408
+
2409
+ // feat-20260609 M2/M5 corrective fixup: default-material entities
2410
+ // (handleRaw===0 / case-B MeshRenderer{data:{}}) must produce
2411
+ // ShadowCaster dispatch entries so the shadow pass includes them.
2412
+ // The pre-existing logic only builds dispatch entries from
2413
+ // resolved material assets; defaultMaterialSnapshot() (mid-grey unlit)
2414
+ // left dispatch empty, causing shadow-m2/m3 test failures.
2415
+ // Requirements §10.5: shadow-casting is default behaviour, opt-out
2416
+ // via castShadow:false. The default material has no opt-out, so
2417
+ // it casts shadows.
2418
+ //
2419
+ // CHARTER NOTE (feat-20260609 T-005-a): the URP literals
2420
+ // `LightMode: 'ShadowCaster'` / `LightMode: 'Forward'` below are a
2421
+ // local URP-bridge — they mirror what `Materials.unlit({ castShadow:
2422
+ // true })` produces at the asset layer. The default-material
2423
+ // handle=0 path bypasses asset registration, so we synthesize the
2424
+ // same dispatch shape inline. Follow-up cleanup (F-1 from
2425
+ // implement-review R1): thread default materials through the
2426
+ // Materials factory so this block can call into the shared
2427
+ // passes[] producer.
2428
+ // tweak-20260701 M1: `materialSnap.shadingModel === 'unlit'` removed —
2429
+ // for handleRaw===0, defaultMaterialSnapshot() was always unlit
2430
+ // (the shadingModel check was a tautology); the isRenderable &&
2431
+ // handleRaw===0 guard alone preserves the exact same dispatch shape.
2432
+ if (isRenderable && handleRaw === 0) {
2433
+ const shadowCasterTags: Record<string, string> = { LightMode: 'ShadowCaster' };
2434
+ const nextRenderableIndex = renderables.length;
2435
+ // M2.5: stage into pendingDispatch; flushed at the renderable push
2436
+ // site below only when the entity survives cull.
2437
+ pendingDispatch.push({
2438
+ entityIndex: entity,
2439
+ materialHandle: 0,
2440
+ renderableIndex: nextRenderableIndex,
2441
+ passIndex: 0,
2442
+ queue: 2000,
2443
+ layer: layerVal,
2444
+ tags: shadowCasterTags,
2445
+ renderState: undefined,
2446
+ defines: undefined,
2447
+ vertexEntry: 'vs_main',
2448
+ fragmentEntry: undefined,
2449
+ materialShaderId: 'forgeax::default-shadow-caster',
2450
+ paramSnapshot: {},
2451
+ });
2452
+ // Also add a Forward pass entry so the entity renders in the
2453
+ // main scene pass (mirrors Materials.unlit default).
2454
+ appendMaterialDispatchEntries(
2455
+ pendingDispatch,
2456
+ [DEFAULT_FORWARD_PASS],
2457
+ entity,
2458
+ 0,
2459
+ nextRenderableIndex,
2460
+ layerVal,
2461
+ {},
2462
+ 1,
2463
+ );
2464
+ }
2465
+
2466
+ if (isRenderable) {
2467
+ // feat-20260612 M2 / m2-6: Skin + Instances coexistence + per-joint
2468
+ // dangling fail-fast + real palette slice allocation. Replaces the
2469
+ // T-21 placeholder ({0,0} discriminator-only sentinel) with full
2470
+ // resolve / validate / write chain (D-9 reset already fired at
2471
+ // extractFrame entry; per-entity allocate + writeJointPalette here).
2472
+ let skinSlice: SkinPaletteSlice | undefined;
2473
+ if (hasSkin) {
2474
+ const skeletonHandleRaw = skinSkeletonView;
2475
+ if (
2476
+ skeletonHandleRaw !== undefined &&
2477
+ skeletonHandleRaw !== 0 &&
2478
+ assets !== undefined &&
2479
+ assets !== null
2480
+ ) {
2481
+ // Skin + Instances coexistence is forbidden (D-10).
2482
+ if (hasInstances) {
2483
+ worldInternal._routeError(new SkinInstancesCoexistForbiddenError(entity), {
2484
+ severity: Severity.Error,
2485
+ systemName: 'RenderSystem.extract (skin-instances-coexist)',
2486
+ });
2487
+
2488
+ continue;
2489
+ }
2490
+ // (a) Resolve skeleton asset; on failure -> skeleton-resolve-failed.
2491
+ const skeletonHandle = toShared<'SkeletonAsset'>(skeletonHandleRaw);
2492
+ const skeletonRes = resolveAssetHandle<SkeletonAsset>(world, skeletonHandle);
2493
+ if (!skeletonRes.ok || skeletonRes.value.kind !== 'skeleton') {
2494
+ worldInternal._routeError(new SkeletonResolveFailedError(entity, skeletonHandleRaw), {
2495
+ severity: Severity.Error,
2496
+ systemName: 'RenderSystem.extract (skeleton-resolve-failed)',
2497
+ });
2498
+ continue;
2499
+ }
2500
+ const skeleton = skeletonRes.value;
2501
+ // (b) Reuse the Skin row already read for its skeleton handle;
2502
+ // the old path repeated a second whole-row world.get here.
2503
+ const skinJoints = skin?.joints;
2504
+ if (skinJoints === undefined) continue;
2505
+ const jointsLength = skinJoints.length;
2506
+ if (jointsLength !== skeleton.jointCount) {
2507
+ worldInternal._routeError(
2508
+ new JointCountMismatchError(entity, skeleton.jointCount, jointsLength),
2509
+ {
2510
+ severity: Severity.Error,
2511
+ systemName: 'RenderSystem.extract (joint-count-mismatch)',
2512
+ },
2513
+ );
2514
+ continue;
2515
+ }
2516
+ // (c) Resolve only each joint's GlobalTransform.world column. The
2517
+ // transient view is consumed before a structural mutation and
2518
+ // therefore preserves the same dangling-joint behavior without
2519
+ // constructing every other Transform field.
2520
+ // Build mat4 list eagerly so write happens once per entity (no
2521
+ // half-written slice on dangling).
2522
+ const jointWorlds = new Array<Mat4>(skeleton.jointCount);
2523
+ let jointDangling = -1;
2524
+ for (let jIdx = 0; jIdx < skeleton.jointCount; jIdx++) {
2525
+ const jointEntityRaw = skinJoints[jIdx] ?? 0;
2526
+ const jointEntity = jointEntityRaw as EntityHandle;
2527
+ const jointWorld = worldInternal._getArrayView(jointEntity, GlobalTransform, 'world');
2528
+ if (jointWorld === undefined) {
2529
+ jointDangling = jIdx;
2530
+ break;
2531
+ }
2532
+ // The allocator consumes the canonical Mat4 brand. Copy the
2533
+ // column view into that owner-created value so the ECS storage
2534
+ // view never crosses the math brand boundary by assertion.
2535
+ const jointWorldMat = mat4.create();
2536
+ jointWorldMat.set(jointWorld);
2537
+ jointWorlds[jIdx] = jointWorldMat;
2538
+ }
2539
+ if (jointDangling >= 0) {
2540
+ worldInternal._routeError(new JointEntityDanglingError(entity, jointDangling), {
2541
+ severity: Severity.Error,
2542
+ systemName: 'RenderSystem.extract (joint-entity-dangling)',
2543
+ });
2544
+ continue;
2545
+ }
2546
+ // (d) Slice the IBM flat Float32Array into per-joint Float32Arrays.
2547
+ // skeleton.inverseBindMatrices length === jointCount * 16.
2548
+ const ibmFlat = skeleton.inverseBindMatrices;
2549
+ const ibms: Float32Array[] = new Array<Float32Array>(skeleton.jointCount);
2550
+ for (let jIdx = 0; jIdx < skeleton.jointCount; jIdx++) {
2551
+ ibms[jIdx] = ibmFlat.subarray(jIdx * 16, jIdx * 16 + 16);
2552
+ }
2553
+ // (e) Allocate slice + write palette via the allocator (D-9 reset
2554
+ // already fired at extractFrame entry). When the pipelineState
2555
+ // surface is absent (test fixtures that pass undefined) the
2556
+ // hasSkin segment is skipped silently — bind-pose equivalent.
2557
+ if (skinPaletteAllocator !== null) {
2558
+ // Keep the narrow extraction seam compatible with older test or
2559
+ // host-owned allocator doubles while the real renderer uses the
2560
+ // stable-key path. The fallback is frame-local and therefore
2561
+ // cannot affect production allocators that implement the new
2562
+ // method.
2563
+ const slice =
2564
+ typeof skinPaletteAllocator.allocateSliceFor === 'function'
2565
+ ? skinPaletteAllocator.allocateSliceFor(
2566
+ `${world.identity}:${entity}`,
2567
+ skeleton.jointCount,
2568
+ )
2569
+ : skinPaletteAllocator.allocateSlice(skeleton.jointCount);
2570
+ skinPaletteAllocator.writeJointPalette(slice, ibms, jointWorlds);
2571
+ skinSlice = {
2572
+ jointCount: slice.jointCount,
2573
+ byteOffset: slice.byteOffset,
2574
+ buffer: slice.buffer,
2575
+ };
2576
+ }
2577
+ }
2578
+ }
2579
+
2580
+ // A pbr-skin PSO requires the complete three-binding group(2) skin
2581
+ // projection. Do not publish a renderable or its staged dispatch when
2582
+ // palette extraction was unavailable; the record stage must never
2583
+ // reinterpret a skinned vertex stream through an ordinary mesh group.
2584
+ if (materialSnap.materialShaderId === 'forgeax::pbr-skin' && skinSlice === undefined) {
2585
+ pendingDispatch.length = 0;
2586
+ continue;
2587
+ }
2588
+
2589
+ // feat-20260601 D-3: read the resolved world mat4 (propagateTransforms
2590
+ // output) straight from the GlobalTransform.world column array view. The
2591
+ // record stage copies these 16 floats into the mesh SSBO with zero
2592
+ // per-snapshot `mat4.compose` (AC-07). A stale slot (generation gone)
2593
+ // skips the renderable, mirroring the Instances dangling-row sweep.
2594
+ // tweak-20260611 M1 / K-3: `_getArrayView` call survives untouched;
2595
+ // only the `entity` source switched to `bundle.Entity.self[i]`.
2596
+ const worldView = worldInternal._getArrayView(entity, GlobalTransform, 'world');
2597
+ if (worldView === undefined) continue;
2598
+ const worldMat = new Float32Array(worldView);
2599
+ const transformSnap: TransformSnapshot = { world: worldMat };
2600
+ // feat-20260608 M5 amend / w11-a: per-submesh `materials[]` array
2601
+ // aligned 1-1 with `MeshAsset.submeshes[]`. materials[0] === the
2602
+ // representative entity-level snapshot already built; materials[i>=1]
2603
+ // are resolved via `resolveMaterialSnapshot` (a non-sprite, single-
2604
+ // pass-equivalent resolver — sprite per-submesh is OOS-1). When the
2605
+ // entity has no materialsView (case-B sentinel) the array is a single
2606
+ // mid-grey default mirroring the legacy single-material path so the
2607
+ // record stage's per-submesh UBO upload loop trivially writes one
2608
+ // slot, no special branch.
2609
+ const materialsArr: MaterialSnapshot[] = [materialSnap];
2610
+ if (assets !== undefined && assets !== null) {
2611
+ for (let mi = 1; mi < materialHandles.length; mi++) {
2612
+ const subHandle = materialHandles[mi] ?? 0;
2613
+ const cachedSubmaterial = materialSnapshotCache.get(subHandle);
2614
+ materialsArr.push(
2615
+ cachedSubmaterial?.snapshot ??
2616
+ resolveMaterialSnapshot(
2617
+ subHandle,
2618
+ world,
2619
+ assets,
2620
+ materialSnapshotCache,
2621
+ persistentMaterialSnapshotCache,
2622
+ ),
2623
+ );
2624
+ }
2625
+ }
2626
+ if (isRenderable && assets !== undefined && assets !== null) {
2627
+ for (let mi = 1; mi < materialHandles.length; mi++) {
2628
+ const subHandle = materialHandles[mi] ?? 0;
2629
+ if (subHandle === handleRaw) continue;
2630
+ const subEntry =
2631
+ materialSnapshotCache.get(subHandle) ??
2632
+ readPersistentMaterialSnapshot(persistentMaterialSnapshotCache, subHandle, assets);
2633
+ appendMaterialDispatchEntries(
2634
+ pendingDispatch,
2635
+ subEntry?.passes ?? (subHandle === 0 ? [DEFAULT_FORWARD_PASS] : []),
2636
+ entity,
2637
+ subHandle,
2638
+ renderables.length,
2639
+ layerVal,
2640
+ materialsArr[mi]?.paramSnapshot,
2641
+ 0,
2642
+ materialsArr[mi]?.materialShaderId,
2643
+ );
2644
+ }
2645
+ }
2646
+
2647
+ // feat-20260625-sprite-instances-and-tilemap-terrain-static-batch M3 /
2648
+ // w10: SpriteInstances validation + snapshot materialisation.
2649
+ // Three structured EcsError fires at this single point (plan-strategy
2650
+ // D-6 "fail-fast at the render domain entry, not at ECS spawn-time"):
2651
+ let spriteInstancesSnap: SpriteInstancesSnapshot | undefined;
2652
+ if (hasSpriteInstances) {
2653
+ // (1) mutually exclusive with Instances (peers — pick one).
2654
+ if (hasInstances) {
2655
+ worldInternal._routeError(
2656
+ new SpriteInstancesMutuallyExclusiveWithInstancesError(entity),
2657
+ {
2658
+ severity: Severity.Error,
2659
+ systemName: 'RenderSystem.extract (sprite-instances-mutually-exclusive)',
2660
+ },
2661
+ );
2662
+ continue;
2663
+ }
2664
+ // (2) requires sprite shader — the per-instance UV region is
2665
+ // consumed by the sprite vertex shader path only (plan-strategy D-4
2666
+ // axis on sprite.wgsl). Post-collapse (PR #520): sprite is no longer
2667
+ // a `shadingModel` enum member; identification is via the first-pass
2668
+ // `materialShaderId === 'forgeax::sprite'` (OOS-1 path retained).
2669
+ //
2670
+ // feat-20260624 M1' / t6: `'forgeax::sprite-lit'` also walks the same
2671
+ // per-instance UV region vertex path (VsOut byte-identical, paramSchema
2672
+ // mirror); accept either shader id.
2673
+ if (
2674
+ materialSnap.materialShaderId !== 'forgeax::sprite' &&
2675
+ materialSnap.materialShaderId !== 'forgeax::sprite-lit'
2676
+ ) {
2677
+ worldInternal._routeError(
2678
+ new SpriteInstancesRequiresSpriteShaderError(
2679
+ entity,
2680
+ materialSnap.materialShaderId ?? 'undefined',
2681
+ ),
2682
+ {
2683
+ severity: Severity.Error,
2684
+ systemName: 'RenderSystem.extract (sprite-instances-requires-sprite-shader)',
2685
+ },
2686
+ );
2687
+ continue;
2688
+ }
2689
+ // (3) count mismatch — transforms.length / 16 === regions.length / 4
2690
+ // (transforms.length=0 + regions.length=0 is the zero-instance lawful
2691
+ // boundary; both derivations are 0 and equality holds, so no fire).
2692
+ const transforms = worldInternal._getArrayView(entity, SpriteInstances, 'transforms');
2693
+ const regions = worldInternal._getArrayView(entity, SpriteInstances, 'regions');
2694
+ if (transforms !== undefined && regions !== undefined) {
2695
+ const transformsLength = transforms.length;
2696
+ const regionsLength = regions.length;
2697
+ // Stride sanity: transforms must be mod 16, regions must be mod 4.
2698
+ // A stride violation expresses as a count mismatch under the
2699
+ // canonical derivation transforms/16 vs regions/4 — fire the
2700
+ // count-mismatch code (the same code carries detail.expectedStride).
2701
+ const tCount = transformsLength / 16;
2702
+ const rCount = regionsLength / 4;
2703
+ if (transformsLength % 16 !== 0 || regionsLength % 4 !== 0 || tCount !== rCount) {
2704
+ worldInternal._routeError(
2705
+ new SpriteInstancesCountMismatchError(transformsLength, regionsLength),
2706
+ {
2707
+ severity: Severity.Error,
2708
+ systemName: 'RenderSystem.extract (sprite-instances-count-mismatch)',
2709
+ },
2710
+ );
2711
+ continue;
2712
+ }
2713
+ // Validation passes — build the snapshot. transforms.length === 0
2714
+ // is lawful (zero-instance) and produces instanceCount=0; the
2715
+ // record stage skips drawIndexed when instanceCount===0.
2716
+ const transformsCopy = new Float32Array(transforms);
2717
+ const regionsCopy = new Float32Array(regions);
2718
+ spriteInstancesSnap = {
2719
+ transforms: transformsCopy,
2720
+ regions: regionsCopy,
2721
+ instanceCount: tCount,
2722
+ cacheKey: entity,
2723
+ archVersion,
2724
+ };
2725
+ }
2726
+ }
2727
+
2728
+ let localAabb: Float32Array | undefined;
2729
+ let lods: readonly MeshLodLevel[] | undefined;
2730
+ let lodHysteresis: number | undefined;
2731
+ let morph: MorphSnapshot | undefined;
2732
+ const assetHandleRaw = Math.round(fAssetHandle ?? 0);
2733
+ if (assetHandleRaw !== 0) {
2734
+ const meshRes = resolveAssetHandle(world, toShared<'MeshAsset'>(assetHandleRaw));
2735
+ if (meshRes.ok && meshRes.value.kind === 'mesh') {
2736
+ const meshAsset = meshRes.value as MeshAsset;
2737
+ lods = meshAsset.lods;
2738
+ lodHysteresis = meshAsset.lodHysteresis;
2739
+ morph = morphSnapshotFor(meshAsset, morphWeightsView);
2740
+ const meshAabb = meshAsset.aabb;
2741
+ // Morph targets can expand the authored bounds. Keep the
2742
+ // specialized lane conservative until a target-aware bounds
2743
+ // projection is available; a false-positive draw is preferable
2744
+ // to culling a valid deformed vertex.
2745
+ if (morph === undefined && hasFiniteOrderedLocalAabb(meshAabb)) {
2746
+ localAabb = new Float32Array(meshAabb);
2747
+ }
2748
+ }
2749
+ }
2750
+
2751
+ const pointsLinesStyle: PointsLinesStyle | undefined =
2752
+ points !== undefined
2753
+ ? (() => {
2754
+ const shape = pointShapeFromU32(points.shape);
2755
+ return shape === undefined
2756
+ ? undefined
2757
+ : { kind: 'points' as const, sizePx: points.sizePx, shape };
2758
+ })()
2759
+ : lines === undefined
2760
+ ? undefined
2761
+ : { kind: 'lines' as const, widthPx: lines.widthPx };
2762
+ const cullingLocalAabb = expandPointsLinesBounds(localAabb ?? [], pointsLinesStyle);
2763
+ const pointsLines =
2764
+ pointsLinesComponent === undefined
2765
+ ? undefined
2766
+ : ({
2767
+ worldId: 0,
2768
+ entityKey: entity,
2769
+ component: pointsLinesComponent,
2770
+ meshHandle: assetHandleRaw,
2771
+ meshGeneration: assets?.catalogEpoch ?? 0,
2772
+ materialHandle: handleRaw,
2773
+ materialGeneration: assets?.catalogEpoch ?? 0,
2774
+ style: pointsLinesStyle,
2775
+ layer: layerVal,
2776
+ sortKey,
2777
+ visible: true,
2778
+ sourceBounds: cullingLocalAabb,
2779
+ viewport: { width: 0, height: 0, dpr: 1 },
2780
+ projection: identityProjection(),
2781
+ } satisfies PointsLinesRetainedSnapshot);
2782
+
2783
+ // Instances are snapshotted before the CPU visibility decision so the
2784
+ // culling owner can derive the union of every instance's transformed
2785
+ // mesh bounds. The same detached snapshot is then carried to record;
2786
+ // do not re-read the collection after culling (a mutation must not
2787
+ // make the cull and draw disagree within one frame).
2788
+ let instancesSnap: InstancesSnapshot | undefined;
2789
+ if (hasInstances) {
2790
+ const transforms =
2791
+ worldInternal._getArrayView(entity, Instances, 'transforms') ?? new Float32Array();
2792
+ if (transforms.length % 16 !== 0) {
2793
+ worldInternal._routeError(
2794
+ new InstanceTransformsStrideMismatchError(transforms.length),
2795
+ {
2796
+ severity: Severity.Error,
2797
+ systemName: 'RenderSystem.extract (Instances stride)',
2798
+ },
2799
+ );
2800
+ continue;
2801
+ }
2802
+ const projected = instanceCollections?.project(world, entity, transforms);
2803
+ instancesSnap = {
2804
+ transforms: projected?.transforms ?? new Float32Array(transforms),
2805
+ instanceCount: transforms.length / 16,
2806
+ cacheKey: entity,
2807
+ archVersion: projected === undefined ? fingerprintNumericArray(transforms) : 0,
2808
+ ...(projected === undefined
2809
+ ? {}
2810
+ : {
2811
+ collectionId: projected.collectionId,
2812
+ revision: projected.revision,
2813
+ }),
2814
+ };
2815
+ }
2816
+
2817
+ const baseRenderable: RenderableSnapshot = {
2818
+ assetHandle: Math.round(fAssetHandle ?? 0),
2819
+ transform: transformSnap,
2820
+ ...(lods === undefined ? {} : { lods }),
2821
+ ...(lodHysteresis === undefined ? {} : { lodHysteresis }),
2822
+ ...(localAabb !== undefined ? { localAabb: cullingLocalAabb } : {}),
2823
+ material: materialSnap,
2824
+ materials: materialsArr,
2825
+ materialBindingSources,
2826
+ materialBindingDiagnostics,
2827
+ worldId: 0,
2828
+ entityKey: entity,
2829
+ ...(authorVisible ? {} : { authorVisible: false }),
2830
+ ...(skinSlice !== undefined ? { skin: skinSlice } : {}),
2831
+ ...(skin?.joints === undefined
2832
+ ? {}
2833
+ : { skinJointEntities: Array.from(skin.joints, (joint) => Number(joint)) }),
2834
+ ...(morph !== undefined ? { morph } : {}),
2835
+ ...(instancesSnap !== undefined ? { instances: instancesSnap } : {}),
2836
+ ...(spriteInstancesSnap !== undefined ? { spriteInstances: spriteInstancesSnap } : {}),
2837
+ ...(pointsLines !== undefined ? { pointsLines } : {}),
2838
+ };
2839
+ const gpuDrivenDraws = buildGpuDrivenDraws({
2840
+ submeshes: gpuDrivenSubmeshes,
2841
+ indexed: gpuDrivenIndexed,
2842
+ materials: materialsArr,
2843
+ fallbackMaterial: materialSnap,
2844
+ ...(gpuDrivenGeometry === undefined || getMaterialShaderArtifact === undefined
2845
+ ? {}
2846
+ : {
2847
+ prepare(draw, drawMaterial) {
2848
+ const materialShaderId = drawMaterial.materialShaderId;
2849
+ if (materialShaderId === undefined) return undefined;
2850
+ const artifact = getMaterialShaderArtifact(materialShaderId);
2851
+ if (artifact?.receipt === undefined) return undefined;
2852
+ const geometry: GpuDrivenGeometryReceipt = {
2853
+ ...gpuDrivenGeometry,
2854
+ topology: draw.topology,
2855
+ indexed: draw.kind === 'indexed',
2856
+ };
2857
+ const result = resolvePreparedGpuDrivenDraw({
2858
+ snapshot: { ...baseRenderable, material: drawMaterial },
2859
+ artifact,
2860
+ geometry,
2861
+ generation: artifact.receipt.generation,
2862
+ draw,
2863
+ });
2864
+ return result.ok ? result.value : undefined;
2865
+ },
2866
+ }),
2867
+ });
2868
+ const renderable =
2869
+ morph === undefined && gpuDrivenDraws.length > 0
2870
+ ? { ...baseRenderable, gpuDrivenDraws }
2871
+ : baseRenderable;
2872
+
2873
+ // feat-20260528-frustum-culling M3 / w10: frustum culling check.
2874
+ // Skip the entity if a valid AABB exists AND ALL cameras' frusta
2875
+ // reject the world-space AABB. Missing or malformed AABBs are
2876
+ // conservative always-visible fallbacks; valid culling bounds are
2877
+ // producer-owned finite local-space AABBs. Culling is unconditional
2878
+ // engine behavior; there is no per-entity opt-out.
2879
+ if (localAabb !== undefined) {
2880
+ // An empty or malformed Instances payload has no meaningful bounds.
2881
+ // Keep it conservative (the draw path later emits zero instances)
2882
+ // instead of manufacturing the entity's identity bounds. For a
2883
+ // valid payload, derive one world-space union for CPU culling while
2884
+ // leaving the mesh-local AABB untouched for GPU per-instance cull.
2885
+ const derivedInstancesBounds =
2886
+ instancesSnap === undefined || instancesSnap.instanceCount === 0
2887
+ ? undefined
2888
+ : deriveInstancesUnionBounds({
2889
+ meshAabb: cullingLocalAabb,
2890
+ entityWorld: transformSnap.world,
2891
+ transforms: instancesSnap.transforms,
2892
+ });
2893
+ if (instancesSnap?.instanceCount === 0) {
2894
+ // No instance can contribute a visible bound. The retained
2895
+ // snapshot still records instanceCount=0 for the record stage.
2896
+ } else if (
2897
+ hasInstances &&
2898
+ (instancesSnap === undefined || derivedInstancesBounds === undefined)
2899
+ ) {
2900
+ // Missing/malformed derived facts are a conservative no-cull
2901
+ // result. The stride validator above already rejects malformed
2902
+ // lengths; this branch covers non-finite producer matrices/AABB.
2903
+ } else {
2904
+ // feat-20260601 D-3: cull AABB uses the resolved world mat4
2905
+ // directly (no compose) -- same source the record stage feeds
2906
+ // the mesh SSBO, so cull stays same-source with render (AC-05).
2907
+ const worldAabb = box3.create();
2908
+ if (derivedInstancesBounds !== undefined) {
2909
+ worldAabb[0] = derivedInstancesBounds[0] ?? 0;
2910
+ worldAabb[1] = derivedInstancesBounds[1] ?? 0;
2911
+ worldAabb[2] = derivedInstancesBounds[2] ?? 0;
2912
+ worldAabb[3] = derivedInstancesBounds[3] ?? 0;
2913
+ worldAabb[4] = derivedInstancesBounds[4] ?? 0;
2914
+ worldAabb[5] = derivedInstancesBounds[5] ?? 0;
2915
+ } else {
2916
+ box3.transformBox3(worldAabb, cullingLocalAabb, transformSnap.world);
2917
+ }
2918
+
2919
+ // Test against all cameras. Entity is visible if one camera
2920
+ // frustum intersects the world-space AABB (or planes are empty
2921
+ // from degenerate projection).
2922
+ frustumTotal += 1;
2923
+ let visible = frustumPlanes.length === 0;
2924
+ for (let ci = 0; ci < frustumPlanes.length; ci++) {
2925
+ const planes = frustumPlanes[ci] as Float32Array;
2926
+ if (planes.length === 0) {
2927
+ visible = true;
2928
+ break;
2929
+ }
2930
+ if (frustum.intersectsBox(planes as frustum.Frustum, worldAabb as box3.Box3Like)) {
2931
+ visible = true;
2932
+ break;
2933
+ }
2934
+ }
2935
+ if (!visible) {
2936
+ frustumCulled += 1;
2937
+ continue;
2938
+ }
2939
+ }
2940
+ }
2941
+
2942
+ flushPendingDispatch(pendingDispatch);
2943
+ renderables.push(renderable);
2944
+ }
2945
+
2946
+ // feat-20260520-2d-sprite-layer-mvp M-3 / w22 + w25: finalise the
2947
+ // pending TransparentEntry with the renderableIndex pointing at the
2948
+ // RenderableSnapshot we just pushed (when isRenderable === true).
2949
+ // The check below also covers a sprite entity that survives the
2950
+ // dangling-Instances branch (silent skip with `dispatchEntry !==
2951
+ // null` early-continue) — in that case renderableIndex is still set
2952
+ // to the just-pushed slot which is correct because materialDispatch
2953
+ // already captures the dispatch position.
2954
+ }
2955
+ }
2956
+
2957
+ // M3 / w26: sort dispatch entries by queue (ascending, stable sort)
2958
+ // per plan-strategy D-3.
2959
+ dispatch = sortDispatchByQueue(dispatch);
2960
+
2961
+ // D-1: collect PostProcessParams entities into Map<shaderId, Uint8Array>.
2962
+ // Last-one-wins when multiple entities bear the same shader id (mirrors
2963
+ // Camera.exposure -> CameraSnapshot pattern; extract stage only reads).
2964
+ const postProcessParams: Map<string, Uint8Array> = new Map();
2965
+ const postProcessParamsQuery = world.query({ with: [PostProcessParams] }).unwrap();
2966
+ for (const row of postProcessParamsQuery) {
2967
+ const entity = row.entity;
2968
+ const read = world.get(entity, PostProcessParams);
2969
+ if (!read.ok) continue;
2970
+ postProcessParams.set(read.value.shader, read.value.data);
2971
+ }
2972
+
2973
+ // feat-20260621 M-A3 / w13 (D-5): engine built-in tonemap data-driven
2974
+ // provider. The engine bridges the active camera's `Camera.exposure /
2975
+ // whitePoint / tonemap` onto the SAME unified params channel custom
2976
+ // post-processes use — `Camera.exposure` stays the AI-user-facing SSOT (D-5),
2977
+ // the engine itself acts as the provider for the Standard tonemap shader
2978
+ // id. The 16B layout keeps the prior recordTonemapPass packing
2979
+ // (render-system-record.ts pre-w14): Float32 [exposure, whitePoint, _,
2980
+ // ditherEnabled], with the mode u32 occupying the third 4-byte slot via
2981
+ // tonemapToU32 (SSOT in camera.ts). The final Output Transform makes a
2982
+ // per-pass copy and writes ditherEnabled at byte offset 12; the extracted
2983
+ // camera snapshot remains the SSOT. Run AFTER the user-entity collection above so the engine's
2984
+ // built-in provider is authoritative for its own reserved key (a user entity
2985
+ // can never shadow the Standard tonemap identity. The single active camera mirrors
2986
+ // recordFrame's `activeCameras[0]` selection.
2987
+ const tonemapCamera = cameras[0];
2988
+ if (tonemapCamera !== undefined) {
2989
+ postProcessParams.set(STANDARD_OUTPUT_TRANSFORM_FEATURE_ID, tonemapParams(tonemapCamera));
2990
+ }
2991
+
2992
+ return {
2993
+ cameras,
2994
+ auxiliaryCameras,
2995
+ cubeCameras,
2996
+ reflectionProbes,
2997
+ lights,
2998
+ environment,
2999
+ environmentReady: true,
3000
+ ...(volumetricFog === undefined ? {} : { volumetricFog }),
3001
+ renderables,
3002
+ dispatch,
3003
+ skylight,
3004
+ skylightCount,
3005
+ lightProbes,
3006
+ skybox,
3007
+ skyboxCount,
3008
+ fog,
3009
+ ...(fogFailure === undefined ? {} : { fogFailure }),
3010
+ frustumStats: { culled: frustumCulled, total: frustumTotal },
3011
+ visibilityStats: { explicitlyHidden: explicitlyHidden.size },
3012
+ postProcessParams,
3013
+ visibilitySnapshots: [context.visibility],
3014
+ featureVisibilitySnapshots: [{ world, snapshot: context.visibility }],
3015
+ hiddenEntityReports: [...explicitlyHidden].map((entity) => ({ world, entity })),
3016
+ };
3017
+ }
3018
+
3019
+ export function defaultMaterialSnapshot(materialHandle = 0): MaterialSnapshot {
3020
+ // Mid-grey unlit fallback (D-Q7 case B + extract-stage missing-spec),
3021
+ // matching the pre-w6 visual outcome where the record stage's force-cast
3022
+ // read of `firstMaterial.baseColorTexture` returned undefined and the
3023
+ // unlit fallback shader was selected.
3024
+ return {
3025
+ baseColor: vec3.create(0.5, 0.5, 0.5),
3026
+ metallic: 0,
3027
+ roughness: 1,
3028
+ materialHandle,
3029
+ };
3030
+ }
3031
+
3032
+ function identityProjection(): Float32Array {
3033
+ const projection = new Float32Array(16);
3034
+ projection[0] = 1;
3035
+ projection[5] = 1;
3036
+ projection[10] = 1;
3037
+ projection[15] = 1;
3038
+ return projection;
3039
+ }