@forgeax/engine-render 0.1.34 → 0.1.35

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (243) hide show
  1. package/README.md +52 -3
  2. package/dist/assembly/device-feature-admission.d.ts +2 -2
  3. package/dist/assembly/host-contract.d.ts +3 -2
  4. package/dist/assembly/host-contract.d.ts.map +1 -1
  5. package/dist/assembly/recovery/renderer-recover.d.ts.map +1 -1
  6. package/dist/assembly/render-target-host.d.ts +5 -0
  7. package/dist/assembly/render-target-host.d.ts.map +1 -1
  8. package/dist/assembly/renderer-facade.d.ts.map +1 -1
  9. package/dist/assembly/webgpu-renderer.d.ts +1 -0
  10. package/dist/assembly/webgpu-renderer.d.ts.map +1 -1
  11. package/dist/authoring.mjs +2 -4
  12. package/dist/authoring.mjs.map +1 -1
  13. package/dist/chunk-3XUBWRY2.mjs +1842 -0
  14. package/dist/chunk-3XUBWRY2.mjs.map +1 -0
  15. package/dist/{chunk-UI5SFODX.mjs → chunk-G6HDNGY7.mjs} +2329 -1776
  16. package/dist/chunk-G6HDNGY7.mjs.map +1 -0
  17. package/dist/{chunk-HEB564WF.mjs → chunk-LM5IE7GF.mjs} +4 -4
  18. package/dist/{chunk-HEB564WF.mjs.map → chunk-LM5IE7GF.mjs.map} +1 -1
  19. package/dist/{chunk-MKDIT2EM.mjs → chunk-LNIUIKQ7.mjs} +143 -246
  20. package/dist/chunk-LNIUIKQ7.mjs.map +1 -0
  21. package/dist/chunk-MXTWKZO4.mjs +3268 -0
  22. package/dist/chunk-MXTWKZO4.mjs.map +1 -0
  23. package/dist/{chunk-ODZWR6JQ.mjs → chunk-MZ4C7EHF.mjs} +2042 -27
  24. package/dist/chunk-MZ4C7EHF.mjs.map +1 -0
  25. package/dist/chunk-RIPAEGI6.mjs +48 -0
  26. package/dist/chunk-RIPAEGI6.mjs.map +1 -0
  27. package/dist/{chunk-OCDLEI6I.mjs → chunk-SGPUJW3F.mjs} +117 -5
  28. package/dist/chunk-SGPUJW3F.mjs.map +1 -0
  29. package/dist/{chunk-ELJFJ2BU.mjs → chunk-X2KA6WHM.mjs} +29 -4
  30. package/dist/chunk-X2KA6WHM.mjs.map +1 -0
  31. package/dist/{chunk-BLXGONR2.mjs → chunk-XSFB7XXQ.mjs} +51 -4
  32. package/dist/chunk-XSFB7XXQ.mjs.map +1 -0
  33. package/dist/cloud/frame-context.d.ts +2 -2
  34. package/dist/cloud/frame-context.d.ts.map +1 -1
  35. package/dist/construct-renderer.mjs +810 -2073
  36. package/dist/construct-renderer.mjs.map +1 -1
  37. package/dist/device/gpu-residency.d.ts +19 -19
  38. package/dist/device/gpu-residency.d.ts.map +1 -1
  39. package/dist/errors/render.d.ts +3 -2
  40. package/dist/errors/render.d.ts.map +1 -1
  41. package/dist/extract/material-context.d.ts +7 -0
  42. package/dist/extract/material-context.d.ts.map +1 -0
  43. package/dist/features/host.d.ts +5 -0
  44. package/dist/features/host.d.ts.map +1 -1
  45. package/dist/features/plan.d.ts +2 -0
  46. package/dist/features/plan.d.ts.map +1 -1
  47. package/dist/features/types.d.ts +4 -0
  48. package/dist/features/types.d.ts.map +1 -1
  49. package/dist/glyph-text-layout-system.d.ts +1 -1
  50. package/dist/glyph-text-layout-system.d.ts.map +1 -1
  51. package/dist/gpu-driven/shadow-ownership.d.ts +3 -3
  52. package/dist/gpu-driven/shadow-ownership.d.ts.map +1 -1
  53. package/dist/ibl/frame-resources.d.ts.map +1 -1
  54. package/dist/ibl/skylight-bind-group.d.ts +4 -4
  55. package/dist/ibl/skylight-bind-group.d.ts.map +1 -1
  56. package/dist/index.d.ts +3 -0
  57. package/dist/index.d.ts.map +1 -1
  58. package/dist/index.mjs +530 -9
  59. package/dist/index.mjs.map +1 -1
  60. package/dist/instances.d.ts +3 -4
  61. package/dist/instances.d.ts.map +1 -1
  62. package/dist/internal.mjs +7 -8
  63. package/dist/internal.mjs.map +1 -1
  64. package/dist/pbr-pipeline.d.ts +3 -3
  65. package/dist/pbr-pipeline.d.ts.map +1 -1
  66. package/dist/pipeline/standard-output/lut-gpu.d.ts +2 -2
  67. package/dist/pipeline/standard-output/lut-gpu.d.ts.map +1 -1
  68. package/dist/pipeline/standard-output/resources.d.ts +2 -2
  69. package/dist/pipeline/standard-output/resources.d.ts.map +1 -1
  70. package/dist/publication/contract.d.ts +77 -0
  71. package/dist/publication/contract.d.ts.map +1 -0
  72. package/dist/publication/dependencies.d.ts +7 -0
  73. package/dist/publication/dependencies.d.ts.map +1 -0
  74. package/dist/publication/prepare-geometry.d.ts +9 -0
  75. package/dist/publication/prepare-geometry.d.ts.map +1 -0
  76. package/dist/publication/programs.d.ts +5 -0
  77. package/dist/publication/programs.d.ts.map +1 -0
  78. package/dist/publication/publisher.d.ts +33 -0
  79. package/dist/publication/publisher.d.ts.map +1 -0
  80. package/dist/publication/receiver.d.ts +29 -0
  81. package/dist/publication/receiver.d.ts.map +1 -0
  82. package/dist/publication/resource-scope.d.ts +18 -0
  83. package/dist/publication/resource-scope.d.ts.map +1 -0
  84. package/dist/publication/targets.d.ts +33 -0
  85. package/dist/publication/targets.d.ts.map +1 -0
  86. package/dist/publication/video.d.ts +5 -0
  87. package/dist/publication/video.d.ts.map +1 -0
  88. package/dist/record/fold-buckets.d.ts +3 -3
  89. package/dist/record/fold-buckets.d.ts.map +1 -1
  90. package/dist/record/frame-snapshot.d.ts +6 -6
  91. package/dist/record/frame-snapshot.d.ts.map +1 -1
  92. package/dist/record/frame.d.ts +5 -4
  93. package/dist/record/frame.d.ts.map +1 -1
  94. package/dist/record/helpers.d.ts +2 -2
  95. package/dist/record/helpers.d.ts.map +1 -1
  96. package/dist/record/main-pass-geometry.d.ts +2 -2
  97. package/dist/record/main-pass-geometry.d.ts.map +1 -1
  98. package/dist/record/main-pass-material.d.ts +7 -9
  99. package/dist/record/main-pass-material.d.ts.map +1 -1
  100. package/dist/record/main-pass-sprite-draws.d.ts +3 -16
  101. package/dist/record/main-pass-sprite-draws.d.ts.map +1 -1
  102. package/dist/record/main-pass.d.ts.map +1 -1
  103. package/dist/record/prepared-material-bindings.d.ts +3 -3
  104. package/dist/record/prepared-material-bindings.d.ts.map +1 -1
  105. package/dist/record/render-context.d.ts +2 -2
  106. package/dist/record/render-context.d.ts.map +1 -1
  107. package/dist/record/sprite-instance-buffer.d.ts +31 -0
  108. package/dist/record/sprite-instance-buffer.d.ts.map +1 -0
  109. package/dist/record/target-capture-graph.d.ts +19 -0
  110. package/dist/record/target-capture-graph.d.ts.map +1 -0
  111. package/dist/record/typed-frame-graph.d.ts +2 -13
  112. package/dist/record/typed-frame-graph.d.ts.map +1 -1
  113. package/dist/record/view-ubo.d.ts.map +1 -1
  114. package/dist/record/volume-params.d.ts +2 -2
  115. package/dist/record/volume-params.d.ts.map +1 -1
  116. package/dist/recovery/render-system-candidate.d.ts +5 -5
  117. package/dist/recovery/render-system-candidate.d.ts.map +1 -1
  118. package/dist/render-contract.d.ts +4 -1
  119. package/dist/render-contract.d.ts.map +1 -1
  120. package/dist/render-system-extract-tail.d.ts.map +1 -1
  121. package/dist/render-system-extract.d.ts +2 -0
  122. package/dist/render-system-extract.d.ts.map +1 -1
  123. package/dist/render-system-presentation.d.ts +2 -2
  124. package/dist/render-system-presentation.d.ts.map +1 -1
  125. package/dist/render-system-projections.d.ts +3 -2
  126. package/dist/render-system-projections.d.ts.map +1 -1
  127. package/dist/render-system-residency.d.ts +2 -2
  128. package/dist/render-system-residency.d.ts.map +1 -1
  129. package/dist/render-system.d.ts +3 -7
  130. package/dist/render-system.d.ts.map +1 -1
  131. package/dist/scene/render-scene.d.ts +8 -4
  132. package/dist/scene/render-scene.d.ts.map +1 -1
  133. package/dist/scene/render-source.d.ts +42 -0
  134. package/dist/scene/render-source.d.ts.map +1 -0
  135. package/dist/scene/source-systems.d.ts +6 -0
  136. package/dist/scene/source-systems.d.ts.map +1 -0
  137. package/dist/systems/skin-palette-allocator.d.ts.map +1 -1
  138. package/dist/systems/skin-palette-types.d.ts +10 -0
  139. package/dist/systems/skin-palette-types.d.ts.map +1 -1
  140. package/dist/systems/transparent-dispatch.d.ts +2 -2
  141. package/dist/systems/transparent-dispatch.d.ts.map +1 -1
  142. package/dist/systems/transparent-sort-config.d.ts +2 -1
  143. package/dist/systems/transparent-sort-config.d.ts.map +1 -1
  144. package/dist/temporal/index.mjs +6 -7
  145. package/package.json +21 -21
  146. package/src/__tests__/auto-exposure-transaction.integration.test.ts +4 -9
  147. package/src/__tests__/device-feature-admission.unit.test.ts +3 -2
  148. package/src/__tests__/gpu-driven-pbr.dawn.test.ts +3 -4
  149. package/src/__tests__/ktx2-basis-gpu-consumer.dawn.test.ts +4 -1
  150. package/src/__tests__/main-pass-material-medium-selection.unit.test.ts +0 -1
  151. package/src/__tests__/materials-standard-contract.unit.test.ts +0 -1
  152. package/src/__tests__/physical-clearcoat.integration.test.ts +23 -23
  153. package/src/__tests__/physical-material-budget.unit.test.ts +40 -0
  154. package/src/__tests__/render-error-code-owner.test-d.ts +1 -0
  155. package/src/__tests__/renderer-factory-material-contract.unit.test.ts +1 -1
  156. package/src/assembly/device-feature-admission.ts +2 -2
  157. package/src/assembly/host-contract.ts +5 -2
  158. package/src/assembly/recovery/renderer-recover.ts +9 -0
  159. package/src/assembly/render-target-host.ts +57 -47
  160. package/src/assembly/renderer-facade.ts +3 -1
  161. package/src/assembly/webgpu-ready.ts +1 -1
  162. package/src/assembly/webgpu-renderer.ts +89 -61
  163. package/src/cloud/frame-context.ts +2 -2
  164. package/src/device/gpu-residency.ts +26 -25
  165. package/src/errors/render.ts +3 -1
  166. package/src/extract/material-context.ts +21 -0
  167. package/src/features/host.ts +13 -5
  168. package/src/features/plan.ts +2 -0
  169. package/src/features/types.ts +4 -0
  170. package/src/glyph-text-layout-system.ts +2 -2
  171. package/src/gpu-driven/shadow-ownership.ts +3 -3
  172. package/src/ibl/frame-resources.ts +0 -1
  173. package/src/ibl/skylight-bind-group.ts +13 -25
  174. package/src/index.ts +9 -0
  175. package/src/instances.ts +9 -6
  176. package/src/pbr-pipeline.ts +11 -17
  177. package/src/pipeline/standard-output/lut-gpu.ts +3 -3
  178. package/src/pipeline/standard-output/resources.ts +2 -2
  179. package/src/publication/__tests__/derived-geometry.integration.test.ts +177 -0
  180. package/src/publication/__tests__/features.integration.test.ts +122 -0
  181. package/src/publication/__tests__/programs.unit.test.ts +25 -0
  182. package/src/publication/__tests__/publication.integration.test.ts +370 -0
  183. package/src/publication/__tests__/targets.integration.test.ts +120 -0
  184. package/src/publication/__tests__/video.browser.test.ts +50 -0
  185. package/src/publication/contract.ts +104 -0
  186. package/src/publication/dependencies.ts +54 -0
  187. package/src/publication/prepare-geometry.ts +94 -0
  188. package/src/publication/programs.ts +45 -0
  189. package/src/publication/publisher.ts +618 -0
  190. package/src/publication/receiver.ts +297 -0
  191. package/src/publication/resource-scope.ts +31 -0
  192. package/src/publication/targets.ts +182 -0
  193. package/src/publication/video.ts +33 -0
  194. package/src/record/__tests__/material-bg-cache.unit.test.ts +15 -1
  195. package/src/record/__tests__/sprite-material-abi.unit.test.ts +8 -10
  196. package/src/record/__tests__/video-texture-view.unit.test.ts +9 -9
  197. package/src/record/fold-buckets.ts +8 -5
  198. package/src/record/frame-snapshot.ts +6 -6
  199. package/src/record/frame.ts +42 -22
  200. package/src/record/helpers.ts +2 -2
  201. package/src/record/main-pass-geometry.ts +21 -2
  202. package/src/record/main-pass-material.ts +37 -33
  203. package/src/record/main-pass-sprite-draws.ts +6 -152
  204. package/src/record/main-pass.ts +8 -7
  205. package/src/record/prepared-material-bindings.ts +11 -6
  206. package/src/record/render-context.ts +2 -2
  207. package/src/record/shadow-pass.ts +0 -3
  208. package/src/record/sprite-instance-buffer.ts +155 -0
  209. package/src/record/target-capture-graph.ts +258 -0
  210. package/src/record/typed-frame-graph.ts +6 -206
  211. package/src/record/view-ubo.ts +1 -1
  212. package/src/record/volume-params.ts +6 -6
  213. package/src/recovery/render-system-candidate.ts +10 -10
  214. package/src/render-contract.ts +6 -1
  215. package/src/render-system-extract-tail.ts +33 -17
  216. package/src/render-system-extract.ts +2 -0
  217. package/src/render-system-presentation.ts +2 -2
  218. package/src/render-system-projections.ts +3 -2
  219. package/src/render-system-residency.ts +2 -2
  220. package/src/render-system.ts +82 -53
  221. package/src/scene/render-scene.ts +110 -100
  222. package/src/scene/render-source.ts +90 -0
  223. package/src/scene/source-systems.ts +33 -0
  224. package/src/systems/skin-palette-allocator.ts +1 -0
  225. package/src/systems/skin-palette-types.ts +11 -0
  226. package/src/systems/transparent-dispatch.ts +2 -2
  227. package/src/systems/transparent-sort-config.ts +3 -1
  228. package/dist/chunk-BLXGONR2.mjs.map +0 -1
  229. package/dist/chunk-ELJFJ2BU.mjs.map +0 -1
  230. package/dist/chunk-ILQ5MEZF.mjs +0 -32
  231. package/dist/chunk-ILQ5MEZF.mjs.map +0 -1
  232. package/dist/chunk-MKDIT2EM.mjs.map +0 -1
  233. package/dist/chunk-OCDLEI6I.mjs.map +0 -1
  234. package/dist/chunk-ODZWR6JQ.mjs.map +0 -1
  235. package/dist/chunk-RXZ3RGOU.mjs +0 -53
  236. package/dist/chunk-RXZ3RGOU.mjs.map +0 -1
  237. package/dist/chunk-SHFUFJ5N.mjs +0 -1781
  238. package/dist/chunk-SHFUFJ5N.mjs.map +0 -1
  239. package/dist/chunk-UI5SFODX.mjs.map +0 -1
  240. package/dist/chunk-UINHLCZA.mjs +0 -2389
  241. package/dist/chunk-UINHLCZA.mjs.map +0 -1
  242. package/dist/chunk-WEX45HKH.mjs +0 -1524
  243. package/dist/chunk-WEX45HKH.mjs.map +0 -1
@@ -0,0 +1,48 @@
1
+ // src/temporal/coverage.ts
2
+ function createTemporalCoverage(width, height) {
3
+ if (!Number.isSafeInteger(width) || width <= 0) throw new RangeError("width must be positive.");
4
+ if (!Number.isSafeInteger(height) || height <= 0)
5
+ throw new RangeError("height must be positive.");
6
+ return Object.freeze({ width, height, bytes: 34 * width * height, fullScreen: true });
7
+ }
8
+ function classifySceneDataCoverage(input) {
9
+ const exactContributorIds = input.contributors.filter((c) => c.kind === "exact").map((c) => c.id);
10
+ const reactiveContributorIds = input.contributors.filter((c) => c.kind === "reactive").map((c) => c.id);
11
+ const available = new Set(input.contributors.map((c) => c.id));
12
+ const missing = input.requiredContributorIds.filter((id) => !available.has(id));
13
+ return {
14
+ exactContributorIds: Object.freeze(exactContributorIds),
15
+ reactiveContributorIds: Object.freeze(reactiveContributorIds),
16
+ missingContributorIds: Object.freeze(missing.slice(0, 32)),
17
+ omittedMissingContributorCount: Math.max(0, missing.length - 32),
18
+ complete: missing.length === 0
19
+ };
20
+ }
21
+ function scanSceneDataCoverage(input) {
22
+ const classification = classifySceneDataCoverage({
23
+ contributors: input.contributorIds.map((id) => ({ id, kind: "exact" })),
24
+ requiredContributorIds: input.requiredContributorIds
25
+ });
26
+ return Object.freeze({
27
+ schema: input.schema,
28
+ lane: input.lane,
29
+ producerId: input.producerId,
30
+ ...classification,
31
+ contributorIds: Object.freeze([...input.contributorIds])
32
+ });
33
+ }
34
+
35
+ // src/scene/probe-blend-record.ts
36
+ var PROBE_BLEND_RECORD_BYTE_SIZE = 160;
37
+ var PROBE_BLEND_RECORD_STRIDE = 256;
38
+ var PROBE_BLEND_RECORD_CAPACITY = 64;
39
+ function probeBlendRecordOffset(objectKey) {
40
+ if (!Number.isInteger(objectKey) || objectKey < 0) {
41
+ throw new Error("probe blend record requires a non-negative object key");
42
+ }
43
+ return (objectKey + 1) * PROBE_BLEND_RECORD_STRIDE;
44
+ }
45
+
46
+ export { PROBE_BLEND_RECORD_BYTE_SIZE, PROBE_BLEND_RECORD_CAPACITY, PROBE_BLEND_RECORD_STRIDE, classifySceneDataCoverage, createTemporalCoverage, probeBlendRecordOffset, scanSceneDataCoverage };
47
+ //# sourceMappingURL=chunk-RIPAEGI6.mjs.map
48
+ //# sourceMappingURL=chunk-RIPAEGI6.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/temporal/coverage.ts","../src/scene/probe-blend-record.ts"],"names":[],"mappings":";AAq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sB,CAAA;AAAA,IAC5D,uBAAuB,MAAA,CAAO,MAAA,CAAO,QAAQ,KAAA,CAAM,CAAA,EAAG,EAAE,CAAC,CAAA;AAAA,IACzD,gCAAgC,IAAA,CAAK,GAAA,CAAI,CAAA,EAAG,OAAA,CAAQ,SAAS,EAAE,CAAA;AAAA,IAC/D,QAAA,EAAU,QAAQ,MAAA,KAAW;AAAA,GAC/B;AACF;AACO,SAAS,sBAAsB,KAAA,EAMhB;AACpB,EAAA,MAAM,iBAAiB,yBAAA,CAA0B;AAAA,IAC/C,YAAA,EAAc,KAAA,CAAM,cAAA,CAAe,GAAA,CAAI,CAAC,QAAQ,EAAE,EAAA,EAAI,IAAA,EAAM,OAAA,EAAiB,CAAE,CAAA;AAAA,IAC/E,wBAAwB,KAAA,CAAM;AAAA,GAC/B,CAAA;AACD,EAAA,OAAO,OAAO,MAAA,CAAO;AAAA,IACnB,QAAQ,KAAA,CAAM,MAAA;AAAA,IACd,MAAM,KAAA,CAAM,IAAA;AAAA,IACZ,YAAY,KAAA,CAAM,UAAA;AAAA,IAClB,GAAG,cAAA;AAAA,IACH,gBAAgB,MAAA,CAAO,MAAA,CAAO,CAAC,GAAG,KAAA,CAAM,cAAc,CAAC;AAAA,GACxD,CAAA;AACH;;;AC3EO,IAAM,4BAAA,GAA+B;AAErC,IAAM,yBAAA,GAA4B;AAGlC,IAAM,2BAAA,GAA8B;AAyCpC,SAAS,uBAAuB,SAAA,EAA2B;AAChE,EAAA,IAAI,CAAC,MAAA,CAAO,SAAA,CAAU,SAAS,CAAA,IAAK,YAAY,CAAA,EAAG;AACjD,IAAA,MAAM,IAAI,MAAM,uDAAuD,CAAA;AAAA,EACzE;AAGA,EAAA,OAAA,CAAQ,YAAY,CAAA,IAAK,yBAAA;AAC3B","file":"chunk-RIPAEGI6.mjs","sourcesContent":["import type { SceneDataLane, SceneDataSchemaId } from './scene-data';\n\nexport interface SceneDataCoverage {\n readonly schema: SceneDataSchemaId;\n readonly lane: SceneDataLane;\n readonly producerId: string;\n readonly complete: boolean;\n readonly contributorIds: readonly string[];\n readonly exactContributorIds: readonly string[];\n readonly reactiveContributorIds: readonly string[];\n readonly missingContributorIds: readonly string[];\n readonly omittedMissingContributorCount: number;\n}\n\nexport interface TemporalCoverage {\n readonly width: number;\n readonly height: number;\n readonly bytes: number;\n readonly fullScreen: true;\n}\n\nexport function createTemporalCoverage(width: number, height: number): TemporalCoverage {\n if (!Number.isSafeInteger(width) || width <= 0) throw new RangeError('width must be positive.');\n if (!Number.isSafeInteger(height) || height <= 0)\n throw new RangeError('height must be positive.');\n return Object.freeze({ width, height, bytes: 34 * width * height, fullScreen: true as const });\n}\n\nexport type SceneDataContributorKind = 'exact' | 'reactive';\nexport interface SceneDataContributor {\n readonly id: string;\n readonly kind: SceneDataContributorKind;\n}\nexport function classifySceneDataCoverage(input: {\n readonly contributors: readonly SceneDataContributor[];\n readonly requiredContributorIds: readonly string[];\n}): {\n readonly exactContributorIds: readonly string[];\n readonly reactiveContributorIds: readonly string[];\n readonly missingContributorIds: readonly string[];\n readonly omittedMissingContributorCount: number;\n readonly complete: boolean;\n} {\n const exactContributorIds = input.contributors.filter((c) => c.kind === 'exact').map((c) => c.id);\n const reactiveContributorIds = input.contributors\n .filter((c) => c.kind === 'reactive')\n .map((c) => c.id);\n const available = new Set(input.contributors.map((c) => c.id));\n const missing = input.requiredContributorIds.filter((id) => !available.has(id));\n return {\n exactContributorIds: Object.freeze(exactContributorIds),\n reactiveContributorIds: Object.freeze(reactiveContributorIds),\n missingContributorIds: Object.freeze(missing.slice(0, 32)),\n omittedMissingContributorCount: Math.max(0, missing.length - 32),\n complete: missing.length === 0,\n };\n}\nexport function scanSceneDataCoverage(input: {\n readonly schema: SceneDataSchemaId;\n readonly lane: SceneDataLane;\n readonly producerId: string;\n readonly contributorIds: readonly string[];\n readonly requiredContributorIds: readonly string[];\n}): SceneDataCoverage {\n const classification = classifySceneDataCoverage({\n contributors: input.contributorIds.map((id) => ({ id, kind: 'exact' as const })),\n requiredContributorIds: input.requiredContributorIds,\n });\n return Object.freeze({\n schema: input.schema,\n lane: input.lane,\n producerId: input.producerId,\n ...classification,\n contributorIds: Object.freeze([...input.contributorIds]),\n });\n}\n","export const PROBE_BLEND_RECORD_BYTE_SIZE = 160;\n/** Dynamic-offset stride; 160B payload plus WebGPU's 256B alignment. */\nexport const PROBE_BLEND_RECORD_STRIDE = 256;\nexport const PROBE_BLEND_RECORD_FLOAT_COUNT =\n PROBE_BLEND_RECORD_BYTE_SIZE / Float32Array.BYTES_PER_ELEMENT;\nexport const PROBE_BLEND_RECORD_CAPACITY = 64;\nexport const PROBE_BLEND_SENTINEL = -1;\n\nexport type ProbeBlendRecordSentinel =\n | 'capacity-exceeded'\n | 'no-active'\n | 'no-lkg'\n | 'outside-radius';\n\nexport interface ProbeBlendRecord {\n readonly objectKey: number;\n readonly generation: number;\n readonly localBlendFraction: number;\n readonly shPreblend: readonly number[];\n readonly bytes: Uint8Array;\n readonly byteLength: number;\n readonly candidate: boolean;\n readonly accepted: boolean;\n readonly lastKnownGood: boolean;\n readonly sentinel?: ProbeBlendRecordSentinel;\n}\n\nexport function emptyProbeBlendRecord(\n objectKey = PROBE_BLEND_SENTINEL,\n sentinel: ProbeBlendRecordSentinel = 'no-lkg',\n): ProbeBlendRecord {\n const bytes = new Uint8Array(PROBE_BLEND_RECORD_BYTE_SIZE);\n return {\n objectKey,\n generation: 0,\n localBlendFraction: 0,\n shPreblend: new Array<number>(27).fill(0),\n bytes,\n byteLength: bytes.byteLength,\n candidate: false,\n accepted: false,\n lastKnownGood: false,\n sentinel,\n };\n}\n\nexport function probeBlendRecordOffset(objectKey: number): number {\n if (!Number.isInteger(objectKey) || objectKey < 0) {\n throw new Error('probe blend record requires a non-negative object key');\n }\n // Lane zero is reserved for the no-LKG sentinel. RenderScene slot identity\n // is the object index, so objectKey N always selects lane N+1.\n return (objectKey + 1) * PROBE_BLEND_RECORD_STRIDE;\n}\n"]}
@@ -1,5 +1,7 @@
1
- import { RenderFeaturePreparedStateMismatchError, SceneDataUnavailableError } from './chunk-WEX45HKH.mjs';
2
- import { err, ok } from '@forgeax/engine-types';
1
+ import { RenderFeaturePreparedStateMismatchError, GPU_TEXTURE_USAGE_RENDER_ATTACHMENT, GPU_TEXTURE_USAGE_TEXTURE_BINDING, GPU_TEXTURE_USAGE_COPY_SRC, SceneDataUnavailableError } from './chunk-MXTWKZO4.mjs';
2
+ import { derive, err, ok } from '@forgeax/engine-types';
3
+ import { ok as ok$1, err as err$1, RhiError } from '@forgeax/engine-rhi';
4
+ import { DEFAULT_STANDARD_PBR_PARAM_SCHEMA } from '@forgeax/engine-shader';
3
5
 
4
6
  // src/pipeline/standard-lighting/layout.ts
5
7
  var DEFAULT_CLUSTER_GRID = { x: 16, y: 9, z: 24 };
@@ -290,7 +292,117 @@ function createSceneDataCatalog(options) {
290
292
  }
291
293
  };
292
294
  }
295
+ var STANDARD_PBR_UBO_SIZE = derive(DEFAULT_STANDARD_PBR_PARAM_SCHEMA).uboLayout.totalBytes;
296
+ var MATERIAL_PER_ENTITY_STRIDE = Math.ceil(STANDARD_PBR_UBO_SIZE / 256) * 256;
297
+ function resolveSurfaceProfile(storageFormat, viewFormat, facts) {
298
+ if (facts.surfaceViewFormats) {
299
+ return ok$1({
300
+ kind: "dual-view",
301
+ storageFormat,
302
+ viewFormat,
303
+ viewFormats: [viewFormat],
304
+ hasDisplayEndpoint: true
305
+ });
306
+ }
307
+ if (!facts.rawAttachment || !facts.floatRenderAttachment) {
308
+ return err$1(
309
+ new RhiError({
310
+ code: "webgpu-runtime-error",
311
+ expected: "raw surface attachment and rgba16float render attachment capabilities",
312
+ hint: "surface profile cannot establish a raw-only linear output route",
313
+ detail: {
314
+ error: {
315
+ code: "surface-raw-endpoint-failed",
316
+ message: "raw-only surface capabilities are incomplete"
317
+ }
318
+ }
319
+ })
320
+ );
321
+ }
322
+ return ok$1({
323
+ kind: "raw-only",
324
+ storageFormat,
325
+ viewFormat: storageFormat,
326
+ viewFormats: [],
327
+ hasDisplayEndpoint: false
328
+ });
329
+ }
330
+ function resolveSurfaceFormatPair(_backendKind, storage, view) {
331
+ return { storage, view };
332
+ }
333
+ function surfaceCapabilityFacts(device, storageFormat) {
334
+ const internal = device;
335
+ return {
336
+ surfaceViewFormats: internal.surfaceViewFormats ?? device.caps?.backendKind !== "wgpu-webgl2",
337
+ rawAttachment: storageFormat === "rgba8unorm" || storageFormat === "bgra8unorm",
338
+ floatRenderAttachment: device.caps?.rgba16floatRenderable ?? true
339
+ };
340
+ }
341
+ function configureSurface(context, device, format, colorAttachmentFormat) {
342
+ const backendKind = device.caps?.backendKind ?? "webgpu";
343
+ const isWebGl2 = backendKind === "wgpu-webgl2";
344
+ const surfaceFormats = resolveSurfaceFormatPair(
345
+ backendKind,
346
+ format,
347
+ colorAttachmentFormat
348
+ );
349
+ const profile = resolveSurfaceProfile(
350
+ surfaceFormats.storage,
351
+ surfaceFormats.view,
352
+ surfaceCapabilityFacts(device, surfaceFormats.storage)
353
+ );
354
+ if (!profile.ok) return profile;
355
+ const supportsTextureBinding = backendKind !== "wgpu-webgl2" && (device.caps?.storageBuffer ?? true);
356
+ const configured = context.configure({
357
+ device,
358
+ format: surfaceFormats.storage,
359
+ alphaMode: isWebGl2 ? "opaque" : "premultiplied",
360
+ usage: GPU_TEXTURE_USAGE_RENDER_ATTACHMENT | (supportsTextureBinding ? GPU_TEXTURE_USAGE_TEXTURE_BINDING : 0) | (isWebGl2 ? 0 : GPU_TEXTURE_USAGE_COPY_SRC),
361
+ viewFormats: [...profile.value.viewFormats]
362
+ });
363
+ if (!configured.ok) return configured;
364
+ if (isWebGl2 && (context.presentationProof === void 0 || !context.presentationProof.descriptor || !context.presentationProof.acquisition || !context.presentationProof.validation || typeof context.presentationProof.surfaceIdentity !== "string" || context.presentationProof.surfaceIdentity.length === 0 || context.presentationProof.requested === void 0 || context.presentationProof.validated === void 0 || JSON.stringify(context.presentationProof.requested) !== JSON.stringify(context.presentationProof.validated))) {
365
+ return err$1(
366
+ new RhiError({
367
+ code: "webgpu-runtime-error",
368
+ expected: "WebGL2 surface storage has descriptor, acquisition, and validation proof",
369
+ hint: "run the concrete presentation probe and retain the last-known-good graph when proof is absent",
370
+ detail: {
371
+ error: {
372
+ code: "surface-raw-endpoint-failed",
373
+ message: "surface storage raw endpoint proof is incomplete"
374
+ }
375
+ }
376
+ })
377
+ );
378
+ }
379
+ return ok$1(void 0);
380
+ }
381
+ function selectSwapChainFormat(storageBufferCapable, surfaceViewFormats = true) {
382
+ if (!storageBufferCapable) {
383
+ return {
384
+ storage: "rgba8unorm",
385
+ view: surfaceViewFormats ? "rgba8unorm-srgb" : "rgba8unorm"
386
+ };
387
+ }
388
+ const nav = globalThis.navigator;
389
+ const gpu = nav?.gpu;
390
+ const getPreferred = gpu?.getPreferredCanvasFormat;
391
+ if (gpu !== void 0 && typeof getPreferred === "function") {
392
+ const storage = getPreferred.call(gpu);
393
+ const view = storage === "rgba8unorm" ? "rgba8unorm-srgb" : storage === "bgra8unorm" ? "bgra8unorm-srgb" : storage;
394
+ return {
395
+ storage,
396
+ view: surfaceViewFormats ? view : storage
397
+ };
398
+ }
399
+ return {
400
+ storage: "rgba8unorm",
401
+ view: surfaceViewFormats ? "rgba8unorm-srgb" : "rgba8unorm",
402
+ fallbackReason: "preferred-canvas-format-missing"
403
+ };
404
+ }
293
405
 
294
- export { CLUSTER_GRID_STRIDE_U32, DEFAULT_CLUSTER_GRID, DEFAULT_STANDARD_PROFILE, LIGHT_INDEX_LIST_CAPACITY, MAX_LIGHTS, REFLECTION_PROBE_IBL_STAGES, SCENE_DATA_TEMPORAL_V1_DESCRIPTOR, SCENE_DATA_TEMPORAL_V1_SCHEMA, STANDARD_LIGHT_COUNTS, STANDARD_PIPELINE_ID, STANDARD_POST_STAGE_NAMES, beginProbeIblUpdate, createIblKernelCache, createProbeIblOutput, createSceneDataCatalog, createStandardClusterLayout, isSceneDataTarget, publishProbeIblOutput, registerSceneDataTarget, resetIblKernelCaches, resolveVolumetricFogProfile, sceneDataError, sceneDataTargetAsAttachment, sceneDataTargetOwner, sceneDataTokenMismatch };
295
- //# sourceMappingURL=chunk-OCDLEI6I.mjs.map
296
- //# sourceMappingURL=chunk-OCDLEI6I.mjs.map
406
+ export { CLUSTER_GRID_STRIDE_U32, DEFAULT_CLUSTER_GRID, DEFAULT_STANDARD_PROFILE, LIGHT_INDEX_LIST_CAPACITY, MATERIAL_PER_ENTITY_STRIDE, MAX_LIGHTS, REFLECTION_PROBE_IBL_STAGES, SCENE_DATA_TEMPORAL_V1_DESCRIPTOR, SCENE_DATA_TEMPORAL_V1_SCHEMA, STANDARD_LIGHT_COUNTS, STANDARD_PBR_UBO_SIZE, STANDARD_PIPELINE_ID, STANDARD_POST_STAGE_NAMES, beginProbeIblUpdate, configureSurface, createIblKernelCache, createProbeIblOutput, createSceneDataCatalog, createStandardClusterLayout, isSceneDataTarget, publishProbeIblOutput, registerSceneDataTarget, resetIblKernelCaches, resolveSurfaceFormatPair, resolveSurfaceProfile, resolveVolumetricFogProfile, sceneDataError, sceneDataTargetAsAttachment, sceneDataTargetOwner, sceneDataTokenMismatch, selectSwapChainFormat };
407
+ //# sourceMappingURL=chunk-SGPUJW3F.mjs.map
408
+ //# sourceMappingURL=chunk-SGPUJW3F.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/pipeline/standard-lighting/layout.ts","../src/pipeline/standard-profile.ts","../src/ibl/kernel-cache.ts","../src/temporal/scene-data.ts","../src/temporal/scene-data-catalog.ts","../src/record/render-context.ts"],"names":["ok","err"],"mappings":";;;;;;AAAO,IAAM,uBAAuB,EAAE,CAAA,EAAG,IAAI,CAAA,EAAG,CAAA,EAAG,GAAG,EAAA;AAC/C,IAAM,uBAAA,GAA0B;AAChC,IAAM,yBAAA,GAA4B;AAClC,IAAM,UAAA,GAAa;AAYnB,SAAS,2BAAA,CACd,OAAuE,oBAAA,EAChD;AACvB,EAAA,MAAM,YAAA,GAAe,IAAA,CAA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V,IAAA,EAAM,+FAAA;AAAA,QACN,MAAA,EAAQ;AAAA,UACN,KAAA,EAAO;AAAA,YACL,IAAA,EAAM,6BAAA;AAAA,YACN,OAAA,EAAS;AAAA;AACX;AACF,OACD;AAAA,KACH;AAAA,EACF;AACA,EAAA,OAAOD,KAAG,MAAS,CAAA;AACrB;AAEO,SAAS,qBAAA,CACd,oBAAA,EACA,kBAAA,GAAqB,IAAA,EACA;AACrB,EAAA,IAAI,CAAC,oBAAA,EAAsB;AACzB,IAAA,OAAO;AAAA,MACL,OAAA,EAAS,YAAA;AAAA,MACT,IAAA,EAAM,qBAAqB,iBAAA,GAAoB;AAAA,KACjD;AAAA,EACF;AACA,EAAA,MAAM,MACJ,UAAA,CACA,SAAA;AACF,EAAA,MAAM,MAAM,GAAA,EAAK,GAAA;AACjB,EAAA,MAAM,eAAe,GAAA,EAAK,wBAAA;AAC1B,EAAA,IAAI,GAAA,KAAQ,MAAA,IAAa,OAAO,YAAA,KAAiB,UAAA,EAAY;AAC3D,IAAA,MAAM,OAAA,GAAU,YAAA,CAAa,IAAA,CAAK,GAAG,CAAA;AACrC,IAAA,MAAM,OACJ,OAAA,KAAY,YAAA,GACR,iBAAA,GACA,OAAA,KAAY,eACV,iBAAA,GACA,OAAA;AACR,IAAA,OAAO;AAAA,MACL,OAAA;AAAA,MACA,IAAA,EAAM,qBAAqB,IAAA,GAAO;AAAA,KACpC;AAAA,EACF;AACA,EAAA,OAAO;AAAA,IACL,OAAA,EAAS,YAAA;AAAA,IACT,IAAA,EAAM,qBAAqB,iBAAA,GAAoB,YAAA;AAAA,IAC/C,cAAA,EAAgB;AAAA,GAClB;AACF","file":"chunk-SGPUJW3F.mjs","sourcesContent":["export const DEFAULT_CLUSTER_GRID = { x: 16, y: 9, z: 24 } as const;\nexport const CLUSTER_GRID_STRIDE_U32 = 2 as const;\nexport const LIGHT_INDEX_LIST_CAPACITY = 1048576 as const;\nexport const MAX_LIGHTS = 256 as const;\n\nexport interface StandardClusterLayout {\n readonly grid: { readonly x: number; readonly y: number; readonly z: number };\n readonly clusterCount: number;\n readonly clusterGridStrideU32: typeof CLUSTER_GRID_STRIDE_U32;\n readonly clusterGridU32Length: number;\n readonly lightIndexListCapacity: typeof LIGHT_INDEX_LIST_CAPACITY;\n readonly lightDataSlotCount: typeof MAX_LIGHTS;\n readonly lightBoundsInt32Length: number;\n}\n\nexport function createStandardClusterLayout(\n grid: { readonly x: number; readonly y: number; readonly z: number } = DEFAULT_CLUSTER_GRID,\n): StandardClusterLayout {\n const clusterCount = grid.x * grid.y * grid.z;\n return Object.freeze({\n grid,\n clusterCount,\n clusterGridStrideU32: CLUSTER_GRID_STRIDE_U32,\n clusterGridU32Length: clusterCount * CLUSTER_GRID_STRIDE_U32,\n lightIndexListCapacity: LIGHT_INDEX_LIST_CAPACITY,\n lightDataSlotCount: MAX_LIGHTS,\n lightBoundsInt32Length: MAX_LIGHTS * 6,\n });\n}\n\nexport const STANDARD_CLUSTER_LAYOUT = createStandardClusterLayout();\n","import type { SsaoParameterConfig } from '../ssao-config';\nexport const STANDARD_PIPELINE_ID = 'forgeax::standard' as const;\nexport const STANDARD_LIGHT_COUNTS = [1, 32, 256] as const;\nexport {\n CLUSTER_GRID_STRIDE_U32,\n DEFAULT_CLUSTER_GRID,\n LIGHT_INDEX_LIST_CAPACITY,\n MAX_LIGHTS,\n} from './standard-lighting/layout';\n\nexport type StandardLightCount = (typeof STANDARD_LIGHT_COUNTS)[number];\nexport type StandardShadowMode = 'off' | 'hard' | 'filtered';\nexport type StandardVolumetricFogQuality = 'low' | 'high';\n\nexport interface StandardVolumetricFogProfile {\n readonly quality: StandardVolumetricFogQuality;\n readonly depth: 48 | 64;\n readonly tileSize: 4 | 16;\n}\n\nexport const STANDARD_POST_STAGE_NAMES = [\n 'transparent-blend',\n 'bloom',\n 'output-transform',\n 'fxaa',\n 'post-effect',\n 'present',\n] as const;\nexport type StandardPostStage = (typeof STANDARD_POST_STAGE_NAMES)[number];\nexport interface StandardProfile {\n readonly pipelineId: typeof STANDARD_PIPELINE_ID;\n readonly lightCount: StandardLightCount;\n /** Graph topology selector; all local lights use the shared Cluster path. */\n readonly renderPath: 'forward' | 'deferred';\n readonly shadows: StandardShadowMode;\n readonly pbr: boolean;\n readonly ibl: boolean;\n readonly ssao: boolean | SsaoParameterConfig;\n /** Renderer-owned 1080p volume profile; tile width/height remain surface-derived. */\n readonly volumetricFog?: StandardVolumetricFogProfile | undefined;\n readonly postStages: typeof STANDARD_POST_STAGE_NAMES;\n}\n\nexport const DEFAULT_STANDARD_PROFILE: StandardProfile = Object.freeze({\n pipelineId: STANDARD_PIPELINE_ID,\n lightCount: 32,\n renderPath: 'forward',\n shadows: 'filtered',\n pbr: true,\n ibl: true,\n ssao: false,\n postStages: STANDARD_POST_STAGE_NAMES,\n});\n\nexport function resolveVolumetricFogProfile(\n profile: Pick<StandardProfile, 'volumetricFog'>,\n): StandardVolumetricFogProfile {\n return profile.volumetricFog ?? { quality: 'high', depth: 64, tileSize: 4 };\n}\n","export const REFLECTION_PROBE_IBL_STAGES = ['raw', 'filtered', 'publish'] as const;\nexport type ReflectionProbeIblStage = (typeof REFLECTION_PROBE_IBL_STAGES)[number];\n\nexport interface IblKernelCache {\n readonly generation: number;\n readonly pipelineIdentity: object;\n readonly samplerIdentity: object;\n readonly brdfLutIdentity: object;\n}\n\nconst kernelCaches = new Map<number, IblKernelCache>();\n\nexport function createIblKernelCache(generation: number): IblKernelCache {\n const existing = kernelCaches.get(generation);\n if (existing !== undefined) return existing;\n const created: IblKernelCache = {\n generation,\n pipelineIdentity: {},\n samplerIdentity: {},\n brdfLutIdentity: {},\n };\n kernelCaches.set(generation, created);\n return created;\n}\n\nexport interface ProbeIblOutput {\n readonly entityKey: number;\n readonly resolution: number;\n readonly deviceGeneration: number;\n readonly raw: object;\n readonly filtered: object;\n readonly rawGeneration: number;\n readonly filteredGeneration: number;\n readonly lkg: boolean;\n}\n\nexport interface ProbeIblUpdate extends ProbeIblOutput {\n readonly stages: typeof REFLECTION_PROBE_IBL_STAGES;\n readonly nextStage: ReflectionProbeIblStage;\n readonly candidateGeneration: number;\n}\n\nexport function createProbeIblOutput(input: {\n readonly entityKey: number;\n readonly resolution: number;\n readonly deviceGeneration: number;\n}): ProbeIblOutput {\n return {\n ...input,\n raw: {},\n filtered: {},\n rawGeneration: 0,\n filteredGeneration: 0,\n lkg: true,\n };\n}\n\nexport function beginProbeIblUpdate(output: ProbeIblOutput): ProbeIblUpdate {\n return {\n ...output,\n stages: REFLECTION_PROBE_IBL_STAGES,\n nextStage: 'raw',\n candidateGeneration: output.filteredGeneration + 1,\n };\n}\n\nexport function publishProbeIblOutput(\n update: ProbeIblUpdate,\n result: { readonly stage: ReflectionProbeIblStage; readonly ok: boolean },\n): ProbeIblOutput {\n if (!result.ok || result.stage !== update.nextStage) return update;\n if (result.stage === 'raw') {\n return {\n ...update,\n rawGeneration: update.candidateGeneration,\n };\n }\n if (result.stage === 'filtered') return update;\n return {\n ...update,\n filteredGeneration: update.candidateGeneration,\n lkg: true,\n };\n}\n\nexport function resetIblKernelCaches(): void {\n kernelCaches.clear();\n}\n","import { type RenderError, RenderFeaturePreparedStateMismatchError } from '../errors/render';\nimport type { RenderFeatureTargetHandle } from '../features/targets';\n\n/** The closed semantic schema namespace published by the render owner. */\nexport const SCENE_DATA_TEMPORAL_V1_SCHEMA = 'forgeax::scene-data::temporal-v1' as const;\nexport type SceneDataSchemaId = typeof SCENE_DATA_TEMPORAL_V1_SCHEMA;\n\nexport type SceneDataLane = 'direct' | 'clustered' | 'cpu-webgl2';\n\nexport interface SceneDataTemporalV1Descriptor {\n readonly schema: typeof SCENE_DATA_TEMPORAL_V1_SCHEMA;\n readonly format: 'rgba16float';\n readonly sampleCount: 1;\n readonly extent: 'render-resolution';\n readonly clearValue: readonly [0, 0, -1, 1];\n readonly channels: Readonly<{\n readonly motionUv: 'rg';\n readonly viewDepth: 'b-log2-1-plus-depth';\n readonly reactive: 'a';\n }>;\n}\n\nexport const SCENE_DATA_TEMPORAL_V1_DESCRIPTOR: SceneDataTemporalV1Descriptor = Object.freeze({\n schema: SCENE_DATA_TEMPORAL_V1_SCHEMA,\n format: 'rgba16float',\n sampleCount: 1,\n extent: 'render-resolution',\n clearValue: [0, 0, -1, 1] as const,\n channels: Object.freeze({\n motionUv: 'rg',\n viewDepth: 'b-log2-1-plus-depth',\n reactive: 'a',\n }),\n});\n\n/** Opaque, sampled-read-only semantic data token. */\nexport interface SceneDataTarget<Schema extends SceneDataSchemaId = SceneDataSchemaId> {\n readonly kind: 'scene-data';\n readonly schema: Schema;\n readonly access: 'sampled-read';\n readonly format: 'rgba16float';\n readonly sampleCount: 1;\n readonly extent: 'render-resolution';\n readonly __sceneDataTarget: unique symbol;\n}\n\nexport type SceneDataTokenMismatch = RenderFeaturePreparedStateMismatchError;\n\nconst targetOwners = new WeakMap<object, SceneDataCatalogIdentity>();\n\nexport interface SceneDataCatalogIdentity {\n readonly featureIdentity: string;\n readonly planIdentity: string;\n readonly generation: number;\n}\n\nexport function registerSceneDataTarget(\n target: SceneDataTarget,\n owner: SceneDataCatalogIdentity,\n): void {\n targetOwners.set(target, owner);\n}\n\nexport function sceneDataTargetOwner(\n target: SceneDataTarget,\n): SceneDataCatalogIdentity | undefined {\n return typeof target === 'object' && target !== null ? targetOwners.get(target) : undefined;\n}\n\nexport function sceneDataTokenMismatch(\n operation: string,\n reason: 'foreign-feature' | 'foreign-kind' | 'generation-mismatch' | 'layout-mismatch',\n owner: SceneDataCatalogIdentity,\n target: Partial<SceneDataTarget> | undefined,\n): SceneDataTokenMismatch {\n const detail =\n reason === 'generation-mismatch'\n ? {\n featureIdentity: owner.featureIdentity,\n order: -1,\n stage: 'contribute' as const,\n operation,\n resourceKind: 'attachment' as const,\n reason,\n expectedGeneration: owner.generation,\n actualGeneration: targetOwners.get(target as object)?.generation ?? -1,\n recovery: 'renderer-recover' as const,\n }\n : reason === 'foreign-feature'\n ? {\n featureIdentity: owner.featureIdentity,\n order: -1,\n stage: 'contribute' as const,\n operation,\n resourceKind: 'attachment' as const,\n reason,\n expectedFeatureIdentity: owner.featureIdentity,\n actualFeatureIdentity: targetOwners.get(target as object)?.featureIdentity ?? 'unknown',\n recovery: 'next-frame' as const,\n }\n : reason === 'foreign-kind'\n ? {\n featureIdentity: owner.featureIdentity,\n order: -1,\n stage: 'contribute' as const,\n operation,\n resourceKind: 'attachment' as const,\n reason,\n expectedKind: 'attachment' as const,\n actualKind: 'pipeline' as const,\n recovery: 'next-frame' as const,\n }\n : {\n featureIdentity: owner.featureIdentity,\n order: -1,\n stage: 'contribute' as const,\n operation,\n resourceKind: 'attachment' as const,\n reason,\n expectedLayout: 'sampled-read-temporal-v1',\n actualLayout: target?.access ?? 'unknown',\n recovery: 'next-frame' as const,\n };\n return new RenderFeaturePreparedStateMismatchError(detail);\n}\n\nexport function isSceneDataTarget(value: unknown): value is SceneDataTarget {\n if (value === null || typeof value !== 'object') return false;\n const candidate = value as Partial<SceneDataTarget>;\n return (\n candidate.kind === 'scene-data' &&\n candidate.schema === SCENE_DATA_TEMPORAL_V1_SCHEMA &&\n candidate.access === 'sampled-read' &&\n candidate.format === 'rgba16float' &&\n candidate.sampleCount === 1 &&\n candidate.extent === 'render-resolution' &&\n targetOwners.has(value)\n );\n}\n\nexport function sceneDataTargetAsAttachment(_target: SceneDataTarget): never {\n throw new TypeError('SceneDataTarget is sampled-read-only and cannot be used as an attachment');\n}\n\nexport type SceneDataTargetInput = RenderFeatureTargetHandle | SceneDataTarget;\n\nexport function sceneDataError(error: SceneDataTokenMismatch): RenderError {\n return error;\n}\n","import { err, ok, type Result } from '@forgeax/engine-types';\nimport type { RenderError } from '../errors/render';\nimport { SceneDataUnavailableError } from '../errors/render';\nimport {\n registerSceneDataTarget,\n SCENE_DATA_TEMPORAL_V1_DESCRIPTOR,\n SCENE_DATA_TEMPORAL_V1_SCHEMA,\n type SceneDataLane,\n type SceneDataSchemaId,\n type SceneDataTarget,\n sceneDataTargetOwner,\n sceneDataTokenMismatch,\n} from './scene-data';\n\nexport type SceneDataAvailability =\n | {\n readonly status: 'available';\n readonly completeness: 'exact' | 'exact-with-reactive-fallback';\n }\n | {\n readonly status: 'unavailable';\n readonly reason:\n | 'capability-missing'\n | 'producer-missing'\n | 'coverage-incomplete'\n | 'renderer-recovering';\n };\n\nexport interface SceneDataInspection {\n readonly schema: SceneDataSchemaId;\n readonly status: SceneDataAvailability['status'];\n readonly generation: number;\n readonly planIdentity: string;\n readonly lane: SceneDataLane;\n readonly completeness?: 'exact' | 'exact-with-reactive-fallback';\n readonly reason?: Exclude<SceneDataAvailability, { status: 'available' }>['reason'];\n readonly missingContributorIds: readonly string[];\n readonly omittedMissingContributorCount: number;\n}\n\nexport interface SceneDataCatalogOptions {\n readonly featureIdentity: string;\n readonly generation: number;\n readonly planIdentity: string;\n readonly lane?: SceneDataLane;\n readonly rgba16floatRenderable: boolean;\n readonly producerPresent?: boolean;\n readonly coverageComplete?: boolean;\n readonly recovering?: boolean;\n readonly reactiveFallback?: boolean;\n readonly missingContributorIds?: readonly string[];\n}\n\nexport interface SceneDataCatalog {\n readonly schema: typeof SCENE_DATA_TEMPORAL_V1_SCHEMA;\n readonly generation: number;\n readonly planIdentity: string;\n readonly availability: SceneDataAvailability;\n require<Schema extends SceneDataSchemaId>(schema: Schema): SceneDataTarget<Schema>;\n validate(target: SceneDataTarget, generation?: number): Result<SceneDataTarget, RenderError>;\n inspect(): SceneDataInspection;\n}\n\nfunction availability(options: SceneDataCatalogOptions): SceneDataAvailability {\n if (options.recovering) return { status: 'unavailable', reason: 'renderer-recovering' };\n if (!options.rgba16floatRenderable)\n return { status: 'unavailable', reason: 'capability-missing' };\n if (options.producerPresent === false)\n return { status: 'unavailable', reason: 'producer-missing' };\n if (options.coverageComplete === false)\n return { status: 'unavailable', reason: 'coverage-incomplete' };\n return {\n status: 'available',\n completeness: options.reactiveFallback ? 'exact-with-reactive-fallback' : 'exact',\n };\n}\n\nfunction createTarget(owner: SceneDataCatalogOptions): SceneDataTarget {\n const target = Object.freeze({\n kind: 'scene-data' as const,\n schema: SCENE_DATA_TEMPORAL_V1_SCHEMA,\n access: 'sampled-read' as const,\n format: 'rgba16float' as const,\n sampleCount: 1 as const,\n extent: 'render-resolution' as const,\n }) as SceneDataTarget;\n registerSceneDataTarget(target, {\n featureIdentity: owner.featureIdentity,\n planIdentity: owner.planIdentity,\n generation: owner.generation,\n });\n return target;\n}\n\nfunction tokenError(catalog: SceneDataCatalogOptions, operation: string): RenderError {\n return sceneDataTokenMismatch(\n operation,\n 'foreign-kind',\n {\n featureIdentity: catalog.featureIdentity,\n planIdentity: catalog.planIdentity,\n generation: catalog.generation,\n },\n undefined,\n );\n}\n\nfunction unavailableError(\n options: SceneDataCatalogOptions,\n reason: Exclude<SceneDataAvailability, { status: 'available' }>['reason'],\n): RenderError {\n const recovery =\n reason === 'capability-missing'\n ? 'enable-capability'\n : reason === 'renderer-recovering'\n ? 'renderer-recover'\n : 'next-frame';\n return new SceneDataUnavailableError({\n featureIdentity: options.featureIdentity,\n schema: SCENE_DATA_TEMPORAL_V1_SCHEMA,\n lane: options.lane ?? 'direct',\n reason,\n missingContributorIds: options.missingContributorIds ?? [],\n omittedMissingContributorCount: 0,\n recovery,\n });\n}\n\nexport function createSceneDataCatalog(options: SceneDataCatalogOptions): SceneDataCatalog {\n const state = availability(options);\n const owner = {\n featureIdentity: options.featureIdentity,\n planIdentity: options.planIdentity,\n generation: options.generation,\n };\n const missing = [...(options.missingContributorIds ?? [])];\n const inspectionBase = {\n schema: SCENE_DATA_TEMPORAL_V1_SCHEMA,\n generation: options.generation,\n planIdentity: options.planIdentity,\n lane: options.lane ?? 'direct',\n missingContributorIds: Object.freeze(missing.slice(0, 32)),\n omittedMissingContributorCount: Math.max(0, missing.length - 32),\n };\n return {\n schema: SCENE_DATA_TEMPORAL_V1_SCHEMA,\n generation: options.generation,\n planIdentity: options.planIdentity,\n availability: state,\n require(schema) {\n if (schema !== SCENE_DATA_TEMPORAL_V1_SCHEMA || state.status !== 'available') {\n if (state.status === 'unavailable') throw unavailableError(options, state.reason);\n throw tokenError(options, 'require scene-data target');\n }\n return createTarget(options) as SceneDataTarget<typeof schema>;\n },\n validate(target, generation = options.generation) {\n const targetOwner = sceneDataTargetOwner(target);\n if (targetOwner === undefined) {\n return err(\n sceneDataTokenMismatch('validate scene-data target', 'foreign-feature', owner, target),\n );\n }\n if (\n targetOwner.planIdentity !== owner.planIdentity ||\n targetOwner.featureIdentity !== owner.featureIdentity\n ) {\n return err(\n sceneDataTokenMismatch('validate scene-data target', 'foreign-feature', owner, target),\n );\n }\n if (generation !== owner.generation || targetOwner.generation !== owner.generation) {\n return err(\n sceneDataTokenMismatch(\n 'validate scene-data target',\n 'generation-mismatch',\n owner,\n target,\n ),\n );\n }\n if (target.access !== 'sampled-read') {\n return err(\n sceneDataTokenMismatch('validate scene-data target', 'layout-mismatch', owner, target),\n );\n }\n return ok(target);\n },\n inspect() {\n return Object.freeze(\n state.status === 'available'\n ? { ...inspectionBase, status: state.status, completeness: state.completeness }\n : { ...inspectionBase, status: state.status, reason: state.reason },\n );\n },\n };\n}\n\nexport { SCENE_DATA_TEMPORAL_V1_SCHEMA } from './scene-data';\nexport { SCENE_DATA_TEMPORAL_V1_DESCRIPTOR };\n","import type { AssetRegistry, DynamicTextureStore } from '@forgeax/engine-assets-runtime';\nimport type { VertexLayoutProjection } from '@forgeax/engine-geometry';\nimport type { Profiler } from '@forgeax/engine-profiler';\nimport type { CompiledRenderGraphInfo } from '@forgeax/engine-render-graph';\nimport type {\n BindGroup,\n BindGroupLayout,\n Buffer,\n ComputePipeline,\n PipelineLayout,\n Result,\n RhiCanvasContext,\n RhiCommandEncoder,\n RhiDevice,\n RenderPipeline as RhiRenderPipeline,\n Sampler,\n ShaderModule,\n Texture,\n TextureFormat,\n TextureView,\n} from '@forgeax/engine-rhi';\nimport { err, ok, RhiError } from '@forgeax/engine-rhi';\nimport {\n DEFAULT_STANDARD_PBR_PARAM_SCHEMA,\n type MaterialRuntimeArtifact,\n type MaterialShaderArtifact,\n} from '@forgeax/engine-shader';\nimport type {\n MaterialAsset,\n MaterialRenderState,\n ParamSchemaEntry,\n PassKind,\n PrimitiveTopology,\n VertexAttributeMap,\n} from '@forgeax/engine-types';\nimport { derive } from '@forgeax/engine-types';\nimport type { MaterialRenderProjection } from '../assembly/material/assembly';\nimport type { DeviceScope } from '../device/device-scope';\nimport type { MeshGpuHandles } from '../device/gpu-residency';\nimport type { EngineMetrics } from '../engine-metrics';\nimport type { RenderFeatureHost } from '../features/host';\nimport type { RenderFeatureShaderModuleMode } from '../features/types';\nimport type { GpuDrivenPbrProgram } from '../gpu-driven/pbr-program';\nimport type { GpuDrivenShadowBatchProjection } from '../gpu-driven/production-raster';\nimport type { ShadowViewStatePool } from '../gpu-driven/shadow-views';\nimport {\n GPU_TEXTURE_USAGE_COPY_SRC,\n GPU_TEXTURE_USAGE_RENDER_ATTACHMENT,\n GPU_TEXTURE_USAGE_TEXTURE_BINDING,\n} from '../gpu-texture-usage';\nimport type { SkylightFallback } from '../ibl/skylight-bind-group';\nimport type { BloomInspection } from '../inspection-types';\nimport type { HealthListenerRegistry, RhiErrorListenerRegistry } from '../lifecycle';\nimport type { PipelineGroup2Contract } from '../pbr-pipeline';\nimport type { StandardTopologyInputValue } from '../pipeline/standard-lighting/topology';\nimport type { StandardProfile } from '../pipeline/standard-profile';\nimport type { PipelineBuilderShaderModuleFactory } from '../pipeline-builder';\nimport type { PointsLinesInspection } from '../points-lines/inspection';\nimport type { PointsLinesRecordPlan } from '../points-lines/record';\nimport type { RenderResourceScope } from '../publication/resource-scope';\nimport type { ReflectionProbeTable } from '../reflection/gpu-table';\nimport type { ReflectionProbeSelectionResult } from '../reflection/projection';\nimport type { FrameObservationDomain } from '../render-contract';\nimport type { SsrAdmissionIdentity } from '../ssr/identity';\nimport type { TypedFrameObservationCapture } from '../typed-render-graph-primitives';\nimport type { GpuPassTimingReason } from './gpu-pass-timing/errors';\nimport type {\n GpuPassTimingCapture,\n GpuPassTimingFrameIdentity,\n GpuPassTimingSession,\n} from './gpu-pass-timing/session';\n\nexport interface PointsLinesRecordSubmission {\n readonly plan: PointsLinesRecordPlan;\n readonly vertexBuffer: Buffer;\n readonly indexBuffer: Buffer;\n readonly layoutProjection: VertexLayoutProjection;\n}\n\nexport interface ReflectionProbeRecordState {\n readonly table: ReflectionProbeTable;\n readonly selections: ReadonlyMap<string, ReflectionProbeSelectionResult>;\n readonly graph: import('./typed-frame-graph').ReflectionProbeGraphState;\n /** Detached committed fallback projections joined by main-pass renderable key. */\n readonly fallbackProjections?: ReadonlyMap<\n string,\n import('../inspection-types').ReflectionFallbackReceipt\n >;\n /** Demand is derived from this frame's renderable/source selection. */\n readonly fallbackDemand?: boolean;\n /** Non-neutral sources require a nonzero diagnostic sample when capture is enabled. */\n readonly fallbackHasNonNeutral?: boolean;\n readonly completeSubmission: (\n submitted: boolean,\n completed?: Promise<unknown>,\n fallbackOutput?: {\n readonly format: TextureFormat;\n readonly size: { readonly width: number; readonly height: number };\n readonly frameId: number;\n readonly graphGeneration: number;\n readonly textureIdentity: number;\n readonly readback?: Promise<{\n readonly linearHdr: readonly [number, number, number, number];\n readonly hash: string;\n readonly graphGeneration: number;\n readonly textureIdentity: number;\n }>;\n },\n fallbackRequested?: boolean,\n ) => Promise<void>;\n}\n\nexport interface MaterialShaderPipelineEntry {\n readonly pipeline: RhiRenderPipeline;\n readonly group2Contract: PipelineGroup2Contract;\n /** Producer receipt for the exact artifact selected with this pipeline. */\n readonly receipt?: {\n readonly identity: string;\n readonly generation: number;\n };\n}\n\nimport type {\n AtmosphereShaderSources,\n RenderDebugOverlay,\n RenderPipelineContext,\n RenderRecordPhase,\n SsrShaderSources,\n VolumetricFogShaderSources,\n} from '../render-contract';\nimport type { GpuDrivenStandardPbrFrameResources } from '../render-pipeline';\nimport type {\n DispatchEntry,\n MaterialSnapshot,\n ShadowCasterMembership,\n SkyboxSnapshot,\n SkylightSnapshot,\n} from '../render-system-extract';\nimport type { SkinPaletteAllocator } from '../systems/skin-palette-allocator';\nimport type { RenderTarget } from '../targets/contracts';\nimport type { RenderTargetPhysical } from '../targets/physical';\nimport type {\n BindGroupCounts,\n BloomFrameReceipts,\n DispatchCounts,\n MaterialBgAssemblyCacheEntry,\n RenderFrameState,\n ValidatedRenderable,\n} from './frame-snapshot';\nimport type { FoldDispatchPlan } from './mesh-ssbo';\n\n/**\n * Armed only for the first published recovery frame. Candidate preparation\n * must make every pipeline and static residency lookup a cache hit before this\n * guard is armed; a miss during draw is a hard failure before queue submission.\n * Explicit preparation between draws remains allowed, including new geometry\n * admitted on the first fixed step after device recovery.\n */\nexport interface RecoveryColdWorkGuard {\n arm(): void;\n beginFrame(): void;\n endFrame(): void;\n notePipelineColdWork(): void;\n noteUploadColdWork(): void;\n finish(): void;\n}\n\nexport interface RenderSystemRuntime {\n readonly device: RhiDevice;\n /** Current renderer device generation used to fence receipt-bound captures. */\n readonly deviceGeneration?: number;\n /** Public receipt identity reserved before graph encoding. */\n readonly observationFrameId?: number | undefined;\n /** Graph identity written by the typed graph for the current receipt. */\n observationGraphGeneration?: number | undefined;\n /** Renderer-owned capture bridge consumed after queue submission. */\n readonly observationCaptureOwner?:\n | {\n register(capture: TypedFrameObservationCapture): void;\n consume(frameNumber: number): readonly TypedFrameObservationCapture[];\n drain(): readonly TypedFrameObservationCapture[];\n }\n | undefined;\n /** Internal backend-fixture hook evaluated at the submit transaction edge. */\n readonly beforeSubmit?: ((device: RhiDevice) => RhiError | undefined) | undefined;\n readonly deviceScope: DeviceScope;\n /** Domains explicitly armed for the frame being encoded. */\n readonly observationCaptureDomains?: readonly FrameObservationDomain[] | undefined;\n /** Resolve a recorder/backend wrapper before configuring the native surface. */\n readonly resolveSurfaceDevice?: (device: RhiDevice) => Result<RhiDevice, RhiError>;\n readonly errorRegistry: RhiErrorListenerRegistry;\n readonly debugOverlay?: RenderDebugOverlay | undefined;\n readonly healthRegistry: HealthListenerRegistry;\n readonly getMaterialProjectionForPayload?: (\n material: MaterialAsset,\n ) => MaterialRenderProjection | undefined;\n readonly getMaterialProjection?: (materialGuid: string) => MaterialRenderProjection | undefined;\n readonly getMaterialArtifact?: (specializationKey: string) => MaterialRuntimeArtifact | undefined;\n /** Producer-owned cooked Standard PBR artifact used by GPU-driven projection. */\n readonly getMaterialShaderArtifact?: (\n materialShaderId: string,\n request?:\n | {\n readonly vertexColorAvailable?: boolean;\n readonly deformation?: 'rigid' | 'skin';\n readonly variantSet?: string;\n readonly clustered?: boolean;\n readonly reflectionFallback?: boolean;\n readonly pass?: 'forward' | 'shadow' | 'depth';\n readonly address?: 'direct' | 'scene-index';\n }\n | boolean,\n ) => MaterialShaderArtifact | undefined;\n readonly getMaterialShaderPipeline?: (\n materialShaderId: string,\n isHdr: boolean,\n renderState?: MaterialRenderState,\n topology?: PrimitiveTopology,\n indexFormat?: 'uint16' | 'uint32',\n variantSet?: string,\n passKind?: PassKind,\n meshAttributes?: VertexAttributeMap,\n sampleCount?: number,\n colorFormatOverride?: GPUTextureFormat,\n shaderUvSetCount?: number,\n depthFormatOverride?: GPUTextureFormat | null,\n vertexLayout?: string,\n vertexLayoutProjection?: VertexLayoutProjection,\n shaderModuleMode?: RenderFeatureShaderModuleMode,\n layoutKindOverride?:\n | 'pbr'\n | 'pbr-skin'\n | 'gpu-driven-pbr'\n | 'gpu-driven-skin'\n | 'gpu-driven-cluster-pbr'\n | 'gpu-driven-cluster-skin'\n | 'surface-direct-pbr'\n | 'surface-direct-cluster-pbr',\n /** Optional vertex entry override for receipt-owned scene-index passes. */\n vertexEntryPoint?: string,\n additionalColorFormats?: readonly GPUTextureFormat[],\n vertexEntry?: string,\n fragmentEntry?: string,\n particleInputLanes?: number,\n fragmentConstants?: Readonly<Record<string, number>>,\n ) => RhiRenderPipeline | null;\n readonly getMaterialShaderPipelineEntry?: (\n materialShaderId: string,\n isHdr: boolean,\n renderState?: MaterialRenderState,\n topology?: PrimitiveTopology,\n indexFormat?: 'uint16' | 'uint32',\n variantSet?: string,\n passKind?: PassKind,\n meshAttributes?: VertexAttributeMap,\n sampleCount?: number,\n colorFormatOverride?: GPUTextureFormat,\n shaderUvSetCount?: number,\n depthFormatOverride?: GPUTextureFormat | null,\n vertexLayout?: string,\n vertexLayoutProjection?: VertexLayoutProjection,\n shaderModuleMode?: RenderFeatureShaderModuleMode,\n layoutKindOverride?:\n | 'pbr'\n | 'pbr-skin'\n | 'gpu-driven-pbr'\n | 'gpu-driven-skin'\n | 'gpu-driven-cluster-pbr'\n | 'gpu-driven-cluster-skin'\n | 'surface-direct-pbr'\n | 'surface-direct-cluster-pbr',\n /** Optional vertex entry override for receipt-owned scene-index passes. */\n vertexEntryPoint?: string,\n additionalColorFormats?: readonly GPUTextureFormat[],\n vertexEntry?: string,\n fragmentEntry?: string,\n particleInputLanes?: number,\n fragmentConstants?: Readonly<Record<string, number>>,\n ) => MaterialShaderPipelineEntry | null;\n /** Reflection-derived UV count included in the material PipelineSpec cache key. */\n readonly getMaterialShaderUvSetCount?: (materialShaderId: string) => number | undefined;\n readonly getMaterialShaderBindingContract?: (\n materialShaderId: string,\n ) =>\n | 'group-0'\n | 'group-0-resource'\n | 'view-only'\n | 'view-and-scene-depth'\n | 'render-material-with-scene-depth'\n | 'render-material-and-scene-depth'\n | 'render-material';\n readonly getParamSchema?: (materialShaderId: string) => readonly ParamSchemaEntry[] | undefined;\n readonly getMaterialBindGroupLayout?: (\n materialShaderId: string,\n materialParamSchema?: readonly ParamSchemaEntry[],\n ) => BindGroupLayout | undefined;\n /** Handle-first factory for built-in same-frame GPU producers. */\n readonly immediateShaderModuleFactory?: PipelineBuilderShaderModuleFactory;\n /** Optional guard for the first recovery frame's cold-work boundary. */\n readonly recoveryColdWorkGuard?: RecoveryColdWorkGuard | undefined;\n readonly metrics: EngineMetrics;\n readonly lookupPostProcess?: (\n id: string,\n ) => import('../fullscreen-post-process-pass').PostProcessShaderEntry | undefined;\n readonly getPostProcessParamsBuffer?: (id: string) => Buffer | undefined;\n readonly getPostProcessPipeline?: (\n id: string,\n bgl: BindGroupLayout,\n colorFormats: readonly GPUTextureFormat[],\n entry?: import('../fullscreen-post-process-pass').PostProcessShaderEntry,\n ) => RhiRenderPipeline | null;\n /** Candidate-owned post-process pipelines transferred at publication. */\n readonly getRecoveryPostProcessPipelines?: () => ReadonlyMap<string, RhiRenderPipeline>;\n readonly clearPostProcessPipelineCache?: (id: string) => void;\n readonly invalidateShaderModule?: (label: string) => void;\n readonly dynamicTextureStore?: DynamicTextureStore | undefined;\n /** Resolves a render-target source to the active generation-owned GPU view. */\n readonly resolveRenderTargetTextureSource?: (\n source: import('../targets/contracts').RenderTargetTextureSource,\n ) => import('../targets/material-source').RenderTargetMaterialSourceBinding | undefined;\n}\n\n/** Renderer-owned bridge from retained Points/Lines facts into main geometry. */\nexport interface PointsLinesRecordOwner {\n prepare(entry: ValidatedRenderable, clustered: boolean): PointsLinesRecordSubmission | undefined;\n beginFrame(): void;\n resetForDeviceLoss(): void;\n inspections(): readonly PointsLinesInspection[];\n}\n\nexport interface PerPassResources {\n depthTexture: Texture | null;\n depthTextureView: TextureView | null;\n depthTextureWidth: number;\n depthTextureHeight: number;\n configured: boolean;\n hdrColorTexture: Texture | null;\n hdrColorView: TextureView | null;\n hdrDepthTexture: Texture | null;\n hdrDepthView: TextureView | null;\n hdrTextureWidth: number;\n hdrTextureHeight: number;\n hdrDepthSampleCount: number;\n readonly fxaaPipeline: RhiRenderPipeline | null;\n readonly fxaaBindGroupLayout: BindGroupLayout | null;\n readonly fxaaSampler: Sampler | null;\n msaaColorTexture: Texture | null;\n msaaColorView: TextureView | null;\n msaaSpriteColorTexture: Texture | null;\n msaaSpriteColorView: TextureView | null;\n msaaDepthTexture: Texture | null;\n msaaDepthView: TextureView | null;\n msaaTextureWidth: number;\n msaaTextureHeight: number;\n hdrColorMsaaTexture: Texture | null;\n hdrColorMsaaView: TextureView | null;\n readonly skyboxPipeline: RhiRenderPipeline | null;\n readonly skyboxPipelineMsaa: RhiRenderPipeline | null;\n readonly skyboxBindGroupLayout: BindGroupLayout | null;\n readonly skyboxSampler: Sampler | null;\n readonly skyboxRotationBuffer: Buffer | null;\n bloomDownsamplePipeline: RhiRenderPipeline | null;\n bloomUpsamplePipeline: RhiRenderPipeline | null;\n bloomCompositePipeline: RhiRenderPipeline | null;\n bloomDownsampleBindGroupLayout: BindGroupLayout | null;\n bloomUpsampleBindGroupLayout: BindGroupLayout | null;\n bloomCompositeBindGroupLayout: BindGroupLayout | null;\n bloomSampler: Sampler | null;\n bloomDownsampleParamsBuffer: Buffer | null;\n bloomUpsampleParamsBuffer: Buffer | null;\n bloomCompositeParamsBuffer: Buffer | null;\n ensureBloomResources?: () => void;\n getBloomResources?: () => BloomPersistentBundle | null;\n commitBloomResources?: () => void;\n commitBloomFrameReceipts?: (receipts: BloomFrameReceipts) => void;\n discardBloomResources?: () => void;\n retireBloomResources?: (completion: Promise<unknown>) => void;\n /** Drain candidate, active, and fence-retiring Bloom generations. */\n drainBloomResources?: () => void;\n inspectBloomResources?: (graph?: CompiledRenderGraphInfo) => BloomInspection;\n ssaoCalcPipeline: RhiRenderPipeline | null;\n ssaoBlurPipeline: RhiRenderPipeline | null;\n ssaoBgl: BindGroupLayout | null;\n ssaoFilteringSampler: Sampler | null;\n ssaoDepthSampler: Sampler | null;\n ssaoFallbackRawView: TextureView | null;\n shadowTexture: Texture | null;\n shadowMapSize: number;\n shadowCascadeCount: number;\n shadowSampler: Sampler | null;\n shadowLightSpaceMatrix: Float32Array | null;\n shadowCsmLightViewProj: Float32Array | null;\n shadowCsmSelection: {\n readonly viewMatrix: Float32Array;\n readonly splitPlanes: Float32Array;\n } | null;\n}\n\n/** Renderer-private Bloom bundle selected for one record transaction. */\nexport interface BloomPersistentBundle {\n readonly scope: DeviceScope;\n readonly generation: number;\n readonly bloomDownsamplePipeline: RhiRenderPipeline | null;\n readonly bloomUpsamplePipeline: RhiRenderPipeline | null;\n readonly bloomCompositePipeline: RhiRenderPipeline | null;\n readonly bloomDownsampleBindGroupLayout: BindGroupLayout | null;\n readonly bloomUpsampleBindGroupLayout: BindGroupLayout | null;\n readonly bloomCompositeBindGroupLayout: BindGroupLayout | null;\n readonly bloomSampler: Sampler | null;\n readonly bloomDownsampleParamsBuffer: Buffer | null;\n readonly bloomUpsampleParamsBuffer: Buffer | null;\n readonly bloomCompositeParamsBuffer: Buffer | null;\n}\n\nexport interface PipelineState {\n /** Device that owns every opaque handle in this pipeline state. */\n readonly device: RhiDevice;\n readonly meshes: ReadonlyMap<number, MeshGpuHandles>;\n readonly format: TextureFormat;\n readonly colorAttachmentFormat: TextureFormat;\n /** Surface route committed by configureSurface for inspection provenance. */\n readonly surfaceProfile?: 'dual-view' | 'raw-only';\n readonly viewBindGroupLayout: BindGroupLayout;\n /** Device capability gate for the optional SpotLight projector binding. */\n readonly projectorAvailable?: boolean;\n readonly materialBindGroupLayout: BindGroupLayout;\n readonly meshBindGroupLayout: BindGroupLayout;\n readonly viewUniformBuffer: Buffer;\n readonly pointsLinesViewBuffer?: Buffer;\n readonly shadowCasterCascadeBuffer: Buffer;\n readonly materialUniformBuffer: { readonly buffer: Buffer; readonly sizeInBytes: number };\n readonly meshStorageBuffer: { readonly buffer: Buffer; readonly sizeInBytes: number };\n readonly instancesBindGroupLayout: BindGroupLayout;\n /** Probe-enabled slot-3 layout; omitted from no-probe bind groups. */\n readonly probeInstancesBindGroupLayout?: BindGroupLayout;\n readonly identityInstanceBuffer: Buffer;\n readonly defaultSampler: Sampler;\n /** Nearest/clamp sampler required by r32float Surface depth input. */\n readonly surfaceMediumDepthSampler?: Sampler;\n readonly fallbackTextureView: TextureView;\n readonly unlitPipeline: RhiRenderPipeline | null;\n readonly standardPipeline: RhiRenderPipeline | null;\n /** Producer-owned Standard PBR module for this device generation. */\n readonly standardPbrShaderModule: ShaderModule | null;\n /** Producer-owned skinned Standard PBR module for this device generation. */\n readonly pbrSkinShaderModule: ShaderModule | null;\n /** Producer-resolved Standard PBR UV ABI count for geometry projection. */\n readonly standardPbrShaderUvSetCount: number;\n readonly unlitPipelineMsaa: RhiRenderPipeline | null;\n readonly unlitPipelineHdrMsaa: RhiRenderPipeline | null;\n readonly pbrPipelineLayout: PipelineLayout | null;\n /** Dedicated slot-3 layout for scene-index GPU-driven Standard PBR draws. */\n readonly gpuDrivenInstancesBindGroupLayout?: BindGroupLayout | null;\n /** Direct Surface slot-3 ABI: instances + retained medium frame resources. */\n readonly surfaceDirectInstancesBindGroupLayout?: BindGroupLayout | null;\n readonly gpuDrivenPbrPipelineLayout?: PipelineLayout | null;\n /** Device-owned shader modules paired with their exact Standard PBR receipts. */\n readonly gpuDrivenPbrPrograms?: ReadonlyMap<string, GpuDrivenPbrProgram>;\n readonly gpuDrivenPbrSkinPipelineLayout?: PipelineLayout | null;\n /** Clustered group(2) layouts paired with the scene-index slot(3). */\n readonly gpuDrivenClusterPbrPipelineLayout?: PipelineLayout | null;\n readonly gpuDrivenClusterPbrSkinPipelineLayout?: PipelineLayout | null;\n readonly gpuDrivenClusterMeshBindGroupLayout?: BindGroupLayout | null;\n readonly pbrProbePipelineLayout?: PipelineLayout | null;\n readonly hdrpPbrPipelineLayout: PipelineLayout | null;\n readonly hdrpMeshBindGroupLayout?: BindGroupLayout | null;\n readonly hdrpProbePbrPipelineLayout?: PipelineLayout | null;\n readonly hdrpClusterMembershipPipeline: ComputePipeline | null;\n readonly hdrpClusterMembershipBindGroupLayout: BindGroupLayout | null;\n readonly pbrSkinPipelineLayout: PipelineLayout | null;\n readonly pbrSkinProbePipelineLayout?: PipelineLayout | null;\n readonly pbrSkinMeshBindGroupLayout: BindGroupLayout | null;\n readonly hdrpSkinPipelineLayout: PipelineLayout | null;\n readonly hdrpSkinMeshBindGroupLayout: BindGroupLayout | null;\n readonly skinPaletteAllocator: SkinPaletteAllocator | null;\n readonly defaultWhiteTextureView: TextureView;\n readonly defaultNormalTextureView: TextureView;\n /** Missing anisotropy maps encode a neutral direction and unit strength. */\n readonly defaultAnisotropyTextureView?: TextureView;\n readonly unlitPipelineHdr: RhiRenderPipeline | null;\n readonly shadowFallbackTextureView: TextureView;\n readonly shadowAtlasFallbackTextureView: TextureView;\n readonly extendedLightingAvailable?: boolean;\n readonly iesProfileTexture?: Texture;\n readonly cookieTexture?: Texture;\n readonly cookieMatrixBuffer?: Buffer;\n spotModifierUploadState?: {\n readonly ies: Map<number, number>;\n readonly cookie: Map<number, number>;\n readonly cookieMatrix: Map<number, number>;\n };\n readonly iesProfileTextureView?: TextureView;\n readonly cookieTextureView?: TextureView;\n readonly ltcLambertTextureView?: TextureView;\n readonly ltcGgxTextureView?: TextureView;\n readonly shadowParamsBuffer: Buffer;\n readonly skylightFallback: SkylightFallback | null;\n readonly perPassResources: PerPassResources;\n}\n\nexport interface RenderSystemInternals extends RenderSystemRuntime {\n readonly canvas: HTMLCanvasElement | OffscreenCanvas;\n /** Build identity injected by the host's build-tool adapter. */\n readonly build?: string | undefined;\n /** Host identity binding for the renderer-owned SSR dependency seam. */\n readonly ssrIdentity?: SsrAdmissionIdentity | undefined;\n readonly captureReflectionFallbackReadback?: boolean | undefined;\n readonly standardProfile?: StandardProfile | undefined;\n readonly standardPipeline: RenderFrameState['activePipeline'];\n readonly featureHost?: RenderFeatureHost | undefined;\n /** Install a detached feature host only at the recovery publication boundary. */\n readonly setFeatureHost?: ((host: RenderFeatureHost) => void) | undefined;\n readonly shaderModuleFactory?: PipelineBuilderShaderModuleFactory;\n readonly createShaderModule?: (\n device: import('@forgeax/engine-rhi').RhiDevice,\n descriptor: { readonly code: string; readonly label?: string },\n ) => Promise<\n Result<import('@forgeax/engine-rhi').ShaderModule, import('@forgeax/engine-rhi').RhiError>\n >;\n /** Optional handle-first factory for feature-owned generated shader programs. */\n readonly immediateShaderModuleFactory?: PipelineBuilderShaderModuleFactory;\n readonly profiler?: Profiler | undefined;\n readonly context: RhiCanvasContext | null;\n readonly getPipelineState: () => PipelineState | null;\n readonly assets: AssetRegistry;\n readonly gpuStore: import('../device/gpu-residency').GpuResidencyCache;\n readonly growMeshSsbo?:\n | ((neededSlots: number) =>\n | { readonly ok: true }\n | {\n readonly ok: false;\n readonly code: 'mesh-ssbo-ceiling-reached' | 'mesh-ssbo-capacity-exceeded';\n readonly degradedToSlotCount: number;\n })\n | undefined;\n readonly meshSsboState?: { readonly slotCount: number } | undefined;\n readonly buildPostProcessPipeline?:\n | ((\n entry: import('../fullscreen-post-process-pass').PostProcessShaderEntry,\n bgl: BindGroupLayout,\n colorFormats: readonly GPUTextureFormat[],\n label: string,\n ) => RhiRenderPipeline | null)\n | undefined;\n gpuPassTimingSession?: GpuPassTimingSession | undefined;\n gpuPassTimingCapture?: GpuPassTimingCapture | undefined;\n gpuPassTimingSubmittedWork?: Promise<void> | undefined;\n gpuPassTimingFrameIdentity?: GpuPassTimingFrameIdentity | undefined;\n gpuPassTimingBeginReason?: GpuPassTimingReason | undefined;\n readonly getRenderTargetPhysical?: (target: RenderTarget) => RenderTargetPhysical | undefined;\n readonly encodeRenderTargetReadbacks?: (\n encoder: RhiCommandEncoder,\n faces?: readonly number[],\n ) => void;\n /** Composed renderer utility sources installed atomically at build-ready. */\n volumetricFogShaders?: VolumetricFogShaderSources | undefined;\n /** Composed renderer utility sources installed atomically at build-ready. */\n ssrShaders?: SsrShaderSources | undefined;\n /** Composed renderer utility sources installed atomically at build-ready. */\n atmosphereShaders?: AtmosphereShaderSources | undefined;\n}\n\nexport interface _StandardForwardSceneView {\n readonly environmentIbl?: { readonly irradiance: TextureView; readonly prefilter: TextureView };\n readonly captureDispatch?: readonly DispatchEntry[];\n readonly assets: AssetRegistry;\n readonly store: import('../device/gpu-residency').GpuResidencyCache;\n readonly pipelineState: PipelineState;\n readonly bloomResources?: BloomPersistentBundle | null;\n readonly runtime: RenderSystemRuntime;\n readonly validated: readonly ValidatedRenderable[];\n readonly validatedOrdered: readonly ValidatedRenderable[];\n readonly viewBindGroup: BindGroup | null;\n /** Dynamic View-UBO slot used by auxiliary cube/probe face cameras. */\n readonly viewBindGroupDynamicOffset?: number;\n readonly meshBindGroup: BindGroup | null;\n readonly frameState: RenderFrameState;\n readonly dispatchCounts: DispatchCounts;\n readonly bindGroupCounts: BindGroupCounts;\n readonly skylight: SkylightSnapshot | undefined;\n readonly skylightCount: number;\n readonly skybox: SkyboxSnapshot | undefined;\n readonly profilePhase?: <T>(phase: RenderRecordPhase, action: () => T) => T;\n readonly directionalShadowCacheReuse: boolean;\n readonly world: RenderResourceScope;\n readonly tonemapActive: boolean;\n readonly geometryColorView: TextureView | null;\n readonly geometryDepthView: TextureView | null;\n readonly geometryDepthKey: string | null;\n readonly skyboxActive: boolean;\n readonly splitLdrSprite: boolean;\n readonly ldrSpritePassView: TextureView | null;\n readonly transparentColorFormat?: GPUTextureFormat;\n /** Second Standard main-pass attachment used by the fallback producer. */\n readonly reflectionFallbackColorFormat?: GPUTextureFormat;\n readonly dispatch: readonly DispatchEntry[];\n readonly hdrpClusterBindGroup: BindGroup | null;\n readonly hdrpClusterMembershipBindGroup: BindGroup | null;\n /** Prepared Standard lighting declaration accepted by this graph frame. */\n readonly standardLighting?: StandardTopologyInputValue;\n readonly foldDispatchPlan: FoldDispatchPlan | null;\n readonly materialSlotIndices: readonly (readonly number[])[];\n readonly materialSlots: readonly MaterialSnapshot[];\n readonly materialSlotOwners: readonly ValidatedRenderable[];\n readonly materialSlotCount: number;\n /** Filled by main-pass material producers before the GPU-driven raster tail. */\n readonly gpuDrivenStandardPbrFrameResources?: GpuDrivenStandardPbrFrameResources;\n /** Scene table retained by the renderer even when no draw is GPU-admitted. */\n readonly gpuDrivenSceneMaterialBuffer?: Buffer;\n /** Concrete main-pass draw identities already claimed by the capable GPU lane. */\n readonly gpuDrivenDrawKeys?: ReadonlySet<string>;\n /** Stable world identities used to construct the claimed draw keys. */\n readonly gpuDrivenWorldKeys?: readonly number[];\n readonly gpuDrivenShadowViews?: ShadowViewStatePool;\n readonly gpuDrivenShadowBatchProjections?: ReadonlyMap<\n string,\n ReadonlyMap<number, GpuDrivenShadowBatchProjection>\n >;\n /** Concrete ShadowCaster keys already claimed by the capable GPU subset. */\n readonly gpuDrivenShadowDrawKeys?: ReadonlySet<string>;\n /** View-scoped ShadowCaster claims for exact CPU residual routing. */\n readonly gpuDrivenShadowDrawKeysByView?: ReadonlyMap<string, ReadonlySet<string>>;\n /** Extracted structured ShadowCaster ownership facts. */\n readonly shadowCasterMembership?: readonly ShadowCasterMembership[];\n /** Complete retained ShadowCaster rows, including camera-culled casters. */\n readonly shadowValidatedOrdered?: readonly ValidatedRenderable[];\n /** Dispatch entries remapped to the complete retained ShadowCaster rows. */\n readonly shadowDispatch?: readonly DispatchEntry[];\n /** Mesh-SSBO slot base reserved for the retained ShadowCaster rows. */\n readonly shadowMeshSsboBase?: number;\n /** Renderer-stable world keys used by ShadowCaster ownership identities. */\n readonly shadowCasterWorldKeys?: readonly number[];\n readonly pointsLines: PointsLinesRecordOwner | undefined;\n readonly materialBgAssemblyCache: Map<string, MaterialBgAssemblyCacheEntry>;\n /** Record-stage proof callback; invoked only after a real draw command is encoded. */\n readonly onRenderableDraw?: (\n entry: ValidatedRenderable,\n submeshIndex?: number,\n receipt?: { readonly lane: 'cpu' | 'gpu'; readonly ready: boolean },\n ) => void;\n readonly reflectionProbes?: ReflectionProbeRecordState;\n materialUboPayloadCache?: {\n readonly materialSlots: readonly MaterialSnapshot[];\n readonly materialSlotCount: number;\n readonly payload: Uint8Array;\n };\n hdrpSsaoBlurredView?: TextureView;\n readonly occlusion?: import('../scene/visibility/occlusion-runtime').OcclusionFrameProjection;\n}\n\nexport type _InternalRenderPipelineContext = RenderPipelineContext & _StandardForwardSceneView;\n\nexport type RecordProfileRunner = <T>(phase: RenderRecordPhase, action: () => T) => T;\n\nexport const STANDARD_PBR_UBO_SIZE = derive(DEFAULT_STANDARD_PBR_PARAM_SCHEMA).uboLayout.totalBytes;\nexport const MATERIAL_PER_ENTITY_STRIDE = Math.ceil(STANDARD_PBR_UBO_SIZE / 256) * 256;\n\nexport type SwapChainFormatPair = {\n readonly storage: GPUTextureFormat;\n readonly view: GPUTextureFormat;\n readonly fallbackReason?: 'preferred-canvas-format-missing';\n};\n\n/** Internal closed projection of the concrete surface route. */\nexport type SurfaceProfile =\n | {\n readonly kind: 'dual-view';\n readonly storageFormat: GPUTextureFormat;\n readonly viewFormat: GPUTextureFormat;\n readonly viewFormats: readonly [GPUTextureFormat];\n readonly hasDisplayEndpoint: true;\n }\n | {\n readonly kind: 'raw-only';\n readonly storageFormat: GPUTextureFormat;\n readonly viewFormat: GPUTextureFormat;\n readonly viewFormats: readonly [];\n readonly hasDisplayEndpoint: false;\n };\n\nexport interface SurfaceCapabilityFacts {\n /** Concrete wgpu downlevel `SURFACE_VIEW_FORMATS` flag. */\n readonly surfaceViewFormats: boolean;\n readonly rawAttachment: boolean;\n readonly floatRenderAttachment: boolean;\n}\n\nexport function resolveSurfaceProfile(\n storageFormat: GPUTextureFormat,\n viewFormat: GPUTextureFormat,\n facts: SurfaceCapabilityFacts,\n): Result<SurfaceProfile, RhiError> {\n if (facts.surfaceViewFormats) {\n return ok({\n kind: 'dual-view',\n storageFormat,\n viewFormat,\n viewFormats: [viewFormat],\n hasDisplayEndpoint: true,\n });\n }\n if (!facts.rawAttachment || !facts.floatRenderAttachment) {\n return err(\n new RhiError({\n code: 'webgpu-runtime-error',\n expected: 'raw surface attachment and rgba16float render attachment capabilities',\n hint: 'surface profile cannot establish a raw-only linear output route',\n detail: {\n error: {\n code: 'surface-raw-endpoint-failed',\n message: 'raw-only surface capabilities are incomplete',\n },\n },\n }),\n );\n }\n return ok({\n kind: 'raw-only',\n storageFormat,\n viewFormat: storageFormat,\n viewFormats: [],\n hasDisplayEndpoint: false,\n });\n}\n\nexport type SurfaceBackendKind = 'webgpu' | 'wgpu-native' | 'wgpu-webgl2' | 'null';\n\nexport function resolveSurfaceFormatPair(\n _backendKind: SurfaceBackendKind,\n storage: GPUTextureFormat,\n view: GPUTextureFormat,\n): SwapChainFormatPair {\n return { storage, view };\n}\n\nfunction surfaceCapabilityFacts(\n device: RhiDevice,\n storageFormat: GPUTextureFormat,\n): SurfaceCapabilityFacts {\n const internal = device as unknown as { readonly surfaceViewFormats?: boolean };\n return {\n surfaceViewFormats: internal.surfaceViewFormats ?? device.caps?.backendKind !== 'wgpu-webgl2',\n rawAttachment: storageFormat === 'rgba8unorm' || storageFormat === 'bgra8unorm',\n floatRenderAttachment: device.caps?.rgba16floatRenderable ?? true,\n };\n}\n\nexport function configureSurface(\n context: RhiCanvasContext,\n device: RhiDevice,\n format: TextureFormat,\n colorAttachmentFormat: TextureFormat,\n): Result<void, RhiError> {\n const backendKind = device.caps?.backendKind ?? 'webgpu';\n const isWebGl2 = backendKind === 'wgpu-webgl2';\n const surfaceFormats = resolveSurfaceFormatPair(\n backendKind,\n format as GPUTextureFormat,\n colorAttachmentFormat as GPUTextureFormat,\n );\n const profile = resolveSurfaceProfile(\n surfaceFormats.storage,\n surfaceFormats.view,\n surfaceCapabilityFacts(device, surfaceFormats.storage),\n );\n if (!profile.ok) return profile;\n // WebGL2 surface pixels are proven by the compositor fixture, so it has no\n // surface consumer for optional TEXTURE_BINDING/COPY_SRC usage. The concrete\n // wgpu surface derives supported usages from SurfaceCapabilities and rejects\n // unsupported requests; this path requests only the guaranteed attachment\n // usage. Raw-only deliberately has no alternate view.\n const supportsTextureBinding =\n backendKind !== 'wgpu-webgl2' && (device.caps?.storageBuffer ?? true);\n const configured = context.configure({\n device,\n format: surfaceFormats.storage,\n alphaMode: isWebGl2 ? 'opaque' : 'premultiplied',\n usage:\n GPU_TEXTURE_USAGE_RENDER_ATTACHMENT |\n (supportsTextureBinding ? GPU_TEXTURE_USAGE_TEXTURE_BINDING : 0) |\n (isWebGl2 ? 0 : GPU_TEXTURE_USAGE_COPY_SRC),\n viewFormats: [...profile.value.viewFormats],\n });\n if (!configured.ok) return configured;\n if (\n isWebGl2 &&\n (context.presentationProof === undefined ||\n !context.presentationProof.descriptor ||\n !context.presentationProof.acquisition ||\n !context.presentationProof.validation ||\n typeof context.presentationProof.surfaceIdentity !== 'string' ||\n context.presentationProof.surfaceIdentity.length === 0 ||\n context.presentationProof.requested === undefined ||\n context.presentationProof.validated === undefined ||\n JSON.stringify(context.presentationProof.requested) !==\n JSON.stringify(context.presentationProof.validated))\n ) {\n return err(\n new RhiError({\n code: 'webgpu-runtime-error',\n expected: 'WebGL2 surface storage has descriptor, acquisition, and validation proof',\n hint: 'run the concrete presentation probe and retain the last-known-good graph when proof is absent',\n detail: {\n error: {\n code: 'surface-raw-endpoint-failed',\n message: 'surface storage raw endpoint proof is incomplete',\n },\n },\n }),\n );\n }\n return ok(undefined);\n}\n\nexport function selectSwapChainFormat(\n storageBufferCapable: boolean,\n surfaceViewFormats = true,\n): SwapChainFormatPair {\n if (!storageBufferCapable) {\n return {\n storage: 'rgba8unorm',\n view: surfaceViewFormats ? 'rgba8unorm-srgb' : 'rgba8unorm',\n };\n }\n const nav = (\n globalThis as { navigator?: { gpu?: { getPreferredCanvasFormat?: () => GPUTextureFormat } } }\n ).navigator;\n const gpu = nav?.gpu;\n const getPreferred = gpu?.getPreferredCanvasFormat;\n if (gpu !== undefined && typeof getPreferred === 'function') {\n const storage = getPreferred.call(gpu);\n const view =\n storage === 'rgba8unorm'\n ? 'rgba8unorm-srgb'\n : storage === 'bgra8unorm'\n ? 'bgra8unorm-srgb'\n : storage;\n return {\n storage,\n view: surfaceViewFormats ? view : storage,\n };\n }\n return {\n storage: 'rgba8unorm',\n view: surfaceViewFormats ? 'rgba8unorm-srgb' : 'rgba8unorm',\n fallbackReason: 'preferred-canvas-format-missing',\n };\n}\n"]}
@@ -1,6 +1,20 @@
1
1
  import { defineComponent } from '@forgeax/engine-ecs';
2
2
 
3
- // src/components/sprite-animation.ts
3
+ // src/components/glyph-text.ts
4
+ var GlyphText = defineComponent("GlyphText", {
5
+ // The layout/render owner re-resolves the font asset on the target world;
6
+ // authoring text and style remain portable simulation state.
7
+ fontHandle: {
8
+ type: "shared<FontAsset>",
9
+ default: 0,
10
+ simulationTransient: true
11
+ },
12
+ text: { type: "string", default: "" },
13
+ fontSize: { type: "f32", default: 16 },
14
+ // color carries an explicit layer-2 default [1,1,1,1] (opaque white); the
15
+ // array layer-3 fallback is all-zero, so the default MUST be explicit (D-5).
16
+ color: { type: "array<f32, 4>", default: new Float32Array([1, 1, 1, 1]) }
17
+ });
4
18
  var SpriteAnimation = defineComponent("SpriteAnimation", {
5
19
  frameCount: { type: "u32" },
6
20
  frameDuration: { type: "f32" },
@@ -13,6 +27,17 @@ var SpriteInstances = defineComponent("SpriteInstances", {
13
27
  transforms: { type: "array<f32>" },
14
28
  regions: { type: "array<f32>" }
15
29
  });
30
+
31
+ // src/components/sprite-playback-mode.ts
32
+ var SPRITE_PLAYBACK_MODE_LOOP = 0;
33
+ var SPRITE_PLAYBACK_MODE_CLAMP = 1;
34
+ var SpritePlayback = Object.freeze({
35
+ loop: SPRITE_PLAYBACK_MODE_LOOP,
36
+ clamp: SPRITE_PLAYBACK_MODE_CLAMP
37
+ });
38
+ function spritePlaybackModeFromU32(value) {
39
+ return value === SPRITE_PLAYBACK_MODE_CLAMP ? "clamp" : "loop";
40
+ }
16
41
  var SpriteRegionOverride = defineComponent("SpriteRegionOverride", {
17
42
  region: { type: "array<f32, 4>" }
18
43
  });
@@ -53,6 +78,6 @@ function selectActiveCameraIndex(cameraEntities, activeEntity) {
53
78
  return cameraEntities.indexOf(activeEntity);
54
79
  }
55
80
 
56
- export { SpriteAnimation, SpriteInstances, SpriteRegionOverride, TileLayer, Tilemap, TilemapSort, decodeSortScope, getActiveCamera, selectActiveCameraIndex, setActiveCamera };
57
- //# sourceMappingURL=chunk-ELJFJ2BU.mjs.map
58
- //# sourceMappingURL=chunk-ELJFJ2BU.mjs.map
81
+ export { GlyphText, SpriteAnimation, SpriteInstances, SpritePlayback, SpriteRegionOverride, TileLayer, Tilemap, TilemapSort, decodeSortScope, getActiveCamera, selectActiveCameraIndex, setActiveCamera, spritePlaybackModeFromU32 };
82
+ //# sourceMappingURL=chunk-X2KA6WHM.mjs.map
83
+ //# sourceMappingURL=chunk-X2KA6WHM.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/components/glyph-text.ts","../src/components/sprite-animation.ts","../src/components/sprite-instances.ts","../src/components/sprite-playback-mode.ts","../src/components/sprite-region-override.ts","../src/components/tile-layer.ts","../src/components/tilemap.ts","../src/systems/active-camera.ts"],"names":["defineComponent"],"mappings":";;;AAkDO,IAAM,SAAA,GAAY,gBAAgB,WAAA,EAAa;AAAA;AAAA;AAAA,EAGpD,UAAA,EAAY;AAAA,IACV,IAAA,EAAM,mBAAA;AAAA,IACN,OAAA,EAAS,CAAA;AAAA,IACT,mBAAA,EAAqB;AAAA,GACvB;AAAA,EACA,IAAA,EAAM,EAAE,IAAA,EAAM,QAAA,EAAU,SAAS,EAAA,EAAG;AAAA,EACpC,QAAA,EAAU,EAAE,IAAA,EAAM,KAAA,EAAO,SAAS,EAAA,EAAG;AAAA;AAAA;AAAA,EAGrC,KAAA,EAAO,EAAE,IAAA,EAAM,eAAA,EAAiB,OAAA,EAAS,IAAI,YAAA,CAAa,CAAC,CAAA,EAAG,CAAA,EAAG,CAAA,EAAG,CAAC,CAAC,CAAA;AACxE,CAAC;ACiGM,IAAM,eAAA,GAAkBA,gBAAgB,iBAAA,EAAmB;AAAA,EAChE,UAAA,EAAY,EAAE,IAAA,EAAM,KAAA,EAAM;AAAA,EAC1B,aAAA,EAAe,EAAE,IAAA,EAAM,KAAA,EAAM;AAAA,EAC7B,YAAA,EAAc,EAAE,IAAA,EAAM,KAAA,EAAO,WAAW,IAAA,EAAK;AAAA,EAC7C,OAAA,EAAS,EAAE,IAAA,EAAM,KAAA,EAAO,WAAW,IAAA,EAAK;AAAA,EACxC,OAAA,EAAS,EAAE,IAAA,EAAM,YAAA,EAAa;AAAA,EAC9B,YAAA,EAAc,EAAE,IAAA,EAAM,KAAA;AACxB,CAAC;ACdM,IAAM,eAAA,GAAkBA,gBAAgB,iBAAA,E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;AAAA;AAAA;AAAA,EAGhC,QAAA,EAAU,EAAE,IAAA,EAAM,eAAA,EAAiB,OAAA,EAAS,IAAI,YAAA,CAAa,CAAC,CAAA,EAAG,CAAC,CAAC,CAAA,EAAE;AAAA,EACrE,SAAA,EAAW,EAAE,IAAA,EAAM,KAAA,EAAO,SAAS,EAAA,EAAG;AAAA,EACtC,OAAA,EAAS,EAAE,IAAA,EAAM,QAAA;AACnB,CAAC;;;ACYM,IAAM,iBAAA,GAAoB,cAAA;AAkB1B,SAAS,gBAAgB,KAAA,EAAwC;AACtE,EAAA,IAAI,CAAC,KAAA,CAAM,WAAA,CAAY,iBAAiB,GAAG,OAAO,MAAA;AAClD,EAAA,OAAO,KAAA,CAAM,YAA0B,iBAAiB,CAAA;AAC1D;AAUO,SAAS,eAAA,CAAgB,OAAc,MAAA,EAAsB;AAClE,EAAA,KAAA,CAAM,cAAA,CAA6B,iBAAA,EAAmB,EAAE,MAAA,EAAQ,CAAA;AAClE;AAiBO,SAAS,uBAAA,CACd,gBACA,YAAA,EACQ;AACR,EAAA,IAAI,YAAA,KAAiB,QAAW,OAAO,EAAA;AACvC,EAAA,OAAO,cAAA,CAAe,QAAQ,YAAY,CAAA;AAC5C","file":"chunk-X2KA6WHM.mjs","sourcesContent":["// @forgeax/engine-runtime - GlyphText component (feat-20260531-world-space-msdf-text-rendering M4 / w14).\n//\n// `GlyphText` is the authoring source component for world-space MSDF text\n// (requirements AC-06 / §domain model). It carries ONLY authoring data; the\n// glyph quad baking + MeshFilter / MeshRenderer attachment is the job of the\n// `glyphTextLayoutSystem` (plan-strategy D-2: GlyphText is pure authoring\n// data, baking is a system responsibility). There is NO `TextLayoutAsset`\n// intermediate (OOS-5) -- layout output lives directly in a baked MeshAsset.\n//\n// Naming: single-semantic component drops the `Component` suffix\n// (AGENTS.md §Component naming rule #1 -- Transform / Camera / GlyphText).\n//\n// Schema vocab:\n// - `fontHandle: 'shared<FontAsset>'` -> `Handle<'FontAsset', 'shared'>`\n// (u32-stored; AssetRegistry owns the FontAsset lifecycle). AI users\n// obtain the handle via `assets.loadByGuid<FontAsset>(guid)`.\n// - `text: 'string'` -> native JS string (UniqueRefStore-backed, same\n// dispatch as `Name.value`).\n// - `fontSize: 'f32'` -> layout scale applied to the FontAsset metrics.\n// - `color: 'array<f32, 4>'` -> linear-space rgba tint (feat-20260709 M3:\n// collapsed from four `colorR/G/B/A` scalar columns into one inline\n// stride-4 SoA column, mirroring the DirectionalLight direction/color\n// idiom). Explicit layer-2 default [1,1,1,1] (opaque white).\n//\n// charter mapping: P1 (single import surface from `@forgeax/engine-render`,\n// co-located with `glyphTextLayoutSystem` that consumes it) + P3\n// (machine-readable schema literal) + P5 (consistent abstraction: same\n// `'shared<T>'` idiom as MeshFilter.assetHandle / MeshRenderer.materials).\n\nimport { defineComponent } from '@forgeax/engine-ecs';\n\n/**\n * Glyph text authoring component (world-space MSDF text).\n *\n * Spawn an entity with a `GlyphText` and the `glyphTextLayoutSystem`\n * (auto-wired by `createRenderer` / `createApp`) lays out the glyph quads,\n * bakes a `MeshAsset`, and attaches `MeshFilter` + `MeshRenderer` on the\n * next frame (Commands-deferred). Mutating `text` / `fontSize` / `color`\n * re-bakes the mesh in place (plan-strategy D-1 updateMesh; registry size\n * unchanged, AC-08).\n *\n * @example Spawn a world-space label:\n * import { GlyphText } from '@forgeax/engine-render/authoring';\n * const font = (await assets.loadByGuid(fontGuid)).unwrap();\n * world.spawn({\n * component: GlyphText,\n * data: { fontHandle: font, text: 'Hello', fontSize: 32,\n * color: [1, 1, 1, 1] },\n * });\n */\nexport const GlyphText = defineComponent('GlyphText', {\n // The layout/render owner re-resolves the font asset on the target world;\n // authoring text and style remain portable simulation state.\n fontHandle: {\n type: 'shared<FontAsset>',\n default: 0 as never,\n simulationTransient: true,\n },\n text: { type: 'string', default: '' },\n fontSize: { type: 'f32', default: 16 },\n // color carries an explicit layer-2 default [1,1,1,1] (opaque white); the\n // array layer-3 fallback is all-zero, so the default MUST be explicit (D-5).\n color: { type: 'array<f32, 4>', default: new Float32Array([1, 1, 1, 1]) },\n});\n","// @forgeax/engine-runtime - SpriteAnimation (per-entity frame-tick clock).\n//\n// 6-field schema (1:1 with requirements section 2.3 table; D-5 + D-6\n// vocab keywords locked):\n//\n// frameCount : 'u32' total frames in the cycle (>= 1).\n// frameDuration : 'f32' per-frame seconds (> 0).\n// currentFrame : 'u32' live frame index, in [0, frameCount).\n// accumDt : 'f32' dt accumulator (research F-3 carries\n// fractional residue across ticks).\n// regions : 'array<f32>' flat per-frame UV rectangles\n// [uMin, vMin, uW, vH]; the M4 tick\n// system enforces\n// `regions.length === frameCount * 4`\n// on first observation (AC-09 fail-fast,\n// D-1 path).\n// playbackMode : 'u32' numeric encoding of `SpritePlaybackMode`\n// (0 = SPRITE_PLAYBACK_MODE_LOOP,\n// 1 = SPRITE_PLAYBACK_MODE_CLAMP).\n//\n// Why u32 for playbackMode? research F-2 + F-5: the ECS schema whitelist\n// rejects string-literal unions. The M1 SSOT\n// `packages/runtime/src/components/sprite-playback-mode.ts` carries the\n// numeric constants + the `spritePlaybackModeFromU32` mapper that turns\n// the column value back into a string-literal union at the M4 tick-system\n// seam — same shape as the M1 Tonemap encoding (`tonemap: 'f32'` +\n// TONEMAP_NONE / TONEMAP_REINHARD_EXTENDED + tonemapFromF32). One mental\n// model across all closed-union schema columns; charter P4 consistent\n// abstraction.\n//\n// Why array<f32> (variable) and not array<f32, N> (fixed) for regions?\n// The length `frameCount * 4` is data-dependent: `frameCount` is itself a\n// per-entity column read at runtime, not a schema-time literal. Same\n// shape as the renderer-owned 3D instance collection snapshot whose length\n// depends on the live instance count; the owners remain separate.\n//\n// dt accumulator clock model (requirements section 2.5 q6 + plan-strategy\n// section 2 D-5):\n// accumDt += Time.delta\n// while (accumDt >= frameDuration) { advance currentFrame; accumDt -= frameDuration }\n// The carry-over `accumDt` survives across ticks so frame timing stays\n// stable under jittery dt; M4 T-23 implements the loop. Per-frame UV\n// is materialised by writing the slice\n// `regions[currentFrame*4 .. currentFrame*4 + 4]` into the entity's\n// `SpriteRegionOverride.region` column (T-11 + M4 T-23).\n//\n// Sprite-only consumption (requirements section 5 constraint #2): the\n// M4 tick system + the M3 extract branch read this component only when\n// the entity routes through the sprite bucket. Opaque buckets ignore\n// the component even when present. Naming keeps the `Sprite` prefix per\n// OOS-01 (no premature 3D generalisation); 3D UV animation lands in a\n// separate component in a future feat.\n//\n// 4-step recipe (charter F1 progressive disclosure — minimum walk-cycle\n// host code; full demo lands in M6 hello-sprite-atlas):\n// 1. Build atlas via `forgeax asset atlas --input <glob> --name <prefix> --output <dir> --root <project>`\n// (M5 build-time hook); load the emitted `<name>.atlas.png` plus\n// `<name>.atlas.meta.json` sidecar.\n// 2. Register the sprite material referencing the atlas\n// `TextureAsset` with the initial frame's `region` rectangle (the\n// runtime tick system overrides this region per entity per frame).\n// 3. `world.spawn` an entity with `MeshFilter(HANDLE_QUAD)` +\n// `MeshRenderer(spriteMaterial)` + `Instances(...)` plus this\n// `SpriteAnimation` (frameCount / frameDuration / regions /\n// playbackMode) and `SpriteRegionOverride { region }` (the tick\n// system writes per-frame UV).\n// 4. Add `spriteAnimationTickSystem` (M4 T-23) to the schedule between\n// input/time and `RenderSystem.extract`.\n//\n// @derives `defineComponent` factory (packages/ecs/src/component.ts) —\n// `'u32'` / `'f32'` are scalar tier-1 keywords; `'array<f32>'` is a\n// tier-2 schema-vocab keyword (variable-capacity; M1 feat-20260515\n// buffer-array vocab). Layer-3 default fallback fills missing\n// `currentFrame` / `accumDt` / `playbackMode` with 0\n// (component-default-fallback typeDefault table).\n// @consumes M4 T-23 (`spriteAnimationTickSystem` reads all 6 fields and\n// writes per-frame slice into SpriteRegionOverride).\n//\n// charter mapping: F1 (single-import barrel discovery + 4-step recipe\n// at the JSDoc head); P3 (4 explicit error fields surface via the M4\n// tick-system fail-fast — `regions.length` mismatch / `frameDuration`\n// non-positive routes through SpriteAnimationInvalidError, M1 T-05);\n// P4 (consistent abstraction — same numeric closed-union encoding as\n// Tonemap / TransparentSortConfig.mode); P5 (producer / consumer\n// separation — atlas regions are produced build-time by\n// vite-plugin-image and consumed runtime as a flat Float32Array; AI\n// users never call a packer at runtime).\n//\n// Anchors: plan-strategy section 2 D-5 + D-6 + section 3.1 SAC + section\n// 4 risks R-SCHEMA-1 + R-SCHEMA-2 + R-TIME-1 reaction; plan-tasks.json\n// T-12; research F-2 + F-3 + F-5; requirements section AC-02 + section\n// 2.3 + section 2.5 + section 7 boundary table.\n\nimport { defineComponent } from '@forgeax/engine-ecs';\n\n/**\n * Per-entity sprite frame-tick clock.\n *\n * Schema (6 fields, 1:1 with requirements section 2.3):\n * - `frameCount: u32` — total frames (>= 1).\n * - `frameDuration: f32` — seconds per frame (> 0).\n * - `currentFrame: u32` — live frame index (0..frameCount). Layer-3\n * default `0` when omitted at spawn.\n * - `accumDt: f32` — dt residue carried across ticks. Layer-3 default\n * `0` when omitted; lives on the component (not on a system-side\n * resource) so the system stays stateless and AI-user setFrame paths\n * can reset both `currentFrame` and `accumDt` atomically.\n * - `regions: array<f32>` — flat per-frame UV rectangles\n * `[uMin, vMin, uW, vH]`; runtime invariant\n * `regions.length === frameCount * 4` (enforced by the M4 tick system).\n * - `playbackMode: u32` — numeric encoding of `SpritePlaybackMode`;\n * `SPRITE_PLAYBACK_MODE_LOOP = 0` (default) /\n * `SPRITE_PLAYBACK_MODE_CLAMP = 1`.\n *\n * Pair with `SpriteRegionOverride` (T-11) — the tick system writes the\n * per-frame UV slice into the override column, which `render-system-\n * extract` then reads in the sprite bucket branch.\n *\n * @example Spawn a 4-frame walk cycle that loops:\n * import { MeshFilter, MeshRenderer } from '@forgeax/engine-render';\n * import {\n * SpriteAnimation, SpriteRegionOverride, SPRITE_PLAYBACK_MODE_LOOP,\n * } from '@forgeax/engine-render/authoring';\n * import { Transform } from '@forgeax/engine-scene';\n * import { HANDLE_QUAD } from '@forgeax/engine-assets-runtime';\n *\n * // 4 frames packed in an atlas, each 64x64 inside a 256x64 row:\n * const regions = new Float32Array([\n * 0.00, 0, 0.25, 1, // walk-0\n * 0.25, 0, 0.25, 1, // walk-1\n * 0.50, 0, 0.25, 1, // walk-2\n * 0.75, 0, 0.25, 1, // walk-3\n * ]);\n * world.spawn(\n * { component: Transform, data: { pos: [0, 0, 0],\n * quat: [0, 0, 0, 1], scale: [1, 1, 1] } },\n * { component: MeshFilter, data: { assetHandle: HANDLE_QUAD } },\n * { component: MeshRenderer, data: { materials: [spriteMaterial] } },\n * { component: SpriteAnimation,\n * data: {\n * frameCount: 4,\n * frameDuration: 0.1,\n * regions,\n * playbackMode: SPRITE_PLAYBACK_MODE_LOOP,\n * } },\n * { component: SpriteRegionOverride,\n * data: { region: new Float32Array([0, 0, 0.25, 1]) } },\n * );\n *\n * @example Manual setFrame — jump to frame 2 atomically:\n * world.set(entity, SpriteAnimation,\n * { currentFrame: 2, accumDt: 0 }).unwrap();\n *\n * Error path (M4 T-23 routes through `SpriteAnimationInvalidError`,\n * `EcsErrorCode === 'sprite-animation-invalid'`; charter P3):\n * - `regions.length !== frameCount * 4` -> detail.field = 'regions-length',\n * detail carries `regionsLength` + `frameCount`.\n * - `frameDuration <= 0` -> detail.field = 'frame-duration', detail carries\n * `frameDuration`.\n */\nexport const SpriteAnimation = defineComponent('SpriteAnimation', {\n frameCount: { type: 'u32' },\n frameDuration: { type: 'f32' },\n currentFrame: { type: 'u32', transient: true },\n accumDt: { type: 'f32', transient: true },\n regions: { type: 'array<f32>' },\n playbackMode: { type: 'u32' },\n});\n","// @forgeax/engine-runtime - SpriteInstances component (per-entity 2D\n// instanced-draw transforms + per-instance UV region).\n//\n// Schema: 2 array<f32> fields. `transforms` carries packed column-major mat4\n// instance transforms (16 f32 per instance, stride = 16). `regions` carries\n// packed per-instance UV vec4 (4 f32 per instance, stride = 4; layout\n// [uMin, vMin, uW, vH] mirroring SpriteAnimation.regions). The pair share\n// the same instance count; the SSOT invariant is\n// transforms.length / 16 === regions.length / 4\n// enforced through a TWO-LAYER contract:\n//\n// 1. AI user set-site: spawn / `world.set` / `world.push` callers pass two\n// Float32Arrays whose lengths satisfy the stride pair. The set site is\n// the AI user's responsibility — the engine cannot prove column-major\n// mat4 packing or per-instance UV intent without caller declaration.\n// 2. RenderSystem extract entry: `render-system-extract.ts` performs a\n// defensive `transforms.length / 16 === regions.length / 4` check on\n// every `world.get(e, SpriteInstances)` snapshot at frame extract time;\n// violations route a structured `SpriteInstancesCountMismatchError`\n// (`code: 'sprite-instances-count-mismatch'`,\n// `detail: { transformsLength, regionsLength, expectedStride: { transforms: 16, regions: 4 } }`)\n// through the World Layer-3 ErrorHandler and the renderable is skipped.\n// Two further extract-entry checks fire:\n// - `'sprite-instances-requires-sprite-shader'` — MaterialAsset's\n// first pass `shader` must be `'forgeax::sprite'`.\n// - `'sprite-instances-mutually-exclusive-with-instances'` — same\n// entity must not carry both Instances + SpriteInstances.\n// (Error class declarations live in `@forgeax/engine-ecs` errors.ts; the\n// extract-entry fire path is owned by feat M3 w12 / w13.)\n//\n// Peer relation to Instances (charter P4 consistent abstraction):\n// - Instances : 3D scene primitive — per-instance mat4 only (stride 16).\n// - SpriteInstances : 2D scene primitive — per-instance mat4 + per-instance\n// UV region (interleaved 80B per instance: 64B mat4 + 16B region).\n// AI users pick by data shape (does the per-instance carry UV?). Both ride\n// the array-vocab path and route through the same Layer-3 error envelope.\n//\n// Group transform chained semantics (charter proposition 5 mental migration):\n// When the same entity carries both `Transform` (entity_world) and\n// `SpriteInstances` (per-instance local transforms), the vertex shader\n// composes per instance:\n// world_position[i] = entity_world * instances_local[i] * vertex_position\n// `SpriteInstances.transforms[i*16..i*16+15]` is interpreted as a local-\n// space transform under the entity, exactly like `Instances.transforms`.\n// Set the entity's `Transform` to identity to make `instances_local[i]`\n// directly world-space.\n//\n// Uniform / storage buffer cap (research D-R-4 + AC-04): 80B per instance\n// * 128-cap fallback = 10240 B < 16384 B uniform max; the storage-buffer\n// path is uncapped and used by capable backends (RenderSystem record-stage\n// cap-gate).\n//\n// 4-segment minimum contract (read this header before reaching for the\n// source body):\n//\n// ===== (a) single-component import + spawn example =====\n//\n// import {\n// createRenderer,\n// MeshFilter, MeshRenderer, Transform,\n// SpriteInstances, type SpriteInstancesData,\n// } from '@forgeax/engine-render';\n//\n// // 1 entity rendering N instanced sprites (16N transforms f32 + 4N regions f32):\n// const transforms = new Float32Array(N * 16);\n// const regions = new Float32Array(N * 4);\n// // ... fill column-major mat4 columns + [uMin, vMin, uW, vH] per instance ...\n// world.spawn(\n// { component: MeshFilter, data: { assetHandle: HANDLE_QUAD } },\n// { component: MeshRenderer, data: { /* sprite-shaded MaterialAsset */ } },\n// { component: SpriteInstances, data: { transforms, regions } },\n// );\n//\n// ===== (b) packed mat4 + region layout =====\n//\n// const transforms = new Float32Array(N * 16); // column-major mat4 per instance\n// const regions = new Float32Array(N * 4); // [uMin, vMin, uW, vH] per instance\n// // instance i occupies floats:\n// // transforms[i*16 .. i*16+15] — column-major mat4 (translation in m03/m13/m23)\n// // regions [i* 4 .. i* 4+ 3] — uMin, vMin, uW, vH (atlas-normalized UV rect)\n//\n// `transforms.length` MUST be a non-zero multiple of 16; `regions.length`\n// MUST be a non-zero multiple of 4; the per-instance count derived from\n// both MUST agree. AI users gate at the set / push site; the RenderSystem\n// extract entry holds the second defensive (see error path 1 below).\n//\n// ===== (c) error code consumption (typed property access, no message regex) =====\n//\n// // Stride / mutual-exclusion / sprite-shader violations surface through\n// // the engine-ecs Layer-3 ErrorHandler when extract reads a malformed\n// // snapshot:\n// // on('error', (err) => {\n// // switch (err.code) {\n// // case 'sprite-instances-count-mismatch':\n// // // err.detail.transformsLength / regionsLength / expectedStride\n// // break;\n// // case 'sprite-instances-requires-sprite-shader':\n// // // err.detail.entityId / observedMaterialShaderId\n// // break;\n// // case 'sprite-instances-mutually-exclusive-with-instances':\n// // // err.detail.entityId\n// // break;\n// // }\n// // });\n//\n// charter mapping (charter v2 numbering, with round-1 v1 aliases retained\n// in parentheses so reviewers tracking the v1 spec can cross-reference;\n// SSOT for the v2 -> v1 alias map is the AI User Charter — see\n// .claude/skills/forgeax-closed-loop/agents/ai-user-charter.md):\n// F1 (alias: proposition 1) — single import surface\n// `import { SpriteInstances, type SpriteInstancesData } from\n// '@forgeax/engine-render'`;\n// P2 (alias: proposition 3) — machine-readable schema > prose:\n// `{ transforms: 'array<f32>', regions: 'array<f32>' }` is the SSOT,\n// stride pair documented here + enforced at the RenderSystem entry;\n// P3 (alias: proposition 4) — explicit failure: 3 structured EcsError\n// codes route per failure shape, not silent half-row;\n// P4 (alias: proposition 5) — consistent abstraction: SpriteInstances\n// mirrors Instances — both ride the array-vocab path; pick by data\n// shape, not by API.\n//\n// Anchors: requirements AC-01 (component schema), AC-03 (3 error codes),\n// AC-09 (IDE autocomplete + type inference); plan-strategy D-1 (interleaved\n// single binding slot), D-6 (3 codes declared in M1 ecs, fired in M3 render),\n// D-7 (type export location), D-8 (barrel re-export at runtime, not ecs).\n\nimport { defineComponent } from '@forgeax/engine-ecs';\n\n/**\n * Per-entity 2D instanced-draw primitive (ECS component).\n *\n * Carries two variable-length `array<f32>` fields:\n * - `transforms` — column-major mat4 per instance (16 f32, stride 16);\n * - `regions` — UV vec4 per instance ([uMin, vMin, uW, vH], 4 f32,\n * stride 4).\n *\n * The pair share the same instance count; the invariant\n * `transforms.length / 16 === regions.length / 4` is enforced at the\n * RenderSystem extract entry (NOT at ECS write paths). The runtime\n * RenderSystem consumer materialises a fresh `Float32Array` snapshot on\n * every `world.get(e, SpriteInstances)` access and uploads an interleaved\n * 80B-per-instance buffer to the GPU in the record stage.\n *\n * @example Spawn an entity rendering 10000 instanced sprites:\n * const transforms = new Float32Array(10000 * 16);\n * const regions = new Float32Array(10000 * 4);\n * // ... fill mat4 columns + [uMin, vMin, uW, vH] ...\n * world.spawn(\n * { component: MeshFilter, data: { assetHandle: HANDLE_QUAD } },\n * { component: MeshRenderer, data: { ... } },\n * { component: SpriteInstances, data: { transforms, regions } },\n * );\n */\nexport const SpriteInstances = defineComponent('SpriteInstances', {\n transforms: { type: 'array<f32>' },\n regions: { type: 'array<f32>' },\n});\n\n/**\n * Type-level hint for `data` at the `SpriteInstances` spawn site.\n *\n * The runtime ECS column shape for `array<f32>` accepts a `Float32Array`\n * payload at spawn / set time (the bytes are copied into the BufferPool\n * slot). Both fields are typed as `Float32Array` so AI-user IDE\n * autocomplete picks up the typed-array shape and the AC-09 inference\n * surfaces without `as` casts inside `world.get(e, SpriteInstances)` and\n * QueryRow access paths.\n *\n * @example\n * import type { SpriteInstancesData } from '@forgeax/engine-render/authoring';\n * const data: SpriteInstancesData = {\n * transforms: new Float32Array(N * 16),\n * regions: new Float32Array(N * 4),\n * };\n */\nexport type SpriteInstancesData = {\n readonly transforms: Float32Array;\n readonly regions: Float32Array;\n};\n","// @forgeax/engine-runtime - SpritePlaybackMode (u32 column encoding + mapper).\n//\n// SSOT for the SpriteAnimation.playbackMode ECS column (M2 T-12) and the\n// runtime tick-system branch selector (M4 T-23). The shape mirrors the M1\n// `Tonemap` block in `./camera.ts:72-90` (TONEMAP_NONE = 0 /\n// TONEMAP_REINHARD_EXTENDED = 1 + `type Tonemap = 'none' |\n// 'reinhard-extended'` + `tonemapFromF32`) for charter P4 consistent\n// abstraction — AI users keep one mental model across all u32-encoded\n// closed-union schema columns.\n//\n// Why `'u32'` + constant + mapper instead of a string-literal column?\n// ECS schema whitelist `SchemaFieldType` (packages/ecs/src/component.ts\n// section schema-field-type) does not accept string-literal unions\n// (research F-2 + F-5). Storing a u32 + translating to a closed\n// `'loop' | 'clamp'` literal union at the tick-system seam preserves\n// AI-user-facing narrowing (`switch (mode) { case 'loop': ... }`)\n// without forcing the ECS column to learn a new field-type vocabulary.\n//\n// Naming convention (plan-strategy section 8.command naming):\n// SPRITE_PLAYBACK_MODE_LOOP / SPRITE_PLAYBACK_MODE_CLAMP mirror M1\n// TONEMAP_* / TRANSPARENT_SORT_MODE_*. `spritePlaybackModeFromU32`\n// mirrors `tonemapFromF32` / `cameraProjectionFromF32`. AI users\n// discover the trio via single-import barrel re-export from\n// `@forgeax/engine-runtime` (wired in by M2 T-13).\n//\n// Anchors: plan-strategy section 2 D-5 + section 3.1 PR block SPM +\n// section 4 risk R-SCHEMA-1 reaction; research F-2 + F-5;\n// requirements section AC-02 + section 2.3 playbackMode row;\n// plan-tasks.json T-07 acceptanceCheck (rg\n// \"SPRITE_PLAYBACK_MODE_LOOP|SPRITE_PLAYBACK_MODE_CLAMP|\n// spritePlaybackModeFromU32\" >= 3 hits in this file).\n\n/**\n * Playback mode discriminator literal union (requirements section AC-02 +\n * section 2.3). Two members for the MVP:\n *\n * `'loop'` — `currentFrame = (currentFrame + 1) % frameCount`; the\n * sprite-animation-tick system wraps the index when\n * `accumDt >= frameDuration` (default for hello-sprite-\n * atlas demo \"100 sprites synchronised walk cycle\").\n * `'clamp'` — `currentFrame = min(currentFrame + 1, frameCount - 1)`;\n * holds the last frame for death / terminator-animation\n * style sequences (requirements section 2.5 q8 lock).\n *\n * Future modes (`'pingpong'`, reverse playback, arbitrary frame index\n * jumps) are deferred per requirements OOS-03. The closed union shape\n * leaves room for additive growth without breaking the u32 enum encoding\n * (plan-strategy section 2 D-5).\n */\nexport type SpritePlaybackMode = 'loop' | 'clamp';\n\n/** Numeric encoding of the loop playback mode (schema value for `playbackMode`). */\nexport const SPRITE_PLAYBACK_MODE_LOOP = 0 as const;\n\n/** Numeric encoding of the clamp playback mode (schema value for `playbackMode`). */\nexport const SPRITE_PLAYBACK_MODE_CLAMP = 1 as const;\n\n/** Grouped authoring values; the numeric ECS encoding stays owner-local. */\nexport const SpritePlayback = Object.freeze({\n loop: SPRITE_PLAYBACK_MODE_LOOP,\n clamp: SPRITE_PLAYBACK_MODE_CLAMP,\n} as const);\n\n/**\n * Map a `SpriteAnimation.playbackMode` numeric column value to the closed\n * `SpritePlaybackMode` string-literal union. The defensive fallback mirrors\n * `cameraProjectionFromF32` / `tonemapFromF32` precedent — a value other\n * than `SPRITE_PLAYBACK_MODE_CLAMP` (1) maps to `'loop'`, so stale or\n * uninitialised entities surface a predictable playback shape through the\n * tick-system query (rather than throwing or returning `undefined`).\n * Validation of `playbackMode` happens at schema-write time, not here.\n *\n * The tick-system in M4 T-23 (`spriteAnimationTickSystem`) consumes the\n * return value via `switch (mode) { case 'loop': ...; case 'clamp': ... }`\n * to pick the per-branch frame-advance arithmetic.\n */\nexport function spritePlaybackModeFromU32(value: number): SpritePlaybackMode {\n return value === SPRITE_PLAYBACK_MODE_CLAMP ? 'clamp' : 'loop';\n}\n","// @forgeax/engine-runtime - SpriteRegionOverride (per-entity UV region\n// override, sprite-only).\n//\n// Schema: 1 fixed-length array column `region: 'array<f32, 4>'` carrying a\n// packed UV sub-rectangle `[uMin, vMin, uW, vH]`. The fixed `4` length is\n// enforced at compile time by the ECS schema-vocab keyword\n// `'array<T, N>'` (D-6: prefer compile-time enforcement over runtime\n// fail-fast for length-bound contracts).\n//\n// Why an entity-side override component instead of a render parameter on\n// MaterialRenderer? Plan-strategy section 1 / requirements section 5\n// constraint #1 (Pipeline Isolation R1, M1 ssot): `AssetRegistry` stays\n// append-only / read-only and `MaterialRenderer` schema is frozen.\n// Per-entity render-parameter overrides ride the same rail as Layer /\n// SortKey — one ECS column per entity, read at extract time, never\n// flowing back to the asset.\n//\n// Sprite-only consumption (requirements section 5 constraint #2 + section\n// 7 boundary line 1): `render-system-extract` reads this component ONLY\n// inside the sprite bucket branch (`pipelineTag === 'sprite'` plus the\n// asset-side sprite discriminant). Opaque (`unlit` / `standard`) buckets\n// ignore the column even when the entity happens to carry it; the M3\n// T-15 grep gate\n// (`packages/runtime/src/__tests__/sprite-only-isolation-grep-gate.test.ts`)\n// asserts this file contains zero substring matches against the asset\n// discriminant identifier as a structural lock (charter P5 producer /\n// consumer separation: the component owner never names the asset\n// discriminant directly).\n//\n// Naming: bare `SpriteRegionOverride` (no `Component` suffix per\n// AGENTS.md section Component naming \"Single-semantic components drop\n// the Component suffix\"). The `Sprite` prefix is intentional — 3D UV\n// region animation lands in a separate component (e.g. future\n// `MaterialRegionOverride`) per OOS-01 to avoid premature 3D\n// generalisation. Plan-strategy section 8 naming convention pins the\n// prefix to make the AC-11 grep gate trivially decidable.\n//\n// @derives `defineComponent` factory (packages/ecs/src/component.ts) —\n// `'array<f32, 4>'` is on the `SchemaVocabKeyword` whitelist (line ~94\n// `array<${ManagedArrayElementType}, ${number}>`).\n// @consumes M3 T-16 (`render-system-extract.ts` sprite bucket branch\n// reads override into `paramSnapshot.region`, post-M3 feat-20260625\n// ablation -- the pre-ablation per-entity hop through the snapshot\n// POD layer collapsed into the generic paramSchema-driven path).\n// @produces M4 T-23 (`spriteAnimationTickSystem` writes per-frame UV\n// slice into `region`).\n//\n// charter mapping: F1 (single-import barrel discovery — joins Layer /\n// SortKey / Transform / SpriteAnimation under a single\n// `from '@forgeax/engine-render'`); P3 (compile-time length=4 lock\n// surfaces mismatched payloads at the TS edge before the column write\n// path observes them); P4 (consistent abstraction — same per-entity\n// override shape AI users already learned for Layer / SortKey).\n//\n// Anchors: plan-strategy section 2 D-6 + section 3.1 SRO + section 4\n// risk R-SCHEMA-2 reaction; plan-tasks.json T-11; research F-5;\n// requirements section AC-01 + section 2.4 + section 5 constraint #2.\n\nimport { defineComponent } from '@forgeax/engine-ecs';\n\n/**\n * Per-entity sprite UV region override (sprite-only).\n *\n * Carries a fixed-length `Float32Array(4)` of `[uMin, vMin, uW, vH]` that\n * `render-system-extract` reads in the sprite bucket branch and writes\n * into `paramSnapshot.region`, replacing the asset-side region for\n * this entity only (feat-20260625 M3 ablation: the prior per-entity POD\n * indirection collapsed into the generic paramSchema-driven snapshot).\n * Opaque buckets ignore this component; the AC-11 grep gate keeps the\n * producer / consumer separation structural (this file never names the\n * asset-side sprite discriminant identifier).\n *\n * Pair with `SpriteAnimation` to drive the override per frame\n * (sprite-animation-tick system, M4 T-23). Standalone use (manual region\n * override without animation) is also supported — set the column once and\n * the next extract picks up the new value.\n *\n * Schema-vocab keyword `'array<f32, 4>'` (D-6) — fixed-length 4 is the\n * compile-time enforcement axis. `Float32Array` payloads with length !== 4\n * round-trip fewer / more bytes per the underlying BufferPool slot, but\n * the slot is sized at schema registration time; AI users keep the\n * payload exactly four-floats wide.\n *\n * @example Spawn a sprite entity that displays the right half of an atlas:\n * import { MeshFilter, MeshRenderer } from '@forgeax/engine-render';\n * import { SpriteRegionOverride } from '@forgeax/engine-render/authoring';\n * import { Transform } from '@forgeax/engine-scene';\n * import { HANDLE_QUAD } from '@forgeax/engine-assets-runtime';\n *\n * world.spawn(\n * { component: Transform, data: { pos: [0, 0, 0],\n * quat: [0, 0, 0, 1], scale: [1, 1, 1] } },\n * { component: MeshFilter, data: { assetHandle: HANDLE_QUAD } },\n * { component: MeshRenderer, data: { materials: [spriteMaterial] } },\n * { component: SpriteRegionOverride,\n * data: { region: new Float32Array([0.5, 0, 0.5, 1]) } },\n * );\n *\n * @example Update the override at runtime (e.g. flip-frame test):\n * world.set(entity, SpriteRegionOverride,\n * { region: new Float32Array([0, 0, 1, 1]) }).unwrap();\n */\nexport const SpriteRegionOverride = defineComponent('SpriteRegionOverride', {\n region: { type: 'array<f32, 4>' },\n});\n","// @forgeax/engine-runtime - TileLayer (one render layer of a Tilemap).\n//\n// Schema (4 fields):\n// tiles array<u32> per-cell tile id (packed Tiled .tmj wire form);\n// length == parent.Tilemap.cols * rows.\n// layerOrder i32 render-order key (higher = drawn on top).\n// dirty u8 0 means clean, non-zero means dirty - the next\n// tilemap-chunk-extract-system pass rebuilds derived\n// per-cell entities for this layer.\n// sortScope u8 (TS: 0 = 'layer' (default) - terrain semantics:\n// closed every derived entity in this\n// 'layer' | layer shares one Layer.value\n// 'per-cell' (layerOrder << 20), so the\n// union) whole layer Y-sorts as a single\n// bucket. AI users grep\n// `sortScope: 'layer'` to confirm.\n// 1 = 'per-cell' - object semantics: each derived\n// entity carries its own foot-Y\n// key; preserves per-cell entity\n// derivation for Y-interleave\n// with sprite entities sharing\n// the same Layer.value.\n//\n// Storage rationale (D-V-3 R-NEW-1 fallback / round-2): ECS schema does not\n// yet support `values: ['layer', 'per-cell']` literal-union constraints\n// on a `'string'` column, so the on-disk shape is `u8` (0/1) but every\n// AI-facing TS surface (`TileLayerData.sortScope`) is the closed\n// `'layer' | 'per-cell'` string union. The bridge functions\n// `encodeSortScope` / `decodeSortScope` are the SSOT for the two-way\n// mapping (charter F1 — single grep target).\n//\n// Each TileLayer entity attaches to a Tilemap entity via ChildOf (the parent\n// field carries the Tilemap entity). M0 supports multiple TileLayer entities\n// per Tilemap (each rendered as an independent z-ordered layer).\n//\n// charter mapping: F1 (single-import barrel + single grep target for\n// `sortScope`), P1 (progressive disclosure — `'layer'` / `'per-cell'`\n// reads directly without a magic-number table), P3 (dirty flag is\n// explicit - silent re-extraction is forbidden), P4 (handle-free row\n// schema mirrors MeshFilter / MeshRenderer conventions).\n\nimport { defineComponent, type EcsError, type EntityHandle, type World } from '@forgeax/engine-ecs';\nimport type { Result } from '@forgeax/engine-types';\n\n/**\n * Closed string-literal union for the TileLayer.sortScope field. AI users\n * grep `sortScope` and land on this single SSOT type alias; switch\n * statements over this type are exhaustive without a default arm.\n *\n * - 'layer' - terrain semantics; whole layer shares one Layer.value\n * bucket and Y-sorts together (chunkIndex is folded into 0).\n * - 'per-cell' - object semantics; each derived entity gets its own\n * chunkIndex tiebreak so it can Y-interleave with\n * sprite entities carrying the same Layer.value (e.g. a\n * player sprite riding the same SPRITE_LAYER_VALUE).\n */\nexport type SortScope = 'layer' | 'per-cell';\n\n/** Compact authoring values for the stored u8 sort-scope field. */\nexport const TilemapSort = Object.freeze({\n layer: 0 as const,\n perCell: 1 as const,\n});\n\n/**\n * Bridge: `SortScope` -> on-disk u8. SSOT for the encoding (`'layer'` -> 0,\n * `'per-cell'` -> 1). The compile-time exhaustive switch guards against\n * silent drift if the union ever grows; adding a new literal here without\n * adding its arm fails typecheck (charter P3 — closed unions never default).\n */\nexport function encodeSortScope(scope: SortScope): 0 | 1 {\n switch (scope) {\n case 'layer':\n return TilemapSort.layer;\n case 'per-cell':\n return TilemapSort.perCell;\n }\n}\n\n/**\n * Bridge: on-disk u8 -> `SortScope`. Defaults to `'layer'` for any value\n * outside `{0, 1}` (defensive — the column is typed `u8` so out-of-range\n * values can only appear if a future schema migration loosens the bound;\n * the default preserves terrain semantics which is the safer of the two).\n */\nexport function decodeSortScope(raw: number | undefined): SortScope {\n return raw === 1 ? 'per-cell' : 'layer';\n}\n\n/**\n * Public TileLayer field shape (`world.spawn({ component: TileLayer, data:\n * { ... } })` payload). `sortScope` is the closed string union surfaced to\n * AI users; the runtime row encodes it as `u8` via `encodeSortScope` at\n * spawn time so on-disk storage stays compact.\n *\n * Treat as the `TileLayer` data SSOT — `defineComponent` schema below\n * mirrors it field-for-field with the bridge `sortScope: u8` in place of\n * the union literal.\n */\nexport interface TileLayerData {\n readonly tiles: Uint32Array;\n readonly layerOrder?: number;\n readonly dirty?: number;\n readonly sortScope?: SortScope;\n}\n\n/**\n * TileLayer component (M0 baseline rebuild + round-2 sortScope rename).\n *\n * AI users typically spawn a TileLayer + ChildOf pair pointing at an\n * existing Tilemap entity:\n *\n * @example\n * const tilesArray = new Uint32Array(cols * rows);\n * tilesArray[5 * cols + 7] = 1; // tile id 1 at cell (7, 5)\n * world.spawn(\n * { component: TileLayer, data: { tiles: tilesArray, layerOrder: 0 } },\n * { component: ChildOf, data: { parent: tilemapEntity } },\n * );\n *\n * Object-layer variant (Y-interleave with sprite entities):\n *\n * > NOTE: schema storage is `u8` (ECS schema does not support\n * > string-literal-union column constraints; see R-NEW-2). The\n * > AI-user surface is the closed `SortScope` string union, but\n * > `world.spawn` requires the numeric encoding — pass through\n * > `encodeSortScope('per-cell')` rather than the literal string.\n *\n * @example\n * world.spawn(\n * { component: TileLayer, data: {\n * tiles: objectTiles,\n * layerOrder: 1000,\n * sortScope: encodeSortScope('per-cell'),\n * } },\n * { component: ChildOf, data: { parent: tilemapEntity } },\n * );\n *\n * Defaults: `layerOrder = 0`, `dirty = 0`, `sortScope = 'layer'` (stored\n * as `u8 = 0`, i.e. `encodeSortScope('layer')`). `tiles` has no default -\n * AI users supply the per-cell array at spawn time. To trigger a re-build\n * after mutating tiles in place, call `markTileLayerDirty(world, layer)`.\n */\nexport const TileLayer = defineComponent('TileLayer', {\n tiles: { type: 'array<u32>' },\n layerOrder: { type: 'i32', default: 0 },\n dirty: { type: 'u8', default: 0 },\n sortScope: { type: 'u8', default: 0 },\n});\n\n/**\n * Mark a TileLayer entity dirty so the next `tilemapChunkExtractSystem`\n * pass purges and re-spawns its derived per-cell entities. Use this after\n * mutating `TileLayer.tiles` (e.g. an in-place patch via a column view).\n *\n * Returns the underlying ECS write result - on `err` branch the caller\n * can read `.code` to recover (`'stale-entity'` if the layer was\n * despawned, `'component-not-present'` if the entity is missing the\n * TileLayer column; both kebab-case literals are members of the closed\n * `EcsErrorCode` union).\n */\nexport function markTileLayerDirty(\n world: World,\n layerEntity: EntityHandle,\n): Result<void, EcsError> {\n return world.set(layerEntity, TileLayer, { dirty: 1 });\n}\n","// @forgeax/engine-runtime - Tilemap (grid + tileset reference).\n//\n// Schema (5 fields):\n// cols u32 total grid columns\n// rows u32 total grid rows\n// tileSize array<f32, 2> per-cell world [width, height] (default [1, 1];\n// feat-20260709 M3: collapsed from the tileSizeX\n// / tileSizeY scalar pair into one inline column)\n// chunkSize u32 per-chunk axis-length in cells (default 16)\n// tileset string durable TilesetAsset GUID\n//\n// Naming: single-semantic Tilemap (AGENTS.md §Component naming drops\n// `Component` suffix). One Tilemap entity per grid; TileLayer entities\n// attach via ChildOf relationship and supply the per-cell tile id array\n// for a single render-layer.\n//\n// charter mapping: F1 (single-import barrel from `@forgeax/engine-runtime`),\n// P1 (progressive disclosure - defaults cover the common case), P4 (durable\n// asset identity stays separate from World-local handles).\n\nimport { defineComponent } from '@forgeax/engine-ecs';\n\n/**\n * Tilemap component (M0 baseline rebuild).\n *\n * A Tilemap entity carries grid metadata + a single durable `tileset` GUID. The\n * actual per-cell tile id array lives on attached `TileLayer` entities\n * (one per render layer; ChildOf points back to the Tilemap entity).\n *\n * Defaults:\n * - `tileSize = [1, 1]` (unit-cell world coordinates).\n * - `chunkSize = 16` (tilemap-chunk-extract-system chunks 16x16 cells).\n *\n * @example Spawn a 32x32 unit-cell Tilemap referencing a TilesetAsset:\n * const tilemap = world.spawn(\n * { component: Tilemap, data: { cols: 32, rows: 32, tileset } },\n * { component: Transform, data: {} },\n * ).unwrap();\n */\nexport const Tilemap = defineComponent('Tilemap', {\n cols: { type: 'u32', default: 0 },\n rows: { type: 'u32', default: 0 },\n // tileSize carries an explicit layer-2 default [1,1] (unit cell); the array\n // layer-3 fallback is all-zero, so the default MUST be explicit (D-5).\n tileSize: { type: 'array<f32, 2>', default: new Float32Array([1, 1]) },\n chunkSize: { type: 'u32', default: 16 },\n tileset: { type: 'string' },\n});\n","// @forgeax/engine-runtime - ActiveCamera KV resource + selection helper.\n//\n// feat-20260630-viewport-2x2-run-x-display-redesign M2 w12 / plan-strategy D-2.\n//\n// PROBLEM (research Finding 4): the render extract stage selects the camera by\n// archetype-query FIRST-HIT (`cameras[0]`) and fires `render-system-multi-camera`\n// when more than one [Camera, Transform, Entity] entity exists. A single engine\n// world that carries BOTH an editor orbit camera AND a game camera therefore\n// cannot pick which one renders. This module adds the minimum neutral mechanism:\n// an `ActiveCamera { entity }` resource naming the entity to render through.\n//\n// ENGINE-NEUTRAL (requirements OOS-4 / AC-16): the engine knows only entity IDs.\n// It does NOT know which entity is \"editor\" or \"game\" -- the caller (editor side)\n// decides what `ActiveCamera.entity` points at. No editor concept enters this\n// file or the engine layer.\n//\n// BACKWARD COMPATIBLE (plan-strategy D-2): when the resource is ABSENT, or the\n// named entity is not among the queried cameras, selection falls back to the\n// existing first-hit behavior unchanged. Single-camera scenes are unaffected.\n//\n// Surface:\n// - interface ActiveCamera { entity: number }\n// - constant ACTIVE_CAMERA_KEY = 'ActiveCamera'\n// - helper getActiveCamera(world): ActiveCamera | undefined\n// - helper setActiveCamera(world, entity): void\n// - pure selectActiveCameraIndex(cameraEntities, activeEntity): number\n//\n// @new-surface KV resource: ECS has no defineResource factory; the TS POD\n// interface + string KV key form is the minimum-new-surface route, mirroring\n// TransparentSortConfig. The world resource store\n// (insertResource / getResource / hasResource) is reused unchanged.\n// @derives world.hasResource / world.insertResource / world.getResource KV API.\n// @fallback getActiveCamera KV missing returns undefined; no warn; no throw\n// (absent ActiveCamera is a legal state -> first-hit fallback in extract).\n//\n// charter mapping: F1 (single-import barrel + single entity pointer, smallest\n// concept face vs a multi-field priority/enabled scheme) + P4 (consistent\n// abstraction -- same world.{has,get,insert}Resource KV API as every other\n// engine resource consumer).\n\nimport type { World } from '@forgeax/engine-ecs';\n\n// ────────────────────────────────────────────────────────────────────────────\n// POD interface + KV key\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Active-camera pointer (plain-data POD). Lives as a world-level resource keyed\n * by `ACTIVE_CAMERA_KEY`. `entity` is the packed entity id (engine `EntityHandle`\n * is a branded number) of the camera the renderer should use.\n *\n * The engine treats `entity` as an opaque id; whether it names an editor camera\n * or a game camera is a caller-side decision (OOS-4 — engine stays neutral).\n */\nexport interface ActiveCamera {\n readonly entity: number;\n}\n\n/** World resource key for the `ActiveCamera` KV entry. */\nexport const ACTIVE_CAMERA_KEY = 'ActiveCamera' as const;\n\n// ────────────────────────────────────────────────────────────────────────────\n// Helpers\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Read the world's `ActiveCamera` resource.\n *\n * @fallback KV missing returns `undefined` — absent ActiveCamera is a legal\n * state (the renderer falls back to archetype first-hit). NO warn, NO throw.\n * The `hasResource` guard precedes the read so this helper never trips\n * `ResourceNotFoundError` from `world.getResource`.\n *\n * @example\n * const a = getActiveCamera(world); // undefined when not set\n * if (a) { ... a.entity ... }\n */\nexport function getActiveCamera(world: World): ActiveCamera | undefined {\n if (!world.hasResource(ACTIVE_CAMERA_KEY)) return undefined;\n return world.getResource<ActiveCamera>(ACTIVE_CAMERA_KEY);\n}\n\n/**\n * Write the world's `ActiveCamera` resource (idempotent last-write-wins via\n * `world.insertResource`). The renderer will use the camera whose entity id\n * equals `entity`, or fall back to first-hit if that id is not a queried camera.\n *\n * @example\n * setActiveCamera(world, gameCameraEntity); // render through the game camera\n */\nexport function setActiveCamera(world: World, entity: number): void {\n world.insertResource<ActiveCamera>(ACTIVE_CAMERA_KEY, { entity });\n}\n\n/**\n * Pure selection: given the entity ids of every camera surfaced by the extract\n * archetype query (in query order) and the optional active-camera entity id,\n * return the index of the active camera in `cameraEntities`, or `-1` to signal\n * \"no selection — use first-hit fallback\".\n *\n * `-1` is returned when `activeEntity` is `undefined` (resource absent) OR when\n * the id is not present among `cameraEntities` (stale / non-camera entity).\n * Both cases preserve the existing first-hit behavior (plan-strategy D-2).\n *\n * @example\n * selectActiveCameraIndex([10, 20, 30], 20) === 1 // pick the 2nd camera\n * selectActiveCameraIndex([10, 20, 30], undefined) === -1 // first-hit\n * selectActiveCameraIndex([10, 20, 30], 999) === -1 // first-hit\n */\nexport function selectActiveCameraIndex(\n cameraEntities: readonly number[],\n activeEntity: number | undefined,\n): number {\n if (activeEntity === undefined) return -1;\n return cameraEntities.indexOf(activeEntity);\n}\n"]}
@@ -1,6 +1,7 @@
1
1
  import { color } from '@forgeax/engine-math';
2
2
  import { DEFAULT_STANDARD_PBR_PARAM_SCHEMA, DEFAULT_STANDARD_SURFACE_MODULE } from '@forgeax/engine-shader';
3
- import { standardSurfaceParameters, deriveStandardLayerPlan } from '@forgeax/engine-types';
3
+ import { err, ok, standardSurfaceParameters, deriveStandardLayerPlan } from '@forgeax/engine-types';
4
+ import { ResourceInvalidValueError } from '@forgeax/engine-ecs/projection';
4
5
 
5
6
  // src/materials.ts
6
7
  var STANDARD_MATERIAL_MODULE = "forgeax_material::standard";
@@ -425,7 +426,53 @@ function standard(options) {
425
426
  return options.surfaceModule === void 0 ? standardDefault(options) : standardCustom(options);
426
427
  }
427
428
  var Materials = { unlit, standard, srgb };
429
+ var TRANSPARENT_SORT_CONFIG_KEY = "TransparentSortConfig";
430
+ var TRANSPARENT_SORT_MODE_LAYER_Z = 0;
431
+ var TRANSPARENT_SORT_MODE_LAYER_Y = 1;
432
+ var TRANSPARENT_SORT_MODE_LAYER_YZ = 2;
433
+ var TRANSPARENT_SORT_MODE_DISTANCE = 3;
434
+ var TransparentSort = Object.freeze({
435
+ layerZ: TRANSPARENT_SORT_MODE_LAYER_Z,
436
+ layerY: TRANSPARENT_SORT_MODE_LAYER_Y,
437
+ layerYZ: TRANSPARENT_SORT_MODE_LAYER_YZ,
438
+ distance: TRANSPARENT_SORT_MODE_DISTANCE,
439
+ configure: setTransparentSortConfig
440
+ });
441
+ var DEFAULT_CONFIG = Object.freeze({
442
+ mode: TRANSPARENT_SORT_MODE_LAYER_Z,
443
+ yzAlpha: 1
444
+ });
445
+ var VALID_MODES = /* @__PURE__ */ new Set([
446
+ TRANSPARENT_SORT_MODE_LAYER_Z,
447
+ TRANSPARENT_SORT_MODE_LAYER_Y,
448
+ TRANSPARENT_SORT_MODE_LAYER_YZ,
449
+ TRANSPARENT_SORT_MODE_DISTANCE
450
+ ]);
451
+ var EXPECTED_MODE = "mode \u2208 {0, 1, 2, 3}";
452
+ var HINT_MODE = "0=layer-z, 1=layer-y, 2=layer-yz, 3=distance";
453
+ function getTransparentSortConfig(world) {
454
+ if ("resolveAsset" in world) return world.transparentSort;
455
+ if (!world.hasResource(TRANSPARENT_SORT_CONFIG_KEY)) {
456
+ return DEFAULT_CONFIG;
457
+ }
458
+ return world.getResource(TRANSPARENT_SORT_CONFIG_KEY);
459
+ }
460
+ function setTransparentSortConfig(world, cfg) {
461
+ if (!VALID_MODES.has(cfg.mode)) {
462
+ return err(
463
+ new ResourceInvalidValueError(EXPECTED_MODE, HINT_MODE, {
464
+ receivedMode: cfg.mode,
465
+ receivedKey: TRANSPARENT_SORT_CONFIG_KEY
466
+ })
467
+ );
468
+ }
469
+ world.insertResource(TRANSPARENT_SORT_CONFIG_KEY, {
470
+ mode: cfg.mode,
471
+ yzAlpha: cfg.yzAlpha
472
+ });
473
+ return ok(void 0);
474
+ }
428
475
 
429
- export { MaterialAuthoringContractError, MaterialTransmissionContractError, Materials, SPRITE_PREMULTIPLIED_ALPHA_BLEND, srgb };
430
- //# sourceMappingURL=chunk-BLXGONR2.mjs.map
431
- //# sourceMappingURL=chunk-BLXGONR2.mjs.map
476
+ export { MaterialAuthoringContractError, MaterialTransmissionContractError, Materials, SPRITE_PREMULTIPLIED_ALPHA_BLEND, TRANSPARENT_SORT_MODE_DISTANCE, TRANSPARENT_SORT_MODE_LAYER_Y, TRANSPARENT_SORT_MODE_LAYER_YZ, TRANSPARENT_SORT_MODE_LAYER_Z, TransparentSort, getTransparentSortConfig, srgb };
477
+ //# sourceMappingURL=chunk-XSFB7XXQ.mjs.map
478
+ //# sourceMappingURL=chunk-XSFB7XXQ.mjs.map