@forgeax/engine-render 0.1.35 → 0.1.36
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -0
- package/dist/assembly/webgpu-vertex-layouts.d.ts.map +1 -1
- package/dist/{chunk-MXTWKZO4.mjs → chunk-2OZAS3WU.mjs} +225 -4
- package/dist/chunk-2OZAS3WU.mjs.map +1 -0
- package/dist/{chunk-G6HDNGY7.mjs → chunk-BZQ4CDRF.mjs} +24 -230
- package/dist/chunk-BZQ4CDRF.mjs.map +1 -0
- package/dist/{chunk-LNIUIKQ7.mjs → chunk-CJOV2XLO.mjs} +77 -19
- package/dist/chunk-CJOV2XLO.mjs.map +1 -0
- package/dist/{chunk-3XUBWRY2.mjs → chunk-D6WSBXJ2.mjs} +4 -4
- package/dist/{chunk-3XUBWRY2.mjs.map → chunk-D6WSBXJ2.mjs.map} +1 -1
- package/dist/{chunk-LM5IE7GF.mjs → chunk-DRF6OULX.mjs} +3 -3
- package/dist/{chunk-LM5IE7GF.mjs.map → chunk-DRF6OULX.mjs.map} +1 -1
- package/dist/{chunk-SGPUJW3F.mjs → chunk-OB5WAFYH.mjs} +3 -3
- package/dist/{chunk-SGPUJW3F.mjs.map → chunk-OB5WAFYH.mjs.map} +1 -1
- package/dist/{chunk-MZ4C7EHF.mjs → chunk-OEYKKMXG.mjs} +5 -5
- package/dist/{chunk-MZ4C7EHF.mjs.map → chunk-OEYKKMXG.mjs.map} +1 -1
- package/dist/construct-renderer.mjs +130 -71
- package/dist/construct-renderer.mjs.map +1 -1
- package/dist/device/device-scope.d.ts.map +1 -1
- package/dist/features/particle-mesh-layout.d.ts +19 -0
- package/dist/features/particle-mesh-layout.d.ts.map +1 -0
- package/dist/features/types.d.ts +5 -1
- package/dist/features/types.d.ts.map +1 -1
- package/dist/gpu-driven/production-raster.d.ts +1 -1
- package/dist/gpu-driven/production-raster.d.ts.map +1 -1
- package/dist/gpu-driven/shadow-views.d.ts +1 -1
- package/dist/gpu-driven/shadow-views.d.ts.map +1 -1
- package/dist/gpu-driven/view-gpu.d.ts +1 -1
- package/dist/gpu-driven/view-gpu.d.ts.map +1 -1
- package/dist/index.mjs +48 -36
- package/dist/index.mjs.map +1 -1
- package/dist/internal.mjs +5 -5
- package/dist/pbr-pipeline.d.ts.map +1 -1
- package/dist/publication/publisher.d.ts +1 -0
- package/dist/publication/publisher.d.ts.map +1 -1
- package/dist/record/frame.d.ts.map +1 -1
- package/dist/record/prepared-material-bindings.d.ts +1 -2
- package/dist/record/prepared-material-bindings.d.ts.map +1 -1
- package/dist/record/render-context.d.ts +2 -0
- package/dist/record/render-context.d.ts.map +1 -1
- package/dist/record/shadow-pass.d.ts +2 -2
- package/dist/record/shadow-pass.d.ts.map +1 -1
- package/dist/record/typed-frame-graph.d.ts.map +1 -1
- package/dist/recovery/render-system-candidate.d.ts +1 -8
- package/dist/recovery/render-system-candidate.d.ts.map +1 -1
- package/dist/render-system-extract-tail.d.ts.map +1 -1
- package/dist/render-system-extract.d.ts.map +1 -1
- package/dist/render-system.d.ts.map +1 -1
- package/dist/temporal/index.mjs +4 -4
- package/dist/typed-shadow-passes.d.ts.map +1 -1
- package/package.json +21 -21
- package/src/__tests__/device-scope-lifecycle.unit.test.ts +26 -0
- package/src/__tests__/gpu-driven-production.integration.test.ts +18 -1
- package/src/__tests__/gpu-driven-shadow-views.unit.test.ts +23 -0
- package/src/__tests__/material-vertex-texture.browser.test.ts +7 -0
- package/src/__tests__/material-vertex-texture.dawn.test.ts +7 -0
- package/src/__tests__/material-vertex-texture.fixture.ts +31 -0
- package/src/__tests__/recovery-candidate-prepare.contract.test.ts +5 -0
- package/src/__tests__/renderer-factory-material-contract.unit.test.ts +106 -4
- package/src/__tests__/runtime-material-program.integration.test.ts +79 -0
- package/src/__tests__/vertex-layouts-ssot.unit.test.ts +23 -3
- package/src/assembly/webgpu-renderer.ts +12 -9
- package/src/assembly/webgpu-vertex-layouts.ts +2 -9
- package/src/device/device-scope.ts +3 -0
- package/src/features/particle-mesh-layout.ts +25 -0
- package/src/features/types.ts +5 -1
- package/src/gpu-driven/production-raster.ts +9 -3
- package/src/gpu-driven/shadow-views.ts +27 -2
- package/src/gpu-driven/view-gpu.ts +5 -0
- package/src/pbr-pipeline.ts +4 -1
- package/src/publication/__tests__/features.integration.test.ts +51 -0
- package/src/publication/__tests__/publication.integration.test.ts +45 -0
- package/src/publication/publisher.ts +56 -29
- package/src/record/__tests__/prepared-runtime-material.integration.test.ts +134 -0
- package/src/record/frame.ts +45 -6
- package/src/record/prepared-material-bindings.ts +11 -37
- package/src/record/render-context.ts +2 -0
- package/src/record/shadow-pass.ts +65 -4
- package/src/record/typed-frame-graph.ts +5 -1
- package/src/recovery/render-system-candidate.ts +1 -9
- package/src/render-system-extract-tail.ts +15 -6
- package/src/render-system-extract.ts +9 -2
- package/src/render-system.ts +0 -1
- package/src/typed-shadow-passes.ts +36 -5
- package/dist/chunk-G6HDNGY7.mjs.map +0 -1
- package/dist/chunk-LNIUIKQ7.mjs.map +0 -1
- package/dist/chunk-MXTWKZO4.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/publication/contract.ts","../src/typed-shadow-atlas.ts","../src/record/frame-targets.ts","../src/targets/contracts.ts","../src/targets/owner.ts","../src/targets/readback.ts","../src/assembly/render-target-host.ts","../src/publication/targets.ts","../src/features/barrel-distortion.ts","../src/cloud/density.ts","../src/cloud/inspection.ts","../src/cloud/resources.ts","../src/cloud/optics.ts","../src/cloud/shadow.ts","../src/cloud/temporal.ts","../src/cloud/feature.ts","../src/surface/gpu-driven.ts","../src/points-lines/admission.ts","../src/point-shadow-inspection.ts","../src/ssr/admission.ts","../src/volume/inspection.ts","../src/surface/dynamic-input.ts","../src/reflection/filter.ts","../src/reflection/gpu-table.ts","../src/reflection/inspection.ts","../src/reflection/projection.ts","../src/scene/visibility/inspection.ts","../src/ssr/inspection.ts","../src/dynamic-geometry.ts","../src/publication/dependencies.ts","../src/tilemap-chunk-extract-system.ts","../src/scene/source-systems.ts","../src/extract/material-context.ts","../src/scene/render-source.ts"],"names":["mipCount","invalid","token","wrapped","ok","x0","y0","z0","x1","y1","z1","fx","fy","fz","smoothstep","normalize","err","pass","failure","resourceStage","ERROR_POLICY","primitiveKey","activeSet","world","ChildOf","GlobalTransform","Transform"],"mappings":";;;;;;;;;;;;;;;;AA0EO,SAAS,2BAA2B,MAAA,EAA0C;AACnF,EAAA,OAAO;AAAA,IACL,OAAO,OAAA,CAAQ,MAAA;AAAA,IACf,OAAO,OAAA,CAAQ,MAAA;AAAA,IACf,OAAO,iBAAA,CAAkB,MAAA;AAAA,IACzB,OAAO,UAAA,CAAW;AAAA,GACpB;AACF;AAWO,IAAM,sBAAA,GAAN,cAAqC,KAAA,CAAM;AAAA,EAKhD,YACW,MAAA,EACT;AACA,IAAA,KAAA,CAAM,+BAA+B,MAAA,CAAO,MAAM,CAAA,EAAA,EAAK,MAAA,CAAO,OAAO,CAAA,CAAE,CAAA;AAF9D,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAGT,IAAA,IAAA,CAAK,IAAA,GAAO,wBAAA;AAAA,EACd;AAAA,EAJW,MAAA;AAAA,EALF,IAAA,GAAO,4BAAA;AAAA,EACP,QAAA,GAAW,sEAAA;AAAA,EACX,IAAA,GACP,kGAAA;AAOJ;;;AC9FO,SAAS,kCACd,YAAA,EAC4B;AAC5B,EAAA,MAAM,KAAA,GAAQ,IAAA,CAAK,GAAA,CAAI,CAAA,EAAG,IAAA,CAAK,GAAA,CAAI,CAAA,EAAG,IAAA,CAAK,KAAA,CAAM,YAAY,CAAC,CAAC,CAAA;AAC/D,EAAA,IAAI,UAAU,CAAA,EAAG,OAAO,EAAE,OAAA,EAAS,CAAA,EAAG,MAAM,CAAA,EAAE;AAC9C,EAAA,IAAI,UAAU,CAAA,EAAG,OAAO,EAAE,OAAA,EAAS,CAAA,EAAG,MAAM,CAAA,EAAE;AAC9C,EAAA,OAAO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AAU,CAAA;AAEzD","file":"chunk-MZ4C7EHF.mjs","sourcesContent":["import type { TimeResource } from '@forgeax/engine-ecs';\nimport type { MaterialRuntimeArtifact, MaterialShaderEntry } from '@forgeax/engine-shader';\nimport type { Asset, Handle } from '@forgeax/engine-types';\nimport type { DispatchEntry, ExtractedFrame, RenderableSnapshot } from '../render-system-extract';\nimport type { TransparentSortConfig } from '../systems/transparent-sort-config';\nimport type { PublishedRenderTarget, PublishedRenderTargetSource } from './targets';\n\n/** Chosen by App before creating the receiver; never inferred from the first packet. */\nexport interface RenderPublicationIdentity {\n readonly source: string;\n readonly epoch: number;\n}\n\nexport type RenderPublicationMetadata = Omit<\n ExtractedFrame,\n | 'renderables'\n | 'dispatch'\n | 'visibilitySnapshots'\n | 'featureVisibilitySnapshots'\n | 'hiddenEntityReports'\n | 'shadowCasterEntityKeys'\n | 'shadowCasterDrawKeys'\n | 'shadowCasterMembership'\n>;\n\nexport interface RenderPublicationTemplate {\n readonly snapshot: Omit<RenderableSnapshot, 'worldId' | 'entityKey' | 'transform'>;\n readonly dispatch: readonly Omit<DispatchEntry, 'entityIndex' | 'renderableIndex'>[];\n}\n\n/** Numeric storage is publisher-owned; no ECS or asset buffer is transferred. */\nexport interface RenderPublication extends RenderPublicationIdentity {\n readonly revision: number;\n readonly base: number;\n readonly baseline: boolean;\n readonly time: TimeResource;\n readonly sampleTimeSeconds: number;\n readonly temporalReset: boolean;\n readonly transparentSort: TransparentSortConfig;\n readonly metadata: RenderPublicationMetadata;\n readonly templates: readonly RenderPublicationTemplate[];\n readonly videoFrames: readonly {\n readonly entity: number;\n readonly clip: number;\n readonly frame: VideoFrame;\n }[];\n readonly targets: readonly PublishedRenderTarget[];\n readonly targetSources: readonly PublishedRenderTargetSource[];\n readonly features: readonly { readonly identity: string; readonly data: unknown }[];\n readonly programs: readonly {\n readonly key: string;\n readonly shader: MaterialShaderEntry;\n readonly artifact?: MaterialRuntimeArtifact;\n }[];\n /** entity, template index pairs. A publication source owns one World. */\n readonly upserts: Uint32Array;\n readonly removed: Uint32Array;\n readonly transformEntities: Uint32Array;\n readonly transforms: Float32Array;\n readonly assets: readonly {\n readonly handle: Handle<string, 'shared'>;\n readonly guid?: string;\n readonly value: Asset;\n }[];\n readonly retiredAssets: readonly Handle<string, 'shared'>[];\n readonly invalidatedAssets: readonly Handle<string, 'shared'>[];\n}\n\nexport interface PublishedRenderFrameInput {\n readonly publication: RenderPublication;\n /** Realm-local adapter invoked only after the feature's graph is submitted. */\n readonly onFeatureSourceSubmitted?: (identity: string, feedback: unknown) => void;\n}\n\nexport function renderPublicationTransfers(packet: RenderPublication): ArrayBuffer[] {\n return [\n packet.upserts.buffer,\n packet.removed.buffer,\n packet.transformEntities.buffer,\n packet.transforms.buffer,\n ] as ArrayBuffer[];\n}\n\nexport type RenderPublicationFailure =\n | 'identity'\n | 'base'\n | 'revision'\n | 'shape'\n | 'unsupported'\n | 'in-flight'\n | 'disposed';\n\nexport class RenderPublicationError extends Error {\n readonly code = 'render-publication-invalid' as const;\n readonly expected = 'one valid publication for the bound source session and accepted base';\n readonly hint =\n 'inspect detail.reason; repair the source or start a new session with a complete current baseline';\n constructor(\n readonly detail: { readonly reason: RenderPublicationFailure; readonly subject: string },\n ) {\n super(`render-publication-invalid: ${detail.reason}: ${detail.subject}`);\n this.name = 'RenderPublicationError';\n }\n}\n","export interface DirectionalShadowAtlasGrid {\n readonly columns: 1 | 2;\n readonly rows: 1 | 2;\n}\n\n/**\n * The directional CSM atlas layout is one compact contract for raster writes\n * and shader reads: 1 -> 1x1, 2 -> 2x1, and 3/4 -> 2x2.\n */\nexport function resolveDirectionalShadowAtlasGrid(\n cascadeCount: number,\n): DirectionalShadowAtlasGrid {\n const count = Math.max(1, Math.min(4, Math.round(cascadeCount)));\n if (count === 1) return { columns: 1, rows: 1 };\n if (count === 2) return { columns: 2, rows: 1 };\n return { columns: 2, rows: 2 };\n}\n","import type { RhiCanvasContext, Texture, TextureView } from '@forgeax/engine-rhi';\nimport type { RenderGraphExecutionPhase } from '../render-contract';\nimport type { ExtractedLights } from '../render-system-extract';\nimport type { RenderTargetDescriptor } from '../targets/contracts';\nimport { resolveDirectionalShadowAtlasGrid } from '../typed-shadow-atlas';\nimport { configureSurface, type PipelineState, type RenderSystemInternals } from './render-context';\n\nexport function graphExecutionPhase(passName: string): RenderGraphExecutionPhase {\n if (passName.startsWith('shadowCascade')) return 'record/graph-execute/shadow';\n if (passName.startsWith('point-shadow')) return 'record/graph-execute/point-shadow';\n if (passName.startsWith('spot-shadow')) return 'record/graph-execute/spot-shadow';\n if (passName === 'ssr-hiz-seed' || passName.startsWith('ssr-hiz-reduce-')) {\n return 'record/graph-execute/ssr-hiz';\n }\n if (passName === 'ssr-trace') return 'record/graph-execute/ssr-trace';\n if (passName === 'ssr-temporal') return 'record/graph-execute/ssr-temporal';\n if (passName.startsWith('ssr-reflection-mip-')) {\n return 'record/graph-execute/ssr-reflection-mip';\n }\n if (passName === 'ssr-compose') return 'record/graph-execute/ssr-compose';\n if (passName.startsWith('bloom-downsample-')) {\n return 'record/graph-execute/bloom-downsample';\n }\n if (passName.startsWith('bloom-upsample-')) {\n return 'record/graph-execute/bloom-upsample';\n }\n switch (passName) {\n case 'cluster-binner-upload':\n case 'cluster-membership-producer':\n return 'record/graph-execute/cluster-binner-upload';\n case 'g-buffer':\n return 'record/graph-execute/g-buffer';\n case 'ssao-calc':\n return 'record/graph-execute/ssao-calc';\n case 'ssao-blur':\n return 'record/graph-execute/ssao-blur';\n case 'lighting':\n return 'record/graph-execute/lighting';\n case 'forward':\n case 'transmission-forward':\n return 'record/graph-execute/forward';\n case 'output-transform':\n return 'record/graph-execute/output-transform';\n case 'present':\n return 'record/graph-execute/present';\n case 'debug-overlay':\n return 'record/graph-execute/debug-overlay';\n case 'shadow':\n return 'record/graph-execute/shadow';\n case 'skybox':\n return 'record/graph-execute/skybox';\n case 'main':\n return 'record/graph-execute/main';\n case 'fxaa':\n return 'record/graph-execute/fxaa';\n case 'bloom-downsample':\n return 'record/graph-execute/bloom-downsample';\n case 'bloom-upsample':\n return 'record/graph-execute/bloom-upsample';\n case 'bloom-composite':\n return 'record/graph-execute/bloom-composite';\n default:\n return 'record/graph-execute/other';\n }\n}\n\nexport function resolveRenderTargetMipExtent(\n descriptor: RenderTargetDescriptor,\n mipLevel: number,\n): { readonly width: number; readonly height: number } {\n const mipCount =\n descriptor.mipLevels === 1\n ? 1\n : Math.floor(Math.log2(Math.max(descriptor.width, descriptor.height))) + 1;\n const level = Math.max(0, Math.min(mipLevel, mipCount - 1));\n return {\n width: Math.max(1, descriptor.width >> level),\n height: Math.max(1, descriptor.height >> level),\n };\n}\n\nexport function acquireSwapChainTarget(\n internals: RenderSystemInternals,\n pipelineState: PipelineState,\n): { currentTexture: Texture; view: TextureView; targetW: number; targetH: number } | null {\n const canvasContext: RhiCanvasContext | null = internals.context;\n if (canvasContext === null) return null;\n\n let currentTextureResult = canvasContext.getCurrentTexture();\n if (!currentTextureResult.ok) {\n const configuredDevice = internals.resolveSurfaceDevice?.(internals.device);\n if (configuredDevice !== undefined && !configuredDevice.ok) {\n internals.errorRegistry.fire(configuredDevice.error);\n internals.healthRegistry.fire({\n reason: 'internal-fault',\n detail: { message: 'surface device resolution failed; current frame skipped' },\n recoverable: true,\n });\n return null;\n }\n const configured = configureSurface(\n canvasContext,\n configuredDevice?.value ?? internals.device,\n pipelineState.format,\n pipelineState.colorAttachmentFormat,\n );\n if (!configured.ok) {\n internals.errorRegistry.fire(configured.error);\n internals.healthRegistry.fire({\n reason: 'internal-fault',\n detail: { message: 'surface configure candidate failed; current frame skipped' },\n recoverable: true,\n });\n return null;\n }\n pipelineState.perPassResources.configured = true;\n (globalThis as Record<string, unknown>).__forgeaxSwapChainFormat = pipelineState.format;\n const retry = canvasContext.getCurrentTexture();\n if (!retry.ok) {\n internals.errorRegistry.fire(retry.error);\n internals.healthRegistry.fire({\n reason: 'internal-fault',\n detail: {\n message:\n 'surface-configure-failed after retry: getCurrentTexture failed twice consecutively',\n },\n recoverable: false,\n });\n return null;\n }\n currentTextureResult = retry;\n }\n const viewDescriptor =\n pipelineState.colorAttachmentFormat === pipelineState.format\n ? {}\n : { format: pipelineState.colorAttachmentFormat as GPUTextureFormat };\n const viewResult = internals.device.createTextureView(currentTextureResult.value, viewDescriptor);\n if (!viewResult.ok) {\n internals.errorRegistry.fire(viewResult.error);\n return null;\n }\n return {\n currentTexture: currentTextureResult.value,\n view: viewResult.value,\n targetW: internals.canvas.width | 0,\n targetH: internals.canvas.height | 0,\n };\n}\n\nexport function resolveShadowMapSize(\n internals: RenderSystemInternals,\n lights: ExtractedLights,\n): number | undefined {\n if (lights.cascadeCount === undefined) return undefined;\n const requested = lights.shadowMapSize;\n if (!(requested !== undefined && requested > 0)) return requested;\n const cascades = Math.max(1, Math.min(4, Math.round(lights.cascadeCount ?? 1)));\n const atlasGrid = resolveDirectionalShadowAtlasGrid(cascades);\n const maxDimension = internals.device.limits.maxTextureDimension2D;\n if (!(maxDimension > 0)) return Math.floor(requested);\n const depthTextureDimension =\n internals.device.caps?.backendKind === 'wgpu-webgl2'\n ? Math.max(1, Math.floor(maxDimension / 2))\n : maxDimension;\n const maxPerTile = Math.max(\n 1,\n Math.floor(depthTextureDimension / Math.max(atlasGrid.columns, atlasGrid.rows)),\n );\n return Math.max(1, Math.min(Math.floor(requested), maxPerTile));\n}\n\n/**\n * Resolve the per-tile size for the graph-owned spot atlas when a frame has\n * no directional shadow map. The typed spot pass still needs a non-zero\n * viewport in a spot-only world; the directional resolver cannot provide\n * that because it intentionally follows only the directional shadow lane.\n */\nexport function resolveSpotShadowMapSize(\n internals: RenderSystemInternals,\n lights: ExtractedLights,\n): number | undefined {\n const requested = lights.spot.find(\n (spot) => spot.shadowAtlasTile >= 0 && spot.lightViewProj !== undefined,\n )?.mapSize;\n if (!(requested !== undefined && requested > 0)) return requested;\n const maxDimension = internals.device.limits.maxTextureDimension2D;\n if (!(maxDimension > 0)) return Math.floor(requested);\n const maxPerTile = Math.max(1, Math.floor(maxDimension / 2));\n return Math.max(1, Math.min(Math.floor(requested), maxPerTile));\n}\n","import type { RenderError } from '../errors/render';\nimport {\n RenderTargetCapabilityMissingError,\n RenderTargetDescriptorInvalidError,\n} from '../errors/render';\nimport type { RenderResult } from '../render-contract';\n\nexport type RenderTargetFormat = 'rgba16float' | 'rgba8unorm' | 'rgba8unorm-srgb';\nexport type RenderTargetShape = '2d' | 'cube';\nexport type RenderTargetMipLevels = 1 | 'full';\nexport type RenderTargetSampleCount = 1 | 4;\nexport type RenderTargetDepthFormat = 'depth24plus-stencil8' | 'depth32float';\n\nexport interface RenderTargetDescriptor {\n readonly shape: RenderTargetShape;\n readonly width: number;\n readonly height: number;\n readonly format: RenderTargetFormat;\n readonly mipLevels: RenderTargetMipLevels;\n readonly sampleCount: RenderTargetSampleCount;\n readonly depth?: RenderTargetDepthFormat;\n readonly sampled: boolean;\n readonly readback: boolean;\n}\n\ndeclare const RenderTargetBrand: unique symbol;\ndeclare const RenderTargetTextureSourceBrand: unique symbol;\ndeclare const RenderTargetReadbackTicketBrand: unique symbol;\n\n/** Opaque logical target lease owned by one Renderer. */\nexport interface RenderTarget {\n readonly [RenderTargetBrand]: 'RenderTarget';\n}\n\nexport type RenderTargetTextureAspect = 'color';\n\nexport interface RenderTargetTextureSourceOptions {\n readonly aspect: RenderTargetTextureAspect;\n readonly dimension: RenderTargetShape;\n readonly mipLevel: number;\n}\n\n/** Renderer-local runtime material source; it is not an asset handle. */\nexport interface RenderTargetTextureSource {\n readonly [RenderTargetTextureSourceBrand]: 'RenderTargetTextureSource';\n}\n\nexport interface RenderTargetReadbackRequest {\n readonly mipLevel: number;\n /** Cube array layer to copy; 2D targets accept only the omitted form. */\n readonly face?: number;\n}\n\n/** One-shot readback request bound to a future matching FrameReceipt. */\nexport interface RenderTargetReadbackTicket {\n readonly [RenderTargetReadbackTicketBrand]: 'RenderTargetReadbackTicket';\n}\n\n/** Bytes released by observe after the ticket's matching frame completes. */\nexport interface RenderTargetReadbackData {\n readonly ticket: RenderTargetReadbackTicket;\n readonly bytes: Uint8Array;\n readonly frameId: number;\n readonly deviceGeneration: number;\n readonly mipLevel: number;\n readonly face?: number;\n readonly bytesPerRow: number;\n readonly byteLength: number;\n}\n\nexport interface RenderTargetAdmissionLimits {\n readonly maxTextureDimension2D: number;\n readonly maxBytesPerTarget: number;\n readonly renderableFormats: readonly RenderTargetFormat[];\n readonly sampleCounts: readonly RenderTargetSampleCount[];\n readonly depthFormats: readonly RenderTargetDepthFormat[];\n}\n\nconst FORMAT_BYTES: Readonly<Record<RenderTargetFormat, number>> = {\n rgba16float: 8,\n rgba8unorm: 4,\n 'rgba8unorm-srgb': 4,\n};\n\nfunction mipFactor(mipLevels: RenderTargetMipLevels): number {\n return mipLevels === 'full' ? 4 / 3 : 1;\n}\n\nfunction estimatedBytes(descriptor: RenderTargetDescriptor): number {\n const layers = descriptor.shape === 'cube' ? 6 : 1;\n const samples = descriptor.sampleCount;\n const depthBytes = descriptor.depth === undefined ? 0 : 4;\n return Math.ceil(\n descriptor.width *\n descriptor.height *\n FORMAT_BYTES[descriptor.format] *\n layers *\n samples *\n mipFactor(descriptor.mipLevels) +\n descriptor.width *\n descriptor.height *\n depthBytes *\n layers *\n samples *\n mipFactor(descriptor.mipLevels),\n );\n}\n\nfunction invalid(\n field: string,\n value: unknown,\n expected: string,\n): RenderResult<never, RenderError> {\n return {\n ok: false,\n error: new RenderTargetDescriptorInvalidError({ field, value, expected }),\n };\n}\n\n/** Validate descriptor facts before a renderer allocates a physical target. */\nexport function admitRenderTargetDescriptor(\n descriptor: RenderTargetDescriptor,\n limits: RenderTargetAdmissionLimits,\n): RenderResult<RenderTargetDescriptor, RenderError> {\n if (!Number.isInteger(descriptor.width) || descriptor.width < 1) {\n return invalid('width', descriptor.width, 'an integer >= 1');\n }\n if (!Number.isInteger(descriptor.height) || descriptor.height < 1) {\n return invalid('height', descriptor.height, 'an integer >= 1');\n }\n if (\n descriptor.width > limits.maxTextureDimension2D ||\n descriptor.height > limits.maxTextureDimension2D\n ) {\n return invalid(\n 'extent',\n { width: descriptor.width, height: descriptor.height },\n `width and height <= ${limits.maxTextureDimension2D}`,\n );\n }\n if (descriptor.shape === 'cube' && descriptor.width !== descriptor.height) {\n return invalid('shape', descriptor.shape, 'cube width === height');\n }\n if (!limits.renderableFormats.includes(descriptor.format)) {\n return {\n ok: false,\n error: new RenderTargetCapabilityMissingError({\n operation: 'create',\n requested: descriptor.format,\n capability: 'renderableFormats',\n actual: limits.renderableFormats.join(', '),\n }),\n };\n }\n if (!limits.sampleCounts.includes(descriptor.sampleCount)) {\n return {\n ok: false,\n error: new RenderTargetCapabilityMissingError({\n operation: 'create',\n requested: String(descriptor.sampleCount),\n capability: 'sampleCounts',\n actual: limits.sampleCounts.join(', '),\n }),\n };\n }\n if (descriptor.depth !== undefined && !limits.depthFormats.includes(descriptor.depth)) {\n return {\n ok: false,\n error: new RenderTargetCapabilityMissingError({\n operation: 'create',\n requested: descriptor.depth,\n capability: 'depthFormats',\n actual: limits.depthFormats.join(', '),\n }),\n };\n }\n const bytes = estimatedBytes(descriptor);\n if (bytes > limits.maxBytesPerTarget) {\n return invalid('bytes', bytes, `estimated allocation <= ${limits.maxBytesPerTarget}`);\n }\n return { ok: true, value: descriptor };\n}\n","import type { RenderError } from '../errors/render';\nimport { RenderTargetOperationFailedError, RenderTargetStateInvalidError } from '../errors/render';\nimport type { RenderResult } from '../render-contract';\nimport type { RenderTarget, RenderTargetDescriptor } from './contracts';\n\nexport type RenderTargetOwnerState =\n | 'uninitialized'\n | 'candidate'\n | 'active'\n | 'rebuilding'\n | 'destroyed';\n\nexport interface RenderTargetPhysicalCandidate {\n readonly generation: number;\n readonly descriptor: RenderTargetDescriptor;\n}\n\nexport interface RenderTargetOwnerInspection {\n readonly token: RenderTarget;\n readonly state: RenderTargetOwnerState;\n readonly generation: number;\n readonly descriptor: RenderTargetDescriptor;\n readonly candidate?: RenderTargetPhysicalCandidate;\n}\n\nexport interface RenderTargetOwnerOptions {\n readonly rendererId: symbol;\n readonly initialGeneration: number;\n}\n\nexport interface RenderTargetOwner {\n create(descriptor: RenderTargetDescriptor): RenderResult<RenderTarget, RenderError>;\n stage(\n target: RenderTarget,\n descriptor?: RenderTargetDescriptor,\n ): RenderResult<RenderTargetPhysicalCandidate, RenderError>;\n promote(target: RenderTarget, generation: number): RenderResult<void, RenderError>;\n rejectCandidate(\n target: RenderTarget,\n generation: number,\n stage: 'allocation' | 'compile' | 'write' | 'submit',\n ): RenderResult<void, RenderError>;\n beginRecovery(target: RenderTarget, generation: number): RenderResult<void, RenderError>;\n finishRecovery(target: RenderTarget): RenderResult<void, RenderError>;\n retire(target: RenderTarget, generation: number): RenderResult<void, RenderError>;\n destroy(target: RenderTarget): RenderResult<void, RenderError>;\n inspect(target: RenderTarget): RenderResult<RenderTargetOwnerInspection, RenderError>;\n}\n\ninterface TargetState {\n readonly target: RenderTarget;\n readonly rendererId: symbol;\n state: RenderTargetOwnerState;\n generation: number;\n descriptor: RenderTargetDescriptor;\n candidate: RenderTargetPhysicalCandidate | undefined;\n retiredGenerations: Set<number>;\n}\n\nfunction frozenDescriptor(descriptor: RenderTargetDescriptor): RenderTargetDescriptor {\n return Object.freeze({ ...descriptor });\n}\n\nfunction invalid(\n operation: 'inspect' | 'resize' | 'source' | 'readback' | 'destroy',\n reason: 'foreign-renderer' | 'destroyed' | 'uninitialized' | 'generation-mismatch',\n state: RenderTargetOwnerState,\n generation: number,\n): RenderResult<never, RenderError> {\n return {\n ok: false,\n error: new RenderTargetStateInvalidError({ operation, reason, state, generation }),\n };\n}\n\nfunction token(): RenderTarget {\n return Object.freeze({}) as RenderTarget;\n}\n\nexport function createRenderTargetOwner(options: RenderTargetOwnerOptions): RenderTargetOwner {\n const targets = new WeakMap<object, TargetState>();\n const requireTarget = (\n target: RenderTarget,\n operation: 'inspect' | 'resize' | 'source' | 'readback' | 'destroy',\n ): RenderResult<TargetState, RenderError> => {\n const state = targets.get(target as object);\n if (state === undefined) return invalid(operation, 'foreign-renderer', 'destroyed', 0);\n if (state.rendererId !== options.rendererId) {\n return invalid(operation, 'foreign-renderer', state.state, state.generation);\n }\n if (state.state === 'destroyed') {\n return invalid(operation, 'destroyed', state.state, state.generation);\n }\n return { ok: true, value: state };\n };\n\n return {\n create(descriptor) {\n const target = token();\n targets.set(target as object, {\n target,\n rendererId: options.rendererId,\n state: 'uninitialized',\n generation: 0,\n descriptor: frozenDescriptor(descriptor),\n candidate: undefined,\n retiredGenerations: new Set(),\n });\n return { ok: true, value: target };\n },\n stage(target, descriptor) {\n const found = requireTarget(target, 'resize');\n if (!found.ok) return found;\n const state = found.value;\n if (state.state === 'rebuilding') {\n return invalid('resize', 'generation-mismatch', state.state, state.generation);\n }\n const candidate = Object.freeze({\n generation: state.state === 'uninitialized' ? options.initialGeneration : state.generation,\n descriptor: frozenDescriptor(descriptor ?? state.descriptor),\n });\n state.candidate = candidate;\n state.state = 'candidate';\n return { ok: true, value: candidate };\n },\n promote(target, generation) {\n const found = requireTarget(target, 'resize');\n if (!found.ok) return found;\n const state = found.value;\n if (state.candidate?.generation !== generation) {\n return invalid('resize', 'generation-mismatch', state.state, state.generation);\n }\n state.descriptor = state.candidate.descriptor;\n state.generation = generation;\n state.candidate = undefined;\n state.state = 'active';\n return { ok: true, value: undefined };\n },\n rejectCandidate(target, generation, stage) {\n const found = requireTarget(target, 'resize');\n if (!found.ok) return found;\n const state = found.value;\n if (state.candidate?.generation !== generation) {\n return invalid('resize', 'generation-mismatch', state.state, state.generation);\n }\n state.candidate = undefined;\n state.state = state.generation === 0 ? 'uninitialized' : 'active';\n return {\n ok: false,\n error: new RenderTargetOperationFailedError({\n operation: 'resize',\n stage,\n generation,\n cause: new Error(`candidate ${generation} failed during ${stage}`),\n recovery: state.generation === 0 ? 'retry' : 'retain-last-known-good',\n }),\n };\n },\n beginRecovery(target, generation) {\n const found = requireTarget(target, 'resize');\n if (!found.ok) return found;\n const state = found.value;\n if (state.state !== 'active' || generation <= state.generation) {\n return invalid('resize', 'generation-mismatch', state.state, state.generation);\n }\n state.generation = generation;\n state.candidate = undefined;\n state.state = 'rebuilding';\n return { ok: true, value: undefined };\n },\n finishRecovery(target) {\n const found = requireTarget(target, 'resize');\n if (!found.ok) return found;\n const state = found.value;\n if (state.state !== 'rebuilding') {\n return invalid('resize', 'generation-mismatch', state.state, state.generation);\n }\n state.state = 'uninitialized';\n return { ok: true, value: undefined };\n },\n retire(target, generation) {\n const found = requireTarget(target, 'destroy');\n if (!found.ok) return found;\n found.value.retiredGenerations.add(generation);\n return { ok: true, value: undefined };\n },\n destroy(target) {\n const state = targets.get(target as object);\n if (state === undefined) return invalid('destroy', 'foreign-renderer', 'destroyed', 0);\n if (state.rendererId !== options.rendererId) {\n return invalid('destroy', 'foreign-renderer', state.state, state.generation);\n }\n if (state.state === 'destroyed') return { ok: true, value: undefined };\n state.candidate = undefined;\n state.state = 'destroyed';\n return { ok: true, value: undefined };\n },\n inspect(target) {\n const found = requireTarget(target, 'inspect');\n if (!found.ok) return found;\n const state = found.value;\n return {\n ok: true,\n value: Object.freeze({\n token: state.target,\n state: state.state,\n generation: state.generation,\n descriptor: state.descriptor,\n ...(state.candidate === undefined ? {} : { candidate: state.candidate }),\n }),\n };\n },\n };\n}\n","import type { RenderError } from '../errors/render';\nimport { RenderTargetOperationFailedError, RenderTargetStateInvalidError } from '../errors/render';\nimport type { RenderResult } from '../render-contract';\nimport type { RenderTarget } from './contracts';\n\nexport interface RenderTargetReadbackReceipt {\n readonly frameId: number;\n readonly deviceGeneration: number;\n}\n\nexport interface RenderTargetReadbackTicketInput {\n readonly frameId?: number;\n deviceGeneration: number;\n readonly mipLevel: number;\n readonly face?: number;\n readonly width: number;\n readonly height: number;\n readonly bytesPerPixel: number;\n}\n\nexport interface RenderTargetReadbackTicket {\n readonly target: RenderTarget;\n frameId: number | undefined;\n deviceGeneration: number;\n readonly mipLevel: number;\n readonly face?: number;\n readonly width: number;\n readonly height: number;\n readonly bytesPerRow: number;\n readonly byteLength: number;\n consumed: boolean;\n}\n\nexport interface RenderTargetReadbackResult {\n readonly bytes: Uint8Array;\n readonly frameId: number;\n readonly deviceGeneration: number;\n readonly mipLevel: number;\n readonly face?: number;\n}\n\nfunction invalidTicket(\n ticket: RenderTargetReadbackTicket,\n reason: 'uninitialized' | 'generation-mismatch' | 'destroyed',\n): RenderResult<never, RenderError> {\n return {\n ok: false,\n error: new RenderTargetStateInvalidError({\n operation: 'readback',\n reason,\n state: reason === 'destroyed' ? 'destroyed' : 'active',\n generation: ticket.deviceGeneration,\n }),\n };\n}\n\nexport function bindRenderTargetReadbackTicket(\n ticket: RenderTargetReadbackTicket,\n receipt: RenderTargetReadbackReceipt,\n): RenderResult<void, RenderError> {\n if (ticket.consumed) return invalidTicket(ticket, 'destroyed');\n if (ticket.frameId !== undefined) {\n return invalidTicket(ticket, 'generation-mismatch');\n }\n ticket.frameId = receipt.frameId;\n ticket.deviceGeneration = receipt.deviceGeneration;\n return { ok: true, value: undefined };\n}\n\nexport function createRenderTargetReadbackTicket(\n target: RenderTarget,\n input: RenderTargetReadbackTicketInput,\n): RenderResult<RenderTargetReadbackTicket, RenderError> {\n if (\n (input.frameId !== undefined && (!Number.isInteger(input.frameId) || input.frameId < 0)) ||\n !Number.isInteger(input.deviceGeneration) ||\n input.deviceGeneration < 0 ||\n !Number.isInteger(input.mipLevel) ||\n input.mipLevel < 0 ||\n !Number.isInteger(input.width) ||\n input.width < 1 ||\n !Number.isInteger(input.height) ||\n input.height < 1 ||\n !Number.isInteger(input.bytesPerPixel) ||\n input.bytesPerPixel < 1\n ) {\n return {\n ok: false,\n error: new RenderTargetOperationFailedError({\n operation: 'readback',\n stage: 'copy',\n generation: input.deviceGeneration,\n cause: new Error('readback dimensions and identity must be non-negative integers'),\n recovery: 'retry',\n }),\n };\n }\n const unalignedRowBytes = input.width * input.bytesPerPixel;\n const bytesPerRow = Math.ceil(unalignedRowBytes / 256) * 256;\n return {\n ok: true,\n value: {\n target,\n frameId: input.frameId,\n deviceGeneration: input.deviceGeneration,\n mipLevel: input.mipLevel,\n ...(input.face === undefined ? {} : { face: input.face }),\n width: input.width,\n height: input.height,\n bytesPerRow,\n byteLength: bytesPerRow * input.height,\n consumed: false,\n },\n };\n}\n\nexport function completeRenderTargetReadback(\n ticket: RenderTargetReadbackTicket,\n receipt: RenderTargetReadbackReceipt,\n bytes: Uint8Array,\n): RenderResult<RenderTargetReadbackResult, RenderError> {\n if (ticket.consumed) return invalidTicket(ticket, 'destroyed');\n if (\n ticket.frameId === undefined ||\n receipt.frameId !== ticket.frameId ||\n receipt.deviceGeneration !== ticket.deviceGeneration\n ) {\n return invalidTicket(ticket, 'generation-mismatch');\n }\n if (bytes.byteLength !== ticket.byteLength) {\n return {\n ok: false,\n error: new RenderTargetOperationFailedError({\n operation: 'readback',\n stage: 'copy',\n generation: ticket.deviceGeneration,\n cause: new Error(`expected ${ticket.byteLength} bytes, received ${bytes.byteLength}`),\n recovery: 'retry',\n }),\n };\n }\n ticket.consumed = true;\n return {\n ok: true,\n value: {\n bytes,\n frameId: ticket.frameId,\n deviceGeneration: ticket.deviceGeneration,\n mipLevel: ticket.mipLevel,\n ...(ticket.face === undefined ? {} : { face: ticket.face }),\n },\n };\n}\n","import type {\n Buffer,\n RhiCommandEncoder,\n RhiDevice,\n Texture,\n TextureView,\n} from '@forgeax/engine-rhi';\nimport type { RenderError } from '../errors/render';\nimport {\n RenderTargetCapabilityMissingError,\n RenderTargetDescriptorInvalidError,\n RenderTargetOperationFailedError,\n RenderTargetStateInvalidError,\n} from '../errors/render';\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 { GPU_BUFFER_USAGE_COPY_DST, GPU_BUFFER_USAGE_MAP_READ } from '../gpu-usage';\nimport { resolveRenderTargetMipExtent } from '../record/frame-targets';\nimport type { RenderResult } from '../render-contract';\nimport {\n admitRenderTargetDescriptor,\n type RenderTarget,\n type RenderTargetAdmissionLimits,\n type RenderTargetDescriptor,\n type RenderTargetReadbackData,\n type RenderTargetReadbackRequest,\n type RenderTargetReadbackTicket,\n type RenderTargetTextureSource,\n type RenderTargetTextureSourceOptions,\n} from '../targets/contracts';\nimport {\n createRenderTargetMaterialSource,\n type RenderTargetMaterialSourceBinding,\n resolveRenderTargetMaterialSource,\n} from '../targets/material-source';\nimport { createRenderTargetOwner, type RenderTargetOwner } from '../targets/owner';\nimport type { RenderTargetPhysical } from '../targets/physical';\nimport {\n bindRenderTargetReadbackTicket,\n completeRenderTargetReadback,\n createRenderTargetReadbackTicket,\n type RenderTargetReadbackTicket as InternalReadbackTicket,\n type RenderTargetReadbackReceipt,\n} from '../targets/readback';\n\nexport interface RenderTargetHostOptions {\n readonly rendererId?: symbol;\n readonly initialGeneration?: number;\n readonly getGeneration?: () => number;\n readonly limits?: RenderTargetAdmissionLimits;\n readonly getDevice?: () => RhiDevice;\n /**\n * Renderer-owned candidate publication gate. Progressive cube capture keeps\n * a target candidate across face submissions and returns true only after the\n * capture scheduler has committed all faces for the matching fence.\n */\n readonly canPromoteTarget?: (target: RenderTarget) => boolean;\n}\n\nconst DEFAULT_LIMITS: RenderTargetAdmissionLimits = {\n maxTextureDimension2D: 8192,\n maxBytesPerTarget: 256 * 1024 * 1024,\n renderableFormats: ['rgba16float', 'rgba8unorm', 'rgba8unorm-srgb'],\n sampleCounts: [1, 4],\n depthFormats: ['depth24plus-stencil8', 'depth32float'],\n};\n\ninterface ReadbackRecord {\n readonly target: RenderTarget;\n readonly request: RenderTargetReadbackRequest;\n readonly ticket: InternalReadbackTicket;\n readonly buffer?: Buffer;\n encoded: boolean;\n}\n\nexport interface RenderTargetHost {\n /** The logical owner for every target lifecycle operation. */\n readonly owner: 'renderer';\n /** Logical descriptions for the source publication boundary; no physical state escapes. */\n descriptions(): readonly {\n readonly target: RenderTarget;\n readonly descriptor: RenderTargetDescriptor;\n }[];\n createRenderTarget(descriptor: RenderTargetDescriptor): RenderResult<RenderTarget, RenderError>;\n resizeRenderTarget(\n target: RenderTarget,\n descriptor: RenderTargetDescriptor,\n ): RenderResult<void, RenderError>;\n createRenderTargetTextureSource(\n target: RenderTarget,\n options: RenderTargetTextureSourceOptions,\n ): RenderResult<RenderTargetTextureSource, RenderError>;\n /** @internal Resolve a source for the existing material projection path. */\n resolveRenderTargetTextureSource(\n source: RenderTargetTextureSource,\n ): RenderTargetMaterialSourceBinding | undefined;\n requestTargetReadback(\n target: RenderTarget,\n request: RenderTargetReadbackRequest,\n ): RenderResult<RenderTargetReadbackTicket, RenderError>;\n observeTargetReadbacks(\n receipt: RenderTargetReadbackReceipt,\n tickets: readonly RenderTargetReadbackTicket[],\n ): Promise<RenderResult<readonly RenderTargetReadbackData[], RenderError>>;\n /** @internal Physical target used by the active Standard frame. */\n getPhysicalTarget(target: RenderTarget): RenderTargetPhysical | undefined;\n /** @internal Add pending target copies to the frame's sole encoder. */\n encodePendingReadbacks(encoder: RhiCommandEncoder, faces?: readonly number[]): void;\n destroyRenderTarget(target: RenderTarget): RenderResult<void, RenderError>;\n /** Called immediately before the existing Standard frame is interpreted. */\n beginFrame(): void;\n /** Called only after the existing Renderer frame submission is accepted. */\n onFrameSubmitted(completed?: Promise<RenderResult<void, RenderError>>): void;\n /** Called after a replacement DeviceScope generation becomes active. */\n recover(): void;\n /** Called before Renderer-owned physical resources are released. */\n dispose(): void;\n}\n\nfunction opaqueTicket(): RenderTargetReadbackTicket {\n return Object.freeze({}) as RenderTargetReadbackTicket;\n}\n\nfunction bytesPerPixel(format: RenderTargetDescriptor['format']): number {\n return format === 'rgba16float' ? 8 : 4;\n}\n\nfunction mipCount(descriptor: RenderTargetDescriptor): number {\n return descriptor.mipLevels === 1\n ? 1\n : Math.floor(Math.log2(Math.max(descriptor.width, descriptor.height))) + 1;\n}\n\nfunction makePhysical(\n device: RhiDevice,\n descriptor: RenderTargetDescriptor,\n generation: number,\n): RenderResult<RenderTargetPhysical, RenderError> {\n const layers = descriptor.shape === 'cube' ? 6 : 1;\n const usage =\n GPU_TEXTURE_USAGE_RENDER_ATTACHMENT |\n (descriptor.sampled ? GPU_TEXTURE_USAGE_TEXTURE_BINDING : 0) |\n (descriptor.readback ? GPU_TEXTURE_USAGE_COPY_SRC : 0);\n const created = device.createTexture({\n label: `render-target.${generation}`,\n size: { width: descriptor.width, height: descriptor.height, depthOrArrayLayers: layers },\n format: descriptor.format,\n mipLevelCount: mipCount(descriptor),\n // WebGPU forbids multisampled array textures. The cube is always the\n // single-sample resolve destination; MSAA capture uses one depth=1 color\n // texture per face below.\n sampleCount: 1,\n dimension: '2d',\n usage,\n viewFormats: undefined,\n textureBindingViewDimension: descriptor.shape === 'cube' ? 'cube' : undefined,\n });\n if (!created.ok)\n return {\n ok: false,\n error: new RenderTargetOperationFailedError({\n operation: 'create',\n stage: 'allocation',\n generation,\n cause: created.error,\n recovery: 'retry',\n }),\n };\n const texture = created.value;\n const view = device.createTextureView(texture, {\n dimension: descriptor.shape,\n baseMipLevel: 0,\n mipLevelCount: mipCount(descriptor),\n baseArrayLayer: 0,\n arrayLayerCount: layers,\n });\n if (!view.ok)\n return {\n ok: false,\n error: new RenderTargetOperationFailedError({\n operation: 'create',\n stage: 'allocation',\n generation,\n cause: view.error,\n recovery: 'retry',\n }),\n };\n const mipViews: TextureView[] = [];\n for (let mip = 0; mip < mipCount(descriptor); mip += 1) {\n const mipView = device.createTextureView(texture, {\n dimension: descriptor.shape,\n baseMipLevel: mip,\n mipLevelCount: 1,\n baseArrayLayer: 0,\n arrayLayerCount: layers,\n });\n if (!mipView.ok)\n return {\n ok: false,\n error: new RenderTargetOperationFailedError({\n operation: 'create',\n stage: 'allocation',\n generation,\n cause: mipView.error,\n recovery: 'retry',\n }),\n };\n mipViews.push(mipView.value);\n }\n const resolveFaceViews: TextureView[] = [];\n for (let face = 0; face < layers; face += 1) {\n const faceView = device.createTextureView(texture, {\n dimension: '2d',\n baseMipLevel: 0,\n mipLevelCount: 1,\n baseArrayLayer: face,\n arrayLayerCount: 1,\n });\n if (!faceView.ok)\n return {\n ok: false,\n error: new RenderTargetOperationFailedError({\n operation: 'create',\n stage: 'allocation',\n generation,\n cause: faceView.error,\n recovery: 'retry',\n }),\n };\n resolveFaceViews.push(faceView.value);\n }\n const colorTextures: Texture[] = [];\n const faceViews: TextureView[] = [];\n const depthTextures: Texture[] = [];\n const depthViews: TextureView[] = [];\n for (let face = 0; face < layers; face += 1) {\n const depth = device.createTexture({\n label: `render-target.${generation}.depth.${face}`,\n size: {\n width: descriptor.width,\n height: descriptor.height,\n depthOrArrayLayers: descriptor.sampleCount === 4 ? 1 : layers,\n },\n mipLevelCount: 1,\n sampleCount: descriptor.sampleCount,\n dimension: '2d',\n format: 'depth24plus-stencil8',\n usage: GPU_TEXTURE_USAGE_RENDER_ATTACHMENT,\n viewFormats: undefined,\n textureBindingViewDimension: undefined,\n });\n if (!depth.ok)\n return {\n ok: false,\n error: new RenderTargetOperationFailedError({\n operation: 'create',\n stage: 'allocation',\n generation,\n cause: depth.error,\n recovery: 'retry',\n }),\n };\n const depthView = device.createTextureView(depth.value, {\n dimension: '2d',\n baseArrayLayer: descriptor.sampleCount === 4 ? 0 : face,\n arrayLayerCount: 1,\n });\n if (!depthView.ok)\n return {\n ok: false,\n error: new RenderTargetOperationFailedError({\n operation: 'create',\n stage: 'allocation',\n generation,\n cause: depthView.error,\n recovery: 'retry',\n }),\n };\n depthTextures.push(depth.value);\n depthViews.push(depthView.value);\n }\n if (descriptor.sampleCount === 4) {\n for (let face = 0; face < layers; face += 1) {\n const msaa = device.createTexture({\n label: `render-target.${generation}.msaa.${face}`,\n size: { width: descriptor.width, height: descriptor.height, depthOrArrayLayers: 1 },\n format: descriptor.format,\n mipLevelCount: 1,\n sampleCount: 4,\n dimension: '2d',\n usage: GPU_TEXTURE_USAGE_RENDER_ATTACHMENT,\n viewFormats: undefined,\n textureBindingViewDimension: undefined,\n });\n if (!msaa.ok)\n return {\n ok: false,\n error: new RenderTargetOperationFailedError({\n operation: 'create',\n stage: 'allocation',\n generation,\n cause: msaa.error,\n recovery: 'retry',\n }),\n };\n const msaaView = device.createTextureView(msaa.value, {\n dimension: '2d',\n baseMipLevel: 0,\n mipLevelCount: 1,\n baseArrayLayer: 0,\n arrayLayerCount: 1,\n });\n if (!msaaView.ok)\n return {\n ok: false,\n error: new RenderTargetOperationFailedError({\n operation: 'create',\n stage: 'allocation',\n generation,\n cause: msaaView.error,\n recovery: 'retry',\n }),\n };\n colorTextures.push(msaa.value);\n faceViews.push(msaaView.value);\n }\n } else {\n for (let face = 0; face < layers; face += 1) {\n colorTextures.push(texture);\n faceViews.push(resolveFaceViews[face] ?? view.value);\n }\n }\n return {\n ok: true,\n value: {\n generation,\n descriptor,\n texture,\n view: view.value,\n mipViews,\n colorTextures,\n faceViews,\n depthTextures,\n depthViews,\n ...(descriptor.sampleCount === 4 ? { resolveTexture: texture } : {}),\n resolveView: view.value,\n resolveFaceViews,\n },\n };\n}\n\nfunction destroyPhysical(\n device: RhiDevice | undefined,\n physical: RenderTargetPhysical | undefined,\n): void {\n if (device === undefined || physical === undefined) return;\n const textures = new Set<Texture>();\n textures.add(physical.texture);\n if (physical.resolveTexture !== undefined) textures.add(physical.resolveTexture);\n for (const texture of physical.colorTextures) textures.add(texture);\n for (const texture of physical.depthTextures) textures.add(texture);\n for (const texture of textures) device.destroyTexture(texture);\n}\n\nexport function createRenderTargetHost(options: RenderTargetHostOptions = {}): RenderTargetHost {\n let disposed = false;\n const limits = options.limits ?? DEFAULT_LIMITS;\n const owner: RenderTargetOwner = createRenderTargetOwner({\n rendererId: options.rendererId ?? Symbol('renderer'),\n initialGeneration: options.initialGeneration ?? 0,\n });\n const targets = new Set<RenderTarget>();\n const staged = new Set<RenderTarget>();\n const activePhysical = new WeakMap<object, RenderTargetPhysical>();\n const candidatePhysical = new WeakMap<object, RenderTargetPhysical>();\n const sources = new WeakMap<object, RenderTargetMaterialSourceBinding>();\n const readbacks = new WeakMap<object, ReadbackRecord>();\n const readbackRecords = new Set<ReadbackRecord>();\n const currentGeneration = (): number =>\n options.getGeneration?.() ?? options.initialGeneration ?? 0;\n const stagePhysical = (\n target: RenderTarget,\n descriptor?: RenderTargetDescriptor,\n ): RenderResult<void, RenderError> => {\n const stagedTarget = owner.stage(target, descriptor);\n if (!stagedTarget.ok) return stagedTarget;\n const device = options.getDevice?.();\n if (device === undefined) {\n staged.add(target);\n return { ok: true, value: undefined };\n }\n const physical = makePhysical(\n device,\n stagedTarget.value.descriptor,\n stagedTarget.value.generation,\n );\n if (!physical.ok) {\n owner.rejectCandidate(target, stagedTarget.value.generation, 'allocation');\n return physical;\n }\n candidatePhysical.set(target as object, physical.value);\n staged.add(target);\n return { ok: true, value: undefined };\n };\n\n return Object.freeze({\n owner: 'renderer' as const,\n descriptions() {\n return [...targets].map((target) => {\n const state = owner.inspect(target);\n if (!state.ok) throw state.error;\n return { target, descriptor: state.value.candidate?.descriptor ?? state.value.descriptor };\n });\n },\n createRenderTarget(\n descriptor: RenderTargetDescriptor,\n ): RenderResult<RenderTarget, RenderError> {\n if (disposed) {\n return {\n ok: false,\n error: new RenderTargetStateInvalidError({\n operation: 'inspect',\n reason: 'destroyed',\n state: 'destroyed',\n generation: currentGeneration(),\n }),\n };\n }\n const admitted = admitRenderTargetDescriptor(descriptor, limits);\n if (!admitted.ok) return admitted;\n const created = owner.create(admitted.value);\n if (created.ok) targets.add(created.value);\n return created;\n },\n resizeRenderTarget(\n target: RenderTarget,\n descriptor: RenderTargetDescriptor,\n ): RenderResult<void, RenderError> {\n const admitted = admitRenderTargetDescriptor(descriptor, limits);\n if (!admitted.ok) return admitted;\n return stagePhysical(target, admitted.value);\n },\n createRenderTargetTextureSource(\n target: RenderTarget,\n sourceOptions: RenderTargetTextureSourceOptions,\n ): RenderResult<RenderTargetTextureSource, RenderError> {\n const inspected = owner.inspect(target);\n if (!inspected.ok) return inspected;\n if (!inspected.value.descriptor.sampled) {\n return {\n ok: false,\n error: new RenderTargetCapabilityMissingError({\n operation: 'source',\n requested: 'sampled=true',\n capability: 'sampled',\n actual: 'false',\n }),\n };\n }\n if (sourceOptions.dimension !== inspected.value.descriptor.shape) {\n return {\n ok: false,\n error: new RenderTargetDescriptorInvalidError({\n field: 'dimension',\n value: sourceOptions.dimension,\n expected: `dimension matches ${inspected.value.descriptor.shape}`,\n }),\n };\n }\n if (\n !Number.isInteger(sourceOptions.mipLevel) ||\n sourceOptions.mipLevel < 0 ||\n (inspected.value.descriptor.mipLevels === 1 && sourceOptions.mipLevel !== 0)\n ) {\n return {\n ok: false,\n error: new RenderTargetDescriptorInvalidError({\n field: 'mipLevel',\n value: sourceOptions.mipLevel,\n expected: 'an admitted mip level for the target',\n }),\n };\n }\n const binding = createRenderTargetMaterialSource(target, inspected.value.descriptor, {\n ...sourceOptions,\n generation: inspected.value.generation,\n });\n if (!binding.ok) return binding;\n sources.set(binding.value.source as object, binding.value);\n return { ok: true, value: binding.value.source };\n },\n resolveRenderTargetTextureSource(source: RenderTargetTextureSource) {\n const binding = sources.get(source as object) ?? resolveRenderTargetMaterialSource(source);\n if (binding === undefined) return undefined;\n const physical = activePhysical.get(binding.target as object);\n if (physical === undefined) return binding;\n const view =\n physical.mipViews[binding.view.mipLevel] ??\n (binding.shape === 'cube' ? physical.view : physical.resolveView);\n if (binding.generation !== physical.generation) return binding;\n return { ...binding, textureView: view };\n },\n requestTargetReadback(\n target: RenderTarget,\n request: RenderTargetReadbackRequest,\n ): RenderResult<RenderTargetReadbackTicket, RenderError> {\n const inspected = owner.inspect(target);\n if (!inspected.ok) return inspected;\n if (!inspected.value.descriptor.readback) {\n return {\n ok: false,\n error: new RenderTargetCapabilityMissingError({\n operation: 'readback',\n requested: 'readback=true',\n capability: 'readback',\n actual: 'false',\n }),\n };\n }\n if (!Number.isInteger(request.mipLevel) || request.mipLevel < 0) {\n return {\n ok: false,\n error: new RenderTargetDescriptorInvalidError({\n field: 'mipLevel',\n value: request.mipLevel,\n expected: 'a non-negative integer',\n }),\n };\n }\n const mipCount =\n inspected.value.descriptor.mipLevels === 1\n ? 1\n : Math.floor(\n Math.log2(\n Math.max(inspected.value.descriptor.width, inspected.value.descriptor.height),\n ),\n ) + 1;\n if (request.mipLevel >= mipCount) {\n return {\n ok: false,\n error: new RenderTargetDescriptorInvalidError({\n field: 'mipLevel',\n value: request.mipLevel,\n expected: `mipLevel < ${mipCount}`,\n }),\n };\n }\n if (\n request.face !== undefined &&\n (!Number.isInteger(request.face) ||\n request.face < 0 ||\n request.face > 5 ||\n inspected.value.descriptor.shape !== 'cube')\n ) {\n return {\n ok: false,\n error: new RenderTargetDescriptorInvalidError({\n field: 'face',\n value: request.face,\n expected:\n inspected.value.descriptor.shape === 'cube'\n ? 'an integer in [0, 5]'\n : 'omitted for a 2d target',\n }),\n };\n }\n const ticket = opaqueTicket();\n const extent = resolveRenderTargetMipExtent(inspected.value.descriptor, request.mipLevel);\n const buffer = options.getDevice?.()?.createBuffer({\n label: `render-target-readback.${request.mipLevel}.${request.face ?? 0}`,\n size:\n Math.ceil((extent.width * bytesPerPixel(inspected.value.descriptor.format)) / 256) *\n 256 *\n extent.height,\n usage: GPU_BUFFER_USAGE_COPY_DST | GPU_BUFFER_USAGE_MAP_READ,\n mappedAtCreation: false,\n });\n if (buffer !== undefined && !buffer.ok) {\n return {\n ok: false,\n error: new RenderTargetOperationFailedError({\n operation: 'readback',\n stage: 'allocation',\n generation: inspected.value.generation,\n cause: buffer.error,\n recovery: 'retry',\n }),\n };\n }\n const internalTicket = createRenderTargetReadbackTicket(target, {\n deviceGeneration: inspected.value.generation,\n mipLevel: request.mipLevel,\n ...(request.face === undefined ? {} : { face: request.face }),\n width: extent.width,\n height: extent.height,\n bytesPerPixel: bytesPerPixel(inspected.value.descriptor.format),\n });\n if (!internalTicket.ok) return internalTicket;\n const record = {\n target,\n request,\n ticket: internalTicket.value,\n ...(buffer === undefined ? {} : { buffer: buffer.value }),\n encoded: false,\n } satisfies ReadbackRecord;\n readbacks.set(ticket as object, record);\n readbackRecords.add(record);\n return { ok: true, value: ticket };\n },\n async observeTargetReadbacks(\n receipt: RenderTargetReadbackReceipt,\n tickets: readonly RenderTargetReadbackTicket[],\n ): Promise<RenderResult<readonly RenderTargetReadbackData[], RenderError>> {\n const results: RenderTargetReadbackData[] = [];\n for (const publicTicket of tickets) {\n const record = readbacks.get(publicTicket as object);\n if (record === undefined) {\n return {\n ok: false,\n error: new RenderTargetStateInvalidError({\n operation: 'readback',\n reason: 'foreign-renderer',\n state: 'destroyed',\n generation: receipt.deviceGeneration,\n }),\n };\n }\n const inspected = owner.inspect(record.target);\n if (!inspected.ok) return inspected;\n if (inspected.value.state !== 'active') {\n return {\n ok: false,\n error: new RenderTargetStateInvalidError({\n operation: 'readback',\n reason: 'uninitialized',\n state: inspected.value.state,\n generation: inspected.value.generation,\n }),\n };\n }\n if (inspected.value.generation !== receipt.deviceGeneration) {\n return {\n ok: false,\n error: new RenderTargetStateInvalidError({\n operation: 'readback',\n reason: 'generation-mismatch',\n state: inspected.value.state,\n generation: inspected.value.generation,\n }),\n };\n }\n const bound = bindRenderTargetReadbackTicket(record.ticket, receipt);\n if (!bound.ok) return bound;\n let bytes = new Uint8Array(record.ticket.byteLength);\n if (record.buffer !== undefined && typeof record.buffer.mapAsync === 'function') {\n const mapped = await record.buffer.mapAsync(1);\n if (!mapped.ok) {\n return {\n ok: false,\n error: new RenderTargetOperationFailedError({\n operation: 'readback',\n stage: 'copy',\n generation: receipt.deviceGeneration,\n cause: mapped.error,\n recovery: 'retry',\n }),\n };\n }\n const range = mapped.value.getMappedRange();\n if (!range.ok) {\n return {\n ok: false,\n error: new RenderTargetOperationFailedError({\n operation: 'readback',\n stage: 'copy',\n generation: receipt.deviceGeneration,\n cause: range.error,\n recovery: 'retry',\n }),\n };\n }\n bytes = new Uint8Array(range.value.slice(0));\n mapped.value.unmap();\n }\n const completed = completeRenderTargetReadback(record.ticket, receipt, bytes);\n if (!completed.ok) return completed;\n results.push({\n ticket: publicTicket,\n bytes: completed.value.bytes,\n frameId: completed.value.frameId,\n deviceGeneration: completed.value.deviceGeneration,\n mipLevel: completed.value.mipLevel,\n ...(completed.value.face === undefined ? {} : { face: completed.value.face }),\n bytesPerRow: record.ticket.bytesPerRow,\n byteLength: record.ticket.byteLength,\n });\n }\n return { ok: true, value: Object.freeze(results) };\n },\n destroyRenderTarget(target: RenderTarget): RenderResult<void, RenderError> {\n const destroyed = owner.destroy(target);\n if (destroyed.ok) {\n destroyPhysical(options.getDevice?.(), activePhysical.get(target as object));\n destroyPhysical(options.getDevice?.(), candidatePhysical.get(target as object));\n activePhysical.delete(target as object);\n candidatePhysical.delete(target as object);\n for (const record of readbackRecords) {\n if (record.target !== target) continue;\n if (record.buffer !== undefined) options.getDevice?.()?.destroyBuffer(record.buffer);\n readbacks.delete(record.ticket as object);\n readbackRecords.delete(record);\n }\n targets.delete(target);\n }\n return destroyed;\n },\n beginFrame(): void {\n if (disposed) return;\n for (const target of targets) {\n const inspected = owner.inspect(target);\n if (\n !inspected.ok ||\n inspected.value.state === 'active' ||\n inspected.value.state === 'candidate'\n ) {\n continue;\n }\n stagePhysical(target);\n }\n },\n onFrameSubmitted(completed = Promise.resolve({ ok: true, value: undefined } as const)): void {\n if (disposed) return;\n const submittedTargets = [...staged];\n staged.clear();\n void completed.then((result) => {\n for (const target of submittedTargets) {\n const candidate = owner.inspect(target);\n if (!candidate.ok || candidate.value.candidate === undefined) continue;\n if (!result.ok) {\n owner.rejectCandidate(target, candidate.value.candidate.generation, 'submit');\n destroyPhysical(options.getDevice?.(), candidatePhysical.get(target as object));\n candidatePhysical.delete(target as object);\n continue;\n }\n // A progressive CubeCamera writes several faces into one physical\n // candidate across multiple submissions. Do not publish that\n // partially-written generation as active: the next face would then\n // bind the same texture as both a sampled source and an attachment.\n // Keep the target in the staged queue so the next accepted frame (or\n // this same completion callback after the final face) retries the\n // publication check.\n if (options.canPromoteTarget?.(target) === false) {\n staged.add(target);\n continue;\n }\n const generation = candidate.value.candidate.generation;\n const physical = candidatePhysical.get(target as object);\n if (physical === undefined) {\n owner.rejectCandidate(target, generation, 'submit');\n continue;\n }\n const promoted = owner.promote(target, generation);\n if (!promoted.ok) {\n destroyPhysical(options.getDevice?.(), physical);\n candidatePhysical.delete(target as object);\n continue;\n }\n const previous = activePhysical.get(target as object);\n activePhysical.set(target as object, physical as RenderTargetPhysical);\n candidatePhysical.delete(target as object);\n destroyPhysical(options.getDevice?.(), previous);\n }\n });\n },\n getPhysicalTarget(target: RenderTarget): RenderTargetPhysical | undefined {\n return candidatePhysical.get(target as object) ?? activePhysical.get(target as object);\n },\n encodePendingReadbacks(encoder: RhiCommandEncoder, faces?: readonly number[]): void {\n for (const record of readbackRecords) {\n if (record.encoded || record.buffer === undefined) continue;\n if (\n faces !== undefined &&\n record.ticket.face !== undefined &&\n !faces.includes(record.ticket.face)\n ) {\n continue;\n }\n const candidate = candidatePhysical.get(record.target as object);\n const physical =\n faces !== undefined &&\n candidate !== undefined &&\n record.ticket.face !== undefined &&\n faces.includes(record.ticket.face)\n ? candidate\n : activePhysical.get(record.target as object);\n if (physical === undefined) continue;\n const source = physical.resolveTexture ?? physical.texture;\n encoder.copyTextureToBuffer(\n {\n texture: source,\n mipLevel: record.ticket.mipLevel,\n origin: { x: 0, y: 0, z: record.ticket.face ?? 0 },\n },\n {\n buffer: record.buffer,\n bytesPerRow: record.ticket.bytesPerRow,\n rowsPerImage: record.ticket.height,\n },\n [record.ticket.width, record.ticket.height, 1],\n );\n record.encoded = true;\n }\n },\n recover(): void {\n if (disposed) return;\n const generation = currentGeneration();\n for (const target of targets) {\n const inspected = owner.inspect(target);\n if (!inspected.ok || inspected.value.state !== 'active') continue;\n destroyPhysical(options.getDevice?.(), activePhysical.get(target as object));\n destroyPhysical(options.getDevice?.(), candidatePhysical.get(target as object));\n activePhysical.delete(target as object);\n candidatePhysical.delete(target as object);\n for (const record of readbackRecords) {\n if (record.target !== target) continue;\n if (record.buffer !== undefined) options.getDevice?.()?.destroyBuffer(record.buffer);\n readbacks.delete(record.ticket as object);\n readbackRecords.delete(record);\n }\n const begun = owner.beginRecovery(target, generation);\n if (begun.ok) owner.finishRecovery(target);\n }\n },\n dispose(): void {\n disposed = true;\n for (const target of [...targets]) {\n destroyPhysical(options.getDevice?.(), activePhysical.get(target as object));\n destroyPhysical(options.getDevice?.(), candidatePhysical.get(target as object));\n for (const record of readbackRecords) {\n if (record.target !== target) continue;\n if (record.buffer !== undefined) options.getDevice?.()?.destroyBuffer(record.buffer);\n readbacks.delete(record.ticket as object);\n readbackRecords.delete(record);\n }\n activePhysical.delete(target as object);\n candidatePhysical.delete(target as object);\n owner.destroy(target);\n }\n targets.clear();\n staged.clear();\n readbackRecords.clear();\n },\n });\n}\n","import { createRenderTargetHost, type RenderTargetHost } from '../assembly/render-target-host';\nimport type {\n RenderTarget,\n RenderTargetDescriptor,\n RenderTargetTextureSource,\n RenderTargetTextureSourceOptions,\n} from '../targets/contracts';\nimport { resolveRenderTargetMaterialSource } from '../targets/material-source';\nimport type { RenderPublicationTemplate } from './contract';\nimport { RenderPublicationError } from './contract';\nimport type { PreparedRenderPublication } from './receiver';\n\n/** Author descriptions synchronously; the consuming Renderer owns physical resources. */\nexport type RenderTargetAuthoring = Pick<\n RenderTargetHost,\n | 'createRenderTarget'\n | 'resizeRenderTarget'\n | 'createRenderTargetTextureSource'\n | 'destroyRenderTarget'\n>;\nexport interface PublishedRenderTarget {\n readonly id: number;\n readonly token: RenderTarget;\n readonly descriptor: RenderTargetDescriptor;\n}\nexport interface PublishedRenderTargetSource {\n readonly token: RenderTargetTextureSource;\n readonly target: RenderTarget;\n readonly options: RenderTargetTextureSourceOptions;\n}\nexport class RenderPublicationTargetOwner {\n private readonly host = createRenderTargetHost();\n private readonly ids = new WeakMap<object, number>();\n private nextId = 0;\n readonly authoring: RenderTargetAuthoring = this.host;\n snapshot(): readonly PublishedRenderTarget[] {\n return this.host.descriptions().map(({ target, descriptor }) => {\n let id = this.ids.get(target);\n if (id === undefined) {\n id = ++this.nextId;\n this.ids.set(target, id);\n }\n return { id, token: target, descriptor };\n });\n }\n dispose(): void {\n this.host.dispose();\n }\n}\n\nexport function publicationTargetSources(\n templates: readonly RenderPublicationTemplate[],\n): readonly PublishedRenderTargetSource[] {\n const sources = new Map<RenderTargetTextureSource, PublishedRenderTargetSource>();\n for (const template of templates)\n for (const material of template.snapshot.materials) {\n for (const source of material.textureSources?.values() ?? []) {\n if (sources.has(source)) continue;\n const binding = resolveRenderTargetMaterialSource(source);\n if (binding === undefined)\n throw new RenderPublicationError({\n reason: 'shape',\n subject: 'unknown material target source',\n });\n sources.set(source, {\n token: source,\n target: binding.target,\n options: {\n aspect: 'color',\n dimension: binding.view.dimension,\n mipLevel: binding.view.mipLevel,\n },\n });\n }\n }\n return [...sources.values()];\n}\n\ninterface ReceivedTarget {\n readonly target: RenderTarget;\n descriptor: RenderTargetDescriptor;\n readonly sources: Map<string, RenderTargetTextureSource>;\n}\n\n/** Translate logical references once at receive time; no source GPU handle crosses realms. */\nexport class RenderPublicationTargetReceiver {\n private readonly targets = new Map<number, ReceivedTarget>();\n constructor(private readonly host: RenderTargetAuthoring) {}\n apply(input: PreparedRenderPublication): PreparedRenderPublication {\n const packet = input.packet;\n if (packet.targets.length === 0 && packet.targetSources.length === 0 && this.targets.size === 0)\n return input;\n const tokens = new Map<RenderTarget, RenderTarget>();\n const records = new Map<RenderTarget, ReceivedTarget>();\n const active = new Set(packet.targets.map((row) => row.id));\n for (const [id, record] of this.targets)\n if (!active.has(id)) {\n const destroyed = this.host.destroyRenderTarget(record.target);\n if (!destroyed.ok) throw destroyed.error;\n this.targets.delete(id);\n }\n for (const row of packet.targets) {\n let record = this.targets.get(row.id);\n if (record === undefined) {\n const created = this.host.createRenderTarget(row.descriptor);\n if (!created.ok) throw created.error;\n record = { target: created.value, descriptor: row.descriptor, sources: new Map() };\n this.targets.set(row.id, record);\n } else if (JSON.stringify(record.descriptor) !== JSON.stringify(row.descriptor)) {\n const resized = this.host.resizeRenderTarget(record.target, row.descriptor);\n if (!resized.ok) throw resized.error;\n record.descriptor = row.descriptor;\n record.sources.clear();\n }\n tokens.set(row.token, record.target);\n records.set(row.token, record);\n }\n const resolve = (token: RenderTarget): RenderTarget => {\n const target = tokens.get(token);\n if (target === undefined)\n throw new RenderPublicationError({ reason: 'shape', subject: 'missing target descriptor' });\n return target;\n };\n const sources = new Map<RenderTargetTextureSource, RenderTargetTextureSource>();\n for (const row of packet.targetSources) {\n const record = records.get(row.target);\n if (record === undefined)\n throw new RenderPublicationError({ reason: 'shape', subject: 'missing material target' });\n const key = JSON.stringify(row.options);\n let source = record.sources.get(key);\n if (source === undefined) {\n const created = this.host.createRenderTargetTextureSource(record.target, row.options);\n if (!created.ok) throw created.error;\n source = created.value;\n record.sources.set(key, source);\n }\n sources.set(row.token, source);\n }\n const camera = <T extends { readonly target?: RenderTarget }>(row: T): T =>\n row.target === undefined ? row : { ...row, target: resolve(row.target) };\n const renderables = input.frame.renderables.map((row) => {\n const materials = row.materials.map((material) => {\n if (material.textureSources === undefined) return material;\n const textureSources = new Map(\n [...material.textureSources].map(([name, token]) => {\n const source = sources.get(token);\n if (source === undefined)\n throw new RenderPublicationError({\n reason: 'shape',\n subject: 'missing material target source',\n });\n return [name, source] as const;\n }),\n );\n return { ...material, textureSources };\n });\n const first = row.materials.indexOf(row.material);\n return { ...row, materials, material: materials[Math.max(0, first)] ?? row.material };\n });\n const snapshots = new Map(renderables.map((row) => [row.entityKey, row]));\n return {\n ...input,\n frame: {\n ...input.frame,\n renderables,\n cameras: input.frame.cameras.map(camera),\n auxiliaryCameras: input.frame.auxiliaryCameras.map(camera),\n cubeCameras: input.frame.cubeCameras.map(camera),\n },\n operations: input.operations.map((operation) => {\n if (operation.kind === 'remove' || operation.snapshot === undefined) return operation;\n const snapshot = snapshots.get(operation.entityKey);\n if (snapshot === undefined)\n throw new RenderPublicationError({\n reason: 'shape',\n subject: 'missing remapped snapshot',\n });\n return { ...operation, snapshot };\n }),\n };\n }\n}\n","/** One graph-valid identity for the barrel stage, feature and shader prewarm. */\nexport const BARREL_DISTORTION_POST_PROCESS_ID = 'fullscreen.forgeax.barrel-distortion';\nexport const BARREL_DISTORTION_FEATURE_IDENTITY = BARREL_DISTORTION_POST_PROCESS_ID;\n\nimport { ok, type Result } from '@forgeax/engine-types';\nimport type { RenderError } from '../errors/render';\nimport type { RenderFeaturePlan } from './plan';\nimport type { RenderFeature, RenderFeatureExtractContext, RenderFeaturePlanContext } from './types';\n\n/**\n * The coordinate function is exported beside the production shader so a real\n * f32 device probe can compile exactly the same implementation. Keeping the\n * probe source here avoids a second test-only equation that could drift from\n * the Standard pass.\n */\nexport const BARREL_DISTORTION_WGSL_COORDINATE = /* wgsl */ `\nstruct BarrelDistortionParams {\n strength : f32,\n centerX : f32,\n centerY : f32,\n radiusSquared : f32,\n};\n\nfn barrel_distortion_display_to_scene_uv(\n inputUv : vec2<f32>,\n params : BarrelDistortionParams,\n dimensions : vec2<f32>,\n) -> vec2<f32> {\n let aspect = dimensions.x / max(dimensions.y, 1.0);\n let p = vec2<f32>(\n 2.0 * aspect * (inputUv.x - params.centerX),\n 2.0 * (inputUv.y - params.centerY),\n );\n let t = dot(p, p) / max(params.radiusSquared, 1e-6);\n let scale = (1.0 - params.strength) / (1.0 - params.strength * t);\n return clamp(\n vec2<f32>(\n params.centerX + (inputUv.x - params.centerX) * scale,\n params.centerY + (inputUv.y - params.centerY) * scale,\n ),\n vec2<f32>(0.0),\n vec2<f32>(1.0),\n );\n}\n`;\n\n/**\n * Manifest-equivalent WGSL for the bounded analytic model. The Standard\n * owner registers this source once and keeps the graph, encoder, and submit\n * lifecycle shared with every other fullscreen stage.\n */\nexport const BARREL_DISTORTION_WGSL = /* wgsl */ `${BARREL_DISTORTION_WGSL_COORDINATE}\nstruct FullscreenOutput {\n @builtin(position) position : vec4<f32>,\n @location(0) uv : vec2<f32>,\n};\n\nfn fullscreen_triangle(vertex_index : u32) -> FullscreenOutput {\n var x : f32 = -1.0;\n var y : f32 = -1.0;\n if (vertex_index == 1u) { x = 3.0; }\n if (vertex_index == 2u) { y = 3.0; }\n let u : f32 = (x + 1.0) * 0.5;\n let v : f32 = 1.0 - (y + 1.0) * 0.5;\n var out : FullscreenOutput;\n out.position = vec4<f32>(x, y, 0.0, 1.0);\n out.uv = vec2<f32>(u, v);\n return out;\n}\n\n@group(1) @binding(0) var sceneColor : texture_2d<f32>;\n@group(1) @binding(1) var sceneSampler : sampler;\n\n@group(1) @binding(2) var<uniform> params : BarrelDistortionParams;\n\n@vertex\nfn vs_main(@builtin(vertex_index) vertex_index : u32) -> FullscreenOutput {\n return fullscreen_triangle(vertex_index);\n}\n\n@fragment\nfn fs_main(input : FullscreenOutput) -> @location(0) vec4<f32> {\n let dimensions = vec2<f32>(textureDimensions(sceneColor));\n let sampleUv = barrel_distortion_display_to_scene_uv(input.uv, params, dimensions);\n return textureSampleLevel(sceneColor, sceneSampler, sampleUv, 0.0);\n}\n`;\n\n/**\n * Ordinary feature registration for the Standard linear-LDR stage.\n * Standard still allocates the stage targets and chooses its position in the\n * post chain; this feature owns the executable fullscreen declaration that is\n * projected into that slot by the existing graph/encoder/submit path.\n */\nexport interface BarrelDistortionFeatureFrame {\n /** True only when the extracted camera requires a spatial warp this frame. */\n readonly active: boolean;\n}\n\nexport function createBarrelDistortionRenderFeature(): RenderFeature<BarrelDistortionFeatureFrame> {\n return Object.freeze({\n identity: BARREL_DISTORTION_FEATURE_IDENTITY,\n requiredCapabilities: ['rgba16floatRenderable'] as const,\n requiredFullscreenPostProcesses: [\n { identity: BARREL_DISTORTION_POST_PROCESS_ID, source: BARREL_DISTORTION_WGSL },\n ],\n extract: (\n context: RenderFeatureExtractContext,\n ): Result<BarrelDistortionFeatureFrame, RenderError> =>\n ok({ active: (context.selectedCamera?.barrelDistortion?.strength ?? 0) > 0 }),\n plan: (\n data: BarrelDistortionFeatureFrame,\n _context: RenderFeaturePlanContext,\n ): Result<RenderFeaturePlan, RenderError> =>\n ok({\n resources: data.active\n ? [\n {\n kind: 'fullscreen-program' as const,\n name: BARREL_DISTORTION_POST_PROCESS_ID,\n source: BARREL_DISTORTION_WGSL,\n reads: ['ldrColor'],\n params: { byteSize: 16, defaultValue: new Uint8Array(16) },\n },\n {\n kind: 'graphics-program' as const,\n name: 'barrel-distortion-pipeline',\n program: {\n shader: BARREL_DISTORTION_POST_PROCESS_ID,\n vertexLayout: 'none',\n colorFormats: ['rgba16float'],\n sampleCount: 1,\n },\n },\n {\n kind: 'graphics-bindings' as const,\n name: 'barrel-distortion-bindings',\n program: 'barrel-distortion-pipeline',\n values: {\n group: 1,\n fullscreen: true,\n shader: BARREL_DISTORTION_POST_PROCESS_ID,\n input: 'barrel-input',\n },\n logicalTargets: { input: 'barrel-input' },\n },\n ]\n : [],\n passes: data.active\n ? [\n {\n kind: 'raster' as const,\n name: 'barrel-distortion',\n colorAttachments: [\n { target: 'barrel-output', loadOp: 'clear' as const, storeOp: 'store' as const },\n ],\n sampledTargets: ['barrel-input'],\n draws: [\n {\n program: 'barrel-distortion-pipeline',\n bindings: ['barrel-distortion-bindings'],\n vertexData: [],\n vertexLayout: 'none' as const,\n draw: { kind: 'draw' as const, vertexCount: 3, instanceCount: 1 },\n },\n ],\n },\n ]\n : [],\n }),\n });\n}\n","import { err, ok, type Result } from '@forgeax/engine-types';\nimport { CloudLayerCacheInvalidError, type CloudLayerError } from '../errors/cloud';\nimport {\n CLOUD_QUALITY_PROFILES,\n type CloudQualityProfile,\n cloudLayerFormationKey,\n type ValidatedCloudLayer,\n} from './parameters';\n\nexport interface CloudDensityCache {\n readonly sourceKey: string;\n readonly resolution: number;\n /** R8 normalized density values in z-major, y, x order. */\n readonly data: Uint8Array;\n /**\n * Weather, body and erosion bases in three contiguous R8 planes. `data` is\n * retained as a diagnostic projection for callers that still need the\n * composed density; runtime sampling uses these formation planes so coverage,\n * density and wind remain evaluation controls.\n */\n readonly formationData: Uint8Array;\n readonly formationByteLength: number;\n /** Bytes uploaded for the reusable formation planes. */\n readonly byteLength: number;\n readonly digest: string;\n}\n\nexport interface CloudDensityCacheSnapshot {\n readonly sourceKey: string;\n readonly resolution: number;\n readonly data: Uint8Array;\n readonly formationData?: Uint8Array;\n readonly digest: string;\n}\n\nexport interface CloudDensitySample {\n readonly density: number;\n readonly heightFraction: number;\n readonly noise: number;\n readonly weather?: number;\n readonly body?: number;\n readonly erosion?: number;\n}\n\nexport interface CloudFormationSample {\n readonly weather: number;\n readonly body: number;\n readonly erosion: number;\n readonly noise: number;\n}\n\n/**\n * The cache is one world-space period. Keep several lattice cells inside that\n * period so a street view sees separate cloud bodies instead of one broad\n * slab. The lattice wraps at the same boundary as the cache, which prevents\n * the old seam from turning into a repeated horizontal band.\n */\nconst CLOUD_SHAPE_CELLS = 4;\nconst CLOUD_WEATHER_CELLS = 2;\nconst CLOUD_DETAIL_CELLS = CLOUD_SHAPE_CELLS * 3;\n// One advective cache period contains four horizontal and two vertical body cells.\n// Integer periods on every axis make the formation continuous when wind wraps\n// through the cache boundary instead of introducing a seam at y = 0/1.\nexport const CLOUD_VERTICAL_CELLS = 1;\n// The cache keeps one advective period, while the formation itself gets two\n// smooth vertical lobes inside that period so the street view does not read as\n// a single sheet. Both are integer-period fields, so the cache seam remains\n// exact.\nconst CLOUD_VERTICAL_NOISE_CELLS = 2;\nconst CLOUD_DETAIL_VERTICAL_CELLS = 3;\n\nfunction saturate(value: number): number {\n return Math.min(1, Math.max(0, value));\n}\n\nfunction smoothstep(edge0: number, edge1: number, value: number): number {\n const t = saturate((value - edge0) / Math.max(1e-6, edge1 - edge0));\n return t * t * (3 - 2 * t);\n}\n\nfunction fract(value: number): number {\n return value - Math.floor(value);\n}\n\nfunction wrapInteger(value: number, period: number): number {\n const wrapped = value % period;\n return wrapped < 0 ? wrapped + period : wrapped;\n}\n\n/** Deterministic integer hash. Every octave uses the same seeded function. */\nfunction hash3(x: number, y: number, z: number, seed: number): number {\n let value = Math.imul(x | 0, 0x45d9f3b);\n value = Math.imul(value ^ Math.imul(y | 0, 0x119de1f3), 0x45d9f3b);\n value = Math.imul(value ^ Math.imul(z | 0, 0x3449f), 0x45d9f3b);\n value ^= seed | 0;\n value = Math.imul(value ^ (value >>> 16), 0x45d9f3b);\n value = Math.imul(value ^ (value >>> 13), 0x27d4eb2d);\n return ((value ^ (value >>> 16)) >>> 0) / 0x100000000;\n}\n\nfunction valueNoise(\n x: number,\n y: number,\n z: number,\n seed: number,\n periodX = 0,\n periodY = 0,\n periodZ = 0,\n): number {\n const ix = Math.floor(x);\n const iy = Math.floor(y);\n const iz = Math.floor(z);\n const fx = x - ix;\n const fy = y - iy;\n const fz = z - iz;\n const ux = fx * fx * (3 - 2 * fx);\n const uy = fy * fy * (3 - 2 * fy);\n const uz = fz * fz * (3 - 2 * fz);\n const lattice = (cellX: number, cellY: number, cellZ: number): number =>\n hash3(\n periodX > 0 ? wrapInteger(cellX, periodX) : cellX,\n periodY > 0 ? wrapInteger(cellY, periodY) : cellY,\n periodZ > 0 ? wrapInteger(cellZ, periodZ) : cellZ,\n seed,\n );\n const c000 = lattice(ix, iy, iz);\n const c100 = lattice(ix + 1, iy, iz);\n const c010 = lattice(ix, iy + 1, iz);\n const c110 = lattice(ix + 1, iy + 1, iz);\n const c001 = lattice(ix, iy, iz + 1);\n const c101 = lattice(ix + 1, iy, iz + 1);\n const c011 = lattice(ix, iy + 1, iz + 1);\n const c111 = lattice(ix + 1, iy + 1, iz + 1);\n const x00 = c000 + (c100 - c000) * ux;\n const x10 = c010 + (c110 - c010) * ux;\n const x01 = c001 + (c101 - c001) * ux;\n const x11 = c011 + (c111 - c011) * ux;\n return x00 + (x10 - x00) * uy + (x01 + (x11 - x01) * uy - (x00 + (x10 - x00) * uy)) * uz;\n}\n\n/** Bounded Worley-like cellular term used to erode the high frequency field. */\nfunction cellularNoise(\n x: number,\n y: number,\n z: number,\n seed: number,\n periodXZ = CLOUD_DETAIL_CELLS,\n periodY = 0,\n): number {\n const ix = Math.floor(x);\n const iy = Math.floor(y);\n const iz = Math.floor(z);\n const fx = x - ix;\n const fy = y - iy;\n const fz = z - iz;\n let nearest = Number.POSITIVE_INFINITY;\n for (let dz = -1; dz <= 1; dz += 1) {\n for (let dy = -1; dy <= 1; dy += 1) {\n for (let dx = -1; dx <= 1; dx += 1) {\n const random = hash3(\n wrapInteger(ix + dx, periodXZ),\n periodY > 0 ? wrapInteger(iy + dy, periodY) : iy + dy,\n wrapInteger(iz + dz, periodXZ),\n seed ^ 0x9e3779b9,\n );\n const px = dx + fract(random * 17.0) - fx;\n const py = dy + fract(random * 31.0) - fy;\n const pz = dz + fract(random * 47.0) - fz;\n nearest = Math.min(nearest, px * px + py * py + pz * pz);\n }\n }\n }\n return 1 - saturate(Math.sqrt(nearest) * 1.25);\n}\n\nfunction heightEnvelope(height: number, body: number, weather: number): number {\n // Let each body choose its own crown height. A fixed upper edge reads as a\n // horizontal slab from the street camera; tying the crown to the cached body\n // makes dense cells grow upward while sparse cells dissolve earlier.\n const lowerEdge = 0.05 + (1 - body) * 0.1;\n const crownEdge = Math.min(0.96, 0.6 + body * 0.3 + weather * 0.08);\n return (\n smoothstep(lowerEdge, Math.min(1, lowerEdge + 0.12), height) *\n (1 - smoothstep(crownEdge, Math.min(1, crownEdge + 0.14), height))\n );\n}\n\n/** Coverage shapes the macro body; detail removes material only at its boundary. */\nfunction composeCloudDensity(\n height: number,\n formation: CloudFormationSample,\n coverage: number,\n): number {\n const threshold = 1 - coverage * (0.45 + formation.weather * 0.55);\n const covered = smoothstep(0, 0.4, (formation.body - threshold) / Math.max(0.001, 1 - threshold));\n const shaped = covered * heightEnvelope(height, formation.body, formation.weather);\n const erosion = (1 - formation.erosion) * 0.18;\n return saturate((shaped - erosion) / (1 - erosion));\n}\n\nfunction formationField(\n x: number,\n y: number,\n z: number,\n seed: number,\n detailRepeat = 1,\n): CloudFormationSample {\n // A low-frequency height-aware warp breaks axis-aligned horizontal sheets\n // while keeping the cache periodic on every axis. The warp is evaluated once while\n // the reusable formation cache is built, so runtime ray steps pay no extra\n // noise cost.\n const macroWarpX =\n valueNoise(\n x * CLOUD_WEATHER_CELLS,\n y * CLOUD_VERTICAL_NOISE_CELLS + 3.0,\n z * CLOUD_WEATHER_CELLS,\n seed + 41023,\n CLOUD_WEATHER_CELLS,\n 2,\n CLOUD_WEATHER_CELLS,\n ) - 0.5;\n const macroWarpZ =\n valueNoise(\n x * CLOUD_WEATHER_CELLS + 5.0,\n y * CLOUD_VERTICAL_NOISE_CELLS - 7.0,\n z * CLOUD_WEATHER_CELLS,\n seed + 41023,\n CLOUD_WEATHER_CELLS,\n 2,\n CLOUD_WEATHER_CELLS,\n ) - 0.5;\n const bodyX = x + macroWarpX * 0.3;\n const bodyZ = z + macroWarpZ * 0.3;\n let amplitude = 0.5;\n let frequency = 1;\n let sum = 0;\n let weight = 0;\n for (let octave = 0; octave < 4; octave += 1) {\n const tilePeriod = CLOUD_SHAPE_CELLS * frequency;\n sum +=\n valueNoise(\n bodyX * tilePeriod,\n y * frequency * CLOUD_VERTICAL_NOISE_CELLS,\n bodyZ * tilePeriod,\n seed + octave * 1013,\n tilePeriod,\n frequency * CLOUD_VERTICAL_NOISE_CELLS,\n tilePeriod,\n ) * amplitude;\n weight += amplitude;\n amplitude *= 0.4;\n frequency *= 2;\n }\n // Perlin-Worley-style body remapping: the broad fBm controls the volume and\n // the cellular field only breaks its boundary. Keeping these values\n // separate is what lets a runtime coverage edit preserve the authored cloud\n // bodies instead of regenerating a final alpha volume.\n const broad = sum / weight;\n // Periodic Worley cells provide bounded breakup. The broad field remains\n // dominant so one cache period reads as a few connected formations instead\n // of a repeated grid of small spheres.\n const cells = cellularNoise(\n bodyX * CLOUD_SHAPE_CELLS,\n y * CLOUD_VERTICAL_NOISE_CELLS,\n bodyZ * CLOUD_SHAPE_CELLS,\n seed + 5011,\n CLOUD_SHAPE_CELLS,\n CLOUD_VERTICAL_NOISE_CELLS,\n );\n // Let the broad field carry the silhouette and use cellular noise as a\n // bounded breakup term. A broad-dominant mix keeps the same cache and ray\n // budget while yielding fewer, wider and less spherical cumulus masses.\n const body = saturate(broad * 0.85 + cells * 0.15 + 0.15);\n const weather = smoothstep(\n 0.34,\n 0.66,\n valueNoise(\n x * CLOUD_WEATHER_CELLS,\n 0.37,\n z * CLOUD_WEATHER_CELLS,\n seed + 17041,\n CLOUD_WEATHER_CELLS,\n 1,\n CLOUD_WEATHER_CELLS,\n ),\n );\n const detailX = x * detailRepeat;\n const detailY = y * detailRepeat;\n const detailZ = z * detailRepeat;\n const warpX =\n valueNoise(\n detailX * CLOUD_WEATHER_CELLS,\n detailY * 2 + 11.0,\n detailZ * CLOUD_WEATHER_CELLS,\n seed + 29011,\n CLOUD_WEATHER_CELLS,\n 2,\n CLOUD_WEATHER_CELLS,\n ) - 0.5;\n const warpZ =\n valueNoise(\n detailX * CLOUD_WEATHER_CELLS + 7.0,\n detailY * 2 - 5.0,\n detailZ * CLOUD_WEATHER_CELLS,\n seed + 29011,\n CLOUD_WEATHER_CELLS,\n 2,\n CLOUD_WEATHER_CELLS,\n ) - 0.5;\n const erosion = cellularNoise(\n (detailX + warpX * 0.22) * CLOUD_DETAIL_CELLS,\n detailY * CLOUD_DETAIL_VERTICAL_CELLS,\n (detailZ + warpZ * 0.22) * CLOUD_DETAIL_CELLS,\n seed + 7919,\n CLOUD_DETAIL_CELLS,\n CLOUD_DETAIL_VERTICAL_CELLS,\n );\n const noise = body;\n return { weather, body, erosion, noise };\n}\n\n/** Evaluate the reusable weather/body/erosion bases at one world position. */\nexport function evaluateCloudFormation(\n params: ValidatedCloudLayer,\n position: ArrayLike<number>,\n timeSeconds = 0,\n): CloudFormationSample {\n const windX = (params.wind[0] ?? 0) * timeSeconds;\n const windY = (params.wind[1] ?? 0) * timeSeconds;\n const windZ = (params.wind[2] ?? 0) * timeSeconds;\n const relativeHeight =\n ((position[1] ?? 0) - params.baseHeight) / Math.max(1e-6, params.thickness);\n const advectedHeight =\n relativeHeight + (windY * params.scale) / Math.max(1e-6, CLOUD_VERTICAL_CELLS);\n return formationField(\n ((position[0] ?? 0) + windX) * params.scale,\n fract(advectedHeight) * CLOUD_VERTICAL_CELLS,\n ((position[2] ?? 0) + windZ) * params.scale,\n params.seed,\n );\n}\n\n/** Analytic field used for cache generation, CPU diagnostics and recovery. */\nexport function evaluateCloudDensity(\n params: ValidatedCloudLayer,\n position: ArrayLike<number>,\n timeSeconds = 0,\n): CloudDensitySample {\n const relativeHeight =\n ((position[1] ?? 0) - params.baseHeight) / Math.max(1e-6, params.thickness);\n if (relativeHeight <= 0 || relativeHeight >= 1 || params.density <= 0 || params.coverage <= 0) {\n return { density: 0, heightFraction: saturate(relativeHeight), noise: 0 };\n }\n const windX = (params.wind[0] ?? 0) * timeSeconds;\n const windY = (params.wind[1] ?? 0) * timeSeconds;\n const windZ = (params.wind[2] ?? 0) * timeSeconds;\n const x = ((position[0] ?? 0) + windX) * params.scale;\n const advectedHeight =\n relativeHeight + (windY * params.scale) / Math.max(1e-6, CLOUD_VERTICAL_CELLS);\n const y = fract(advectedHeight) * CLOUD_VERTICAL_CELLS;\n const z = ((position[2] ?? 0) + windZ) * params.scale;\n const formation = formationField(x, y, z, params.seed, 3);\n const noise = formation.noise;\n return {\n density: composeCloudDensity(relativeHeight, formation, params.coverage) * params.density,\n heightFraction: relativeHeight,\n noise,\n weather: formation.weather,\n body: formation.body,\n erosion: formation.erosion,\n };\n}\n\nfunction cacheIndex(resolution: number, x: number, y: number, z: number): number {\n return z * resolution * resolution + y * resolution + x;\n}\n\nfunction digestBytes(data: Uint8Array): string {\n // FNV-1a is stable and intentionally cheap; this is an identity receipt,\n // not a cryptographic integrity boundary.\n let hash = 0x811c9dc5;\n for (const byte of data) {\n hash ^= byte;\n hash = Math.imul(hash, 0x01000193);\n }\n return (hash >>> 0).toString(16).padStart(8, '0');\n}\n\n/** Build one canonical, periodic formation cache. */\nexport function buildCloudDensityCache(\n params: ValidatedCloudLayer,\n profile: CloudQualityProfile = CLOUD_QUALITY_PROFILES[params.quality],\n): CloudDensityCache {\n const resolution = Math.max(4, Math.floor(profile.cacheResolution));\n const data = new Uint8Array(resolution * resolution * resolution);\n const formationData = new Uint8Array(data.byteLength * 3);\n const position = [0, 0, 0];\n for (let z = 0; z < resolution; z += 1) {\n for (let y = 0; y < resolution; y += 1) {\n position[1] = params.baseHeight + ((y + 0.5) / resolution) * params.thickness;\n for (let x = 0; x < resolution; x += 1) {\n // One cache period is one noise period in world space. This makes the\n // x/z addressing periodic and lets advection wrap without seams.\n position[0] = (x + 0.5) / resolution / params.scale;\n position[2] = (z + 0.5) / resolution / params.scale;\n const index = cacheIndex(resolution, x, y, z);\n const formation = evaluateCloudFormation(params, position, 0);\n formationData[index] = Math.round(saturate(formation.weather) * 255);\n formationData[data.byteLength + index] = Math.round(saturate(formation.body) * 255);\n formationData[data.byteLength * 2 + index] = Math.round(saturate(formation.erosion) * 255);\n }\n }\n }\n const cache: CloudDensityCache = {\n sourceKey: cloudLayerFormationKey(params),\n resolution,\n data,\n formationData,\n formationByteLength: formationData.byteLength,\n byteLength: formationData.byteLength,\n digest: digestBytes(formationData),\n };\n for (let z = 0; z < resolution; z++) {\n for (let y = 0; y < resolution; y++) {\n for (let x = 0; x < resolution; x++) {\n position[0] = (x + 0.5) / resolution / params.scale;\n position[1] = params.baseHeight + ((y + 0.5) / resolution) * params.thickness;\n position[2] = (z + 0.5) / resolution / params.scale;\n data[cacheIndex(resolution, x, y, z)] = Math.round(\n saturate(sampleCloudDensity(cache, params, position)) * 255,\n );\n }\n }\n }\n return Object.freeze(cache);\n}\n\n/** Export a detached snapshot suitable for persistence or a worker boundary. */\nexport function snapshotCloudDensityCache(cache: CloudDensityCache): CloudDensityCacheSnapshot {\n return Object.freeze({\n sourceKey: cache.sourceKey,\n resolution: cache.resolution,\n data: new Uint8Array(cache.data),\n formationData: new Uint8Array(cache.formationData),\n digest: cache.digest,\n });\n}\n\n/** Reconstruct a cache without running the procedural generator again. */\nexport function reconstructCloudDensityCache(\n params: ValidatedCloudLayer,\n snapshot: CloudDensityCacheSnapshot,\n): Result<CloudDensityCache, CloudLayerError> {\n const expectedKey = cloudLayerFormationKey(params);\n if (snapshot.sourceKey !== expectedKey) {\n return err(new CloudLayerCacheInvalidError(snapshot.sourceKey, 'source key mismatch'));\n }\n if (\n !Number.isInteger(snapshot.resolution) ||\n snapshot.resolution < 4 ||\n snapshot.resolution > 256 ||\n snapshot.data.byteLength !== snapshot.resolution ** 3 ||\n (snapshot.formationData !== undefined &&\n snapshot.formationData.byteLength !== snapshot.resolution ** 3 * 3)\n ) {\n return err(\n new CloudLayerCacheInvalidError(snapshot.sourceKey, 'resolution and payload length mismatch'),\n );\n }\n const formationData =\n snapshot.formationData === undefined\n ? new Uint8Array(snapshot.data.length * 3).fill(0)\n : new Uint8Array(snapshot.formationData);\n const digest = digestBytes(formationData);\n if (digest !== snapshot.digest) {\n return err(new CloudLayerCacheInvalidError(snapshot.sourceKey, 'payload digest mismatch'));\n }\n const data = new Uint8Array(snapshot.data);\n return ok(\n Object.freeze({\n sourceKey: snapshot.sourceKey,\n resolution: snapshot.resolution,\n data,\n formationData,\n formationByteLength: formationData.byteLength,\n byteLength: formationData.byteLength,\n digest,\n }),\n );\n}\n\nfunction wrapped(value: number, resolution: number): number {\n const result = value - Math.floor(value);\n return Math.min(resolution - 1e-6, Math.max(0, result * resolution));\n}\n\n/** Sample the cached field with periodic x/z addressing and wind advection. */\nexport function sampleCloudDensity(\n cache: CloudDensityCache,\n params: ValidatedCloudLayer,\n position: ArrayLike<number>,\n timeSeconds = 0,\n): number {\n const height = ((position[1] ?? 0) - params.baseHeight) / Math.max(1e-6, params.thickness);\n if (height <= 0 || height >= 1 || params.coverage <= 0 || params.density <= 0) return 0;\n const period = 1 / Math.max(1e-6, params.scale);\n const x = wrapped(\n ((position[0] ?? 0) + (params.wind[0] ?? 0) * timeSeconds) / period - 0.5 / cache.resolution,\n cache.resolution,\n );\n const z = wrapped(\n ((position[2] ?? 0) + (params.wind[2] ?? 0) * timeSeconds) / period - 0.5 / cache.resolution,\n cache.resolution,\n );\n // The cache's y axis stores the normalized formation coordinate before\n // vertical advection. Map the authored noise shift back through the same\n // vertical cell aspect used by formationField; the world-space envelope\n // below remains anchored to the current receiver height.\n const advectedHeight =\n height +\n ((params.wind[1] ?? 0) * timeSeconds * params.scale) / Math.max(1e-6, CLOUD_VERTICAL_CELLS);\n const y = wrapped(advectedHeight - 0.5 / cache.resolution, cache.resolution);\n const x0 = Math.floor(x);\n const y0 = Math.floor(y);\n const z0 = Math.floor(z);\n const x1 = (x0 + 1) % cache.resolution;\n const y1 = (y0 + 1) % cache.resolution;\n const z1 = (z0 + 1) % cache.resolution;\n const fx = x - x0;\n const fy = y - y0;\n const fz = z - z0;\n const stride = cache.resolution ** 3;\n if (cache.formationData === undefined || cache.formationData.byteLength < stride * 3) {\n const sampleLegacy = (sx: number, sy: number, sz: number): number =>\n (cache.data[cacheIndex(cache.resolution, sx, sy, sz)] ?? 0) / 255;\n const c00 =\n sampleLegacy(x0, y0, z0) + (sampleLegacy(x1, y0, z0) - sampleLegacy(x0, y0, z0)) * fx;\n const c10 =\n sampleLegacy(x0, y1, z0) + (sampleLegacy(x1, y1, z0) - sampleLegacy(x0, y1, z0)) * fx;\n const c01 =\n sampleLegacy(x0, y0, z1) + (sampleLegacy(x1, y0, z1) - sampleLegacy(x0, y0, z1)) * fx;\n const c11 =\n sampleLegacy(x0, y1, z1) + (sampleLegacy(x1, y1, z1) - sampleLegacy(x0, y1, z1)) * fx;\n return (\n (c00 + (c10 - c00) * fy + (c01 + (c11 - c01) * fy - (c00 + (c10 - c00) * fy)) * fz) *\n heightEnvelope(height, 1, 0.5) *\n params.density\n );\n }\n const samplePlane = (plane: number, sx: number, sy: number, sz: number): number => {\n const payload = cache.formationData;\n const offset = plane * stride + cacheIndex(cache.resolution, sx, sy, sz);\n return (payload[offset] ?? 0) / 255;\n };\n const sample = (plane: number): number => {\n const repeat = plane === 2 ? 3 : 1;\n const sx = wrapped(\n ((x + 0.5) / cache.resolution) * repeat - 0.5 / cache.resolution,\n cache.resolution,\n );\n const sy = wrapped(\n ((y + 0.5) / cache.resolution) * repeat - 0.5 / cache.resolution,\n cache.resolution,\n );\n const sz = wrapped(\n ((z + 0.5) / cache.resolution) * repeat - 0.5 / cache.resolution,\n cache.resolution,\n );\n const x0 = Math.floor(sx),\n y0 = Math.floor(sy),\n z0 = Math.floor(sz);\n const x1 = (x0 + 1) % cache.resolution,\n y1 = (y0 + 1) % cache.resolution,\n z1 = (z0 + 1) % cache.resolution;\n const fx = sx - x0,\n fy = sy - y0,\n fz = sz - z0;\n\n const c00 =\n samplePlane(plane, x0, y0, z0) +\n (samplePlane(plane, x1, y0, z0) - samplePlane(plane, x0, y0, z0)) * fx;\n const c10 =\n samplePlane(plane, x0, y1, z0) +\n (samplePlane(plane, x1, y1, z0) - samplePlane(plane, x0, y1, z0)) * fx;\n const c01 =\n samplePlane(plane, x0, y0, z1) +\n (samplePlane(plane, x1, y0, z1) - samplePlane(plane, x0, y0, z1)) * fx;\n const c11 =\n samplePlane(plane, x0, y1, z1) +\n (samplePlane(plane, x1, y1, z1) - samplePlane(plane, x0, y1, z1)) * fx;\n return c00 + (c10 - c00) * fy + (c01 + (c11 - c01) * fy - (c00 + (c10 - c00) * fy)) * fz;\n };\n const weather = sample(0);\n const body = sample(1);\n const erosion = sample(2);\n return (\n composeCloudDensity(height, { weather, body, erosion, noise: body }, params.coverage) *\n params.density\n );\n}\n","import type { RhiCaps } from '@forgeax/engine-rhi';\nimport type { CloudLayerResourceFacts } from './resources';\nimport type { CloudTemporalResetReason } from './temporal';\n\nexport type CloudLayerInspectionStatus = 'off' | 'available' | 'unavailable' | 'degraded';\nexport type CloudLayerResourceStage = 'none' | 'candidate' | 'accepted' | 'lkg' | 'recovering';\n/** Physical-adapter evidence is explicit; RHI backend labels cannot prove it. */\nexport type CloudPhysicalGpuEvidence = 'unknown' | 'available' | 'unavailable';\n\nexport interface CloudLayerBudgetObservation {\n readonly measured: boolean;\n readonly physicalGpu: CloudPhysicalGpuEvidence;\n readonly gpuTimestamp: boolean;\n readonly quality: 'low' | 'medium' | 'high' | undefined;\n readonly warmupFrames: number;\n readonly sampleFrames: number;\n readonly p50GpuMs: number | undefined;\n readonly p95GpuMs: number | undefined;\n readonly coldGenerationMs: number | undefined;\n readonly frameBudgetMs: number | undefined;\n readonly reason?: string;\n}\n\nexport interface CloudLayerInspection {\n readonly status: CloudLayerInspectionStatus;\n readonly resourceStage: CloudLayerResourceStage;\n readonly sourceKey: string | undefined;\n readonly generation: number | undefined;\n readonly candidateGeneration: number | undefined;\n readonly lkgGeneration: number | undefined;\n readonly shadowRevision: number | undefined;\n readonly temporalResets: number;\n readonly lastTemporalReset: CloudTemporalResetReason | undefined;\n readonly resourceFacts: CloudLayerResourceFacts | undefined;\n readonly capability: {\n readonly compute: boolean;\n readonly storageBuffer: boolean;\n readonly rgba16floatRenderable: boolean;\n readonly physicalGpu: CloudPhysicalGpuEvidence;\n readonly timestampQuery: boolean;\n };\n readonly budget: CloudLayerBudgetObservation;\n}\n\nexport interface CloudLayerInspectionInput {\n readonly authored: boolean;\n readonly sourceKey?: string;\n readonly generation?: number;\n readonly candidateGeneration?: number;\n readonly lkgGeneration?: number;\n readonly shadowRevision?: number;\n readonly temporalResets?: number;\n readonly lastTemporalReset?: CloudTemporalResetReason;\n readonly resourceFacts?: CloudLayerResourceFacts;\n readonly capability?: Partial<CloudLayerInspection['capability']>;\n readonly degraded?: boolean;\n readonly budget?: Partial<CloudLayerBudgetObservation>;\n}\n\nfunction resourceStage(input: CloudLayerInspectionInput): CloudLayerResourceStage {\n if (!input.authored || input.generation === undefined) return 'none';\n if (input.candidateGeneration !== undefined) return 'candidate';\n if (input.degraded === true || input.lkgGeneration !== undefined) return 'lkg';\n return 'accepted';\n}\n\n/** Capability and lifecycle facts are inspectable even when the lane is unavailable. */\nexport function inspectCloudLayer(input: CloudLayerInspectionInput): CloudLayerInspection {\n const capability = {\n compute: input.capability?.compute ?? false,\n storageBuffer: input.capability?.storageBuffer ?? false,\n rgba16floatRenderable: input.capability?.rgba16floatRenderable ?? false,\n physicalGpu: input.capability?.physicalGpu ?? 'unknown',\n timestampQuery: input.capability?.timestampQuery ?? false,\n };\n const budget: CloudLayerBudgetObservation = {\n measured: input.budget?.measured ?? false,\n physicalGpu: input.budget?.physicalGpu ?? capability.physicalGpu,\n gpuTimestamp: input.budget?.gpuTimestamp ?? capability.timestampQuery,\n quality: input.budget?.quality,\n warmupFrames: input.budget?.warmupFrames ?? 0,\n sampleFrames: input.budget?.sampleFrames ?? 0,\n p50GpuMs: input.budget?.p50GpuMs,\n p95GpuMs: input.budget?.p95GpuMs,\n coldGenerationMs: input.budget?.coldGenerationMs,\n frameBudgetMs: input.budget?.frameBudgetMs,\n ...(input.budget?.reason === undefined ? {} : { reason: input.budget.reason }),\n };\n // CloudLayer's production plan allocates an HDR shadow/composite target and\n // therefore requires the complete feature capability tuple. Reporting\n // `available` from compute/storage alone lets inspection lie while the graph\n // admission correctly disables the feature on LDR-only adapters.\n const available =\n capability.compute && capability.storageBuffer && capability.rgba16floatRenderable;\n return Object.freeze({\n status: !input.authored\n ? 'off'\n : !available\n ? 'unavailable'\n : input.degraded === true\n ? 'degraded'\n : 'available',\n resourceStage: resourceStage(input),\n sourceKey: input.sourceKey,\n generation: input.generation,\n candidateGeneration: input.candidateGeneration,\n lkgGeneration: input.lkgGeneration,\n shadowRevision: input.shadowRevision,\n temporalResets: input.temporalResets ?? 0,\n lastTemporalReset: input.lastTemporalReset,\n resourceFacts: input.resourceFacts,\n capability,\n budget,\n });\n}\n\n/** Convert RHI facts without letting inspection invent physical measurements. */\nexport function cloudCapabilitiesFromRhi(\n caps: Readonly<RhiCaps>,\n): CloudLayerInspection['capability'] {\n return Object.freeze({\n compute: caps.compute === true,\n storageBuffer: caps.storageBuffer === true,\n rgba16floatRenderable: caps.rgba16floatRenderable === true,\n // RHI caps intentionally do not claim a physical adapter. A browser or\n // Dawn receipt must promote this fact to available/unavailable.\n physicalGpu: 'unknown',\n timestampQuery: caps.timestampQuery === true,\n });\n}\n","import type { CloudDensityCache } from './density';\nimport type { CloudShadowProjection } from './shadow';\nimport type { CloudHistory } from './temporal';\n\n/** Evidence level for bytes owned by the prepared GPU path. */\nexport type CloudGpuResourceEvidence = 'unavailable' | 'declared' | 'measured';\n\n/** rgba16float is four 16-bit channels (8 bytes per texel). */\nexport const CLOUD_RGBA16FLOAT_BYTES_PER_TEXEL = 8;\n/** Two ping-pong surfaces for each of radiance/transmittance/depth. */\nexport const CLOUD_HISTORY_SURFACE_COUNT = 6;\n\nexport interface CloudLayerResourceFacts {\n readonly generation: number;\n /** CPU-side packed formation payload; this is not GPU residency. */\n readonly cacheBytes: number;\n /** Measured GPU bytes, or zero when no prepared-owner receipt was supplied. */\n readonly shadowBytes: number;\n readonly historyBytes: number;\n readonly inFlightBytes: number;\n readonly residentBytes: number;\n readonly resourceCount: number;\n /** Whether the GPU byte fields are measured, only graph-declared, or unknown. */\n readonly gpuEvidence: CloudGpuResourceEvidence;\n /** Descriptor-derived allocation sizes, independent from physical residency. */\n readonly declaredShadowBytes: number;\n readonly declaredHistoryBytes: number;\n readonly declaredResidentBytes: number;\n readonly declaredResourceCount: number;\n /** Measured GPU resource count, kept separate from logical declarations. */\n readonly measuredGpuResourceCount: number;\n readonly cacheResolution: number;\n readonly shadowResolution: number;\n}\n\nexport interface CloudLayerResourceInputs {\n readonly generation: number;\n readonly cache?: CloudDensityCache;\n readonly shadow?: CloudShadowProjection;\n readonly history?: CloudHistory;\n /** Bytes reported by the prepared GPU owner; absent means unavailable. */\n readonly shadowBytes?: number;\n readonly historyBytes?: number;\n readonly inFlightBytes?: number;\n}\n\n/** Derive one inspection receipt from the resources owned by the current generation. */\nexport function inspectCloudLayerResources(\n input: CloudLayerResourceInputs,\n): CloudLayerResourceFacts {\n const cacheBytes = input.cache?.byteLength ?? 0;\n const shadowResolution = input.shadow?.resolution ?? 0;\n const declaredShadowBytes =\n shadowResolution * shadowResolution * CLOUD_RGBA16FLOAT_BYTES_PER_TEXEL;\n const historyWidth = input.history?.width ?? 0;\n const historyHeight = input.history?.height ?? 0;\n const declaredHistoryBytes =\n historyWidth * historyHeight * CLOUD_HISTORY_SURFACE_COUNT * CLOUD_RGBA16FLOAT_BYTES_PER_TEXEL;\n const shadowBytes = input.shadowBytes ?? 0;\n const historyBytes = input.historyBytes ?? 0;\n const inFlightBytes = Math.max(0, input.inFlightBytes ?? 0);\n const residentBytes = cacheBytes + shadowBytes + historyBytes;\n const measuredGpuResourceCount =\n Number(input.shadowBytes !== undefined) + Number(input.historyBytes !== undefined);\n const gpuEvidence: CloudGpuResourceEvidence =\n measuredGpuResourceCount > 0 || input.inFlightBytes !== undefined\n ? 'measured'\n : input.shadow !== undefined || input.history !== undefined\n ? 'declared'\n : 'unavailable';\n const resourceCount =\n Number(input.cache !== undefined) +\n Number(input.shadow !== undefined) +\n Number(input.history !== undefined);\n return Object.freeze({\n generation: input.generation,\n cacheBytes,\n shadowBytes,\n historyBytes,\n inFlightBytes,\n residentBytes,\n resourceCount,\n gpuEvidence,\n declaredShadowBytes,\n declaredHistoryBytes,\n declaredResidentBytes: cacheBytes + declaredShadowBytes + declaredHistoryBytes,\n declaredResourceCount: resourceCount,\n measuredGpuResourceCount,\n cacheResolution: input.cache?.resolution ?? 0,\n shadowResolution,\n });\n}\n\nexport interface CloudLayerGeneration {\n readonly generation: number;\n readonly sourceKey: string;\n readonly resourceFacts: CloudLayerResourceFacts;\n readonly status: 'candidate' | 'active' | 'lkg' | 'retiring';\n}\n\n/** Candidate -> active transition used by the renderer's existing graph owner. */\nexport function acceptCloudLayerGeneration(\n candidate: CloudLayerGeneration,\n previous: CloudLayerGeneration | undefined,\n): { readonly active: CloudLayerGeneration; readonly lkg: CloudLayerGeneration | undefined } {\n return Object.freeze({\n active: Object.freeze({ ...candidate, status: 'active' as const }),\n lkg:\n previous === undefined ? undefined : Object.freeze({ ...previous, status: 'lkg' as const }),\n });\n}\n\n/** A failed candidate never replaces the LKG; retirement is fence-owned by Render. */\nexport function retainCloudLayerAfterFailure(\n active: CloudLayerGeneration | undefined,\n candidate: CloudLayerGeneration,\n): { readonly active: CloudLayerGeneration | undefined; readonly retiring: CloudLayerGeneration } {\n return Object.freeze({\n active,\n retiring: Object.freeze({ ...candidate, status: 'retiring' as const }),\n });\n}\n","import type { CloudDensityCache } from './density';\nimport { evaluateCloudDensity, sampleCloudDensity } from './density';\nimport { CLOUD_EXTINCTION_COEFFICIENT, type ValidatedCloudLayer } from './parameters';\n\nexport type CloudOpticalPath = 'camera' | 'solar-column' | 'cloud-interior';\n\nexport interface CloudRay {\n readonly origin: readonly [number, number, number];\n readonly direction: readonly [number, number, number];\n readonly maxDistance: number;\n}\n\nexport interface CloudOpticalResult {\n readonly path: CloudOpticalPath;\n readonly transmittance: number;\n readonly scattering: readonly [number, number, number];\n readonly opticalDepth: number;\n readonly representativeDepth: number;\n readonly steps: number;\n readonly entered: boolean;\n readonly exited: boolean;\n}\n\nexport interface CloudInteriorLighting {\n readonly sunRadiance: readonly [number, number, number];\n readonly sunDirection: readonly [number, number, number];\n readonly phaseG?: number;\n}\n\nexport interface CloudOpticsInput {\n readonly params: ValidatedCloudLayer;\n readonly ray: CloudRay;\n readonly path: CloudOpticalPath;\n readonly timeSeconds?: number;\n readonly cache?: CloudDensityCache;\n readonly steps?: number;\n readonly lighting?: CloudInteriorLighting;\n}\n\nconst EMPTY_SCATTERING: readonly [number, number, number] = [0, 0, 0];\n\nfunction normalize(vector: ArrayLike<number>): readonly [number, number, number] {\n const x = vector[0] ?? 0;\n const y = vector[1] ?? 0;\n const z = vector[2] ?? 0;\n const length = Math.hypot(x, y, z);\n return length <= 1e-8 ? [0, 1, 0] : [x / length, y / length, z / length];\n}\n\nfunction rayBoxInterval(\n ray: CloudRay,\n params: ValidatedCloudLayer,\n): { readonly start: number; readonly end: number } | undefined {\n const min = [Number.NEGATIVE_INFINITY, params.baseHeight, Number.NEGATIVE_INFINITY];\n const max = [\n Number.POSITIVE_INFINITY,\n params.baseHeight + params.thickness,\n Number.POSITIVE_INFINITY,\n ];\n let start = 0;\n let end = Math.max(0, ray.maxDistance);\n for (let axis = 0; axis < 3; axis += 1) {\n const origin = ray.origin[axis] ?? 0;\n const direction = ray.direction[axis] ?? 0;\n const lower = min[axis] ?? 0;\n const upper = max[axis] ?? 0;\n if (Math.abs(direction) < 1e-8) {\n if (origin < lower || origin > upper) return undefined;\n continue;\n }\n const a = (lower - origin) / direction;\n const b = (upper - origin) / direction;\n start = Math.max(start, Math.min(a, b));\n end = Math.min(end, Math.max(a, b));\n if (end <= start) return undefined;\n }\n return end > start ? { start, end } : undefined;\n}\n\nexport function intersectCloudLayer(\n ray: CloudRay,\n params: ValidatedCloudLayer,\n): { readonly start: number; readonly end: number } | undefined {\n return rayBoxInterval(ray, params);\n}\n\nfunction phaseFunction(cosTheta: number, g: number): number {\n const boundedG = Math.max(-0.95, Math.min(0.95, g));\n const denominator = Math.max(1e-4, 1 + boundedG * boundedG - 2 * boundedG * cosTheta);\n return ((1 - boundedG * boundedG) / denominator ** 1.5) * (1 / (4 * Math.PI));\n}\n\nfunction cloudPhase(cosTheta: number, forwardG: number): number {\n // Match the bounded dual-lobe phase used by the fullscreen WGSL path.\n return phaseFunction(cosTheta, forwardG) * 0.8 + phaseFunction(cosTheta, -0.2) * 0.2;\n}\n\nfunction smoothstep(edge0: number, edge1: number, value: number): number {\n const t = Math.max(0, Math.min(1, (value - edge0) / Math.max(1e-6, edge1 - edge0)));\n return t * t * (3 - 2 * t);\n}\n\n/** Unit-sun incident light, using the same phase basis as production volumes. */\nexport function cloudIncidentLight(\n solarT: number,\n cosTheta: number,\n height: number,\n forwardG = 0.55,\n): readonly [number, number, number] {\n const direct = solarT * cloudPhase(cosTheta, forwardG);\n const multiple = (0.5 * Math.sqrt(solarT) + 0.25 * solarT ** 0.25) / (4 * Math.PI);\n const energy = (direct + multiple) * (4 * Math.PI);\n const skyFill = 0.025 + 0.05 * smoothstep(0.1, 0.85, height);\n return [energy + 0.72 * skyFill, energy + 0.84 * skyFill, energy + skyFill];\n}\n\nfunction densityAt(input: CloudOpticsInput, position: readonly [number, number, number]): number {\n return input.cache === undefined\n ? evaluateCloudDensity(input.params, position, input.timeSeconds ?? 0).density\n : sampleCloudDensity(input.cache, input.params, position, input.timeSeconds ?? 0);\n}\n\n/**\n * Integrate one explicitly named optical path through the layer.\n *\n * Camera, solar-column and cloud-interior paths are intentionally separate\n * call sites. A caller cannot accidentally use a camera interval as the\n * light interval and apply the same cloud attenuation twice.\n */\nexport function integrateCloudPath(input: CloudOpticsInput): CloudOpticalResult {\n const direction = normalize(input.ray.direction);\n const interval = rayBoxInterval({ ...input.ray, direction }, input.params);\n if (interval === undefined || input.params.density <= 0) {\n return {\n path: input.path,\n transmittance: 1,\n scattering: EMPTY_SCATTERING,\n opticalDepth: 0,\n representativeDepth: input.ray.maxDistance,\n steps: 0,\n entered: false,\n exited: false,\n };\n }\n const steps = Math.max(1, Math.floor(input.steps ?? 32));\n const length = interval.end - interval.start;\n const stepLength = length / steps;\n let opticalDepth = 0;\n const scattering: [number, number, number] = [0, 0, 0];\n let weightedDepth = 0;\n let scatteringWeight = 0;\n const lighting = input.lighting;\n const lightDirection = lighting === undefined ? undefined : normalize(lighting.sunDirection);\n const viewDirection = normalize(input.ray.direction);\n for (let index = 0; index < steps; index += 1) {\n const distance = interval.start + (index + 0.5) * stepLength;\n const position: [number, number, number] = [\n (input.ray.origin[0] ?? 0) + direction[0] * distance,\n (input.ray.origin[1] ?? 0) + direction[1] * distance,\n (input.ray.origin[2] ?? 0) + direction[2] * distance,\n ];\n const localDensity = Math.max(0, densityAt(input, position));\n const extinction = localDensity * CLOUD_EXTINCTION_COEFFICIENT * stepLength;\n const transmittanceBefore = Math.exp(-opticalDepth);\n opticalDepth += extinction;\n if (lighting !== undefined && lightDirection !== undefined && localDensity > 0) {\n const localShadow = integrateCloudPath({\n params: input.params,\n path: 'solar-column',\n ray: {\n origin: position,\n direction: lightDirection,\n maxDistance: input.params.shadowRange,\n },\n steps: Math.max(4, Math.ceil((input.steps ?? 32) * 0.5)),\n ...(input.timeSeconds === undefined ? {} : { timeSeconds: input.timeSeconds }),\n ...(input.cache === undefined ? {} : { cache: input.cache }),\n });\n const cosTheta =\n viewDirection[0] * lightDirection[0] +\n viewDirection[1] * lightDirection[1] +\n viewDirection[2] * lightDirection[2];\n const segmentWeight = transmittanceBefore * (1 - Math.exp(-extinction));\n const heightFraction = Math.max(\n 0,\n Math.min(1, ((position[1] ?? 0) - input.params.baseHeight) / input.params.thickness),\n );\n const incident = cloudIncidentLight(\n localShadow.transmittance,\n cosTheta,\n heightFraction,\n lighting.phaseG,\n );\n for (let channel = 0; channel < 3; channel++) {\n scattering[channel] =\n (scattering[channel] ?? 0) +\n (lighting.sunRadiance[channel] ?? 0) * (incident[channel] ?? 0) * segmentWeight;\n }\n const weight = segmentWeight;\n scatteringWeight += weight;\n weightedDepth += distance * weight;\n }\n }\n const transmittance = Math.exp(-opticalDepth);\n return {\n path: input.path,\n transmittance,\n scattering,\n opticalDepth,\n representativeDepth:\n scatteringWeight > 1e-6 ? weightedDepth / scatteringWeight : interval.start,\n steps,\n entered: true,\n exited: interval.end < input.ray.maxDistance,\n };\n}\n\nexport function integrateCloudCameraPath(\n params: ValidatedCloudLayer,\n ray: CloudRay,\n options: Omit<CloudOpticsInput, 'params' | 'ray' | 'path'> = {},\n): CloudOpticalResult {\n return integrateCloudPath({ ...options, params, ray, path: 'camera' });\n}\n\nexport function integrateCloudSolarColumn(\n params: ValidatedCloudLayer,\n origin: readonly [number, number, number],\n sunDirection: readonly [number, number, number],\n options: Omit<CloudOpticsInput, 'params' | 'ray' | 'path'> & {\n readonly maxDistance?: number;\n } = {},\n): CloudOpticalResult {\n return integrateCloudPath({\n ...options,\n params,\n path: 'solar-column',\n ray: {\n origin,\n direction: sunDirection,\n maxDistance: options.maxDistance ?? params.shadowRange,\n },\n });\n}\n\nexport function integrateCloudInterior(\n params: ValidatedCloudLayer,\n ray: CloudRay,\n lighting: CloudInteriorLighting,\n options: Omit<CloudOpticsInput, 'params' | 'ray' | 'path' | 'lighting'> = {},\n): CloudOpticalResult {\n return integrateCloudPath({ ...options, params, ray, path: 'cloud-interior', lighting });\n}\n\n/** Standard's one selected sun term consumes this factor exactly once. */\nexport function applyCloudSolarTransmittance(\n directSunRadiance: readonly [number, number, number],\n cloudTransmittance: number,\n meshVisibility = 1,\n): readonly [number, number, number] {\n const factor =\n Math.min(1, Math.max(0, cloudTransmittance)) * Math.min(1, Math.max(0, meshVisibility));\n return [\n (directSunRadiance[0] ?? 0) * factor,\n (directSunRadiance[1] ?? 0) * factor,\n (directSunRadiance[2] ?? 0) * factor,\n ];\n}\n\n/** Scene-linear HDR composition at the cloud interval/depth boundary. */\nexport function compositeCloudRadiance(\n sceneLinearHdr: readonly [number, number, number, number],\n cloud: CloudOpticalResult,\n sceneDepth: number,\n cloudDepth = cloud.representativeDepth,\n): readonly [number, number, number, number] {\n if (!Number.isFinite(sceneDepth) || cloudDepth > sceneDepth) return sceneLinearHdr;\n const transmittance = Math.min(1, Math.max(0, cloud.transmittance));\n return [\n (sceneLinearHdr[0] ?? 0) * transmittance + (cloud.scattering[0] ?? 0),\n (sceneLinearHdr[1] ?? 0) * transmittance + (cloud.scattering[1] ?? 0),\n (sceneLinearHdr[2] ?? 0) * transmittance + (cloud.scattering[2] ?? 0),\n 1,\n ];\n}\n","import type { CloudDensityCache } from './density';\nimport { integrateCloudSolarColumn } from './optics';\nimport type { ValidatedCloudLayer } from './parameters';\n\nexport interface CloudShadowProjection {\n readonly revision: number;\n readonly resolution: number;\n readonly range: number;\n readonly texelSize: number;\n readonly center: readonly [number, number, number];\n readonly origin: readonly [number, number, number];\n readonly right: readonly [number, number, number];\n readonly up: readonly [number, number, number];\n readonly sunDirection: readonly [number, number, number];\n readonly lowSun: boolean;\n}\n\nexport interface CloudShadowSample {\n readonly transmittance: number;\n readonly uv: readonly [number, number] | undefined;\n readonly valid: boolean;\n readonly fallback: 'none' | 'low-sun' | 'outside-range' | 'empty-coverage';\n readonly revision: number;\n}\n\nfunction normalize(vector: ArrayLike<number>): readonly [number, number, number] {\n const x = vector[0] ?? 0;\n const y = vector[1] ?? 0;\n const z = vector[2] ?? 0;\n const length = Math.hypot(x, y, z);\n return length <= 1e-8 ? [0, 1, 0] : [x / length, y / length, z / length];\n}\n\nfunction cross(\n a: readonly [number, number, number],\n b: readonly [number, number, number],\n): readonly [number, number, number] {\n return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];\n}\n\nfunction dot(a: ArrayLike<number>, b: ArrayLike<number>): number {\n return (a[0] ?? 0) * (b[0] ?? 0) + (a[1] ?? 0) * (b[1] ?? 0) + (a[2] ?? 0) * (b[2] ?? 0);\n}\n\nfunction stableRevision(input: {\n readonly center: readonly [number, number, number];\n readonly sunDirection: readonly [number, number, number];\n readonly range: number;\n readonly resolution: number;\n}): number {\n let hash = 2166136261;\n const values = [...input.center, ...input.sunDirection, input.range, input.resolution];\n for (const value of values) {\n const bits = new Float32Array([value]);\n const bytes = new Uint8Array(bits.buffer);\n for (const byte of bytes) hash = Math.imul(hash ^ byte, 16777619);\n }\n return hash >>> 0;\n}\n\n/**\n * Build a camera-independent light-space projection. The center is a world\n * anchor chosen by Render (usually the active scene bounds), and is snapped to\n * one texel so camera motion cannot crawl the cloud shadow.\n */\nexport function createCloudShadowProjection(input: {\n readonly center: readonly [number, number, number];\n readonly sunDirection: readonly [number, number, number];\n readonly range: number;\n readonly resolution?: number;\n}): CloudShadowProjection {\n const sunDirection = normalize(input.sunDirection);\n const resolution = Math.max(16, Math.floor(input.resolution ?? 1024));\n const range = Math.max(1, input.range);\n const texelSize = range / resolution;\n const reference = Math.abs(sunDirection[1]) < 0.95 ? ([0, 1, 0] as const) : ([1, 0, 0] as const);\n const right = normalize(cross(reference, sunDirection));\n const up = normalize(cross(sunDirection, right));\n const center = input.center;\n const lightX = dot(center, right);\n const lightY = dot(center, up);\n const lightZ = dot(center, sunDirection);\n const snappedX = Math.floor(lightX / texelSize + 0.5) * texelSize;\n const snappedY = Math.floor(lightY / texelSize + 0.5) * texelSize;\n const origin: [number, number, number] = [\n right[0] * snappedX + up[0] * snappedY + sunDirection[0] * lightZ,\n right[1] * snappedX + up[1] * snappedY + sunDirection[1] * lightZ,\n right[2] * snappedX + up[2] * snappedY + sunDirection[2] * lightZ,\n ];\n return Object.freeze({\n revision: stableRevision({ center, sunDirection, range, resolution }),\n resolution,\n range,\n texelSize,\n center: Object.freeze([...center] as [number, number, number]),\n origin: Object.freeze(origin),\n right,\n up,\n sunDirection,\n lowSun: sunDirection[1] <= 0.08,\n });\n}\n\nexport function projectCloudShadowUv(\n projection: CloudShadowProjection,\n position: readonly [number, number, number],\n): { readonly uv: readonly [number, number]; readonly inRange: boolean } {\n const relative: [number, number, number] = [\n position[0] - projection.origin[0],\n position[1] - projection.origin[1],\n position[2] - projection.origin[2],\n ];\n const x = dot(relative, projection.right);\n const y = dot(relative, projection.up);\n const uv: [number, number] = [0.5 + x / projection.range, 0.5 + y / projection.range];\n return { uv, inRange: uv[0] >= 0 && uv[0] <= 1 && uv[1] >= 0 && uv[1] <= 1 };\n}\n\n/** Evaluate the stable world-space shadow term used by surface and volume sun paths. */\nexport function sampleCloudShadow(\n params: ValidatedCloudLayer,\n projection: CloudShadowProjection,\n worldPosition: readonly [number, number, number],\n options: { readonly cache?: CloudDensityCache; readonly timeSeconds?: number } = {},\n): CloudShadowSample {\n const projected = projectCloudShadowUv(projection, worldPosition);\n if (projection.lowSun) {\n return {\n transmittance: 1,\n uv: projected.uv,\n valid: false,\n fallback: 'low-sun',\n revision: projection.revision,\n };\n }\n if (!projected.inRange) {\n return {\n transmittance: 1,\n uv: projected.uv,\n valid: false,\n fallback: 'outside-range',\n revision: projection.revision,\n };\n }\n if (params.coverage >= 1 || params.density <= 0) {\n return {\n transmittance: 1,\n uv: projected.uv,\n valid: false,\n fallback: 'empty-coverage',\n revision: projection.revision,\n };\n }\n const integrated = integrateCloudSolarColumn(params, worldPosition, projection.sunDirection, {\n steps: 20,\n maxDistance: projection.range,\n ...(options.cache === undefined ? {} : { cache: options.cache }),\n ...(options.timeSeconds === undefined ? {} : { timeSeconds: options.timeSeconds }),\n });\n return {\n transmittance: integrated.transmittance,\n uv: projected.uv,\n valid: integrated.entered,\n fallback: 'none',\n revision: projection.revision,\n };\n}\n","import type { CloudQuality } from '../components/cloud-layer';\n\nexport type CloudTemporalResetReason =\n | 'authoring-generation'\n | 'camera-cut'\n | 'resize'\n | 'recovery'\n | 'time-discontinuity'\n | 'cloud-shadow-revision'\n | 'device-generation'\n | 'history-missing'\n | 'reprojection-outside'\n | 'scene-depth-disocclusion';\n\nexport interface CloudTemporalSignature {\n readonly sourceKey: string;\n readonly viewId: string;\n readonly authoringGeneration: number;\n readonly cloudShadowRevision: number;\n readonly cameraRevision: number;\n readonly deviceGeneration: number;\n readonly width: number;\n readonly height: number;\n readonly timeSeconds: number;\n readonly quality: CloudQuality;\n /** Scene-depth producer revision used to reject disoccluded history. */\n readonly sceneDepthVersion?: number;\n}\n\nexport interface CloudHistory {\n readonly width: number;\n readonly height: number;\n readonly signature: string;\n readonly temporal: CloudTemporalSignature;\n readonly generation: number;\n readonly valid: boolean;\n}\n\nexport interface CloudTemporalDecision {\n readonly reset: boolean;\n readonly reasons: readonly CloudTemporalResetReason[];\n readonly signature: string;\n readonly history: CloudHistory | undefined;\n}\n\nexport interface CloudTemporalFrame {\n readonly signature: CloudTemporalSignature;\n readonly history: CloudHistory | undefined;\n readonly reset: boolean;\n readonly reasons: readonly CloudTemporalResetReason[];\n}\n\nexport interface CloudHistoryReprojectionInput {\n readonly currentDepth: number;\n readonly historyDepth: number;\n readonly motion: readonly [number, number];\n readonly currentPixel: readonly [number, number];\n readonly historySize: readonly [number, number];\n readonly depthTolerance?: number;\n}\n\nexport interface CloudHistoryReprojection {\n readonly accepted: boolean;\n readonly historyUv: readonly [number, number];\n readonly weight: number;\n readonly reason: 'accepted' | 'outside' | 'depth-disocclusion';\n}\n\nexport function cloudTemporalSignature(input: CloudTemporalSignature): string {\n return [\n 'cloud-temporal-v1',\n input.viewId,\n input.sourceKey,\n input.authoringGeneration,\n input.cloudShadowRevision,\n input.cameraRevision,\n input.deviceGeneration,\n input.width,\n input.height,\n input.timeSeconds,\n input.quality,\n input.sceneDepthVersion ?? 0,\n ].join(':');\n}\n\nfunction sameLayout(left: CloudTemporalSignature, right: CloudTemporalSignature): boolean {\n return left.viewId === right.viewId && left.width === right.width && left.height === right.height;\n}\n\n/** Compare the facts that make a cloud history safe to reuse. */\nexport function cloudTemporalResetReasons(\n previous: CloudTemporalSignature | undefined,\n next: CloudTemporalSignature,\n options: { readonly cameraCut?: boolean; readonly recovery?: boolean } = {},\n): readonly CloudTemporalResetReason[] {\n if (previous === undefined) return ['history-missing'];\n const reasons: CloudTemporalResetReason[] = [];\n if (\n previous.sourceKey !== next.sourceKey ||\n previous.authoringGeneration !== next.authoringGeneration\n ) {\n reasons.push('authoring-generation');\n }\n if (previous.cloudShadowRevision !== next.cloudShadowRevision)\n reasons.push('cloud-shadow-revision');\n if (previous.deviceGeneration !== next.deviceGeneration) reasons.push('device-generation');\n if (\n previous.sceneDepthVersion !== undefined &&\n next.sceneDepthVersion !== undefined &&\n previous.sceneDepthVersion !== next.sceneDepthVersion\n ) {\n reasons.push('scene-depth-disocclusion');\n }\n if (!sameLayout(previous, next)) reasons.push('resize');\n if (options.cameraCut === true || previous.cameraRevision !== next.cameraRevision)\n reasons.push('camera-cut');\n const dt = next.timeSeconds - previous.timeSeconds;\n if (!Number.isFinite(dt) || dt < 0 || dt > 0.5) reasons.push('time-discontinuity');\n if (options.recovery === true) reasons.push('recovery');\n return Object.freeze(reasons);\n}\n\nexport function createCloudHistory(\n signature: CloudTemporalSignature,\n generation: number,\n valid = false,\n): CloudHistory {\n return Object.freeze({\n width: Math.max(1, Math.floor(signature.width)),\n height: Math.max(1, Math.floor(signature.height)),\n signature: cloudTemporalSignature(signature),\n temporal: Object.freeze({ ...signature }),\n generation,\n valid,\n });\n}\n\n/** Per-view histories are keyed by the renderer's view identity. */\nexport class CloudHistoryStore {\n private readonly maxViews: number;\n private readonly entries = new Map<\n string,\n { readonly history: CloudHistory; readonly signature: CloudTemporalSignature }\n >();\n\n constructor(maxViews = 4) {\n this.maxViews = Math.max(1, Math.floor(maxViews));\n }\n\n begin(\n signature: CloudTemporalSignature,\n options: { readonly cameraCut?: boolean; readonly recovery?: boolean } = {},\n ): CloudTemporalDecision {\n const key = signature.viewId;\n const previousEntry = this.entries.get(key);\n const previous = previousEntry?.history;\n const reasons = cloudTemporalResetReasons(previousEntry?.signature, signature, options);\n const reset = reasons.length > 0;\n return Object.freeze({\n reset,\n reasons,\n signature: cloudTemporalSignature(signature),\n history: reset ? undefined : previous,\n });\n }\n\n commit(signature: CloudTemporalSignature, history: CloudHistory): void {\n if (\n history.width !== Math.max(1, Math.floor(signature.width)) ||\n history.height !== Math.max(1, Math.floor(signature.height))\n ) {\n this.entries.delete(signature.viewId);\n return;\n }\n this.entries.set(signature.viewId, { history, signature: Object.freeze({ ...signature }) });\n while (this.entries.size > this.maxViews) {\n const oldest = this.entries.keys().next().value as string | undefined;\n if (oldest === undefined) break;\n this.entries.delete(oldest);\n }\n }\n\n reset(viewId?: string): void {\n if (viewId === undefined) this.entries.clear();\n else this.entries.delete(viewId);\n }\n\n get(viewId: string): CloudHistory | undefined {\n return this.entries.get(viewId)?.history;\n }\n\n dispose(): void {\n this.entries.clear();\n }\n}\n\n/** Project one current pixel into the previous cloud history. */\nexport function reprojectCloudHistory(\n input: CloudHistoryReprojectionInput,\n historyWeight = 0.9,\n): CloudHistoryReprojection {\n const width = Math.max(1, input.historySize[0] ?? 1);\n const height = Math.max(1, input.historySize[1] ?? 1);\n const uv: [number, number] = [\n ((input.currentPixel[0] ?? 0) - (input.motion[0] ?? 0)) / width,\n ((input.currentPixel[1] ?? 0) - (input.motion[1] ?? 0)) / height,\n ];\n if (uv[0] < 0 || uv[0] > 1 || uv[1] < 0 || uv[1] > 1) {\n return { accepted: false, historyUv: uv, weight: 0, reason: 'outside' };\n }\n const depthTolerance =\n input.depthTolerance ?? Math.max(0.01, Math.abs(input.currentDepth) * 0.02);\n if (\n !Number.isFinite(input.currentDepth) ||\n !Number.isFinite(input.historyDepth) ||\n Math.abs(input.currentDepth - input.historyDepth) > depthTolerance\n ) {\n return { accepted: false, historyUv: uv, weight: 0, reason: 'depth-disocclusion' };\n }\n return {\n accepted: true,\n historyUv: uv,\n weight: Math.min(0.99, Math.max(0, historyWeight)),\n reason: 'accepted',\n };\n}\n","import { ok, type Result } from '@forgeax/engine-types';\nimport type { RenderError } from '../errors/render';\nimport type { RenderFeaturePlan, RenderFeaturePlanContext } from '../features/plan';\nimport type { RenderFeature, RenderFeatureExtractContext } from '../features/types';\nimport { buildCloudDensityCache, CLOUD_VERTICAL_CELLS, type CloudDensityCache } from './density';\nimport {\n type CloudLayerInspection,\n cloudCapabilitiesFromRhi,\n inspectCloudLayer,\n} from './inspection';\nimport {\n CLOUD_EXTINCTION_COEFFICIENT,\n CLOUD_QUALITY_PROFILES,\n cloudLayerFormationKey,\n cloudShadowResolutionForQuality,\n cloudViewDistanceForQuality,\n type ValidatedCloudLayer,\n} from './parameters';\nimport { inspectCloudLayerResources } from './resources';\nimport { type CloudShadowProjection, createCloudShadowProjection } from './shadow';\nimport {\n CloudHistoryStore,\n type CloudTemporalFrame,\n type CloudTemporalSignature,\n createCloudHistory,\n} from './temporal';\n\nexport const CLOUD_LAYER_FEATURE_IDENTITY = 'forgeax.cloud-layer';\nexport const CLOUD_LAYER_DENSITY_PROGRAM = 'cloud-layer-density';\nexport const CLOUD_LAYER_DENSITY_BINDINGS = 'cloud-layer-density-bindings';\nexport const CLOUD_LAYER_DENSITY_CACHE = 'cloud-layer-density-cache';\nexport const CLOUD_LAYER_DENSITY_OUTPUT = 'cloud-layer-density-output';\n\nconst COMPUTE_STAGE = 0x4;\nconst CLOUD_WORKGROUP_SIZE = 64;\n// 24 vec4/u32 lanes: authored field, sun, integration mode and the\n// renderer-owned stable light-space shadow projection. The same POD is used by\n// the display and shadow entry points so they cannot drift in their density or\n// cache addressing contract.\n// The final lane carries temporal validity/reset/blend. Keep the payload\n// explicitly 16-byte aligned so the public schema, prepared UBO and WGSL stay\n// one contract.\nexport const CLOUD_VIEW_PARAMS_BYTES = 176;\n\n/** R8 cache bytes are packed into little-endian u32 storage elements. */\nfunction packCloudDensityCache(cache: CloudDensityCache): Uint32Array {\n const packed = new Uint32Array(Math.max(1, Math.ceil(cache.formationData.byteLength / 4)));\n for (let index = 0; index < cache.formationData.byteLength; index += 1) {\n const wordIndex = index >>> 2;\n packed[wordIndex] =\n (packed[wordIndex] ?? 0) | ((cache.formationData[index] ?? 0) << ((index & 3) * 8));\n }\n return packed;\n}\n\n/** Minimal copy compute; one invocation owns one packed u32 cache element. */\nexport const CLOUD_DENSITY_COMPUTE_WGSL = /* wgsl */ `\nstruct CloudCacheParams { count: u32, }\n@group(0) @binding(0) var<storage, read> sourceDensity: array<u32>;\n@group(0) @binding(1) var<storage, read_write> cachedDensity: array<u32>;\n@group(0) @binding(2) var<uniform> params: CloudCacheParams;\n@compute @workgroup_size(64)\nfn cloud_density_cache(@builtin(global_invocation_id) id: vec3<u32>) {\n if (id.x >= params.count) { return; }\n cachedDensity[id.x] = sourceDensity[id.x];\n}\n`;\n\n/**\n * Cloud view transport. The View group is the renderer-owned camera/light\n * source of truth; group(1) carries frame-local cloud parameters, depth and\n * the bounded packed 3D cache. Camera, solar-column and cloud-interior\n * integration all call cloud_density(), so wind only changes the sample\n * coordinate and never the authored field.\n */\nexport const CLOUD_VIEW_FULLSCREEN_WGSL = /* wgsl */ `\nconst CLOUD_VERTICAL_CELLS: f32 = ${CLOUD_VERTICAL_CELLS};\nconst CLOUD_VERTICAL_NOISE_CELLS: f32 = 2.0;\n\nstruct CloudCameraView {\n worldViewProj: mat4x4<f32>,\n lightDir: vec3<f32>,\n lightColor: vec3<f32>,\n cameraPos: vec3<f32>,\n lightViewProj_A: mat4x4<f32>,\n inverseViewProj: mat4x4<f32>,\n lightViewProj_B: mat4x4<f32>,\n lightViewProj_C: mat4x4<f32>,\n lightViewProj_D: mat4x4<f32>,\n splitPlanes: array<vec4<f32>, 4>,\n cascadeCount: f32,\n cascadeBlend: f32,\n depthBias: f32,\n normalBias: f32,\n directionalShadowFilter: vec4<f32>,\n spotLightViewProj: array<mat4x4<f32>, 4>,\n temporalCurrentViewProj: mat4x4<f32>,\n temporalPreviousViewProj: mat4x4<f32>,\n temporalProjection: vec4<f32>,\n temporalPreviousCameraPos: vec4<f32>,\n ssrParams: vec4<f32>,\n};\n\nstruct CloudViewParams {\n layer: vec4<f32>, // baseHeight, thickness, scale, density\n field: vec4<f32>, // coverage, timeSeconds, maxDistance, seed\n wind: vec4<f32>, // xyz m/s\n sunDirection: vec4<f32>,\n sunRadiance: vec4<f32>,\n integration: vec4<u32>, // cacheResolution, viewSteps, solarSteps, reserved\n shadowOrigin: vec4<f32>,\n shadowRight: vec4<f32>,\n shadowUp: vec4<f32>,\n shadowProjection: vec4<f32>, // range, valid, lowSun, texelSize\n temporal: vec4<f32>, // valid, reset, historyWeight, reserved\n};\n\n@group(0) @binding(0) var<uniform> view: CloudCameraView;\n@group(1) @binding(0) var sceneColor: texture_2d<f32>;\n@group(1) @binding(1) var sceneSampler: sampler;\n@group(1) @binding(2) var<uniform> cloud: CloudViewParams;\n@group(1) @binding(3) var sceneDepth: texture_depth_2d;\n@group(1) @binding(4) var depthSampler: sampler;\n@group(1) @binding(5) var previousRadiance: texture_2d<f32>;\n@group(1) @binding(6) var previousTransmittance: texture_2d<f32>;\n@group(1) @binding(7) var previousDepth: texture_2d<f32>;\n@group(1) @binding(8) var<storage, read> densityCache: array<u32>;\n\nstruct CloudViewOut {\n @builtin(position) position: vec4<f32>,\n @location(0) uv: vec2<f32>,\n};\n\nfn cloud_hash3(cell: vec3<i32>, seed: u32) -> f32 {\n var h = bitcast<u32>(cell.x) * 0x45d9f3bu;\n h = (h ^ (bitcast<u32>(cell.y) * 0x119de1f3u)) * 0x45d9f3bu;\n h = (h ^ (bitcast<u32>(cell.z) * 0x3449fu)) * 0x45d9f3bu;\n h = h ^ seed;\n h = (h ^ (h >> 16u)) * 0x45d9f3bu;\n h = (h ^ (h >> 13u)) * 0x27d4eb2du;\n return f32(h ^ (h >> 16u)) / 4294967296.0;\n}\n\nfn cloud_wrap_cell(value: i32, period: i32) -> i32 {\n let wrapped = value % period;\n return select(wrapped, wrapped + period, wrapped < 0);\n}\n\nfn cloud_hash3_periodic(\n cell: vec3<i32>,\n seed: u32,\n periodX: i32,\n periodY: i32,\n periodZ: i32,\n) -> f32 {\n return cloud_hash3(\n vec3<i32>(\n cloud_wrap_cell(cell.x, periodX),\n cloud_wrap_cell(cell.y, periodY),\n cloud_wrap_cell(cell.z, periodZ),\n ),\n seed,\n );\n}\n\nfn cloud_value_noise(\n position: vec3<f32>,\n seed: u32,\n periodX: i32,\n periodY: i32,\n periodZ: i32,\n) -> f32 {\n let cell = vec3<i32>(floor(position));\n let fraction = fract(position);\n let smoothFraction = fraction * fraction * (3.0 - 2.0 * fraction);\n let c000 = cloud_hash3_periodic(cell + vec3<i32>(0, 0, 0), seed, periodX, periodY, periodZ);\n let c100 = cloud_hash3_periodic(cell + vec3<i32>(1, 0, 0), seed, periodX, periodY, periodZ);\n let c010 = cloud_hash3_periodic(cell + vec3<i32>(0, 1, 0), seed, periodX, periodY, periodZ);\n let c110 = cloud_hash3_periodic(cell + vec3<i32>(1, 1, 0), seed, periodX, periodY, periodZ);\n let c001 = cloud_hash3_periodic(cell + vec3<i32>(0, 0, 1), seed, periodX, periodY, periodZ);\n let c101 = cloud_hash3_periodic(cell + vec3<i32>(1, 0, 1), seed, periodX, periodY, periodZ);\n let c011 = cloud_hash3_periodic(cell + vec3<i32>(0, 1, 1), seed, periodX, periodY, periodZ);\n let c111 = cloud_hash3_periodic(cell + vec3<i32>(1, 1, 1), seed, periodX, periodY, periodZ);\n let x00 = mix(c000, c100, smoothFraction.x);\n let x10 = mix(c010, c110, smoothFraction.x);\n let x01 = mix(c001, c101, smoothFraction.x);\n let x11 = mix(c011, c111, smoothFraction.x);\n return mix(mix(x00, x10, smoothFraction.y), mix(x01, x11, smoothFraction.y), smoothFraction.z);\n}\n\nfn cloud_cellular_noise(position: vec3<f32>, seed: u32, periodXZ: i32, periodY: i32) -> f32 {\n let cell = vec3<i32>(floor(position));\n let fraction = fract(position);\n var nearest = 1e9;\n var dz: i32 = -1;\n loop {\n var dy: i32 = -1;\n loop {\n var dx: i32 = -1;\n loop {\n let random = cloud_hash3_periodic(\n cell + vec3<i32>(dx, dy, dz),\n seed ^ 0x9e3779b9u,\n periodXZ,\n periodY,\n periodXZ,\n );\n let point = vec3<f32>(\n f32(dx) + fract(random * 17.0) - fraction.x,\n f32(dy) + fract(random * 31.0) - fraction.y,\n f32(dz) + fract(random * 47.0) - fraction.z,\n );\n nearest = min(nearest, dot(point, point));\n if (dx >= 1) { break; }\n dx = dx + 1;\n }\n if (dy >= 1) { break; }\n dy = dy + 1;\n }\n if (dz >= 1) { break; }\n dz = dz + 1;\n }\n return 1.0 - clamp(sqrt(nearest) * 1.25, 0.0, 1.0);\n}\n\nfn cloud_weather_field(position: vec3<f32>, seed: u32) -> f32 {\n return smoothstep(\n 0.34,\n 0.66,\n cloud_value_noise(\n vec3<f32>(position.x * 2.0, 0.37, position.z * 2.0),\n seed + 17041u,\n 2,\n 1,\n 2,\n ),\n );\n}\n\nfn cloud_formation_field(position: vec3<f32>, seed: u32) -> vec3<f32> {\n let macroWarpX = cloud_value_noise(\n vec3<f32>(position.x * 2.0, position.y * CLOUD_VERTICAL_NOISE_CELLS + 3.0, position.z * 2.0),\n seed + 41023u,\n 2,\n 2,\n 2,\n ) - 0.5;\n let macroWarpZ = cloud_value_noise(\n vec3<f32>(position.x * 2.0 + 5.0, position.y * CLOUD_VERTICAL_NOISE_CELLS - 7.0, position.z * 2.0),\n seed + 41023u,\n 2,\n 2,\n 2,\n ) - 0.5;\n let bodyX = position.x + macroWarpX * 0.3;\n let bodyZ = position.z + macroWarpZ * 0.3;\n var noise = 0.0;\n var weight = 0.0;\n var amplitude = 0.5;\n var frequency = 1.0;\n for (var octave = 0u; octave < 4u; octave = octave + 1u) {\n let tilePeriod = 4.0 * frequency;\n noise = noise + cloud_value_noise(\n vec3<f32>(bodyX * tilePeriod, position.y * frequency * CLOUD_VERTICAL_NOISE_CELLS, bodyZ * tilePeriod),\n seed + octave * 1013u,\n i32(tilePeriod),\n i32(frequency * CLOUD_VERTICAL_NOISE_CELLS),\n i32(tilePeriod),\n ) * amplitude;\n weight = weight + amplitude;\n amplitude = amplitude * 0.4;\n frequency = frequency * 2.0;\n }\n let broad = noise / max(0.0001, weight);\n let cells = cloud_cellular_noise(\n vec3<f32>(bodyX * 4.0, position.y * CLOUD_VERTICAL_NOISE_CELLS, bodyZ * 4.0),\n seed + 5011u,\n 4,\n i32(CLOUD_VERTICAL_NOISE_CELLS),\n );\n // Keep the broad field responsible for the cloud silhouette and use the\n // cellular term as bounded breakup. A broad-dominant mix reads as fewer,\n // wider formations instead of evenly spaced foam balls.\n let base = clamp(broad * 0.85 + cells * 0.15 + 0.15, 0.0, 1.0);\n let weather = cloud_weather_field(position, seed);\n let detailPosition = position * 3.0;\n let warpX = cloud_value_noise(\n vec3<f32>(detailPosition.x * 2.0, detailPosition.y * 2.0 + 11.0, detailPosition.z * 2.0),\n seed + 29011u,\n 2,\n 2,\n 2,\n ) - 0.5;\n let warpZ = cloud_value_noise(\n vec3<f32>(detailPosition.x * 2.0 + 7.0, detailPosition.y * 2.0 - 5.0, detailPosition.z * 2.0),\n seed + 29011u,\n 2,\n 2,\n 2,\n ) - 0.5;\n let erosion = cloud_cellular_noise(\n vec3<f32>(\n (detailPosition.x + warpX * 0.22) * 12.0,\n detailPosition.y * 3.0,\n (detailPosition.z + warpZ * 0.22) * 12.0,\n ),\n seed + 7919u,\n 12,\n 3,\n );\n return vec3<f32>(weather, base, erosion);\n}\n\nfn cloud_height_profile(height: f32, body: f32, weather: f32) -> f32 {\n // A body-dependent crown breaks the fixed horizontal slab silhouette while\n // keeping the profile smooth enough for the bounded ray step budget.\n let lowerEdge = 0.05 + (1.0 - body) * 0.1;\n let crownEdge = min(0.96, 0.6 + body * 0.3 + weather * 0.08);\n let lower = smoothstep(lowerEdge, min(1.0, lowerEdge + 0.12), height);\n let upper = 1.0 - smoothstep(crownEdge, min(1.0, crownEdge + 0.14), height);\n return lower * upper;\n}\n\nfn cloud_compose_density(height: f32, formation: vec3<f32>, coverage: f32) -> f32 {\n let threshold = 1.0 - coverage * (0.45 + formation.x * 0.55);\n let covered = smoothstep(0.0, 0.4, (formation.y - threshold) / max(0.001, 1.0 - threshold));\n let shaped = covered * cloud_height_profile(height, formation.y, formation.x);\n let erosion = (1.0 - formation.z) * 0.18;\n return clamp((shaped - erosion) / (1.0 - erosion), 0.0, 1.0);\n}\n\nfn cloud_analytic_density(position: vec3<f32>) -> f32 {\n let height = (position.y - cloud.layer.x) / max(0.000001, cloud.layer.y);\n if (height <= 0.0 || height >= 1.0 || cloud.layer.w <= 0.0 || cloud.field.x <= 0.0) { return 0.0; }\n let advected = position + cloud.wind.xyz * cloud.field.y;\n let advectedHeight = height +\n cloud.wind.y * cloud.field.y * cloud.layer.z / max(CLOUD_VERTICAL_CELLS, 0.000001);\n let p = vec3<f32>(\n advected.x * cloud.layer.z,\n fract(advectedHeight) * CLOUD_VERTICAL_CELLS,\n advected.z * cloud.layer.z,\n );\n let formation = cloud_formation_field(p, u32(round(cloud.field.w)));\n return cloud_compose_density(height, formation, cloud.field.x) * cloud.layer.w;\n}\n\nfn cloud_cache_byte(index: u32) -> f32 {\n let word = densityCache[index >> 2u];\n let shift = (index & 3u) * 8u;\n return f32((word >> shift) & 255u) / 255.0;\n}\n\nfn cloud_cache_component(plane: u32, index: u32, stride: u32) -> f32 {\n return cloud_cache_byte(plane * stride + index);\n}\n\nfn cloud_cache_trilinear(\n plane: u32,\n resolution: u32,\n x0: u32,\n x1: u32,\n y0: u32,\n y1: u32,\n z0: u32,\n z1: u32,\n fx: f32,\n fy: f32,\n fz: f32,\n) -> f32 {\n let stride = resolution * resolution * resolution;\n let layer = resolution * resolution;\n let c000 = cloud_cache_component(plane, z0 * layer + y0 * resolution + x0, stride);\n let c100 = cloud_cache_component(plane, z0 * layer + y0 * resolution + x1, stride);\n let c010 = cloud_cache_component(plane, z0 * layer + y1 * resolution + x0, stride);\n let c110 = cloud_cache_component(plane, z0 * layer + y1 * resolution + x1, stride);\n let c001 = cloud_cache_component(plane, z1 * layer + y0 * resolution + x0, stride);\n let c101 = cloud_cache_component(plane, z1 * layer + y0 * resolution + x1, stride);\n let c011 = cloud_cache_component(plane, z1 * layer + y1 * resolution + x0, stride);\n let c111 = cloud_cache_component(plane, z1 * layer + y1 * resolution + x1, stride);\n let x00 = mix(c000, c100, fx);\n let x10 = mix(c010, c110, fx);\n let x01 = mix(c001, c101, fx);\n let x11 = mix(c011, c111, fx);\n return mix(mix(x00, x10, fy), mix(x01, x11, fy), fz);\n}\n\nfn cloud_density(position: vec3<f32>) -> f32 {\n let height = (position.y - cloud.layer.x) / max(0.000001, cloud.layer.y);\n if (height <= 0.0 || height >= 1.0 || cloud.layer.w <= 0.0 || cloud.field.x <= 0.0) { return 0.0; }\n let resolution = cloud.integration.x;\n if (resolution < 4u) { return max(cloud_analytic_density(position), 0.0); }\n let periodCoordinate = fract((position.xz + cloud.wind.xz * cloud.field.y) * cloud.layer.z);\n let x = fract(periodCoordinate.x - 0.5 / f32(resolution)) * f32(resolution);\n let z = fract(periodCoordinate.y - 0.5 / f32(resolution)) * f32(resolution);\n let advectedHeight = height +\n cloud.wind.y * cloud.field.y * cloud.layer.z / max(CLOUD_VERTICAL_CELLS, 0.000001);\n let y = fract(advectedHeight - 0.5 / f32(resolution)) * f32(resolution);\n let x0 = u32(floor(x));\n let y0 = u32(floor(y));\n let z0 = u32(floor(z));\n let x1 = (x0 + 1u) % resolution;\n let y1 = (y0 + 1u) % resolution;\n let z1 = (z0 + 1u) % resolution;\n let fx = x - f32(x0);\n let fy = y - f32(y0);\n let fz = z - f32(z0);\n let weather = cloud_cache_trilinear(0u, resolution, x0, x1, y0, y1, z0, z1, fx, fy, fz);\n let body = cloud_cache_trilinear(1u, resolution, x0, x1, y0, y1, z0, z1, fx, fy, fz);\n // Repeat only the independent erosion plane: fine boundary structure with\n // the same eight packed reads and the same cache allocation.\n let detail = fract(vec3<f32>(periodCoordinate.x, advectedHeight, periodCoordinate.y) * 3.0 - vec3<f32>(0.5 / f32(resolution))) * f32(resolution);\n let d0 = vec3<u32>(floor(detail));\n let d1 = (d0 + vec3<u32>(1u)) % vec3<u32>(resolution);\n let df = fract(detail);\n let erosion = cloud_cache_trilinear(2u, resolution, d0.x, d1.x, d0.y, d1.y, d0.z, d1.z, df.x, df.y, df.z);\n return cloud_compose_density(height, vec3<f32>(weather, body, erosion), cloud.field.x) * cloud.layer.w;\n}\n\nfn cloud_layer_interval(origin: vec3<f32>, direction: vec3<f32>, maxDistance: f32) -> vec2<f32> {\n if (abs(direction.y) < 0.000001) {\n if (origin.y < cloud.layer.x || origin.y > cloud.layer.x + cloud.layer.y) {\n return vec2<f32>(1.0, 0.0);\n }\n return vec2<f32>(0.0, maxDistance);\n }\n let lower = (cloud.layer.x - origin.y) / direction.y;\n let upper = (cloud.layer.x + cloud.layer.y - origin.y) / direction.y;\n return vec2<f32>(\n max(0.0, min(lower, upper)),\n min(maxDistance, max(lower, upper)),\n );\n}\n\nfn cloud_solar_transmittance(position: vec3<f32>) -> f32 {\n let sunDirection = normalize(-view.lightDir);\n let solarDistance = select(cloud.field.z, cloud.shadowProjection.x, cloud.shadowProjection.x > 0.0);\n let interval = cloud_layer_interval(position, sunDirection, solarDistance);\n if (interval.y <= interval.x) { return 1.0; }\n let steps = min(cloud.integration.z, 64u);\n let stepLength = (interval.y - interval.x) / max(1.0, f32(steps));\n var opticalDepth = 0.0;\n let solarJitter = cloud_solar_jitter(position);\n for (var index = 0u; index < 64u; index = index + 1u) {\n if (index >= steps) { break; }\n let samplePosition = position + sunDirection * (interval.x + (f32(index) + solarJitter) * stepLength);\n opticalDepth = opticalDepth + cloud_density(samplePosition) * ${CLOUD_EXTINCTION_COEFFICIENT} * stepLength;\n }\n return exp(-max(opticalDepth, 0.0));\n}\n\nfn cloud_henyey_greenstein(cosTheta: f32, g: f32) -> f32 {\n let denominator = max(0.0001, 1.0 + g * g - 2.0 * g * cosTheta);\n return (1.0 - g * g) / (denominator * sqrt(denominator)) * 0.0795774715;\n}\n\nfn cloud_phase(cosTheta: f32) -> f32 {\n // A bounded dual lobe gives a readable forward highlight and a small\n // back-scatter rim without another solar march.\n return cloud_henyey_greenstein(cosTheta, 0.55) * 0.8 +\n cloud_henyey_greenstein(cosTheta, -0.2) * 0.2;\n}\n\n// Reuse the same remaining-path optical depth for two bounded scattering\n// orders. This adds arithmetic only; no extra density or light-ray samples.\nfn cloud_incident_light(solarT: f32, cosTheta: f32, height: f32) -> vec3<f32> {\n let direct = solarT * cloud_phase(cosTheta);\n let multiple = (0.5 * pow(solarT, 0.5) + 0.25 * pow(solarT, 0.25)) * 0.0795774715;\n let skyFill = mix(0.025, 0.075, smoothstep(0.1, 0.85, height));\n // Match volume-integrate: the shared DirectionalLight value uses the\n // unnormalized phase convention. Convert the normalized HG basis once.\n return cloud.sunRadiance.xyz *\n (vec3<f32>((direct + multiple) * 12.5663706144) + vec3<f32>(0.72, 0.84, 1.0) * skyFill);\n}\n\nfn cloud_ray_jitter(pixel: vec2<f32>) -> f32 {\n // A stable per-pixel offset removes view-step contour bands without adding\n // a frame-varying noise source that would fight temporal reprojection.\n return fract(sin(dot(pixel, vec2<f32>(12.9898, 78.233))) * 43758.5453);\n}\n\nfn cloud_solar_jitter(position: vec3<f32>) -> f32 {\n // Dither the light-column samples in world space so low shadow-step\n // profiles do not paint parallel contour bands across cloud bases.\n return fract(sin(dot(position.xz, vec2<f32>(19.193, 47.117))) * 15731.743);\n}\n\nfn reconstruct_world(uv: vec2<f32>, depth: f32) -> vec3<f32> {\n let ndc = vec4<f32>(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, depth, 1.0);\n let world = view.inverseViewProj * ndc;\n return world.xyz / max(abs(world.w), 0.00001);\n}\n\n@vertex\nfn vs_main(@builtin(vertex_index) index: u32) -> CloudViewOut {\n var positions = array<vec2<f32>, 3>(\n vec2<f32>(-1.0, -1.0),\n vec2<f32>(3.0, -1.0),\n vec2<f32>(-1.0, 3.0),\n );\n var output: CloudViewOut;\n output.position = vec4<f32>(positions[index], 0.0, 1.0);\n // WebGPU clip-space Y grows upward while sampled framebuffer rows and the\n // depth texture use a top-left origin. Keep this one top-left UV for color,\n // depth and inverse-projection reconstruction; flipping only the final\n // color would leave the camera ray and depth cut mirrored.\n output.uv = vec2<f32>(\n positions[index].x * 0.5 + 0.5,\n 1.0 - (positions[index].y * 0.5 + 0.5),\n );\n return output;\n}\n\n@fragment\nfn fs_main(input: CloudViewOut) -> @location(0) vec4<f32> {\n // The shadow producer uses this same production density/cache contract but\n // rasterizes a camera-independent, texel-snapped light-space map. It does\n // not consume scene colour; the generic fullscreen host still supplies the\n // input binding to keep the feature binding ABI single and validated.\n if (cloud.integration.w == 1u) {\n let projection = cloud.shadowProjection;\n if (projection.y < 0.5 || projection.z > 0.5 || projection.x <= 0.0) {\n return vec4<f32>(1.0);\n }\n let offset = (input.uv - vec2<f32>(0.5)) * projection.x;\n let receiver = cloud.shadowOrigin.xyz +\n cloud.shadowRight.xyz * offset.x + cloud.shadowUp.xyz * offset.y;\n let sunDirection = normalize(-view.lightDir);\n let interval = cloud_layer_interval(receiver, sunDirection, projection.x);\n if (interval.y <= interval.x) { return vec4<f32>(1.0); }\n let steps = min(cloud.integration.z, 64u);\n let stepLength = (interval.y - interval.x) / max(1.0, f32(steps));\n var opticalDepth = 0.0;\n var firstHeight = 1.0;\n var lastHeight = 0.0;\n var occupied = false;\n let solarJitter = cloud_solar_jitter(receiver);\n for (var index = 0u; index < 64u; index = index + 1u) {\n if (index >= steps) { break; }\n let samplePosition = receiver + sunDirection *\n (interval.x + (f32(index) + solarJitter) * stepLength);\n let localDensity = cloud_density(samplePosition);\n opticalDepth = opticalDepth + localDensity * ${CLOUD_EXTINCTION_COEFFICIENT} * stepLength;\n if (localDensity > 0.0001) {\n let sampleHeight = clamp(\n (samplePosition.y - cloud.layer.x) / max(0.0001, cloud.layer.y),\n 0.0,\n 1.0,\n );\n if (!occupied) { firstHeight = sampleHeight; }\n lastHeight = sampleHeight;\n occupied = true;\n }\n }\n let transmittance = exp(-max(opticalDepth, 0.0));\n // R stores full-column transmittance. G/B preserve the first/last\n // occupied normalized layer heights so interior samples can estimate the\n // remaining segment without pretending optical depth is uniform through\n // the whole layer. A stores the integrated optical depth and distinguishes\n // an empty projected column from a valid, nearly-clear one.\n return vec4<f32>(\n transmittance,\n select(1.0, firstHeight, occupied),\n select(0.0, lastHeight, occupied),\n select(0.0, opticalDepth, occupied),\n );\n }\n // The shadow producer branch above is per-fragment (its light-space\n // interval depends on the rasterized receiver), so derivative-based\n // sampling here would violate WGSL uniform-control-flow rules. The cloud\n // scene path already owns an explicit level-0 sampler contract.\n // Keep point semantics for the current full-resolution scene path. The\n // half-resolution transport contract is introduced with its own resolve\n // shader so this path retains the established depth convention.\n let depthPixel = vec2<i32>(input.position.xy);\n let depth = textureLoad(sceneDepth, depthPixel, 0);\n let farWorld = reconstruct_world(input.uv, 1.0);\n let sceneWorld = reconstruct_world(input.uv, clamp(depth, 0.0, 1.0));\n let ray = normalize(farWorld - view.cameraPos);\n let rayJitter = cloud_ray_jitter(input.position.xy);\n let sceneDistance = select(cloud.field.z, length(sceneWorld - view.cameraPos), depth < 0.999999);\n let interval = cloud_layer_interval(view.cameraPos, ray, sceneDistance);\n\n // The depth producer shares the same camera ray, interval and density\n // contract as the display path. It writes a cloud representative world\n // position and a validity bit so history remains comparable after camera\n // translation or rotation and never uses an opaque scene distance as a\n // proxy for a participating medium.\n if (cloud.integration.w == 2u) {\n if (interval.y <= interval.x) { return vec4<f32>(sceneWorld, 0.0); }\n let depthSteps = min(cloud.integration.y, 64u);\n let depthStepLength = (interval.y - interval.x) / max(1.0, f32(depthSteps));\n var depthTransmittance = 1.0;\n var weightedDistance = 0.0;\n var opticalWeight = 0.0;\n for (var depthIndex = 0u; depthIndex < 64u; depthIndex = depthIndex + 1u) {\n if (depthIndex >= depthSteps) { break; }\n let sampleDistance = interval.x + (f32(depthIndex) + rayJitter) * depthStepLength;\n let samplePosition = view.cameraPos + ray * sampleDistance;\n let localDensity = cloud_density(samplePosition);\n let localTransmittance = exp(-max(localDensity * ${CLOUD_EXTINCTION_COEFFICIENT} * depthStepLength, 0.0));\n let weight = depthTransmittance * (1.0 - localTransmittance);\n weightedDistance = weightedDistance + sampleDistance * weight;\n opticalWeight = opticalWeight + weight;\n depthTransmittance = depthTransmittance * localTransmittance;\n }\n let hasCloud = opticalWeight > 0.00001;\n let representativeDistance = select(sceneDistance, weightedDistance / opticalWeight, hasCloud);\n let representativeWorld = view.cameraPos + ray * representativeDistance;\n return vec4<f32>(representativeWorld, select(0.0, 1.0, hasCloud));\n }\n\n let scene = textureSampleLevel(sceneColor, sceneSampler, input.uv, 0.0);\n if (interval.y <= interval.x) { return scene; }\n let steps = min(cloud.integration.y, 64u);\n let stepLength = (interval.y - interval.x) / max(1.0, f32(steps));\n var transmittance = 1.0;\n var scattering = vec3<f32>(0.0);\n var weightedDistance = 0.0;\n var opticalWeight = 0.0;\n let sunDirection = normalize(-view.lightDir);\n for (var index = 0u; index < 64u; index = index + 1u) {\n if (index >= steps) { break; }\n let distance = interval.x + (f32(index) + rayJitter) * stepLength;\n let samplePosition = view.cameraPos + ray * distance;\n let localDensity = cloud_density(samplePosition);\n let extinction = localDensity * ${CLOUD_EXTINCTION_COEFFICIENT} * stepLength;\n let localTransmittance = exp(-max(extinction, 0.0));\n let depthWeight = transmittance * (1.0 - localTransmittance);\n weightedDistance = weightedDistance + distance * depthWeight;\n opticalWeight = opticalWeight + depthWeight;\n // Empty samples are common in the separated-cloud field. Avoid a nested\n // solar march for them and stop once the camera path is effectively opaque.\n if (localDensity > 0.0001 && transmittance > 0.01) {\n let solarTransmittance = cloud_solar_transmittance(samplePosition);\n let cloudHeight = clamp(\n (samplePosition.y - cloud.layer.x) / max(0.0001, cloud.layer.y), 0.0, 1.0,\n );\n scattering = scattering + cloud_incident_light(\n solarTransmittance, dot(ray, sunDirection), cloudHeight,\n ) * depthWeight;\n }\n transmittance = transmittance * localTransmittance;\n if (transmittance < 0.01) { break; }\n }\n let hasCloud = opticalWeight > 0.00001;\n let representativeDistance = select(sceneDistance, weightedDistance / opticalWeight, hasCloud);\n let representativeWorld = view.cameraPos + ray * representativeDistance;\n // Wind is an advective coordinate change. Reproject the cloud point into\n // the previous frame's world before applying the previous camera matrix;\n // authored field values remain immutable.\n let windDelta = cloud.wind.xyz * max(0.0, cloud.field.y - cloud.temporal.w);\n // cloud_density evaluates the authored field at position + wind*time.\n // Keeping the same field sample in the previous frame therefore advances\n // the previous world point by the elapsed wind delta as well.\n let previousCloudWorld = representativeWorld + windDelta;\n let previousCloudClip = view.temporalPreviousViewProj * vec4<f32>(previousCloudWorld, 1.0);\n let previousCloudNdc = previousCloudClip.xyz / max(abs(previousCloudClip.w), 0.00001);\n let previousCloudUv = vec2<f32>(\n previousCloudNdc.x * 0.5 + 0.5,\n 1.0 - (previousCloudNdc.y * 0.5 + 0.5),\n );\n let cloudInBounds = all(previousCloudUv >= vec2<f32>(0.0)) && all(previousCloudUv <= vec2<f32>(1.0));\n let cloudHistoryUv = clamp(previousCloudUv, vec2<f32>(0.0), vec2<f32>(1.0));\n let cloudHistoryDepthSample = textureSampleLevel(previousDepth, depthSampler, cloudHistoryUv, 0.0);\n let cloudHistoryWorld = cloudHistoryDepthSample.xyz;\n let previous = textureSampleLevel(previousRadiance, sceneSampler, cloudHistoryUv, 0.0);\n let previousTransport = textureSampleLevel(\n previousTransmittance,\n sceneSampler,\n cloudHistoryUv,\n 0.0,\n );\n let worldTolerance = max(0.05, length(previousCloudWorld - view.cameraPos) * 0.02);\n let depthAccepted = cloudHistoryDepthSample.a > 0.5 &&\n distance(cloudHistoryWorld, previousCloudWorld) <= worldTolerance;\n let accepted =\n hasCloud && cloud.temporal.x > 0.5 && cloud.temporal.y < 0.5 && cloudInBounds &&\n depthAccepted && previousTransport.a > 0.0;\n let historyWeight = select(0.0, clamp(cloud.temporal.z, 0.0, 0.95), accepted);\n let cloudRadiance = mix(scattering, previous.rgb, historyWeight);\n // Preserve scene-linear HDR output for the downstream material lane. The\n // history owner receives cloudRadiance separately through the history pass.\n return vec4<f32>(scene.rgb * transmittance + cloudRadiance, transmittance);\n}\n\n// The light-space shadow producer already paid for a bounded column integral.\n// Reuse that texel for camera samples instead of starting a full solar march\n// for every occupied camera step. Outside the occupied interval the cached\n// full-column transmittance is exact for the projected column. Inside the\n// interval, the cache supplies the stable projection/bounds and a short\n// residual march resolves the non-uniform density that a linear optical-depth\n// interpolation would lose. Invalid/out-of-range projections retain the\n// analytic path as an explicit fallback.\nfn cloud_solar_cached_transmittance(position: vec3<f32>) -> f32 {\n let projection = cloud.shadowProjection;\n if (projection.y < 0.5 || projection.x <= 0.0) {\n return cloud_solar_transmittance(position);\n }\n let relative = position - cloud.shadowOrigin.xyz;\n let uv = vec2<f32>(\n dot(relative, cloud.shadowRight.xyz) / projection.x + 0.5,\n dot(relative, cloud.shadowUp.xyz) / projection.x + 0.5,\n );\n if (any(uv < vec2<f32>(0.0)) || any(uv > vec2<f32>(1.0))) {\n return cloud_solar_transmittance(position);\n }\n let cachedShadow = textureSampleLevel(previousRadiance, sceneSampler, uv, 0.0);\n let cachedOpticalDepth = max(cachedShadow.a, 0.0);\n let layerHeight = clamp(\n (position.y - cloud.layer.x) / max(0.0001, cloud.layer.y),\n 0.0,\n 1.0,\n );\n if (cachedOpticalDepth <= 0.0001) { return 1.0; }\n let firstHeight = clamp(cachedShadow.g, 0.0, 1.0);\n let lastHeight = clamp(cachedShadow.b, 0.0, 1.0);\n let occupiedMin = min(firstHeight, lastHeight);\n let occupiedMax = max(firstHeight, lastHeight);\n let sunDirection = normalize(-view.lightDir);\n // G/B are ordered along the light ray, not necessarily bottom-to-top. Only\n // use the cached full/empty fast paths when the light has enough vertical\n // component to make that ordering meaningful; grazing light stays on the\n // residual path so a low-sun column cannot invert the cache bounds.\n if (abs(sunDirection.y) > 0.2) {\n if (sunDirection.y > 0.0) {\n if (layerHeight <= occupiedMin) { return exp(-cachedOpticalDepth); }\n if (layerHeight >= occupiedMax) { return 1.0; }\n } else {\n if (layerHeight >= occupiedMax) { return exp(-cachedOpticalDepth); }\n if (layerHeight <= occupiedMin) { return 1.0; }\n }\n }\n\n // A short residual march is only paid for samples inside the projected\n // cloud span. Vertical light uses twelve taps, oblique light sixteen, and\n // grazing light up to thirty-two because the same layer projects across a\n // much longer solar segment. This removes the large error caused by\n // assuming optical depth is uniform between the first and last occupied\n // heights while keeping the normal camera path far below a second full\n // solar integration.\n let solarDistance = select(cloud.field.z, projection.x, projection.x > 0.0);\n let interval = cloud_layer_interval(position, sunDirection, solarDistance);\n if (interval.y <= interval.x) { return 1.0; }\n let absLightY = abs(sunDirection.y);\n let directionBudget = select(\n 32u,\n select(16u, 12u, absLightY > 0.5),\n absLightY > 0.2,\n );\n let residualSteps = min(directionBudget, max(8u, cloud.integration.z * 3u));\n let stepLength = (interval.y - interval.x) / max(1.0, f32(residualSteps));\n var opticalDepth = 0.0;\n let solarJitter = cloud_solar_jitter(position);\n for (var index = 0u; index < 32u; index = index + 1u) {\n if (index >= residualSteps) { break; }\n let samplePosition = position + sunDirection *\n (interval.x + (f32(index) + solarJitter) * stepLength);\n opticalDepth = opticalDepth + cloud_density(samplePosition) *\n ${CLOUD_EXTINCTION_COEFFICIENT} * stepLength;\n }\n return exp(-max(opticalDepth, 0.0));\n}\n\nstruct CloudTransportOutput {\n @location(0) radiance: vec4<f32>,\n @location(1) transmittance: vec4<f32>,\n @location(2) depth: vec4<f32>,\n};\n\n// One half-resolution transport pass writes all three reusable cloud fields.\n// The full-resolution resolve below reconstructs colour and applies temporal\n// history; no second full raymarch exists solely to obtain cloud depth.\n@fragment\nfn fs_transport(input: CloudViewOut) -> CloudTransportOutput {\n let depth = textureSampleLevel(sceneDepth, depthSampler, input.uv, 0u);\n let farWorld = reconstruct_world(input.uv, 1.0);\n let sceneWorld = reconstruct_world(input.uv, clamp(depth, 0.0, 1.0));\n let ray = normalize(farWorld - view.cameraPos);\n let rayJitter = cloud_ray_jitter(input.position.xy);\n let sceneDistance = select(cloud.field.z, length(sceneWorld - view.cameraPos), depth < 0.999999);\n let interval = cloud_layer_interval(view.cameraPos, ray, sceneDistance);\n var output: CloudTransportOutput;\n output.radiance = vec4<f32>(0.0, 0.0, 0.0, 0.0);\n output.transmittance = vec4<f32>(1.0, 1.0, 1.0, 1.0);\n output.depth = vec4<f32>(sceneWorld, 0.0);\n if (interval.y <= interval.x) { return output; }\n\n let steps = min(cloud.integration.y, 64u);\n let stepLength = (interval.y - interval.x) / max(1.0, f32(steps));\n var transmittance = 1.0;\n var scattering = vec3<f32>(0.0);\n var weightedDistance = 0.0;\n var opticalWeight = 0.0;\n let sunDirection = normalize(-view.lightDir);\n for (var index = 0u; index < 64u; index = index + 1u) {\n if (index >= steps) { break; }\n let distance = interval.x + (f32(index) + rayJitter) * stepLength;\n let samplePosition = view.cameraPos + ray * distance;\n let localDensity = cloud_density(samplePosition);\n let extinction = localDensity * ${CLOUD_EXTINCTION_COEFFICIENT} * stepLength;\n let localTransmittance = exp(-max(extinction, 0.0));\n let depthWeight = transmittance * (1.0 - localTransmittance);\n weightedDistance = weightedDistance + distance * depthWeight;\n opticalWeight = opticalWeight + depthWeight;\n if (localDensity > 0.0001 && transmittance > 0.01) {\n let solarTransmittance = cloud_solar_cached_transmittance(samplePosition);\n let cloudHeight = clamp(\n (samplePosition.y - cloud.layer.x) / max(0.0001, cloud.layer.y), 0.0, 1.0,\n );\n scattering = scattering + cloud_incident_light(\n solarTransmittance, dot(ray, sunDirection), cloudHeight,\n ) * depthWeight;\n }\n transmittance = transmittance * localTransmittance;\n if (transmittance < 0.01) { break; }\n }\n let hasCloud = opticalWeight > 0.00001;\n let representativeDistance = select(sceneDistance, weightedDistance / max(opticalWeight, 0.00001), hasCloud);\n output.radiance = vec4<f32>(scattering, select(0.0, 1.0, hasCloud));\n output.transmittance = vec4<f32>(transmittance, transmittance, transmittance, 1.0);\n output.depth = vec4<f32>(view.cameraPos + ray * representativeDistance, select(0.0, 1.0, hasCloud));\n return output;\n}\n`;\n\n/** Shared cloud transport module; `fs_transport` is selected by the MRT PSO. */\nexport const CLOUD_TRANSPORT_FULLSCREEN_WGSL = CLOUD_VIEW_FULLSCREEN_WGSL;\n/** Analytic fallback for adapters without a projected cloud-shadow target. */\nexport const CLOUD_TRANSPORT_ANALYTIC_FULLSCREEN_WGSL = CLOUD_VIEW_FULLSCREEN_WGSL.replace(\n 'cloud_solar_cached_transmittance(samplePosition)',\n 'cloud_solar_transmittance(samplePosition)',\n);\n\n/**\n * History writer. It is a separate MRT pass so the cloud composite remains a\n * normal scene-linear color producer while the renderer owns the ping-pong\n * radiance/transmittance/depth attachments and advances them only on submit.\n */\nexport const CLOUD_HISTORY_FULLSCREEN_WGSL = /* wgsl */ `\nstruct CloudCameraView {\n worldViewProj: mat4x4<f32>,\n lightDir: vec3<f32>,\n lightColor: vec3<f32>,\n cameraPos: vec3<f32>,\n lightViewProj_A: mat4x4<f32>,\n inverseViewProj: mat4x4<f32>,\n lightViewProj_B: mat4x4<f32>,\n lightViewProj_C: mat4x4<f32>,\n lightViewProj_D: mat4x4<f32>,\n splitPlanes: array<vec4<f32>, 4>,\n cascadeCount: f32,\n cascadeBlend: f32,\n depthBias: f32,\n normalBias: f32,\n directionalShadowFilter: vec4<f32>,\n spotLightViewProj: array<mat4x4<f32>, 4>,\n temporalCurrentViewProj: mat4x4<f32>,\n temporalPreviousViewProj: mat4x4<f32>,\n temporalProjection: vec4<f32>,\n temporalPreviousCameraPos: vec4<f32>,\n ssrParams: vec4<f32>,\n};\n\nstruct CloudHistoryParams {\n temporal: vec4<f32>, // valid, reset, historyWeight, reserved\n windTime: vec4<f32>, // wind.xyz, elapsed seconds since previous submit\n};\n\n@group(0) @binding(0) var<uniform> view: CloudCameraView;\n@group(1) @binding(0) var currentRadiance: texture_2d<f32>;\n@group(1) @binding(1) var sceneSampler: sampler;\n@group(1) @binding(2) var<uniform> params: CloudHistoryParams;\n@group(1) @binding(3) var sceneDepth: texture_depth_2d;\n@group(1) @binding(4) var depthSampler: sampler;\n@group(1) @binding(5) var currentCloudDepth: texture_2d<f32>;\n@group(1) @binding(6) var sceneBackground: texture_2d<f32>;\n\nstruct CloudHistoryInput {\n @builtin(position) position: vec4<f32>,\n @location(0) uv: vec2<f32>,\n};\n\nstruct CloudHistoryOutput {\n @location(0) radiance: vec4<f32>,\n @location(1) transmittance: vec4<f32>,\n};\n\nfn reconstruct_world(uv: vec2<f32>, depth: f32) -> vec3<f32> {\n let ndc = vec4<f32>(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, depth, 1.0);\n let world = view.inverseViewProj * ndc;\n return world.xyz / max(abs(world.w), 0.00001);\n}\n\n@vertex\nfn vs_main(@builtin(vertex_index) index: u32) -> CloudHistoryInput {\n var positions = array<vec2<f32>, 3>(\n vec2<f32>(-1.0, -1.0),\n vec2<f32>(3.0, -1.0),\n vec2<f32>(-1.0, 3.0),\n );\n var output: CloudHistoryInput;\n output.position = vec4<f32>(positions[index], 0.0, 1.0);\n output.uv = vec2<f32>(\n positions[index].x * 0.5 + 0.5,\n 1.0 - (positions[index].y * 0.5 + 0.5),\n );\n return output;\n}\n\n@fragment\nfn fs_main(input: CloudHistoryInput) -> CloudHistoryOutput {\n let current = textureSampleLevel(currentRadiance, sceneSampler, input.uv, 0.0);\n let background = textureSampleLevel(sceneBackground, sceneSampler, input.uv, 0.0);\n let cloudDepth = textureSampleLevel(currentCloudDepth, depthSampler, input.uv, 0.0);\n let currentValid = cloudDepth.a > 0.5;\n // currentRadiance is the scene-linear cloud composite. Remove the\n // unchanged scene background before writing history so the persistent owner\n // stores raw cloud radiance only. The view pass is the sole temporal blend\n // owner; blending here as well would accumulate history twice per frame.\n let currentCloudRadiance = max(current.rgb - background.rgb * current.a, vec3<f32>(0.0));\n let currentTransmittance = vec4<f32>(current.a, current.a, current.a, 1.0);\n var output: CloudHistoryOutput;\n output.radiance = vec4<f32>(currentCloudRadiance, select(0.0, 1.0, currentValid));\n output.transmittance = currentTransmittance;\n return output;\n}\n`;\n\n/** Full-resolution resolve for the half-resolution transport MRT. */\nexport const CLOUD_RESOLVE_FULLSCREEN_WGSL = /* wgsl */ `\nstruct CloudCameraView {\n worldViewProj: mat4x4<f32>,\n lightDir: vec3<f32>,\n lightColor: vec3<f32>,\n cameraPos: vec3<f32>,\n lightViewProj_A: mat4x4<f32>,\n inverseViewProj: mat4x4<f32>,\n lightViewProj_B: mat4x4<f32>,\n lightViewProj_C: mat4x4<f32>,\n lightViewProj_D: mat4x4<f32>,\n splitPlanes: array<vec4<f32>, 4>,\n cascadeCount: f32,\n cascadeBlend: f32,\n depthBias: f32,\n normalBias: f32,\n directionalShadowFilter: vec4<f32>,\n spotLightViewProj: array<mat4x4<f32>, 4>,\n temporalCurrentViewProj: mat4x4<f32>,\n temporalPreviousViewProj: mat4x4<f32>,\n temporalProjection: vec4<f32>,\n temporalPreviousCameraPos: vec4<f32>,\n ssrParams: vec4<f32>,\n};\n\nstruct CloudResolveParams {\n layer: vec4<f32>,\n field: vec4<f32>,\n wind: vec4<f32>,\n sunDirection: vec4<f32>,\n sunRadiance: vec4<f32>,\n integration: vec4<u32>,\n shadowOrigin: vec4<f32>,\n shadowRight: vec4<f32>,\n shadowUp: vec4<f32>,\n shadowProjection: vec4<f32>,\n temporal: vec4<f32>,\n};\n\n@group(0) @binding(0) var<uniform> view: CloudCameraView;\n@group(1) @binding(0) var sceneColor: texture_2d<f32>;\n@group(1) @binding(1) var sceneSampler: sampler;\n@group(1) @binding(2) var<uniform> cloud: CloudResolveParams;\n@group(1) @binding(3) var sceneDepth: texture_depth_2d;\n@group(1) @binding(4) var depthSampler: sampler;\n@group(1) @binding(5) var currentRadiance: texture_2d<f32>;\n@group(1) @binding(6) var currentTransmittance: texture_2d<f32>;\n@group(1) @binding(7) var currentDepth: texture_2d<f32>;\n@group(1) @binding(8) var previousRadiance: texture_2d<f32>;\n@group(1) @binding(9) var previousTransmittance: texture_2d<f32>;\n@group(1) @binding(10) var previousDepth: texture_2d<f32>;\n\nstruct CloudResolveInput {\n @builtin(position) position: vec4<f32>,\n @location(0) uv: vec2<f32>,\n};\n\nfn reconstruct_world(uv: vec2<f32>, depth: f32) -> vec3<f32> {\n let ndc = vec4<f32>(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, depth, 1.0);\n let world = view.inverseViewProj * ndc;\n return world.xyz / max(abs(world.w), 0.00001);\n}\n\n@vertex\nfn vs_main(@builtin(vertex_index) index: u32) -> CloudResolveInput {\n var positions = array<vec2<f32>, 3>(\n vec2<f32>(-1.0, -1.0),\n vec2<f32>(3.0, -1.0),\n vec2<f32>(-1.0, 3.0),\n );\n var output: CloudResolveInput;\n output.position = vec4<f32>(positions[index], 0.0, 1.0);\n output.uv = vec2<f32>(\n positions[index].x * 0.5 + 0.5,\n 1.0 - (positions[index].y * 0.5 + 0.5),\n );\n return output;\n}\n\n@fragment\nfn fs_main(input: CloudResolveInput) -> @location(0) vec4<f32> {\n let scene = textureSampleLevel(sceneColor, sceneSampler, input.uv, 0.0);\n // The resolve owns the full-resolution foreground test. Reject the current\n // low-resolution transport before any history or radiance is composited;\n // gating history alone still lets a newly sampled cloud bleed over geometry.\n let sceneDepthValue = textureLoad(sceneDepth, vec2<i32>(input.position.xy), 0);\n let sceneWorld = reconstruct_world(input.uv, clamp(sceneDepthValue, 0.0, 1.0));\n let sceneDistance = length(sceneWorld - view.cameraPos);\n let transport = textureSampleLevel(currentRadiance, sceneSampler, input.uv, 0.0);\n let transportT = textureSampleLevel(currentTransmittance, sceneSampler, input.uv, 0.0);\n // The transport depth is an rgba16float color attachment, not the scene's\n // depth texture. Sample it with the filtering color sampler; binding the\n // non-filtering scene-depth sampler here makes the shader contract depend on\n // an incompatible sampler/texture pair on strict WebGPU implementations.\n let cloudDepth = textureSampleLevel(currentDepth, sceneSampler, input.uv, 0.0);\n let currentValid = transport.a > 0.5 && cloudDepth.a > 0.5;\n let cloudDistance = length(cloudDepth.xyz - view.cameraPos);\n let foregroundAccepted = sceneDepthValue >= 0.999999 ||\n cloudDistance <= sceneDistance + max(0.05, sceneDistance * 0.01);\n if (!currentValid || !foregroundAccepted) { return scene; }\n\n let previousClip = view.temporalPreviousViewProj * vec4<f32>(\n cloudDepth.xyz + cloud.wind.xyz * max(0.0, cloud.field.y - cloud.temporal.w),\n 1.0,\n );\n let previousNdc = previousClip.xyz / max(abs(previousClip.w), 0.00001);\n let previousUv = vec2<f32>(\n previousNdc.x * 0.5 + 0.5,\n 1.0 - (previousNdc.y * 0.5 + 0.5),\n );\n let inBounds = all(previousUv >= vec2<f32>(0.0)) && all(previousUv <= vec2<f32>(1.0));\n let historyUv = clamp(previousUv, vec2<f32>(0.0), vec2<f32>(1.0));\n let historyDepth = textureSampleLevel(previousDepth, sceneSampler, historyUv, 0.0);\n let previous = textureSampleLevel(previousRadiance, sceneSampler, historyUv, 0.0);\n let previousTransport = textureSampleLevel(previousTransmittance, sceneSampler, historyUv, 0.0);\n let dims = vec2<f32>(textureDimensions(previousRadiance));\n let texel = 1.0 / max(dims, vec2<f32>(1.0));\n // Clamp reprojected history against the current low-resolution transport\n // neighborhood. Using only previous-frame neighbors (and including the\n // previous center in both extrema) is a no-op and lets stale bright cloud\n // pixels leak across a newly exposed edge.\n let c0 = transport.rgb;\n let c1 = textureSampleLevel(currentRadiance, sceneSampler, clamp(input.uv + vec2<f32>(-texel.x, 0.0), vec2<f32>(0.0), vec2<f32>(1.0)), 0.0).rgb;\n let c2 = textureSampleLevel(currentRadiance, sceneSampler, clamp(input.uv + vec2<f32>(texel.x, 0.0), vec2<f32>(0.0), vec2<f32>(1.0)), 0.0).rgb;\n let c3 = textureSampleLevel(currentRadiance, sceneSampler, clamp(input.uv + vec2<f32>(0.0, -texel.y), vec2<f32>(0.0), vec2<f32>(1.0)), 0.0).rgb;\n let c4 = textureSampleLevel(currentRadiance, sceneSampler, clamp(input.uv + vec2<f32>(0.0, texel.y), vec2<f32>(0.0), vec2<f32>(1.0)), 0.0).rgb;\n let minRadiance = min(c0, min(min(c1, c2), min(c3, c4)));\n let maxRadiance = max(c0, max(max(c1, c2), max(c3, c4)));\n let t1 = textureSampleLevel(currentTransmittance, sceneSampler, clamp(input.uv + vec2<f32>(-texel.x, 0.0), vec2<f32>(0.0), vec2<f32>(1.0)), 0.0).r;\n let t2 = textureSampleLevel(currentTransmittance, sceneSampler, clamp(input.uv + vec2<f32>(texel.x, 0.0), vec2<f32>(0.0), vec2<f32>(1.0)), 0.0).r;\n let t3 = textureSampleLevel(currentTransmittance, sceneSampler, clamp(input.uv + vec2<f32>(0.0, -texel.y), vec2<f32>(0.0), vec2<f32>(1.0)), 0.0).r;\n let t4 = textureSampleLevel(currentTransmittance, sceneSampler, clamp(input.uv + vec2<f32>(0.0, texel.y), vec2<f32>(0.0), vec2<f32>(1.0)), 0.0).r;\n let minTransport = min(transportT.r, min(min(t1, t2), min(t3, t4)));\n let maxTransport = max(transportT.r, max(max(t1, t2), max(t3, t4)));\n let worldTolerance = max(0.05, distance(cloudDepth.xyz, view.cameraPos) * 0.02);\n let depthAccepted = historyDepth.a > 0.5 && distance(historyDepth.xyz, cloudDepth.xyz) <= worldTolerance;\n let accepted = cloud.temporal.x > 0.5 && cloud.temporal.y < 0.5 && inBounds && depthAccepted;\n let historyWeight = select(0.0, clamp(cloud.temporal.z, 0.0, 0.92), accepted);\n let stableHistory = clamp(previous.rgb, minRadiance, maxRadiance);\n let stableTransport = clamp(previousTransport.r, minTransport, maxTransport);\n let radiance = mix(transport.rgb, stableHistory, historyWeight);\n let transmittance = mix(transportT.r, stableTransport, historyWeight);\n return vec4<f32>(scene.rgb * transmittance + radiance, transmittance);\n}\n`;\n\nexport interface CloudLayerFeatureFrame {\n readonly params: ValidatedCloudLayer | undefined;\n readonly cache: CloudDensityCache | undefined;\n readonly sourceKey: string | undefined;\n readonly timeSeconds: number;\n readonly sunDirection: readonly [number, number, number] | undefined;\n readonly sunRadiance: readonly [number, number, number] | undefined;\n readonly shadowProjection: CloudShadowProjection | undefined;\n readonly temporal: CloudTemporalFrame | undefined;\n readonly generation: number;\n readonly inspection: CloudLayerInspection;\n}\n\nexport interface CloudLayerFeatureOptions {\n /** Disable the renderer-owned CloudLayer projection while retaining the component. */\n readonly enabled?: boolean;\n}\n\nfunction makeCloudViewParams(\n frame: CloudLayerFeatureFrame,\n cache: CloudDensityCache,\n mode: 0 | 1 | 2 = 0,\n): Uint8Array {\n const params = new ArrayBuffer(CLOUD_VIEW_PARAMS_BYTES);\n const floats = new Float32Array(params);\n const integers = new Uint32Array(params);\n const profile = CLOUD_QUALITY_PROFILES[frame.params?.quality ?? 'medium'];\n const authored = frame.params;\n floats[0] = authored?.baseHeight ?? 0;\n floats[1] = authored?.thickness ?? 1;\n floats[2] = authored?.scale ?? 1;\n floats[3] = authored?.density ?? 0;\n floats[4] = authored?.coverage ?? 1;\n floats[5] = frame.timeSeconds;\n floats[6] =\n mode === 1\n ? (authored?.shadowRange ?? 0)\n : cloudViewDistanceForQuality(authored?.quality ?? 'medium');\n floats[7] = authored?.seed ?? 0;\n floats[8] = authored?.wind[0] ?? 0;\n floats[9] = authored?.wind[1] ?? 0;\n floats[10] = authored?.wind[2] ?? 0;\n floats[12] = frame.sunDirection?.[0] ?? 0;\n floats[13] = frame.sunDirection?.[1] ?? -1;\n floats[14] = frame.sunDirection?.[2] ?? 0;\n floats[15] = 0.2;\n floats[16] = frame.sunRadiance?.[0] ?? 0;\n floats[17] = frame.sunRadiance?.[1] ?? 0;\n floats[18] = frame.sunRadiance?.[2] ?? 0;\n integers[20] = cache.resolution;\n integers[21] = Math.max(1, Math.min(64, Math.floor(profile.viewSteps)));\n integers[22] = Math.max(1, Math.min(64, Math.floor(profile.shadowSteps)));\n integers[23] = mode;\n const projection = frame.shadowProjection;\n if (projection !== undefined) {\n floats[24] = projection.origin[0];\n floats[25] = projection.origin[1];\n floats[26] = projection.origin[2];\n floats[28] = projection.right[0];\n floats[29] = projection.right[1];\n floats[30] = projection.right[2];\n floats[32] = projection.up[0];\n floats[33] = projection.up[1];\n floats[34] = projection.up[2];\n floats[36] = projection.range;\n floats[37] = projection.lowSun ? 0 : 1;\n floats[38] = projection.lowSun ? 1 : 0;\n floats[39] = projection.texelSize;\n }\n const temporal = frame.temporal;\n floats[40] = temporal !== undefined && temporal.reset === false ? 1 : 0;\n floats[41] = temporal?.reset === true ? 1 : 0;\n floats[42] = temporal === undefined ? 0 : profile.historyWeight;\n // The history entry is the last successfully submitted signature. Carry its\n // timestamp so the shader can advect the representative cloud point by the\n // exact elapsed time during reprojection.\n floats[43] = temporal?.history?.temporal.timeSeconds ?? frame.timeSeconds;\n return new Uint8Array(params);\n}\n\nfunction planCloudDensity(\n frame: CloudLayerFeatureFrame,\n packedCache: Uint32Array,\n context: RenderFeaturePlanContext,\n): RenderFeaturePlan {\n const cacheCount = packedCache.length;\n const params = new Uint32Array([cacheCount]);\n const inputTarget = context.targets.find((target) => target.name === 'motion-input');\n const outputTarget = context.targets.find((target) => target.name === 'motion-output');\n const historyRadiancePrevious = context.targets.find(\n (target) => target.name === 'cloud-history-radiance-previous',\n );\n const historyTransmittancePrevious = context.targets.find(\n (target) => target.name === 'cloud-history-transmittance-previous',\n );\n const historyDepthPrevious = context.targets.find(\n (target) => target.name === 'cloud-history-depth-previous',\n );\n const historyRadianceCurrent = context.targets.find(\n (target) => target.name === 'cloud-history-radiance-current',\n );\n const historyTransmittanceCurrent = context.targets.find(\n (target) => target.name === 'cloud-history-transmittance-current',\n );\n const historyDepthCurrent = context.targets.find(\n (target) => target.name === 'cloud-history-depth-current',\n );\n const hasHistoryTargets =\n historyRadiancePrevious !== undefined &&\n historyTransmittancePrevious !== undefined &&\n historyDepthPrevious !== undefined &&\n historyRadianceCurrent !== undefined &&\n historyTransmittanceCurrent !== undefined &&\n historyDepthCurrent !== undefined;\n const shadowTarget = context.targets.find((target) => target.name === 'cloud-shadow');\n const canShadow =\n shadowTarget !== undefined &&\n shadowTarget.sampleCount === 1 &&\n frame.shadowProjection !== undefined &&\n hasHistoryTargets;\n const canCompose =\n inputTarget !== undefined &&\n outputTarget !== undefined &&\n inputTarget.sampleCount === 1 &&\n outputTarget.sampleCount === 1 &&\n hasHistoryTargets;\n const transportReads = ['motion-input', { key: 'depth', sampleType: 'depth' as const }] as const;\n const transportCacheReads = [\n 'motion-input',\n 'cloud-shadow',\n { key: 'depth', sampleType: 'depth' as const },\n ] as const;\n const historyReads = [\n 'motion-input',\n 'cloud-history-radiance-previous',\n 'cloud-history-transmittance-previous',\n 'cloud-history-depth-previous',\n { key: 'depth', sampleType: 'depth' as const },\n ] as const;\n const historyAdditionalTextures = [\n 'cloud-history-radiance-previous',\n 'cloud-history-transmittance-previous',\n 'cloud-history-depth-previous',\n ] as const;\n const viewParams = makeCloudViewParams(frame, frame.cache as CloudDensityCache);\n const shadowParams = canShadow\n ? makeCloudViewParams(frame, frame.cache as CloudDensityCache, 1)\n : undefined;\n const transportUsesShadowCache = canCompose && canShadow;\n return {\n resources: [\n {\n kind: 'compute-program',\n name: CLOUD_LAYER_DENSITY_PROGRAM,\n program: {\n wgsl: CLOUD_DENSITY_COMPUTE_WGSL,\n entryPoints: ['cloud_density_cache'],\n bindings: [\n {\n label: 'forgeax.cloud-layer.cache',\n entries: [\n { binding: 0, visibility: COMPUTE_STAGE, buffer: { type: 'read-only-storage' } },\n { binding: 1, visibility: COMPUTE_STAGE, buffer: { type: 'storage' } },\n { binding: 2, visibility: COMPUTE_STAGE, buffer: { type: 'uniform' } },\n ],\n },\n ],\n },\n },\n {\n kind: 'buffer',\n name: CLOUD_LAYER_DENSITY_CACHE,\n size: packedCache.byteLength,\n usage: ['storage', 'copy-src'],\n data: packedCache,\n },\n {\n kind: 'buffer',\n name: CLOUD_LAYER_DENSITY_OUTPUT,\n size: packedCache.byteLength,\n usage: ['storage', 'copy-src'],\n },\n {\n kind: 'buffer',\n name: 'cloud-layer-density-params',\n size: params.byteLength,\n usage: ['uniform'],\n data: params,\n },\n {\n kind: 'compute-bindings',\n name: CLOUD_LAYER_DENSITY_BINDINGS,\n program: CLOUD_LAYER_DENSITY_PROGRAM,\n entries: [\n { binding: 0, resource: CLOUD_LAYER_DENSITY_CACHE },\n { binding: 1, resource: CLOUD_LAYER_DENSITY_OUTPUT },\n { binding: 2, resource: 'cloud-layer-density-params' },\n ],\n },\n {\n kind: 'fullscreen-program',\n name: 'cloud-layer-view',\n source: CLOUD_VIEW_FULLSCREEN_WGSL,\n usesView: true,\n storageBindings: [8],\n reads: historyReads,\n params: {\n byteSize: viewParams.byteLength,\n defaultValue: viewParams,\n },\n },\n ...(shadowParams === undefined\n ? []\n : [\n {\n kind: 'fullscreen-program' as const,\n name: 'cloud-layer-shadow',\n source: CLOUD_VIEW_FULLSCREEN_WGSL,\n usesView: true,\n storageBindings: [8],\n reads: historyReads,\n params: {\n byteSize: shadowParams.byteLength,\n defaultValue: shadowParams,\n },\n },\n ]),\n ...(canCompose\n ? [\n {\n kind: 'fullscreen-program' as const,\n name: 'cloud-layer-transport',\n source: transportUsesShadowCache\n ? CLOUD_TRANSPORT_FULLSCREEN_WGSL\n : CLOUD_TRANSPORT_ANALYTIC_FULLSCREEN_WGSL,\n fragmentEntryPoint: 'fs_transport',\n usesView: true,\n storageBindings: [8],\n reads: transportUsesShadowCache ? transportCacheReads : transportReads,\n params: {\n byteSize: viewParams.byteLength,\n defaultValue: viewParams,\n },\n },\n {\n kind: 'fullscreen-program' as const,\n name: 'cloud-layer-resolve',\n source: CLOUD_RESOLVE_FULLSCREEN_WGSL,\n usesView: true,\n reads: [\n 'motion-input',\n 'cloud-history-radiance-current',\n 'cloud-history-transmittance-current',\n 'cloud-history-depth-current',\n 'cloud-history-radiance-previous',\n 'cloud-history-transmittance-previous',\n 'cloud-history-depth-previous',\n { key: 'depth', sampleType: 'depth' as const },\n ],\n params: {\n byteSize: viewParams.byteLength,\n defaultValue: viewParams,\n },\n },\n ]\n : []),\n ...(canCompose\n ? [\n {\n kind: 'graphics-program' as const,\n name: 'cloud-layer-transport-pipeline',\n program: {\n shader: 'cloud-layer-transport',\n vertexLayout: 'none',\n colorFormats: [\n historyRadianceCurrent.format,\n historyTransmittanceCurrent.format,\n historyDepthCurrent.format,\n ],\n sampleCount: 1 as const,\n renderState: {\n depthWriteEnabled: false,\n depthCompare: 'always' as const,\n },\n },\n },\n {\n kind: 'graphics-bindings' as const,\n name: 'cloud-layer-transport-view-bindings',\n program: 'cloud-layer-transport-pipeline',\n values: { group: 0, view: true },\n },\n {\n kind: 'graphics-bindings' as const,\n name: 'cloud-layer-transport-bindings',\n program: 'cloud-layer-transport-pipeline',\n values: {\n group: 1,\n fullscreen: true,\n shader: 'cloud-layer-transport',\n input: 'motion-input',\n depth: 'depth',\n additionalTextures: transportUsesShadowCache ? ['cloud-shadow'] : [],\n storageBuffers: [CLOUD_LAYER_DENSITY_OUTPUT],\n },\n logicalTargets: { input: 'motion-input' },\n },\n {\n kind: 'graphics-program' as const,\n name: 'cloud-layer-resolve-pipeline',\n program: {\n shader: 'cloud-layer-resolve',\n vertexLayout: 'none',\n colorFormats: [outputTarget.format],\n sampleCount: 1 as const,\n renderState: {\n depthWriteEnabled: false,\n depthCompare: 'always' as const,\n },\n },\n },\n {\n kind: 'graphics-bindings' as const,\n name: 'cloud-layer-resolve-view-bindings',\n program: 'cloud-layer-resolve-pipeline',\n values: { group: 0, view: true },\n },\n {\n kind: 'graphics-bindings' as const,\n name: 'cloud-layer-resolve-bindings',\n program: 'cloud-layer-resolve-pipeline',\n values: {\n group: 1,\n fullscreen: true,\n shader: 'cloud-layer-resolve',\n input: 'motion-input',\n depth: 'depth',\n additionalTextures: [\n 'cloud-history-radiance-current',\n 'cloud-history-transmittance-current',\n 'cloud-history-depth-current',\n 'cloud-history-radiance-previous',\n 'cloud-history-transmittance-previous',\n 'cloud-history-depth-previous',\n ],\n },\n },\n ]\n : []),\n ...(canShadow\n ? [\n {\n kind: 'graphics-program' as const,\n name: 'cloud-layer-shadow-pipeline',\n program: {\n shader: 'cloud-layer-shadow',\n vertexLayout: 'none',\n colorFormats: [shadowTarget.format],\n sampleCount: 1 as const,\n renderState: {\n depthWriteEnabled: false,\n depthCompare: 'always' as const,\n blend: {\n color: {\n srcFactor: 'one' as const,\n dstFactor: 'zero' as const,\n operation: 'add' as const,\n },\n alpha: {\n srcFactor: 'one' as const,\n dstFactor: 'zero' as const,\n operation: 'add' as const,\n },\n },\n },\n },\n },\n {\n kind: 'graphics-bindings' as const,\n name: 'cloud-layer-shadow-view-bindings',\n program: 'cloud-layer-shadow-pipeline',\n values: { group: 0, view: true },\n },\n {\n kind: 'graphics-bindings' as const,\n name: 'cloud-layer-shadow-bindings',\n program: 'cloud-layer-shadow-pipeline',\n values: {\n group: 1,\n fullscreen: true,\n shader: 'cloud-layer-shadow',\n input: false,\n depth: 'depth',\n // The shadow branch's WGSL keeps the shared depth binding\n // shape, but its light-space path never samples scene depth.\n // Bind the renderer-owned far-depth fallback instead of\n // introducing a read-before-main graph dependency.\n depthFallback: true,\n additionalTextures: historyAdditionalTextures,\n storageBuffers: [CLOUD_LAYER_DENSITY_OUTPUT],\n },\n },\n ]\n : []),\n ],\n passes:\n context.caps.compute && context.caps.storageBuffer\n ? [\n {\n kind: 'compute' as const,\n name: 'cloud-layer-density-cache',\n program: CLOUD_LAYER_DENSITY_PROGRAM,\n bindings: CLOUD_LAYER_DENSITY_BINDINGS,\n dispatches: [\n {\n kind: 'direct' as const,\n entryPoint: 'cloud_density_cache',\n workgroups: [Math.max(1, Math.ceil(cacheCount / CLOUD_WORKGROUP_SIZE))],\n },\n ],\n },\n ...(canShadow\n ? [\n {\n kind: 'raster' as const,\n name: 'cloud-layer-shadow',\n colorAttachments: [\n {\n target: 'cloud-shadow',\n loadOp: 'clear' as const,\n storeOp: 'store' as const,\n },\n ],\n sampledTargets: [\n 'cloud-history-radiance-previous',\n 'cloud-history-transmittance-previous',\n 'cloud-history-depth-previous',\n ],\n draws: [\n {\n program: 'cloud-layer-shadow-pipeline',\n bindings: [\n 'cloud-layer-shadow-view-bindings',\n 'cloud-layer-shadow-bindings',\n ],\n vertexData: [],\n vertexLayout: 'none' as const,\n draw: { kind: 'draw' as const, vertexCount: 3, instanceCount: 1 },\n },\n ],\n },\n ]\n : []),\n ...(canCompose\n ? [\n {\n kind: 'raster' as const,\n name: 'cloud-layer-transport',\n colorAttachments: [\n {\n target: 'cloud-history-radiance-current',\n loadOp: 'clear' as const,\n storeOp: 'store' as const,\n },\n {\n target: 'cloud-history-transmittance-current',\n loadOp: 'clear' as const,\n storeOp: 'store' as const,\n },\n {\n target: 'cloud-history-depth-current',\n loadOp: 'clear' as const,\n storeOp: 'store' as const,\n },\n ],\n sampledTargets: [\n 'motion-input',\n 'depth',\n ...(transportUsesShadowCache ? ['cloud-shadow'] : []),\n ],\n draws: [\n {\n program: 'cloud-layer-transport-pipeline',\n bindings: [\n 'cloud-layer-transport-view-bindings',\n 'cloud-layer-transport-bindings',\n ],\n vertexData: [],\n vertexLayout: 'none' as const,\n draw: { kind: 'draw' as const, vertexCount: 3, instanceCount: 1 },\n },\n ],\n },\n {\n kind: 'raster' as const,\n name: 'cloud-layer-resolve',\n colorAttachments: [\n {\n target: 'motion-output',\n loadOp: 'clear' as const,\n storeOp: 'store' as const,\n },\n ],\n sampledTargets: [\n 'motion-input',\n 'depth',\n 'cloud-history-radiance-current',\n 'cloud-history-transmittance-current',\n 'cloud-history-depth-current',\n 'cloud-history-radiance-previous',\n 'cloud-history-transmittance-previous',\n 'cloud-history-depth-previous',\n ],\n draws: [\n {\n program: 'cloud-layer-resolve-pipeline',\n bindings: [\n 'cloud-layer-resolve-view-bindings',\n 'cloud-layer-resolve-bindings',\n ],\n vertexData: [],\n vertexLayout: 'none' as const,\n draw: { kind: 'draw' as const, vertexCount: 3, instanceCount: 1 },\n },\n ],\n },\n ]\n : []),\n ]\n : [],\n };\n}\n\n/**\n * Renderer-installed cloud producer. Authoring is read once from World at\n * extraction; resource preparation, graph ordering and retirement stay with\n * RenderFeatureHost.\n */\nexport function createCloudLayerFeature(\n options: CloudLayerFeatureOptions = {},\n): RenderFeature<CloudLayerFeatureFrame> {\n let cachedSourceKey: string | undefined;\n let cached: CloudDensityCache | undefined;\n let packedCache: Uint32Array | undefined;\n let generation = 0;\n const histories = new CloudHistoryStore();\n let temporalResetCount = 0;\n let lastTemporalReset: CloudTemporalFrame['reasons'][number] | undefined;\n return Object.freeze({\n identity: CLOUD_LAYER_FEATURE_IDENTITY,\n placement: 'scene' as const,\n requiredCapabilities: ['compute', 'storageBuffer', 'rgba16floatRenderable'] as const,\n // Cloud programs are generated by the feature and have no user-authored\n // manifest entry to await. Use the immediate module path so first-frame\n // feature admission does not publish a transient pending-shader failure;\n // pipeline creation remains the validation boundary for this WGSL.\n shaderModuleMode: 'immediate' as const,\n extract: (\n context: RenderFeatureExtractContext,\n ): Result<CloudLayerFeatureFrame, RenderError> => {\n if (options.enabled === false) {\n histories.reset();\n return ok({\n params: undefined,\n cache: undefined,\n sourceKey: undefined,\n timeSeconds: 0,\n sunDirection: undefined,\n sunRadiance: undefined,\n shadowProjection: undefined,\n temporal: undefined,\n generation,\n inspection: inspectCloudLayer({ authored: false }),\n });\n }\n const world = context.worlds[context.owner];\n if (world === undefined) {\n histories.reset();\n return ok({\n params: undefined,\n cache: undefined,\n sourceKey: undefined,\n timeSeconds: 0,\n sunDirection: undefined,\n sunRadiance: undefined,\n shadowProjection: undefined,\n temporal: undefined,\n generation,\n inspection: inspectCloudLayer({ authored: false }),\n });\n }\n // The normal RenderSystem extract owns World reads and selected-sun\n // resolution. Direct feature probes must provide the same frame facts;\n // this keeps the feature from growing a detached authoring callback or\n // a second per-feature ECS registry.\n const cloud = context.frame?.cloudLayer;\n const capability =\n context.caps === undefined ? undefined : cloudCapabilitiesFromRhi(context.caps);\n if (cloud === undefined) {\n histories.reset();\n return ok({\n params: undefined,\n cache: undefined,\n sourceKey: undefined,\n timeSeconds: 0,\n sunDirection: undefined,\n sunRadiance: undefined,\n shadowProjection: undefined,\n temporal: undefined,\n generation,\n inspection: inspectCloudLayer({\n authored: false,\n ...(capability === undefined ? {} : { capability }),\n }),\n });\n }\n const formationKey = cloudLayerFormationKey(cloud.params);\n if (cached === undefined || cachedSourceKey !== formationKey) {\n cached = buildCloudDensityCache(cloud.params);\n packedCache = packCloudDensityCache(cached);\n cachedSourceKey = formationKey;\n generation += 1;\n }\n const view = context.frame?.view;\n const shadowProjection =\n view === undefined || cloud.sunDirection === undefined\n ? undefined\n : createCloudShadowProjection({\n center: view.shadowAnchor ?? view.cameraPosition,\n sunDirection: cloud.sunDirection,\n range: cloud.params.shadowRange,\n resolution: cloudShadowResolutionForQuality(cloud.params.quality),\n });\n const temporalSignature: CloudTemporalSignature | undefined =\n view === undefined\n ? undefined\n : {\n sourceKey: cloud.sourceKey,\n viewId: view.identity,\n authoringGeneration: generation,\n cloudShadowRevision: shadowProjection?.revision ?? 0,\n cameraRevision: view.cameraRevision,\n deviceGeneration: view.deviceGeneration,\n width: view.width,\n height: view.height,\n timeSeconds: cloud.worldTimeSeconds,\n quality: cloud.params.quality,\n ...(view.sceneDepthVersion === undefined\n ? {}\n : { sceneDepthVersion: view.sceneDepthVersion }),\n };\n const temporal =\n temporalSignature === undefined\n ? undefined\n : (() => {\n const decision = histories.begin(temporalSignature, {\n ...(view?.cameraCut === undefined ? {} : { cameraCut: view.cameraCut }),\n ...(view?.recovery === undefined ? {} : { recovery: view.recovery }),\n });\n const history =\n decision.history ?? createCloudHistory(temporalSignature, generation, false);\n return Object.freeze({\n signature: temporalSignature,\n history,\n reset: decision.reset,\n reasons: decision.reasons,\n });\n })();\n const resourceFacts = inspectCloudLayerResources({\n generation,\n cache: cached,\n ...(shadowProjection === undefined ? {} : { shadow: shadowProjection }),\n ...(temporal?.history === undefined ? {} : { history: temporal.history }),\n });\n const temporalReset = temporal?.reasons.at(-1);\n if (temporal?.reset === true) temporalResetCount += 1;\n if (temporalReset !== undefined) lastTemporalReset = temporalReset;\n return ok({\n params: cloud.params,\n cache: cached,\n sourceKey: cloud.sourceKey,\n timeSeconds: cloud.worldTimeSeconds,\n sunDirection: cloud.sunDirection,\n sunRadiance: cloud.sunRadiance,\n shadowProjection,\n temporal,\n generation,\n inspection: inspectCloudLayer({\n authored: true,\n sourceKey: cloud.sourceKey,\n generation,\n resourceFacts,\n ...(shadowProjection === undefined ? {} : { shadowRevision: shadowProjection.revision }),\n ...(temporal === undefined\n ? {}\n : {\n temporalResets: temporalResetCount,\n ...(lastTemporalReset === undefined ? {} : { lastTemporalReset }),\n }),\n ...(capability === undefined ? {} : { capability }),\n budget: {\n quality: cloud.params.quality,\n reason:\n 'physical GPU timing and residency receipts are unavailable until a prepared adapter submits them',\n },\n }),\n });\n },\n onFrameSubmitted: (frame: CloudLayerFeatureFrame) => {\n if (frame.temporal?.history !== undefined) {\n // Advance the metadata timestamp only after submit. The next frame's\n // GPU reprojection then receives the elapsed time since this exact\n // submitted signature, while an aborted frame keeps the old entry.\n histories.commit(\n frame.temporal.signature,\n createCloudHistory(frame.temporal.signature, frame.generation, true),\n );\n }\n },\n onFrameAborted: (frame: CloudLayerFeatureFrame) => {\n // A reset candidate is committed only after queue submission. The store\n // still contains the previous entry while this frame is rejected.\n void frame;\n },\n plan: (\n frame: CloudLayerFeatureFrame,\n context: RenderFeaturePlanContext,\n ): Result<RenderFeaturePlan, RenderError> => {\n if (frame.cache === undefined || packedCache === undefined || frame.params === undefined) {\n return ok({ resources: [], passes: [] });\n }\n return ok(planCloudDensity(frame, packedCache, context));\n },\n });\n}\n","import type { RhiCaps } from '@forgeax/engine-rhi';\nimport type { MaterialProgramAbi, MaterialSurfacePassKind } from '@forgeax/engine-types';\nimport { err, ok, type Result } from '@forgeax/engine-types';\n\nexport type SurfaceGpuCapability = 'compute' | 'storageBuffer' | 'indirectDrawing';\nexport type SurfaceGpuFallbackReason = SurfaceGpuCapability;\n\nexport type SurfaceGpuSubmissionErrorCode =\n | 'surface-abi-missing'\n | 'surface-pass-missing'\n | 'surface-producer-not-ready'\n | 'surface-generation-stale';\n\nexport interface SurfaceGpuSubmissionError {\n readonly code: SurfaceGpuSubmissionErrorCode;\n readonly expected: string;\n readonly hint: string;\n readonly pass: MaterialSurfacePassKind;\n readonly owner: 'surface-producer' | 'render-scene' | 'render-generation';\n readonly actual?: unknown;\n}\n\nexport interface SurfaceGpuPassAdmission {\n readonly pass: MaterialSurfacePassKind;\n readonly lane: 'gpu-driven' | 'direct';\n readonly reason?: SurfaceGpuFallbackReason;\n}\n\nexport interface SurfaceGpuSubmissionAdmission {\n readonly model: 'single-layer-medium';\n readonly lane: 'gpu-driven' | 'direct';\n readonly passes: readonly [SurfaceGpuPassAdmission, SurfaceGpuPassAdmission];\n readonly deviceGeneration: number;\n}\n\nexport interface SurfaceGpuSubmissionInput {\n readonly abi: MaterialProgramAbi;\n readonly caps: Pick<RhiCaps, 'compute' | 'storageBuffer' | 'indirectDrawing'>;\n readonly sceneIndexReady: boolean;\n readonly resourcesReady: boolean;\n readonly dynamicInputReady: boolean;\n readonly deviceGeneration: number;\n readonly preparedDeviceGeneration: number;\n}\n\nconst ERROR_POLICY: Readonly<\n Record<SurfaceGpuSubmissionErrorCode, { readonly expected: string; readonly hint: string }>\n> = {\n 'surface-abi-missing': {\n expected: 'a producer-published single-layer-medium ABI is present',\n hint: 'compose, reflect, and publish the Surface model before preparing the draw',\n },\n 'surface-pass-missing': {\n expected: 'the published model contains both nearest-layer and color passes',\n hint: 'recook the complete model publication; do not synthesize a missing pass',\n },\n 'surface-producer-not-ready': {\n expected: 'scene-index, resources, and dynamic input facts are ready for the published model',\n hint: 'repair the owning producer publication and retry; capability fallback does not cover stale assets',\n },\n 'surface-generation-stale': {\n expected: 'prepared Surface facts belong to the current device generation',\n hint: 'rebuild the prepared surface resources for the current device generation',\n },\n};\n\nfunction failure(\n code: SurfaceGpuSubmissionErrorCode,\n pass: MaterialSurfacePassKind,\n owner: SurfaceGpuSubmissionError['owner'],\n actual?: unknown,\n): SurfaceGpuSubmissionError {\n return {\n code,\n expected: ERROR_POLICY[code].expected,\n hint: ERROR_POLICY[code].hint,\n pass,\n owner,\n ...(actual === undefined ? {} : { actual }),\n };\n}\n\nfunction capabilityFallback(\n caps: SurfaceGpuSubmissionInput['caps'],\n): SurfaceGpuFallbackReason | undefined {\n if (!caps.compute) return 'compute';\n if (!caps.storageBuffer) return 'storageBuffer';\n if (!caps.indirectDrawing) return 'indirectDrawing';\n return undefined;\n}\n\n/**\n * Admit the two Surface passes together. Capability fallback is explicit and\n * symmetric; a missing promised publication is a producer error and never a\n * silent direct fallback.\n */\nexport function admitSingleLayerMediumSubmission(\n input: SurfaceGpuSubmissionInput,\n): Result<SurfaceGpuSubmissionAdmission, SurfaceGpuSubmissionError> {\n const firstPass: MaterialSurfacePassKind = 'nearest-layer';\n const surface = input.abi.surface;\n if (surface === undefined || surface.model !== 'single-layer-medium') {\n return err(failure('surface-abi-missing', firstPass, 'surface-producer', surface));\n }\n if (!surface.passes.includes('nearest-layer') || !surface.passes.includes('color')) {\n return err(failure('surface-pass-missing', firstPass, 'surface-producer', surface.passes));\n }\n if (input.deviceGeneration !== input.preparedDeviceGeneration) {\n return err(\n failure('surface-generation-stale', firstPass, 'render-generation', {\n deviceGeneration: input.deviceGeneration,\n preparedDeviceGeneration: input.preparedDeviceGeneration,\n }),\n );\n }\n const dynamicRequired = surface.dynamicInput !== undefined;\n if (\n !input.sceneIndexReady ||\n !input.resourcesReady ||\n (dynamicRequired && !input.dynamicInputReady)\n ) {\n return err(\n failure('surface-producer-not-ready', firstPass, 'surface-producer', {\n sceneIndexReady: input.sceneIndexReady,\n resourcesReady: input.resourcesReady,\n dynamicInputReady: input.dynamicInputReady,\n }),\n );\n }\n const fallback = capabilityFallback(input.caps);\n const admitted: [SurfaceGpuPassAdmission, SurfaceGpuPassAdmission] =\n fallback === undefined\n ? [\n { pass: firstPass, lane: 'gpu-driven' },\n { pass: 'color', lane: 'gpu-driven' },\n ]\n : [\n { pass: firstPass, lane: 'direct', reason: fallback },\n { pass: 'color', lane: 'direct', reason: fallback },\n ];\n return ok({\n model: 'single-layer-medium',\n lane: fallback === undefined ? 'gpu-driven' : 'direct',\n passes: admitted,\n deviceGeneration: input.deviceGeneration,\n });\n}\n","import { err, type MaterialAsset, type MeshAsset, ok, type Result } from '@forgeax/engine-types';\nimport { type PointShape, PointShapeValue, pointShapeFromU32 } from '../components/points';\nimport type {\n PointsLinesBudgetExceededError,\n PointsLinesInvalidStyleError,\n PointsLinesMaterialUnsupportedError,\n PointsLinesStyleUnsupportedError,\n PointsLinesTopologyMismatchError,\n} from '../errors/render';\nimport {\n PointsLinesBudgetExceededError as BudgetError,\n PointsLinesInvalidStyleError as InvalidStyleError,\n PointsLinesMaterialUnsupportedError as MaterialError,\n PointsLinesStyleUnsupportedError as StyleError,\n PointsLinesTopologyMismatchError as TopologyError,\n} from '../errors/render';\n\nexport interface PointsStyleInput {\n readonly sizePx?: number;\n readonly shape?: number;\n}\n\nexport interface LinesStyleInput {\n readonly widthPx?: number;\n}\n\nexport interface PointsLinesAdmissionLimits {\n readonly maxPoints?: number;\n readonly maxSegments?: number;\n}\n\nexport interface PointsLinesAdmissionInput {\n readonly entity: number;\n readonly points?: PointsStyleInput;\n readonly lines?: LinesStyleInput;\n readonly mesh: MeshAsset;\n readonly material: MaterialAsset;\n readonly limits?: PointsLinesAdmissionLimits;\n readonly materialId?: string;\n}\n\nexport interface PointsLinesAdmission {\n readonly component: 'Points' | 'Lines';\n readonly shape?: PointShape;\n readonly sizePx?: number;\n readonly widthPx?: number;\n readonly pointCount: number;\n readonly segmentCount: number;\n readonly submeshes: readonly number[];\n}\n\nexport type PointsLinesAdmissionError =\n | PointsLinesInvalidStyleError\n | PointsLinesTopologyMismatchError\n | PointsLinesStyleUnsupportedError\n | PointsLinesMaterialUnsupportedError\n | PointsLinesBudgetExceededError;\n\nfunction invalidStyle(\n input: PointsLinesAdmissionInput,\n component: 'Points' | 'Lines' | 'Points/Lines',\n field: string,\n value: number | string | undefined,\n expected: string,\n): Result<never, PointsLinesAdmissionError> {\n return err(new InvalidStyleError({ entity: input.entity, component, field, value, expected }));\n}\n\nfunction topologyMismatch(\n input: PointsLinesAdmissionInput,\n submesh: number,\n expected: string,\n actual: string,\n): Result<never, PointsLinesAdmissionError> {\n return err(new TopologyError({ entity: input.entity, submesh, expected, actual }));\n}\n\nfunction checkStyle(\n input: PointsLinesAdmissionInput,\n): Result<\n { component: 'Points' | 'Lines'; shape?: PointShape; sizePx?: number; widthPx?: number },\n PointsLinesAdmissionError\n> {\n const hasPoints = input.points !== undefined;\n const hasLines = input.lines !== undefined;\n if (hasPoints && hasLines) {\n return invalidStyle(\n input,\n 'Points/Lines',\n 'components',\n 'Points + Lines',\n 'exactly one style component',\n );\n }\n if (!hasPoints && !hasLines) {\n return invalidStyle(input, 'Points/Lines', 'components', undefined, 'one style component');\n }\n\n if (hasPoints) {\n const sizePx = input.points?.sizePx ?? 4;\n const shapeValue = input.points?.shape ?? PointShapeValue.square;\n const shape = pointShapeFromU32(shapeValue);\n if (!Number.isFinite(sizePx) || sizePx <= 0) {\n return invalidStyle(input, 'Points', 'sizePx', sizePx, 'finite sizePx > 0');\n }\n if (shape === undefined) {\n return invalidStyle(input, 'Points', 'shape', shapeValue, \"shape is 'square' or 'circle'\");\n }\n return ok({ component: 'Points', shape, sizePx });\n }\n\n const widthPx = input.lines?.widthPx ?? 1;\n if (!Number.isFinite(widthPx) || widthPx <= 0) {\n return invalidStyle(input, 'Lines', 'widthPx', widthPx, 'finite widthPx > 0');\n }\n return ok({ component: 'Lines', widthPx });\n}\n\nfunction checkTopology(\n input: PointsLinesAdmissionInput,\n component: 'Points' | 'Lines',\n): Result<\n { pointCount: number; segmentCount: number; submeshes: readonly number[] },\n PointsLinesAdmissionError\n> {\n const expected = component === 'Points' ? 'point-list' : 'line-list';\n let pointCount = 0;\n let segmentCount = 0;\n const acceptedSubmeshes: number[] = [];\n let sawNonEmpty = false;\n\n for (const [submeshIndex, submesh] of input.mesh.submeshes.entries()) {\n const indexed = input.mesh.indices !== undefined && submesh.indexCount > 0;\n const elementCount = indexed ? submesh.indexCount : submesh.vertexCount;\n if (elementCount === 0) continue;\n sawNonEmpty = true;\n\n if (component === 'Lines' && submesh.topology === 'line-strip') {\n return err(\n new StyleError({\n lane: 'admission',\n field: 'topology',\n member: 'line-strip',\n supported: ['line-list'],\n }),\n );\n }\n if (submesh.topology !== expected) {\n return topologyMismatch(input, submeshIndex, expected, submesh.topology);\n }\n if (component === 'Lines' && elementCount % 2 !== 0) {\n return topologyMismatch(input, submeshIndex, 'line-list pairs', 'line-list odd tail');\n }\n acceptedSubmeshes.push(submeshIndex);\n if (component === 'Points') pointCount += elementCount;\n else segmentCount += elementCount / 2;\n }\n\n if (!sawNonEmpty) return topologyMismatch(input, 0, expected, 'empty-range');\n return ok({ pointCount, segmentCount, submeshes: acceptedSubmeshes });\n}\n\nfunction checkMaterial(input: PointsLinesAdmissionInput): Result<void, PointsLinesAdmissionError> {\n const passes = input.material.passes ?? [];\n const unlitModules = new Set(['forgeax_material::unlit', 'forgeax::default-unlit']);\n if (passes.length !== 1 || passes[0] === undefined) {\n const pass =\n passes.find(\n (candidate) => candidate.name === 'deferred' || candidate.name === 'shadow-caster',\n ) ?? passes[0];\n return err(\n new MaterialError({\n entity: input.entity,\n material: input.materialId ?? '<anonymous>',\n pass: pass?.name ?? '<empty>',\n module: pass?.program.module ?? '<empty>',\n reason: 'points-lines admission requires one unlit forward pass',\n }),\n );\n }\n const pass = passes[0];\n const lightMode = (pass.renderState?.tags as Record<string, unknown> | undefined)?.LightMode;\n if (\n !unlitModules.has(pass.program.module) ||\n pass.name !== 'forward' ||\n lightMode === 'ShadowCaster'\n ) {\n return err(\n new MaterialError({\n entity: input.entity,\n material: input.materialId ?? '<anonymous>',\n pass: pass.name,\n module: pass.program.module,\n reason: 'points-lines admission requires an engine-owned unlit forward pass',\n }),\n );\n }\n return ok(undefined);\n}\n\n/** Validate one complete Points/Lines candidate before any renderer publication. */\nexport function admitPointsLines(\n input: PointsLinesAdmissionInput,\n): Result<PointsLinesAdmission, PointsLinesAdmissionError> {\n const style = checkStyle(input);\n if (!style.ok) return style;\n const topology = checkTopology(input, style.value.component);\n if (!topology.ok) return topology;\n const material = checkMaterial(input);\n if (!material.ok) return material;\n\n if (style.value.component === 'Points' && input.limits?.maxPoints !== undefined) {\n if (topology.value.pointCount > input.limits.maxPoints) {\n return err(\n new BudgetError({\n lane: 'admission',\n requested: topology.value.pointCount,\n limit: input.limits.maxPoints,\n unit: 'points',\n }),\n );\n }\n }\n if (style.value.component === 'Lines' && input.limits?.maxSegments !== undefined) {\n if (topology.value.segmentCount > input.limits.maxSegments) {\n return err(\n new BudgetError({\n lane: 'admission',\n requested: topology.value.segmentCount,\n limit: input.limits.maxSegments,\n unit: 'segments',\n }),\n );\n }\n }\n\n return ok({ ...style.value, ...topology.value });\n}\n","import type { PointShadowSnapshot } from './render-system-extract';\n\n/**\n * Detached point-shadow budget facts from one completed extract/record frame.\n *\n * `requested` is the number of PointLight + PointLightShadow pairs. The\n * renderer owns the bounded cube-array atlas, so `admitted`, `shadowed`, and\n * `shadowAtlasOccupancy` are all derived from the layer sentinel emitted by\n * the same extract owner. No consumer needs to maintain a second budget\n * ledger.\n */\nexport interface PointShadowInspection {\n readonly status: 'inactive' | 'ready' | 'over-budget';\n readonly requested: number;\n readonly admitted: number;\n readonly shadowed: number;\n readonly shadowAtlasOccupancy: number;\n readonly shadowAtlasCapacity: number;\n}\n\n/** Project point-shadow snapshots to the public, JSON-safe inspection shape. */\nexport function inspectPointShadow(\n snapshots: readonly PointShadowSnapshot[],\n shadowAtlasCapacity: number,\n): PointShadowInspection {\n const requested = snapshots.length;\n const admitted = snapshots.reduce(\n (count, snapshot) =>\n snapshot.shadowAtlasLayer >= 0 && snapshot.shadowAtlasLayer < shadowAtlasCapacity\n ? count + 1\n : count,\n 0,\n );\n // Never publish a misleading `ready` state when any requested shadow owns\n // no atlas layer. The extract sentinel is the single admission projection;\n // a partial or all-sentinel frame is therefore a failed/over-budget\n // admission, not an active shadow path with incomplete output.\n const status =\n requested === 0\n ? ('inactive' as const)\n : requested > shadowAtlasCapacity || admitted !== requested\n ? ('over-budget' as const)\n : ('ready' as const);\n return Object.freeze({\n status,\n requested,\n admitted,\n // A point shadow only samples an atlas after it owns an atlas layer. Keep\n // these names explicit for AI diagnostics while deriving both from the\n // one layer projection above.\n shadowed: admitted,\n shadowAtlasOccupancy: admitted,\n shadowAtlasCapacity,\n });\n}\n","/**\n * Consumer-only SSR M0 admission.\n *\n * This module consumes detached producer receipts. It owns no capture,\n * device, graph, or recovery handle and therefore cannot repair a missing\n * producer. A complete receipt set is the only route to an admitted result.\n */\n\nimport {\n type RhiTextureFormatCapabilityReceipt,\n validateR32FloatReceipt,\n} from '@forgeax/engine-rhi';\nimport { err, ok, type Result } from '@forgeax/engine-types';\nimport type { ScreenSpaceReflectionData } from '../components/screen-space-reflection';\nimport type { ReflectionFallbackReceipt } from '../inspection-types';\nimport type {\n SsrConfigField,\n SsrConfigInvalidError,\n SsrConfigRange,\n SsrOwnerRecoveryAction,\n SsrSpatialUnavailableReason,\n SsrUnavailableError,\n} from './errors';\nimport type { SsrAdmissionIdentity } from './identity';\n\nexport const SSR_FORMAT_PROFILE = 'r32float-mip-sampled-storage' as const;\n\nexport const SSR_FORMAT_STAGES = Object.freeze([\n 'texture-create',\n 'mip-view',\n 'sampled-storage-bind-group',\n 'pipeline-bind',\n 'finish',\n 'submit',\n 'completion',\n 'readback',\n] as const);\n\nexport type { SsrAdmissionIdentity } from './identity';\n\nexport type SsrFormatStage = (typeof SSR_FORMAT_STAGES)[number];\n\n/**\n * The admission input is the real renderer owner receipt plus the one\n * integration identity supplied by the host. It deliberately does not\n * recreate submitted/source/LKG boolean flags.\n */\nexport type SsrReflectionFallbackReceipt = ReflectionFallbackReceipt & {\n readonly identity: SsrAdmissionIdentity;\n};\n\n/** RHI capability receipt with the same host-supplied integration identity. */\nexport type SsrFormatReceipt = RhiTextureFormatCapabilityReceipt & {\n readonly identity: SsrAdmissionIdentity;\n};\n\nexport interface SsrTemporalReceipt {\n readonly identity: SsrAdmissionIdentity;\n readonly successfulSubmit: true;\n readonly generation: number;\n}\n\nexport interface SsrAdmissionWork {\n readonly attachmentCount: number;\n readonly passCount: number;\n readonly bindingCount: number;\n readonly resourceCount: number;\n readonly historyCount: 0;\n readonly temporalDemand: 0;\n}\n\nexport interface SsrAdmissionBudget {\n readonly probeExecutions: 0 | 1;\n readonly resetCount: 0;\n readonly rebuildCount: 0;\n}\n\nexport interface SsrAdmissionFailure {\n readonly code:\n | 'ssr-not-requested'\n | 'ssr-reflection-fallback-unavailable'\n | 'ssr-format-unavailable'\n | 'ssr-temporal-unavailable'\n | 'ssr-receipt-identity-mismatch'\n | 'ssr-receipt-stale';\n readonly expected: string;\n readonly hint: string;\n readonly detail: Readonly<{\n readonly owner: 'producer' | 'format' | 'temporal' | 'consumer';\n /** Owner-directed action an AI consumer can take without parsing hint text. */\n readonly action: SsrOwnerRecoveryAction;\n readonly generation?: number;\n readonly identityField?: keyof SsrAdmissionIdentity;\n }>;\n}\n\nexport type SsrAdmissionResult =\n | {\n readonly status: 'admitted';\n readonly identity: SsrAdmissionIdentity | undefined;\n readonly generation: number;\n readonly work: SsrAdmissionWork;\n readonly budget: SsrAdmissionBudget;\n readonly failure?: undefined;\n }\n | {\n readonly status: 'fallback-only';\n readonly identity: SsrAdmissionIdentity | undefined;\n readonly generation: number;\n readonly work: SsrAdmissionWork;\n readonly budget: SsrAdmissionBudget;\n readonly failure: SsrAdmissionFailure;\n };\n\nexport interface SsrAdmissionInput {\n readonly requested: boolean;\n readonly identity: SsrAdmissionIdentity;\n readonly reflectionFallback?: SsrReflectionFallbackReceipt;\n readonly format?: SsrFormatReceipt;\n readonly temporal?: SsrTemporalReceipt;\n readonly previousGeneration?: number;\n}\n\n/** Public renderer projection consumed by the parent SSR feature. */\nexport interface SsrDependenciesInspection {\n readonly status: 'admitted' | 'fallback-only';\n /** Absent until the host binds an exact source/tree/lock/build identity. */\n readonly identity: SsrAdmissionIdentity | undefined;\n readonly requested: boolean;\n readonly reflectionFallback: ReflectionFallbackReceipt | undefined;\n readonly format: SsrFormatReceipt | undefined;\n readonly temporal: SsrTemporalReceipt | undefined;\n readonly admission: SsrAdmissionResult;\n readonly work: SsrAdmissionWork;\n readonly budget: SsrAdmissionBudget;\n readonly failure: SsrAdmissionFailure | undefined;\n}\n\nconst ZERO_WORK: SsrAdmissionWork = Object.freeze({\n attachmentCount: 0,\n passCount: 0,\n bindingCount: 0,\n resourceCount: 0,\n historyCount: 0,\n temporalDemand: 0,\n});\n\nconst ADMITTED_WORK: SsrAdmissionWork = Object.freeze({\n attachmentCount: 1,\n passCount: 1,\n bindingCount: 1,\n resourceCount: 1,\n historyCount: 0,\n temporalDemand: 0,\n});\n\nconst ZERO_BUDGET: SsrAdmissionBudget = Object.freeze({\n probeExecutions: 0,\n resetCount: 0,\n rebuildCount: 0,\n});\n\nconst ADMITTED_BUDGET: SsrAdmissionBudget = Object.freeze({\n probeExecutions: 1,\n resetCount: 0,\n rebuildCount: 0,\n});\n\nfunction identityFieldMismatch(\n expected: SsrAdmissionIdentity,\n actual: SsrAdmissionIdentity,\n): keyof SsrAdmissionIdentity | undefined {\n for (const field of ['sourceHead', 'sourceTree', 'lockSha256', 'buildSha256'] as const) {\n if (expected[field] !== actual[field]) return field;\n }\n return undefined;\n}\n\nfunction blocked(\n identity: SsrAdmissionIdentity | undefined,\n failure: SsrAdmissionFailure,\n generation = 0,\n): SsrAdmissionResult {\n return Object.freeze({\n status: 'fallback-only',\n identity,\n generation,\n work: ZERO_WORK,\n budget: ZERO_BUDGET,\n failure,\n });\n}\n\nfunction failure(\n code: SsrAdmissionFailure['code'],\n owner: SsrAdmissionFailure['detail']['owner'],\n hint: string,\n detail: Omit<SsrAdmissionFailure['detail'], 'owner' | 'action'> = {},\n): SsrAdmissionFailure {\n const action: SsrOwnerRecoveryAction = recoveryActionFor(code);\n return Object.freeze({\n code,\n expected: 'all producer, format, and temporal receipts share one admitted identity',\n hint,\n detail: Object.freeze({ owner, action, ...detail }),\n });\n}\n\nfunction recoveryActionFor(code: SsrAdmissionFailure['code']): SsrOwnerRecoveryAction {\n switch (code) {\n case 'ssr-reflection-fallback-unavailable':\n case 'ssr-receipt-identity-mismatch':\n return 'rebuild';\n case 'ssr-not-requested':\n case 'ssr-format-unavailable':\n case 'ssr-temporal-unavailable':\n case 'ssr-receipt-stale':\n return 'retry';\n }\n}\n\nfunction receiptFailure(\n input: SsrAdmissionInput,\n receipt: { readonly identity: SsrAdmissionIdentity },\n owner: SsrAdmissionFailure['detail']['owner'],\n): SsrAdmissionResult | undefined {\n const field = identityFieldMismatch(input.identity, receipt.identity);\n if (field === undefined) return undefined;\n return blocked(\n input.identity,\n failure('ssr-receipt-identity-mismatch', owner, 'rebuild the owner receipt for this identity', {\n identityField: field,\n }),\n );\n}\n\nfunction validFallback(receipt: SsrReflectionFallbackReceipt | undefined): boolean {\n return (\n receipt !== undefined &&\n receipt.candidateVisible === false &&\n Number.isFinite(receipt.coverage) &&\n receipt.coverage >= 0 &&\n receipt.coverage <= 1 &&\n (receipt.sourceKey === undefined || receipt.sourceKey.length > 0) &&\n (receipt.extent === undefined ||\n (receipt.extent.length === 3 &&\n receipt.extent.every((value) => Number.isFinite(value) && value > 0))) &&\n Number.isInteger(receipt.sourceGeneration) &&\n receipt.sourceGeneration >= 0 &&\n Number.isInteger(receipt.projectionGeneration) &&\n receipt.projectionGeneration >= 0 &&\n Number.isInteger(receipt.deviceGeneration) &&\n receipt.deviceGeneration >= 0 &&\n receipt.brdfSignature === 'standard-pbr-ibl-v1' &&\n ((receipt.source === 'probe' && (receipt.state === 'active' || receipt.state === 'lkg')) ||\n (receipt.source === 'skylight' && (receipt.state === 'active' || receipt.state === 'lkg')) ||\n (receipt.source === 'neutral' && receipt.state === 'neutral'))\n );\n}\n\nfunction validFormat(receipt: SsrFormatReceipt | undefined): boolean {\n if (\n receipt?.profile !== SSR_FORMAT_PROFILE ||\n receipt.verdict !== 'admitted' ||\n receipt.evidence !== 'real' ||\n !Number.isInteger(receipt.deviceGeneration) ||\n receipt.deviceGeneration < 0\n ) {\n return false;\n }\n if (\n !SSR_FORMAT_STAGES.every((stage) =>\n receipt.stages.some((entry) => entry.stage === stage && entry.verdict === 'admitted'),\n )\n ) {\n return false;\n }\n return validateR32FloatReceipt(receipt).ok;\n}\n\nfunction validTemporal(receipt: SsrTemporalReceipt | undefined): boolean {\n return (\n receipt?.successfulSubmit === true &&\n Number.isInteger(receipt.generation) &&\n receipt.generation >= 0\n );\n}\n\nexport function admitSsrM0(input: SsrAdmissionInput): SsrAdmissionResult {\n if (!input.requested) {\n return blocked(\n input.identity,\n failure('ssr-not-requested', 'consumer', 'request SSR before evaluating M0 admission'),\n );\n }\n if (input.reflectionFallback === undefined) {\n return blocked(\n input.identity,\n failure('ssr-reflection-fallback-unavailable', 'producer', 'use LKG, Skylight, or neutral'),\n );\n }\n const fallbackIdentityFailure = receiptFailure(input, input.reflectionFallback, 'producer');\n if (fallbackIdentityFailure !== undefined) return fallbackIdentityFailure;\n if (!validFallback(input.reflectionFallback)) {\n return blocked(\n input.identity,\n failure(\n 'ssr-reflection-fallback-unavailable',\n 'producer',\n 'inspect and rebuild the producer receipt',\n ),\n input.reflectionFallback.projectionGeneration,\n );\n }\n if (input.format === undefined) {\n return blocked(\n input.identity,\n failure('ssr-format-unavailable', 'format', 'probe the exact format profile for this device'),\n input.reflectionFallback.projectionGeneration,\n );\n }\n const formatIdentityFailure = receiptFailure(input, input.format, 'format');\n if (formatIdentityFailure !== undefined) return formatIdentityFailure;\n if (!validFormat(input.format)) {\n return blocked(\n input.identity,\n failure('ssr-format-unavailable', 'format', 'complete the full r32float profile probe'),\n input.reflectionFallback.projectionGeneration,\n );\n }\n // Prior submitted history is optional for fresh spatial SSR. If supplied,\n // its identity and validity still obey the temporal owner's contract.\n const temporalIdentityFailure =\n input.temporal === undefined ? undefined : receiptFailure(input, input.temporal, 'temporal');\n if (temporalIdentityFailure !== undefined) return temporalIdentityFailure;\n if (input.temporal !== undefined && !validTemporal(input.temporal)) {\n return blocked(\n input.identity,\n failure('ssr-temporal-unavailable', 'temporal', 'inspect and rebuild the temporal receipt'),\n input.reflectionFallback.projectionGeneration,\n );\n }\n if (\n input.previousGeneration !== undefined &&\n input.previousGeneration !== input.reflectionFallback.projectionGeneration\n ) {\n return blocked(\n input.identity,\n failure(\n 'ssr-receipt-stale',\n 'consumer',\n 'discard stale completion and reinspect the owners',\n {\n generation: input.reflectionFallback.projectionGeneration,\n },\n ),\n input.reflectionFallback.projectionGeneration,\n );\n }\n return Object.freeze({\n status: 'admitted',\n identity: input.identity,\n generation: input.reflectionFallback.projectionGeneration,\n work: ADMITTED_WORK,\n budget: ADMITTED_BUDGET,\n });\n}\n\n/**\n * Joins the live owner projections at the renderer boundary. The only casts\n * here add the host identity to receipts that otherwise remain canonical RHI\n * or ReflectionProbe PODs; no producer fact is copied or renamed.\n */\nexport function projectSsrDependencies(input: {\n readonly requested: boolean;\n readonly identity: SsrAdmissionIdentity | undefined;\n readonly reflectionFallback: ReflectionFallbackReceipt | undefined;\n readonly format: RhiTextureFormatCapabilityReceipt | undefined;\n readonly temporal: { readonly successfulSubmit: true; readonly generation: number } | undefined;\n readonly previousGeneration?: number;\n}): SsrDependenciesInspection {\n const identity = input.identity;\n const reflectionFallback =\n identity === undefined || input.reflectionFallback?.identity === undefined\n ? undefined\n : (input.reflectionFallback as SsrReflectionFallbackReceipt);\n const format =\n identity === undefined || input.format === undefined\n ? undefined\n : ({ ...input.format, identity } satisfies SsrFormatReceipt);\n const temporal =\n identity === undefined || input.temporal === undefined\n ? undefined\n : ({ identity, ...input.temporal } satisfies SsrTemporalReceipt);\n const admission =\n identity === undefined\n ? blocked(\n undefined,\n failure(\n input.requested ? 'ssr-receipt-identity-mismatch' : 'ssr-not-requested',\n 'consumer',\n input.requested\n ? 'bind the exact source, tree, lock, and build identity before admission'\n : 'request SSR before evaluating M0 admission',\n input.requested ? { identityField: 'sourceHead' } : {},\n ),\n )\n : admitSsrM0({\n requested: input.requested,\n identity,\n ...(reflectionFallback === undefined ? {} : { reflectionFallback }),\n ...(format === undefined ? {} : { format }),\n ...(temporal === undefined ? {} : { temporal }),\n ...(input.previousGeneration === undefined\n ? {}\n : { previousGeneration: input.previousGeneration }),\n });\n return Object.freeze({\n status: admission.status,\n identity,\n requested: input.requested,\n reflectionFallback: input.reflectionFallback,\n format,\n temporal,\n admission,\n work: admission.work,\n budget: admission.budget,\n failure: admission.failure,\n });\n}\n\nexport function zeroSsrAdmissionWork(): SsrAdmissionWork {\n return ZERO_WORK;\n}\n\n/**\n * Projects the admission decision into the existing temporal reset seam.\n * Admission never creates temporal history; only a changed committed\n * producer generation can request a reset through the coordinator.\n */\nexport function resolveSsrAdmissionGeneration(\n previousGeneration: number | undefined,\n nextGeneration: number | undefined,\n): { readonly changed: boolean; readonly generation: number | undefined } {\n return {\n changed:\n previousGeneration !== undefined &&\n nextGeneration !== undefined &&\n previousGeneration !== nextGeneration,\n generation: nextGeneration,\n };\n}\n\n/** Standard spatial lanes that may consume an SSR candidate. */\nexport type SsrSpatialLane = 'clustered' | 'deferred' | 'direct' | 'cpu-webgl2' | 'forward';\n\n/** Capability facts required by the M1 spatial path. */\nexport interface SsrSpatialCapabilities {\n readonly compute: boolean;\n readonly storageTexture: boolean;\n readonly rgba16floatRenderable: boolean;\n readonly r32floatSampledStorage: boolean;\n}\n\n/** Detached owner facts consumed by spatial admission. */\nexport interface SsrSpatialEnvironment {\n readonly lane: SsrSpatialLane;\n readonly m0: Pick<SsrAdmissionResult, 'status'>;\n readonly sceneInputs: boolean;\n /** Current-frame motion/coverage producer, not reusable previous-frame history. */\n readonly temporal: boolean;\n readonly reflectionFallback: boolean;\n readonly capabilities: SsrSpatialCapabilities;\n /** Recovery readiness is optional for callers that have no recovery fault. */\n readonly recovery?: boolean;\n}\n\n/** The only camera fields used by the spatial admission owner. */\nexport interface SsrSpatialCamera {\n readonly projection: 'perspective' | 'orthographic';\n readonly near: number;\n readonly far: number;\n readonly screenSpaceReflection?: ScreenSpaceReflectionData;\n}\n\nexport interface SsrSpatialWork {\n readonly attachmentCount: number;\n readonly passCount: number;\n readonly bindingCount: number;\n readonly resourceCount: number;\n readonly historyCount: 0;\n readonly temporalDemand: 0;\n}\n\nexport type SsrSpatialStatus =\n | 'not-requested'\n | 'requested'\n | 'admitted'\n | 'fallback-only'\n | 'structural-only';\n\nexport interface SsrSpatialAdmissionBase {\n readonly status: SsrSpatialStatus;\n readonly lane: SsrSpatialLane;\n readonly config: ScreenSpaceReflectionData | undefined;\n readonly viewRange: number;\n readonly work: SsrSpatialWork;\n}\n\nexport type SsrSpatialAdmission =\n | (SsrSpatialAdmissionBase & {\n readonly status: 'not-requested' | 'requested';\n readonly failure?: undefined;\n })\n | (SsrSpatialAdmissionBase & {\n readonly status: 'admitted';\n readonly config: ScreenSpaceReflectionData;\n readonly failure?: undefined;\n })\n | (SsrSpatialAdmissionBase & {\n readonly status: 'fallback-only' | 'structural-only';\n readonly failure: SsrConfigInvalidError | SsrUnavailableError;\n });\n\nconst ZERO_SPATIAL_WORK: SsrSpatialWork = Object.freeze({\n attachmentCount: 0,\n passCount: 0,\n bindingCount: 0,\n resourceCount: 0,\n historyCount: 0,\n temporalDemand: 0,\n});\n\nconst ADMITTED_SPATIAL_WORK: SsrSpatialWork = Object.freeze({\n attachmentCount: 3,\n passCount: 4,\n bindingCount: 4,\n resourceCount: 3,\n historyCount: 0,\n temporalDemand: 0,\n});\n\nfunction configRange(\n field: SsrConfigField,\n viewRange: number,\n maxDistance: number,\n): SsrConfigRange {\n switch (field) {\n case 'maxDistance':\n return { min: 0, minInclusive: false, max: viewRange, maxInclusive: true };\n case 'thickness':\n return { min: 0, minInclusive: false, max: maxDistance, maxInclusive: true };\n case 'maxRoughness':\n return { min: 0, minInclusive: true, max: 1, maxInclusive: true };\n }\n}\n\nfunction configError(\n field: SsrConfigField,\n value: number,\n range: SsrConfigRange,\n): SsrConfigInvalidError {\n const left = range.minInclusive ? '[' : '(';\n const right = range.maxInclusive ? ']' : ')';\n return Object.freeze({\n code: 'ssr-config-invalid',\n expected: `finite ${field} in ${left}${range.min}, ${range.max}${right}`,\n hint: `set ${field} to a finite value inside the reported range before retrying`,\n detail: Object.freeze({ field, value, range: Object.freeze(range) }),\n });\n}\n\n/** Validate one schema-derived component value against the active view. */\nexport function validateScreenSpaceReflection(\n config: ScreenSpaceReflectionData,\n input: { readonly viewRange: number },\n): Result<ScreenSpaceReflectionData, SsrConfigInvalidError> {\n const viewRange = input.viewRange;\n if (!Number.isFinite(viewRange) || viewRange <= 0) {\n return err(\n configError('maxDistance', config.maxDistance, configRange('maxDistance', viewRange, 0)),\n );\n }\n if (\n !Number.isFinite(config.maxDistance) ||\n config.maxDistance <= 0 ||\n config.maxDistance > viewRange\n ) {\n return err(\n configError(\n 'maxDistance',\n config.maxDistance,\n configRange('maxDistance', viewRange, config.maxDistance),\n ),\n );\n }\n if (\n !Number.isFinite(config.thickness) ||\n config.thickness <= 0 ||\n config.thickness > config.maxDistance\n ) {\n return err(\n configError(\n 'thickness',\n config.thickness,\n configRange('thickness', viewRange, config.maxDistance),\n ),\n );\n }\n if (!Number.isFinite(config.maxRoughness) || config.maxRoughness < 0 || config.maxRoughness > 1) {\n return err(\n configError(\n 'maxRoughness',\n config.maxRoughness,\n configRange('maxRoughness', viewRange, config.maxDistance),\n ),\n );\n }\n return ok(\n Object.freeze({\n maxDistance: config.maxDistance,\n thickness: config.thickness,\n maxRoughness: config.maxRoughness,\n }),\n );\n}\n\nfunction unavailable(\n lane: SsrSpatialLane,\n reason: SsrSpatialUnavailableReason,\n required: readonly string[],\n actual: Readonly<Record<string, boolean | number | string>>,\n): SsrUnavailableError {\n const recovery =\n reason === 'lane-unsupported' || reason === 'projection-unsupported'\n ? 'select a perspective clustered or deferred Standard lane'\n : reason === 'reflection-fallback-unavailable'\n ? 'repair the submitted reflection fallback owner receipt'\n : reason === 'temporal-unavailable'\n ? 'submit the matching temporal-v1 producer receipt'\n : reason === 'recovery-unavailable'\n ? 'complete device and producer recovery before retrying'\n : 'restore the required scene, capability, or format input before retrying';\n return Object.freeze({\n code: 'ssr-unavailable',\n expected: 'SSR spatial admission has a complete Standard input and capability set',\n hint: recovery,\n detail: Object.freeze({\n lane,\n reason,\n required: Object.freeze([...required]),\n actual: Object.freeze({ ...actual }),\n recovery,\n }),\n });\n}\n\nfunction unavailableResult(\n lane: SsrSpatialLane,\n viewRange: number,\n failure: SsrUnavailableError,\n): SsrSpatialAdmission {\n return Object.freeze({\n status: 'fallback-only',\n lane,\n config: undefined,\n viewRange,\n work: ZERO_SPATIAL_WORK,\n failure,\n });\n}\n\n/**\n * Admit the active camera's schema-derived component into the M1 spatial\n * path. No graph/resource handle crosses this boundary.\n */\nexport function admitSsrSpatial(input: {\n readonly camera: SsrSpatialCamera;\n readonly environment: SsrSpatialEnvironment;\n}): SsrSpatialAdmission {\n const camera = input.camera;\n const environment = input.environment;\n const viewRange = camera.far - camera.near;\n const config = camera.screenSpaceReflection;\n if (config === undefined) {\n return Object.freeze({\n status: 'not-requested',\n lane: environment.lane,\n config: undefined,\n viewRange,\n work: ZERO_SPATIAL_WORK,\n });\n }\n\n const valid = validateScreenSpaceReflection(config, { viewRange });\n if (!valid.ok) {\n return Object.freeze({\n status: 'fallback-only',\n lane: environment.lane,\n config,\n viewRange,\n work: ZERO_SPATIAL_WORK,\n failure: valid.error,\n });\n }\n\n if (environment.m0.status !== 'admitted') {\n return unavailableResult(\n environment.lane,\n viewRange,\n unavailable(\n environment.lane,\n 'reflection-fallback-unavailable',\n ['admitted M0 dependency receipt'],\n { m0: false },\n ),\n );\n }\n if (environment.lane !== 'clustered' && environment.lane !== 'deferred') {\n return unavailableResult(\n environment.lane,\n viewRange,\n unavailable(environment.lane, 'lane-unsupported', ['clustered or deferred Standard lane'], {\n lane: environment.lane,\n }),\n );\n }\n if (camera.projection !== 'perspective') {\n return unavailableResult(\n environment.lane,\n viewRange,\n unavailable(environment.lane, 'projection-unsupported', ['perspective camera'], {\n projection: camera.projection,\n }),\n );\n }\n if (!environment.sceneInputs) {\n return unavailableResult(\n environment.lane,\n viewRange,\n unavailable(\n environment.lane,\n 'scene-input-unavailable',\n ['deferred Standard scene/material/fallback inputs'],\n { sceneInputs: false },\n ),\n );\n }\n if (!environment.temporal) {\n return unavailableResult(\n environment.lane,\n viewRange,\n unavailable(environment.lane, 'temporal-unavailable', ['temporal-v1'], { temporal: false }),\n );\n }\n if (!environment.reflectionFallback) {\n return unavailableResult(\n environment.lane,\n viewRange,\n unavailable(\n environment.lane,\n 'reflection-fallback-unavailable',\n ['submitted BRDF-projected fallback'],\n { reflectionFallback: false },\n ),\n );\n }\n if (environment.recovery === false) {\n return unavailableResult(\n environment.lane,\n viewRange,\n unavailable(environment.lane, 'recovery-unavailable', ['ready device and owners'], {\n recovery: false,\n }),\n );\n }\n const capabilities = environment.capabilities;\n if (\n !capabilities.compute ||\n !capabilities.storageTexture ||\n !capabilities.rgba16floatRenderable\n ) {\n return unavailableResult(\n environment.lane,\n viewRange,\n unavailable(\n environment.lane,\n 'capability-unavailable',\n ['compute', 'storageTexture', 'rgba16floatRenderable'],\n {\n compute: capabilities.compute,\n storageTexture: capabilities.storageTexture,\n rgba16floatRenderable: capabilities.rgba16floatRenderable,\n },\n ),\n );\n }\n if (!capabilities.r32floatSampledStorage) {\n return unavailableResult(\n environment.lane,\n viewRange,\n unavailable(\n environment.lane,\n 'format-unavailable',\n ['r32float sampled and storage mip chain'],\n { r32floatSampledStorage: false },\n ),\n );\n }\n return Object.freeze({\n status: 'admitted',\n lane: environment.lane,\n config: valid.value,\n viewRange,\n work: ADMITTED_SPATIAL_WORK,\n });\n}\n","import type { TextureFormat } from '@forgeax/engine-rhi';\nimport type { VolumeRecoveryState, VolumeSelectedLightFacts } from './recovery';\nimport type { VolumetricFogResourceFacts } from './resources';\n\nexport type VolumetricFogInspectionStatus = 'off' | 'available' | 'unavailable' | 'degraded';\n\nexport type VolumetricFogResourceStage = 'none' | 'candidate' | 'accepted' | 'lkg' | 'recovering';\n\nexport interface VolumetricFogInspection {\n /** Owners in the last successfully submitted volume collection. */\n readonly ownerCount: number;\n readonly status: VolumetricFogInspectionStatus;\n readonly resourceStage: VolumetricFogResourceStage;\n readonly guid: string | undefined;\n readonly generation: number | undefined;\n readonly digest: string | undefined;\n readonly candidateGeneration: number | undefined;\n readonly candidateDigest: string | undefined;\n readonly lkgGeneration: number | undefined;\n readonly candidateFailure: VolumeRecoveryState['candidateFailure'];\n readonly deviceEpoch: number;\n readonly format: TextureFormat | undefined;\n readonly passCount: number;\n readonly sampleCount: number;\n readonly memoryBytes: number;\n readonly resourceFacts: VolumetricFogResourceFacts | undefined;\n readonly selectedLight: VolumeSelectedLightFacts | undefined;\n readonly candidateSelectedLight: VolumeSelectedLightFacts | undefined;\n}\n\nexport interface VolumetricFogInspectionInput {\n readonly authored: boolean;\n readonly capability: 'available' | 'unavailable';\n readonly degraded?: boolean;\n readonly recovery?: VolumeRecoveryState;\n readonly acceptedDigest?: string;\n readonly format?: TextureFormat;\n readonly passCount?: number;\n readonly sampleCount?: number;\n readonly memoryBytes?: number;\n readonly resourceFacts?: VolumetricFogResourceFacts;\n}\n\nfunction resourceStage(input: VolumetricFogInspectionInput): VolumetricFogResourceStage {\n if (!input.authored || input.recovery === undefined) return 'none';\n if (input.recovery.status === 'candidate') return 'candidate';\n if (input.recovery.status === 'recovering') return 'recovering';\n if (input.recovery.status === 'degraded') return 'lkg';\n return 'accepted';\n}\n\nexport function inspectVolumetricFog(input: VolumetricFogInspectionInput): VolumetricFogInspection {\n const recovery = input.recovery;\n const status: VolumetricFogInspectionStatus = !input.authored\n ? 'off'\n : input.capability === 'unavailable'\n ? 'unavailable'\n : input.degraded === true || recovery?.status === 'degraded'\n ? 'degraded'\n : 'available';\n return Object.freeze({\n ownerCount: 0,\n status,\n resourceStage: resourceStage(input),\n guid: recovery?.guid,\n generation: recovery?.generation,\n digest: input.acceptedDigest,\n candidateGeneration: recovery?.candidateGeneration,\n candidateDigest: recovery?.candidateDigest,\n lkgGeneration: recovery?.lkgGeneration,\n candidateFailure: recovery?.candidateFailure,\n deviceEpoch: recovery?.deviceEpoch ?? 0,\n format: input.format,\n passCount: input.passCount ?? 0,\n sampleCount: input.sampleCount ?? 0,\n memoryBytes: input.memoryBytes ?? 0,\n resourceFacts: input.resourceFacts,\n selectedLight: recovery?.selectedLight,\n candidateSelectedLight: recovery?.candidateSelectedLight,\n });\n}\n","import type {\n MaterialDynamicFieldType,\n MaterialDynamicInputLayout,\n MaterialDynamicInputSchema,\n} from '@forgeax/engine-types';\nimport { deriveMaterialDynamicInputLayout, err, ok, type Result } from '@forgeax/engine-types';\n\nexport type DynamicInputValue = number | readonly number[];\n\n/** Stable public address of one admitted Surface draw member. */\nexport interface SurfaceDynamicInputMemberIdentity {\n /** `World.identity`; stable across renderer-local World reordering. */\n readonly worldIdentity: string;\n readonly entityKey: number;\n readonly drawItemIndex: number;\n readonly instanceOrdinal: number;\n}\n\nexport interface DynamicInputRange {\n readonly pageId: number;\n readonly sourceId: string;\n /** Producer-owned domain identity retained across device regeneration. */\n readonly domain: string;\n readonly byteOffset: number;\n readonly recordStart: number;\n readonly recordCount: number;\n readonly instanceIndex: number;\n readonly member: SurfaceDynamicInputMemberIdentity;\n readonly contentRevision: number;\n readonly bufferGeneration: number;\n readonly deviceGeneration: number;\n}\n\nexport interface DynamicInputDirtyRange {\n readonly byteStart: number;\n readonly byteEnd: number;\n}\n\nexport interface DynamicInputUploadReceipt {\n readonly sourceId: string;\n readonly pageId: number;\n readonly contentRevision: number;\n readonly bufferGeneration: number;\n readonly deviceGeneration: number;\n readonly ranges: readonly DynamicInputDirtyRange[];\n readonly bytes: number;\n}\n\nexport interface DynamicInputConsumptionReceipt extends DynamicInputRange {\n readonly frameNumber: number;\n readonly uploadedRevision: number;\n}\n\n/**\n * Renderer input for one frame of a published Surface dynamic page.\n *\n * `ranges` join by their stable World/entity/draw/instance member identity.\n * Producer order is irrelevant and cannot redirect one member's dynamic\n * records to another member after culling or World reordering.\n */\nexport interface SurfaceDynamicInputFrame {\n readonly page: ReadonlyDynamicInputPage;\n readonly ranges?: readonly DynamicInputRange[];\n /** Producer-owned membership/address revision; time and record values do not advance it. */\n readonly projectionRevision: number;\n readonly frameTime: number;\n}\n\nexport type DynamicInputErrorCode =\n | 'invalid-schema'\n | 'invalid-record'\n | 'range-overflow'\n | 'domain-overflow'\n | 'not-uploaded'\n | 'stale-generation'\n | 'released';\n\nexport interface DynamicInputErrorDetail {\n readonly operation:\n | 'create'\n | 'write'\n | 'reserve'\n | 'upload'\n | 'consume'\n | 'reconfigure'\n | 'release';\n readonly field?: string;\n readonly expected: string;\n readonly actual?: unknown;\n readonly sourceId?: string;\n readonly pageId?: number;\n}\n\nconst ERROR_POLICY: Readonly<\n Record<DynamicInputErrorCode, { readonly expected: string; readonly hint: string }>\n> = {\n 'invalid-schema': {\n expected: 'the dynamic input schema has one derived bounded record layout',\n hint: 'repair the root MaterialSurface dynamicInput declaration and recook it',\n },\n 'invalid-record': {\n expected: 'each dynamic record matches the derived scalar/vector fields',\n hint: 'write finite values using the field names and types declared by the material',\n },\n 'range-overflow': {\n expected: 'the instance range stays within the declared read-only page',\n hint: 'reduce the range or increase the producer page budget before publication',\n },\n 'domain-overflow': {\n expected: 'the page stays within its declared number of producer domains',\n hint: 'reuse an existing domain or publish a larger bounded declaration',\n },\n 'not-uploaded': {\n expected: 'the current page revision was uploaded before frame consumption',\n hint: 'submit the page upload receipt and retry the same frame',\n },\n 'stale-generation': {\n expected: 'the range, upload, and device use one current page generation',\n hint: 'discard stale addresses and rebuild the producer projection for the current device',\n },\n released: {\n expected: 'the read-only page is still attached to its owning Render lifecycle',\n hint: 'create a new page after releasing the old owner',\n },\n};\n\nexport class DynamicInputError extends Error {\n readonly code: DynamicInputErrorCode;\n readonly expected: string;\n readonly hint: string;\n readonly detail: DynamicInputErrorDetail;\n\n constructor(code: DynamicInputErrorCode, detail: DynamicInputErrorDetail) {\n super(`${code}: ${ERROR_POLICY[code].expected}`);\n this.name = 'DynamicInputError';\n this.code = code;\n this.expected = ERROR_POLICY[code].expected;\n this.hint = ERROR_POLICY[code].hint;\n this.detail = Object.freeze({ ...detail });\n }\n}\n\nexport type DynamicInputResult<T> = Result<T, DynamicInputError>;\n\ninterface DomainRecord {\n readonly name: string;\n readonly start: number;\n readonly end: number;\n}\n\nfunction alignRange(ranges: DynamicInputDirtyRange[], start: number, end: number): void {\n if (start >= end) return;\n let index = 0;\n while (index < ranges.length && (ranges[index]?.byteEnd ?? 0) < start) index += 1;\n while (index < ranges.length) {\n const existing = ranges[index];\n if (existing === undefined || existing.byteStart > end) break;\n start = Math.min(start, existing.byteStart);\n end = Math.max(end, existing.byteEnd);\n ranges.splice(index, 1);\n }\n ranges.splice(index, 0, { byteStart: start, byteEnd: end });\n}\n\nfunction fieldWidth(type: MaterialDynamicFieldType): number {\n switch (type) {\n case 'f32':\n case 'u32':\n return 1;\n case 'vec2<f32>':\n return 2;\n case 'vec3<f32>':\n return 3;\n case 'vec4<f32>':\n return 4;\n }\n}\n\nfunction finiteNumber(value: unknown): value is number {\n return typeof value === 'number' && Number.isFinite(value);\n}\n\nfunction invalid(\n code: DynamicInputErrorCode,\n operation: DynamicInputErrorDetail['operation'],\n expected: string,\n actual?: unknown,\n field?: string,\n page?: Readonly<{ sourceId: string; pageId: number }>,\n): DynamicInputError {\n return new DynamicInputError(code, {\n operation,\n expected,\n ...(actual === undefined ? {} : { actual }),\n ...(field === undefined ? {} : { field }),\n ...(page === undefined ? {} : page),\n });\n}\n\n/**\n * Generic Render-owned CPU side of a read-only dynamic input page. The page\n * has no GPU handle: the renderer's existing resource owner can upload the\n * detached bytes and attach the receipt to a prepared pass.\n */\nexport class ReadonlyDynamicInputPage {\n readonly sourceId: string;\n readonly pageId: number;\n readonly schema: MaterialDynamicInputSchema;\n readonly layout: MaterialDynamicInputLayout;\n readonly bytes: Uint8Array;\n private contentRevisionValue = 1;\n private bufferGenerationValue = 1;\n private deviceGenerationValue = 1;\n private uploadedRevisionValue = 0;\n private lastUploadedBytesValue = 0;\n private released = false;\n private readonly ownedRanges = new WeakSet<object>();\n private readonly ownedUploads = new WeakSet<object>();\n private readonly dirty = [\n {\n byteStart: 0,\n byteEnd: 0,\n } as DynamicInputDirtyRange,\n ];\n private readonly domains = new Map<string, DomainRecord>();\n\n private constructor(\n sourceId: string,\n pageId: number,\n schema: MaterialDynamicInputSchema,\n layout: MaterialDynamicInputLayout,\n ) {\n this.sourceId = sourceId;\n this.pageId = pageId;\n this.schema = schema;\n this.layout = layout;\n this.bytes = new Uint8Array(schema.maxPageBytes);\n this.dirty.length = 0;\n }\n\n static create(input: {\n readonly sourceId: string;\n readonly pageId: number;\n readonly schema: MaterialDynamicInputSchema;\n }): DynamicInputResult<ReadonlyDynamicInputPage> {\n if (input.sourceId.length === 0 || !Number.isSafeInteger(input.pageId) || input.pageId < 0) {\n return err(\n invalid(\n 'invalid-schema',\n 'create',\n 'sourceId is non-empty and pageId is non-negative',\n input.pageId,\n ),\n );\n }\n const layout = deriveMaterialDynamicInputLayout(input.schema);\n if (!layout.ok) {\n return err(\n invalid(\n 'invalid-schema',\n 'create',\n layout.error.expected,\n layout.error.actual,\n layout.error.field,\n ),\n );\n }\n return ok(\n new ReadonlyDynamicInputPage(input.sourceId, input.pageId, input.schema, layout.value),\n );\n }\n\n get contentRevision(): number {\n return this.contentRevisionValue;\n }\n\n get bufferGeneration(): number {\n return this.bufferGenerationValue;\n }\n\n get deviceGeneration(): number {\n return this.deviceGenerationValue;\n }\n\n get uploadedRevision(): number {\n return this.uploadedRevisionValue;\n }\n\n get lastUploadedBytes(): number {\n return this.lastUploadedBytesValue;\n }\n\n /** Write one complete record and mark only its byte interval dirty. */\n writeRecord(\n index: number,\n values: Readonly<Record<string, DynamicInputValue>>,\n ): DynamicInputResult<number> {\n const live = this.assertLive('write');\n if (!live.ok) return live;\n if (!Number.isSafeInteger(index) || index < 0 || index >= this.schema.maxRecords) {\n return err(\n invalid(\n 'range-overflow',\n 'write',\n `record index is within [0, ${this.schema.maxRecords})`,\n index,\n 'index',\n this,\n ),\n );\n }\n const recordOffset = index * this.layout.stride;\n // Encode into detached bytes first. A malformed later field must leave the\n // previously published record and its dirty/revision state untouched.\n const encoded = new Uint8Array(this.layout.stride);\n const view = new DataView(encoded.buffer, encoded.byteOffset, encoded.byteLength);\n for (const field of this.layout.fields) {\n const value = values[field.name];\n if (value === undefined) {\n return err(\n invalid(\n 'invalid-record',\n 'write',\n `record contains field ${field.name}`,\n value,\n field.name,\n this,\n ),\n );\n }\n const width = fieldWidth(field.type);\n const numbers = typeof value === 'number' ? [value] : value;\n if (numbers.length !== width || numbers.some((candidate) => !finiteNumber(candidate))) {\n return err(\n invalid(\n 'invalid-record',\n 'write',\n `${field.name} is a finite ${field.type}`,\n value,\n field.name,\n this,\n ),\n );\n }\n if (\n field.type === 'u32' &&\n (!Number.isInteger(numbers[0]) ||\n (numbers[0] as number) < 0 ||\n (numbers[0] as number) > 0xffffffff)\n ) {\n return err(\n invalid(\n 'invalid-record',\n 'write',\n `${field.name} is an unsigned 32-bit integer`,\n value,\n field.name,\n this,\n ),\n );\n }\n for (const [component, number] of numbers.entries()) {\n const offset = field.offset + component * 4;\n if (field.type === 'u32') view.setUint32(offset, number as number, true);\n else view.setFloat32(offset, number as number, true);\n }\n }\n this.bytes.set(encoded, recordOffset);\n this.contentRevisionValue += 1;\n alignRange(this.dirty, recordOffset, recordOffset + this.layout.stride);\n return ok(this.contentRevisionValue);\n }\n\n /** Reserve one explicit instance range; no skin address field is involved. */\n reserveRange(input: {\n readonly domain: string;\n readonly recordStart: number;\n readonly recordCount: number;\n readonly instanceIndex: number;\n readonly member: SurfaceDynamicInputMemberIdentity;\n }): DynamicInputResult<DynamicInputRange> {\n const live = this.assertLive('reserve');\n if (!live.ok) return live;\n if (input.domain.length === 0) {\n return err(\n invalid(\n 'domain-overflow',\n 'reserve',\n 'domain is a non-empty identity',\n input.domain,\n 'domain',\n this,\n ),\n );\n }\n if (!this.domains.has(input.domain) && this.domains.size >= this.schema.maxDomains) {\n return err(\n invalid(\n 'domain-overflow',\n 'reserve',\n `at most ${this.schema.maxDomains} domains are active`,\n this.domains.size + 1,\n 'domain',\n this,\n ),\n );\n }\n if (\n !Number.isSafeInteger(input.instanceIndex) ||\n input.instanceIndex < 0 ||\n input.instanceIndex > 0xffffffff\n ) {\n return err(\n invalid(\n 'range-overflow',\n 'reserve',\n 'instance index is an exact unsigned 32-bit integer',\n input.instanceIndex,\n 'instanceIndex',\n this,\n ),\n );\n }\n if (\n input.member.worldIdentity.length === 0 ||\n !Number.isSafeInteger(input.member.entityKey) ||\n input.member.entityKey < 0 ||\n input.member.entityKey > 0xffffffff ||\n !Number.isSafeInteger(input.member.drawItemIndex) ||\n input.member.drawItemIndex < 0 ||\n input.member.drawItemIndex > 0xffffffff ||\n !Number.isSafeInteger(input.member.instanceOrdinal) ||\n input.member.instanceOrdinal < 0 ||\n input.member.instanceOrdinal > 0xffffffff\n ) {\n return err(\n invalid(\n 'range-overflow',\n 'reserve',\n 'member is a stable World identity plus exact unsigned 32-bit entity, draw-item, and instance identities',\n input.member,\n 'member',\n this,\n ),\n );\n }\n if (\n !Number.isSafeInteger(input.recordStart) ||\n !Number.isSafeInteger(input.recordCount) ||\n input.recordStart < 0 ||\n input.recordCount <= 0 ||\n input.recordStart + input.recordCount > this.schema.maxRecords\n ) {\n return err(\n invalid(\n 'range-overflow',\n 'reserve',\n 'record range and instance index fit the declared page',\n input,\n 'recordStart',\n this,\n ),\n );\n }\n const range: DynamicInputRange = {\n pageId: this.pageId,\n sourceId: this.sourceId,\n domain: input.domain,\n byteOffset: input.recordStart * this.layout.stride,\n recordStart: input.recordStart,\n recordCount: input.recordCount,\n instanceIndex: input.instanceIndex,\n member: Object.freeze({ ...input.member }),\n contentRevision: this.contentRevisionValue,\n bufferGeneration: this.bufferGenerationValue,\n deviceGeneration: this.deviceGenerationValue,\n };\n this.ownedRanges.add(range);\n this.domains.set(input.domain, {\n name: input.domain,\n start: input.recordStart,\n end: input.recordStart + input.recordCount,\n });\n return ok(range);\n }\n\n /** Return detached dirty bytes for the existing resource owner to upload. */\n beginUpload(): DynamicInputResult<DynamicInputUploadReceipt> {\n const live = this.assertLive('upload');\n if (!live.ok) return live;\n const ranges = this.dirty.map((range) => ({ ...range }));\n const bytes = ranges.reduce((sum, range) => sum + range.byteEnd - range.byteStart, 0);\n const receipt: DynamicInputUploadReceipt = {\n sourceId: this.sourceId,\n pageId: this.pageId,\n contentRevision: this.contentRevisionValue,\n bufferGeneration: this.bufferGenerationValue,\n deviceGeneration: this.deviceGenerationValue,\n ranges,\n bytes,\n };\n this.ownedUploads.add(receipt);\n return ok(receipt);\n }\n\n /**\n * Commit an upload only after the owning queue write has succeeded. A\n * producer that changed the page while a write was in flight leaves the\n * dirty bytes pending and must retry the new revision.\n */\n commitUpload(receipt: DynamicInputUploadReceipt): DynamicInputResult<true> {\n const live = this.assertLive('upload');\n if (!live.ok) return live;\n if (\n !this.ownedUploads.has(receipt) ||\n receipt.sourceId !== this.sourceId ||\n receipt.pageId !== this.pageId ||\n receipt.bufferGeneration !== this.bufferGenerationValue ||\n receipt.deviceGeneration !== this.deviceGenerationValue ||\n receipt.contentRevision !== this.contentRevisionValue\n ) {\n return err(\n invalid(\n 'stale-generation',\n 'upload',\n 'the upload receipt still describes the current page revision and generation',\n receipt,\n 'receipt',\n this,\n ),\n );\n }\n this.uploadedRevisionValue = receipt.contentRevision;\n this.lastUploadedBytesValue = receipt.bytes;\n for (const range of receipt.ranges) {\n const index = this.dirty.findIndex(\n (candidate) =>\n candidate.byteStart === range.byteStart && candidate.byteEnd === range.byteEnd,\n );\n if (index >= 0) this.dirty.splice(index, 1);\n }\n return ok(true);\n }\n\n /** CPU-only convenience: begin and commit are still explicit in production. */\n upload(): DynamicInputResult<DynamicInputUploadReceipt> {\n const receipt = this.beginUpload();\n if (!receipt.ok) return receipt;\n const committed = this.commitUpload(receipt.value);\n if (!committed.ok) return committed;\n return receipt;\n }\n\n /** Consume an uploaded range after graph submission has completed. */\n consume(\n range: DynamicInputRange,\n frameNumber: number,\n ): DynamicInputResult<DynamicInputConsumptionReceipt> {\n const live = this.assertLive('consume');\n if (!live.ok) return live;\n if (\n !this.ownedRanges.has(range) ||\n range.sourceId !== this.sourceId ||\n range.pageId !== this.pageId ||\n range.bufferGeneration !== this.bufferGenerationValue ||\n range.deviceGeneration !== this.deviceGenerationValue ||\n range.recordStart < 0 ||\n range.recordCount <= 0 ||\n range.recordStart + range.recordCount > this.schema.maxRecords\n ) {\n return err(\n invalid(\n 'stale-generation',\n 'consume',\n 'range belongs to this current page generation',\n range,\n 'generation',\n this,\n ),\n );\n }\n if (this.uploadedRevisionValue < range.contentRevision) {\n return err(\n invalid(\n 'not-uploaded',\n 'consume',\n 'range content revision was uploaded before consumption',\n this.uploadedRevisionValue,\n 'contentRevision',\n this,\n ),\n );\n }\n return ok({ ...range, frameNumber, uploadedRevision: this.uploadedRevisionValue });\n }\n\n /** Device loss/rebuild changes physical generations while source identity stays stable. */\n reconfigureDevice(deviceGeneration: number): DynamicInputResult<number> {\n const live = this.assertLive('reconfigure');\n if (!live.ok) return live;\n if (!Number.isSafeInteger(deviceGeneration) || deviceGeneration < 0) {\n return err(\n invalid(\n 'stale-generation',\n 'reconfigure',\n 'deviceGeneration is a non-negative safe integer',\n deviceGeneration,\n 'deviceGeneration',\n this,\n ),\n );\n }\n const rendererInitialGeneration =\n this.bufferGenerationValue === 1 &&\n this.deviceGenerationValue === 1 &&\n deviceGeneration === 0;\n if (deviceGeneration < this.deviceGenerationValue && !rendererInitialGeneration) {\n return err(\n invalid(\n 'stale-generation',\n 'reconfigure',\n 'deviceGeneration does not precede the current device generation',\n deviceGeneration,\n 'deviceGeneration',\n this,\n ),\n );\n }\n this.deviceGenerationValue = deviceGeneration;\n this.bufferGenerationValue += 1;\n this.uploadedRevisionValue = 0;\n alignRange(this.dirty, 0, this.schema.maxRecords * this.layout.stride);\n return ok(this.bufferGenerationValue);\n }\n\n release(): DynamicInputResult<true> {\n if (this.released) return ok(true);\n this.released = true;\n this.domains.clear();\n this.dirty.length = 0;\n return ok(true);\n }\n\n private assertLive(operation: DynamicInputErrorDetail['operation']): DynamicInputResult<true> {\n return this.released\n ? err(\n invalid(\n 'released',\n operation,\n ERROR_POLICY.released.expected,\n undefined,\n undefined,\n this,\n ),\n )\n : ok(true);\n }\n}\n","export interface ProbeFilterState {\n readonly probeIndex: number;\n readonly faceCount: number;\n readonly mipCount: number;\n readonly cursor: number;\n readonly activeGeneration: number;\n}\n\nexport function createProbeFilterState(input: {\n readonly probeIndex: number;\n readonly faceCount?: number;\n readonly mipCount: number;\n readonly activeGeneration?: number;\n}): ProbeFilterState {\n return {\n probeIndex: input.probeIndex,\n faceCount: input.faceCount ?? 6,\n mipCount: input.mipCount,\n cursor: 0,\n activeGeneration: input.activeGeneration ?? 0,\n };\n}\n\nexport function advanceProbeFilter(\n state: ProbeFilterState,\n):\n | { readonly probeIndex: number; readonly faceIndex: number; readonly mipLevel: number }\n | undefined {\n const total = state.faceCount * state.mipCount;\n if (state.cursor >= total) return undefined;\n return {\n probeIndex: state.probeIndex,\n faceIndex: state.cursor % state.faceCount,\n mipLevel: Math.floor(state.cursor / state.faceCount),\n };\n}\n\nexport function commitProbeFilterStep(state: ProbeFilterState, success: boolean): ProbeFilterState {\n if (!success) return state;\n const nextCursor = state.cursor + 1;\n const complete = nextCursor >= state.faceCount * state.mipCount;\n return {\n ...state,\n cursor: nextCursor,\n activeGeneration: complete ? state.activeGeneration + 1 : state.activeGeneration,\n };\n}\n\nexport function probeFilterIsSteady(state: ProbeFilterState): boolean {\n return state.cursor >= state.faceCount * state.mipCount;\n}\n\nfunction normalize(vector: readonly [number, number, number]): [number, number, number] {\n const length = Math.hypot(vector[0], vector[1], vector[2]);\n if (length === 0) return [0, 0, 1];\n return [vector[0] / length, vector[1] / length, vector[2] / length];\n}\n\nexport function boxProjectReflectionDirection(\n direction: readonly [number, number, number],\n boxCenter: readonly [number, number, number],\n halfExtents: readonly [number, number, number],\n point: readonly [number, number, number],\n): [number, number, number] {\n const ray = normalize(direction);\n for (const axis of [0, 1, 2] as const) {\n if (Math.abs(point[axis] - boxCenter[axis]) >= halfExtents[axis]) return ray;\n }\n let distance = Number.POSITIVE_INFINITY;\n for (let axis = 0; axis < 3; axis += 1) {\n const component = ray[axis] ?? 0;\n if (component === 0) continue;\n const extent = halfExtents[axis] ?? 0;\n const edge = component > 0 ? (boxCenter[axis] ?? 0) + extent : (boxCenter[axis] ?? 0) - extent;\n const candidate = (edge - (point[axis] ?? 0)) / component;\n if (candidate > 0) distance = Math.min(distance, candidate);\n }\n if (!Number.isFinite(distance)) return ray;\n return normalize([\n (point[0] ?? 0) + ray[0] * distance - (boxCenter[0] ?? 0),\n (point[1] ?? 0) + ray[1] * distance - (boxCenter[1] ?? 0),\n (point[2] ?? 0) + ray[2] * distance - (boxCenter[2] ?? 0),\n ]);\n}\n","import type { Buffer, Sampler, TextureView } from '@forgeax/engine-rhi';\n\nexport interface ReflectionProbeTableRow {\n readonly primitiveKey?: string;\n readonly index: number;\n readonly worldId: number;\n readonly entityKey: number;\n readonly center: readonly [number, number, number];\n readonly halfExtents: readonly [number, number, number];\n readonly intensity: number;\n readonly generation: number;\n /** Renderer-owned filtered cube used by the Standard material lane. */\n readonly filteredView?: TextureView;\n /** Renderer-owned sampler paired with filteredView. */\n readonly sampler?: Sampler;\n /** Per-probe uniform payload; keeps MaterialAsset ABI unchanged. */\n readonly uniformBuffer?: Buffer;\n}\n\nexport interface ReflectionProbeTable {\n readonly rows: readonly ReflectionProbeTableRow[];\n readonly cpuIndexByPrimitive: (primitiveKey: string) => number | undefined;\n readonly gpuIndexByPrimitive: (primitiveKey: string) => number | undefined;\n}\n\nexport function buildReflectionProbeTable(\n rows: readonly ReflectionProbeTableRow[],\n): ReflectionProbeTable {\n const ordered = rows.slice().sort((a, b) => a.index - b.index);\n const indices = new Map<string, number>();\n for (const row of ordered) {\n if (row.primitiveKey !== undefined) indices.set(row.primitiveKey, row.index);\n }\n const indexFor = (primitiveKey: string): number | undefined => indices.get(primitiveKey);\n return {\n rows: Object.freeze(ordered),\n cpuIndexByPrimitive: indexFor,\n gpuIndexByPrimitive: indexFor,\n };\n}\n\nexport function reflectionProbeTableBytes(table: ReflectionProbeTable): number {\n return table.rows.length * 48;\n}\n","import type {\n ReflectionFallbackFailureStage,\n ReflectionFallbackInspection,\n ReflectionFallbackReceipt,\n ReflectionFallbackRecoveryAction,\n} from '../inspection-types';\n\nexport interface ReflectionFallbackFailureInput {\n readonly stage: ReflectionFallbackFailureStage;\n readonly code: string;\n readonly expected: string;\n readonly detail?: Readonly<Record<string, unknown>>;\n}\n\nfunction recoveryFor(\n receipt: ReflectionFallbackReceipt,\n failure?: ReflectionFallbackFailureInput,\n): ReflectionFallbackRecoveryAction {\n if (failure !== undefined) {\n const code = failure.code.toLowerCase();\n if (code.includes('device') || code.includes('format') || code.includes('capability')) {\n return 'rebuild';\n }\n if (failure.stage === 'prepare' || failure.stage === 'filter') return 'recapture';\n if (failure.stage === 'build' || failure.stage === 'encode') return 'rebuild';\n if (failure.stage === 'finish' || failure.stage === 'submit') return 'retry';\n // Completion failures may still retain a source-identical committed row;\n // use it as LKG, otherwise retry the producer completion.\n if (failure.stage === 'completion') {\n if (receipt.source === 'probe' && (receipt.state === 'active' || receipt.state === 'lkg')) {\n return 'use-LKG';\n }\n if (\n receipt.source === 'skylight' &&\n (receipt.state === 'active' || receipt.state === 'lkg')\n ) {\n return 'use-Skylight';\n }\n if (receipt.source === 'neutral' && receipt.state === 'neutral') return 'use-neutral';\n return 'retry';\n }\n }\n if (receipt.source === 'probe' && (receipt.state === 'active' || receipt.state === 'lkg')) {\n return 'use-LKG';\n }\n if (receipt.source === 'skylight' || receipt.state === 'lkg') return 'use-Skylight';\n return 'use-neutral';\n}\n\n/** Projects producer state and the latest closed failure into detached facts. */\nexport function inspectReflectionFallback(\n receipt: ReflectionFallbackReceipt,\n failure?: ReflectionFallbackFailureInput,\n): ReflectionFallbackInspection {\n return {\n receipt,\n recoveryAction: recoveryFor(receipt, failure),\n ...(failure === undefined\n ? {}\n : {\n failureStage: failure.stage,\n failureCode: failure.code,\n expected: failure.expected,\n ...(failure.detail === undefined ? {} : { detail: failure.detail }),\n }),\n };\n}\n","import type { ReflectionProbeUpdateIntent } from '../components/reflection-probe';\n\nexport const REFLECTION_PROBE_BYTES_PER_TEXEL = 8;\nexport const DEFAULT_REFLECTION_PROBE_LIMITS = Object.freeze({\n maxProbes: 16,\n maxResolution: 256,\n maxBytes: 64 * 1024 * 1024,\n});\n\nexport interface ReflectionProbeInput {\n readonly halfExtents: readonly [number, number, number];\n readonly priority: number;\n readonly intensity: number;\n readonly resolution: number;\n readonly boxProjection?: boolean;\n}\n\nexport interface ReflectionProbeFact extends ReflectionProbeInput {\n readonly worldId: number;\n readonly entityKey: number;\n readonly center: readonly [number, number, number];\n readonly revision: number;\n readonly updateIntent?: ReflectionProbeUpdateIntent;\n readonly invalidationVersion?: number;\n}\n\nexport interface ReflectionProbeAdmissionLimits {\n readonly maxProbes?: number;\n readonly maxResolution?: number;\n readonly maxBytes?: number;\n}\n\nexport interface ReflectionProbeInvalidInput {\n readonly code: 'reflection-probe-input-invalid';\n readonly field: string;\n readonly value: unknown;\n readonly expected: string;\n}\n\nexport interface ReflectionProbeBudgetFailure {\n readonly code: 'reflection-probe-budget-exceeded';\n readonly requested: number;\n readonly activeCount: number;\n readonly activeBytes: number;\n readonly maxProbes: number;\n readonly maxBytes: number;\n}\n\nexport type ReflectionProbeAdmission =\n | { readonly ok: true; readonly acceptedBytes: number }\n | { readonly ok: false; readonly error: ReflectionProbeBudgetFailure };\n\nexport function validateReflectionProbeInput(\n input: ReflectionProbeInput,\n): { readonly ok: true } | { readonly ok: false; readonly error: ReflectionProbeInvalidInput } {\n for (let index = 0; index < input.halfExtents.length; index += 1) {\n const value = input.halfExtents[index];\n if (value === undefined || !Number.isFinite(value) || value <= 0) {\n return {\n ok: false,\n error: {\n code: 'reflection-probe-input-invalid',\n field: `halfExtents[${index}]`,\n value,\n expected: 'a finite number greater than zero',\n },\n };\n }\n }\n if (!Number.isFinite(input.priority)) {\n return {\n ok: false,\n error: {\n code: 'reflection-probe-input-invalid',\n field: 'priority',\n value: input.priority,\n expected: 'a finite number',\n },\n };\n }\n if (!Number.isFinite(input.intensity) || input.intensity < 0) {\n return {\n ok: false,\n error: {\n code: 'reflection-probe-input-invalid',\n field: 'intensity',\n value: input.intensity,\n expected: 'a finite number greater than or equal to zero',\n },\n };\n }\n if (\n !Number.isInteger(input.resolution) ||\n input.resolution < 16 ||\n (input.resolution & (input.resolution - 1)) !== 0\n ) {\n return {\n ok: false,\n error: {\n code: 'reflection-probe-input-invalid',\n field: 'resolution',\n value: input.resolution,\n expected: 'a power of two of at least 16 pixels',\n },\n };\n }\n return { ok: true };\n}\n\nexport function estimateReflectionProbeBytes(\n resolution: number,\n limits: ReflectionProbeAdmissionLimits = DEFAULT_REFLECTION_PROBE_LIMITS,\n): number {\n const maxResolution = limits.maxResolution ?? DEFAULT_REFLECTION_PROBE_LIMITS.maxResolution;\n const clamped = Math.min(resolution, maxResolution);\n let filteredTexels = 0;\n for (let mip = 0; mip < 5; mip++) {\n const size = Math.max(1, Math.floor(clamped / 2 ** mip));\n filteredTexels += size * size;\n }\n // Raw cube + two alternating filtered cubes + their depth attachments.\n return (\n (clamped * clamped + 2 * filteredTexels) * 6 * REFLECTION_PROBE_BYTES_PER_TEXEL +\n 3 * clamped * clamped * 4\n );\n}\n\nexport function admitReflectionProbe(\n input: ReflectionProbeInput,\n current: { readonly acceptedCount: number; readonly acceptedBytes: number },\n limits: ReflectionProbeAdmissionLimits = DEFAULT_REFLECTION_PROBE_LIMITS,\n): ReflectionProbeAdmission {\n const maxProbes = limits.maxProbes ?? DEFAULT_REFLECTION_PROBE_LIMITS.maxProbes;\n const maxBytes = limits.maxBytes ?? DEFAULT_REFLECTION_PROBE_LIMITS.maxBytes;\n const maxResolution = limits.maxResolution ?? DEFAULT_REFLECTION_PROBE_LIMITS.maxResolution;\n const requested = estimateReflectionProbeBytes(input.resolution, { maxResolution });\n if (\n input.resolution > maxResolution ||\n current.acceptedCount >= maxProbes ||\n current.acceptedBytes + requested > maxBytes\n ) {\n return {\n ok: false,\n error: {\n code: 'reflection-probe-budget-exceeded',\n requested,\n activeCount: current.acceptedCount,\n activeBytes: current.acceptedBytes,\n maxProbes,\n maxBytes,\n },\n };\n }\n return { ok: true, acceptedBytes: current.acceptedBytes + requested };\n}\n\nexport interface ReflectionProbeSelection {\n readonly kind: 'probe';\n readonly worldId: number;\n readonly entityKey: number;\n readonly normalizedDistance: number;\n}\n\nexport interface SkylightSelection {\n readonly kind: 'skylight';\n}\n\nexport type ReflectionProbeSelectionResult = ReflectionProbeSelection | SkylightSelection;\n\nexport type ReflectionFallbackSource = 'probe' | 'skylight' | 'neutral';\n\nexport interface ReflectionFallbackProjectionInput {\n /** Stable renderable identity used to join the main-pass projection. */\n readonly renderableKey?: string;\n /** Stable producer source identity; never a live GPU handle. */\n readonly sourceKey?: string;\n readonly source: ReflectionFallbackSource;\n readonly coverage: number;\n readonly extent?: readonly [number, number, number];\n readonly linearHdr: readonly [number, number, number, number];\n readonly brdfSignature: string;\n}\n\nexport interface ReflectionFallbackProjection extends ReflectionFallbackProjectionInput {\n readonly source: ReflectionFallbackSource;\n}\n\nexport type ReflectionFallbackMismatchKind = 'source' | 'coverage' | 'extent' | 'brdf';\n\nexport interface ReflectionFallbackMismatch {\n readonly code:\n | 'reflection-fallback-source-mismatch'\n | 'reflection-fallback-coverage-mismatch'\n | 'reflection-fallback-extent-mismatch'\n | 'reflection-fallback-brdf-mismatch';\n readonly expected: string;\n readonly actual: string;\n}\n\nexport interface ReflectionFallbackInputInvalid {\n readonly code: 'reflection-fallback-input-invalid';\n readonly field: string;\n readonly expected: string;\n}\n\nexport type ReflectionFallbackProjectionResult =\n | { readonly ok: true; readonly value: ReflectionFallbackProjection }\n | { readonly ok: false; readonly error: ReflectionFallbackInputInvalid };\n\nexport function resolveReflectionFallbackSource(\n selection: ReflectionProbeSelectionResult,\n probeReady: boolean,\n skylightAvailable = true,\n): ReflectionFallbackSource {\n if (selection.kind === 'probe' && probeReady) return 'probe';\n // An unavailable probe follows the producer recovery order: use the active\n // Skylight when one exists, then the producer-owned neutral zero. Returning\n // neutral directly here would make the main Standard lighting lane and the\n // detached fallback projection disagree.\n if (skylightAvailable) return 'skylight';\n return 'neutral';\n}\n\nexport function reflectionFallbackCoverage(\n source: ReflectionFallbackSource,\n fact: ReflectionProbeFact | undefined,\n selection: ReflectionProbeSelectionResult,\n): number {\n if (source === 'neutral') return 0;\n if (source === 'skylight') return 1;\n if (fact === undefined || selection.kind !== 'probe') return 0;\n const normalized = Math.sqrt(Math.max(0, selection.normalizedDistance));\n return Math.max(0, Math.min(1, 1 - normalized / Math.sqrt(3)));\n}\n\nexport function reflectionFallbackSourceKey(\n source: ReflectionFallbackSource,\n selection: ReflectionProbeSelectionResult,\n skylight?: { readonly entityHandle: number; readonly equirectHandle: number },\n): string {\n if (source === 'probe' && selection.kind === 'probe') {\n return `probe:${selection.worldId}:${selection.entityKey}`;\n }\n if (source === 'skylight' && skylight !== undefined) {\n return `skylight:${skylight.entityHandle}:${skylight.equirectHandle}`;\n }\n return source;\n}\n\nexport function reflectionFallbackProjectionSignature(\n input: ReflectionFallbackProjectionInput,\n): string {\n return JSON.stringify({\n renderableKey: input.renderableKey,\n sourceKey: input.sourceKey,\n source: input.source,\n coverage: input.coverage,\n extent: input.extent,\n brdfSignature: input.brdfSignature,\n });\n}\n\nexport function deriveReflectionFallbackProjection(\n input: ReflectionFallbackProjectionInput,\n): ReflectionFallbackProjectionResult {\n if (!Number.isFinite(input.coverage) || input.coverage < 0 || input.coverage > 1) {\n return {\n ok: false,\n error: {\n code: 'reflection-fallback-input-invalid',\n field: 'coverage',\n expected: 'a finite number between zero and one',\n },\n };\n }\n if (input.extent?.some((value) => !Number.isFinite(value) || value <= 0)) {\n return {\n ok: false,\n error: {\n code: 'reflection-fallback-input-invalid',\n field: 'extent',\n expected: 'three finite numbers greater than zero',\n },\n };\n }\n if (input.linearHdr.some((value) => !Number.isFinite(value))) {\n return {\n ok: false,\n error: {\n code: 'reflection-fallback-input-invalid',\n field: 'linearHdr',\n expected: 'four finite linear HDR values',\n },\n };\n }\n if (input.brdfSignature.length === 0) {\n return {\n ok: false,\n error: {\n code: 'reflection-fallback-input-invalid',\n field: 'brdfSignature',\n expected: 'a non-empty BRDF signature',\n },\n };\n }\n const linearHdr = input.source === 'neutral' ? ([0, 0, 0, 0] as const) : [...input.linearHdr];\n return {\n ok: true,\n value: Object.freeze({\n ...(input.renderableKey === undefined ? {} : { renderableKey: input.renderableKey }),\n ...(input.sourceKey === undefined ? {} : { sourceKey: input.sourceKey }),\n source: input.source,\n coverage: input.coverage,\n ...(input.extent === undefined\n ? {}\n : {\n extent: Object.freeze([...input.extent]) as readonly [number, number, number],\n }),\n linearHdr: Object.freeze(linearHdr) as ReflectionFallbackProjection['linearHdr'],\n brdfSignature: input.brdfSignature,\n }),\n };\n}\n\nexport function validateReflectionFallbackCompatibility(\n expected: ReflectionFallbackProjectionInput,\n actual: ReflectionFallbackProjectionInput,\n): { readonly ok: true } | { readonly ok: false; readonly error: ReflectionFallbackMismatch } {\n const mismatch = (\n kind: ReflectionFallbackMismatchKind,\n expectedValue: string,\n actualValue: string,\n ): { readonly ok: false; readonly error: ReflectionFallbackMismatch } => ({\n ok: false,\n error: {\n code: `reflection-fallback-${kind}-mismatch` as ReflectionFallbackMismatch['code'],\n expected: expectedValue,\n actual: actualValue,\n },\n });\n if (expected.source !== actual.source) {\n return mismatch('source', expected.source, actual.source);\n }\n if (expected.coverage !== actual.coverage) {\n return mismatch('coverage', String(expected.coverage), String(actual.coverage));\n }\n const expectedExtent = expected.extent;\n const actualExtent = actual.extent;\n if (\n (expectedExtent === undefined && actualExtent !== undefined) ||\n (expectedExtent !== undefined &&\n (actualExtent === undefined ||\n expectedExtent.some((value, index) => value !== actualExtent[index])))\n ) {\n return mismatch('extent', JSON.stringify(expectedExtent), JSON.stringify(actualExtent));\n }\n if (expected.brdfSignature !== actual.brdfSignature) {\n return mismatch('brdf', expected.brdfSignature, actual.brdfSignature);\n }\n return { ok: true };\n}\n\nfunction contains(fact: ReflectionProbeFact, point: readonly [number, number, number]): boolean {\n return fact.halfExtents.every((extent, axis) => {\n const center = fact.center[axis] ?? 0;\n const coordinate = point[axis] ?? 0;\n return Math.abs(coordinate - center) <= extent;\n });\n}\n\nfunction normalizedDistance(\n fact: ReflectionProbeFact,\n point: readonly [number, number, number],\n): number {\n let squared = 0;\n for (let axis = 0; axis < 3; axis += 1) {\n const delta = (point[axis] ?? 0) - (fact.center[axis] ?? 0);\n const extent = fact.halfExtents[axis] ?? 1;\n squared += (delta / extent) ** 2;\n }\n return squared;\n}\n\nfunction isBetter(\n candidate: ReflectionProbeSelection,\n current: ReflectionProbeSelection,\n facts: readonly ReflectionProbeFact[],\n): boolean {\n const candidateFact = facts.find(\n (fact) => fact.worldId === candidate.worldId && fact.entityKey === candidate.entityKey,\n );\n const currentFact = facts.find(\n (fact) => fact.worldId === current.worldId && fact.entityKey === current.entityKey,\n );\n if (candidateFact === undefined || currentFact === undefined) return false;\n if (candidateFact.priority !== currentFact.priority)\n return candidateFact.priority > currentFact.priority;\n if (candidate.normalizedDistance !== current.normalizedDistance) {\n return candidate.normalizedDistance < current.normalizedDistance;\n }\n return (\n candidate.worldId < current.worldId ||\n (candidate.worldId === current.worldId && candidate.entityKey < current.entityKey)\n );\n}\n\nexport function selectReflectionProbe(\n facts: readonly ReflectionProbeFact[],\n primitiveCenter: readonly [number, number, number],\n): ReflectionProbeSelectionResult {\n let selected: ReflectionProbeSelection | undefined;\n for (const fact of facts) {\n if (!contains(fact, primitiveCenter)) continue;\n const candidate: ReflectionProbeSelection = {\n kind: 'probe',\n worldId: fact.worldId,\n entityKey: fact.entityKey,\n normalizedDistance: normalizedDistance(fact, primitiveCenter),\n };\n if (selected === undefined || isBetter(candidate, selected, facts)) selected = candidate;\n }\n return selected ?? { kind: 'skylight' };\n}\n\nexport interface ReflectionProbePrimitive {\n readonly worldId: number;\n readonly entityKey: number;\n /** Main-pass renderable key; world/entity is retained as the compatibility fallback. */\n readonly renderableKey?: string;\n readonly center: readonly [number, number, number];\n}\n\nexport interface ReflectionProbeProjectionSnapshot {\n readonly revision: number;\n readonly facts: readonly ReflectionProbeFact[];\n readonly selected: ReadonlyMap<string, ReflectionProbeSelectionResult>;\n readonly scannedPrimitives: number;\n}\n\nfunction primitiveKey(worldId: number, entityKey: number): string {\n return `${worldId}:${entityKey}`;\n}\n\nexport class ReflectionProbeProjection {\n private revision = 0;\n private facts: readonly ReflectionProbeFact[] = [];\n private selected = new Map<string, ReflectionProbeSelectionResult>();\n private signature = '';\n private scannedPrimitives = 0;\n\n update(\n facts: readonly ReflectionProbeFact[],\n primitives: readonly ReflectionProbePrimitive[],\n ): ReflectionProbeProjectionSnapshot {\n const nextFacts = facts\n .slice()\n .sort((a, b) => a.worldId - b.worldId || a.entityKey - b.entityKey);\n const signature = JSON.stringify({ facts: nextFacts, primitives });\n if (signature === this.signature) return this.snapshot();\n this.signature = signature;\n this.facts = nextFacts;\n this.selected = new Map();\n for (const primitive of primitives) {\n this.selected.set(\n primitive.renderableKey ?? primitiveKey(primitive.worldId, primitive.entityKey),\n selectReflectionProbe(nextFacts, primitive.center),\n );\n }\n this.scannedPrimitives = primitives.length;\n this.revision += 1;\n return this.snapshot();\n }\n\n snapshot(): ReflectionProbeProjectionSnapshot {\n return {\n revision: this.revision,\n facts: this.facts,\n selected: this.selected,\n scannedPrimitives: this.scannedPrimitives,\n };\n }\n\n selection(worldId: number, entityKey: number): ReflectionProbeSelectionResult {\n return this.selected.get(primitiveKey(worldId, entityKey)) ?? { kind: 'skylight' };\n }\n}\n","import { createVisibilityBudget } from './budget';\n\n/** Detached, bounded LOD/occlusion facts for renderer inspection consumers. */\n\nexport const LOD_OCCLUSION_INSPECTION_SCHEMA = 'forgeax::lod-occlusion-inspection::v2' as const;\nexport const LOD_OCCLUSION_INSPECTION_MAX_BYTES = 16 * 1024;\nconst MAX_INSPECTION_SAMPLES = 64;\n\nexport type LodOcclusionInspectionError = {\n readonly code: string;\n readonly expected: string;\n readonly hint: string;\n readonly detail?: Readonly<Record<string, string | number | boolean>>;\n};\n\nexport type LodOcclusionFallback =\n | { readonly active: false }\n | {\n readonly active: true;\n readonly reason: 'producer-failed' | 'page-exhausted' | 'query-failed' | 'device-loss';\n readonly error: LodOcclusionInspectionError;\n };\n\nexport type LodOcclusionDegradation =\n | { readonly active: false }\n | { readonly active: true; readonly reason: 'all-visible' | 'query-unavailable' };\n\nexport interface LodOcclusionInspectionSample {\n readonly primitiveSlot: number;\n readonly level: number;\n readonly visible: boolean;\n}\n\nexport interface LodOcclusionInspectionRow {\n readonly root: { readonly guid: string; readonly sourceKey: string };\n readonly view: {\n readonly attachmentId: string;\n readonly cameraEntity: number;\n readonly viewRole: 'main' | 'shadow' | 'reflection' | 'probe';\n readonly viewGeneration: number;\n };\n readonly slot: { readonly primitiveSlot: number; readonly slotGeneration: number };\n readonly generation: number;\n readonly count: {\n readonly candidates: number;\n readonly visible: number;\n readonly occluded: number;\n };\n readonly lodHistogram: readonly { readonly level: number; readonly count: number }[];\n /** Map latency for the most recently completed query page (bounded POD). */\n readonly queryLatencyUs: {\n readonly median: number;\n readonly p95: number;\n readonly last: number;\n };\n readonly pagePressure: { readonly used: number; readonly capacity: number };\n readonly fallback: LodOcclusionFallback;\n readonly degradation: LodOcclusionDegradation;\n readonly samples: readonly LodOcclusionInspectionSample[];\n}\n\nexport interface LodOcclusionInspectionSubmit {\n readonly frameId: number;\n readonly build: string;\n readonly deviceGeneration: number;\n}\n\n/**\n * Per-World attribution is only authoritative when the renderer publishes\n * the GPU facts from the same submit that owns the parent inspection. The\n * normal projection path remains useful diagnostics, but it must not be used\n * as evidence for a World-reorder or per-World LOD claim.\n */\nexport type LodOcclusionWorldAttribution =\n | { readonly status: 'unavailable'; readonly reason: 'projection-only' }\n | { readonly status: 'same-submit'; readonly submit: LodOcclusionInspectionSubmit };\n\nexport interface LodOcclusionWorldInspection {\n readonly attachmentId: string;\n readonly rows: readonly LodOcclusionInspectionRow[];\n readonly attribution: LodOcclusionWorldAttribution;\n}\n\nexport interface LodOcclusionInspectionBudget {\n readonly configuredQueryBudget: number;\n readonly effectiveQueryBudget: number;\n readonly settleSubmits: number;\n readonly retestSubmits: number;\n readonly expirySubmits: number;\n}\n\nexport interface LodOcclusionInspection extends LodOcclusionInspectionRow {\n readonly schema: typeof LOD_OCCLUSION_INSPECTION_SCHEMA;\n /** Atomic identity for the submit that produced every row below. */\n readonly submit: LodOcclusionInspectionSubmit;\n /** Immutable budget values used by the query and confidence owners. */\n readonly budget: LodOcclusionInspectionBudget;\n /** Stable attachment identity; array order is never an attribution key. */\n readonly worlds: readonly LodOcclusionWorldInspection[];\n}\n\nexport type LodOcclusionInspectionInput = Omit<\n LodOcclusionInspection,\n 'schema' | 'submit' | 'budget' | 'worlds'\n> & {\n readonly submit?: LodOcclusionInspectionSubmit;\n readonly budget?: LodOcclusionInspectionBudget;\n readonly worlds?: readonly LodOcclusionWorldInspectionInput[];\n};\n\nexport type LodOcclusionWorldInspectionInput = Omit<LodOcclusionWorldInspection, 'attribution'> & {\n readonly attribution?: LodOcclusionWorldAttribution;\n};\n\nexport type LodOcclusionInspectionAction =\n | { readonly action: 'none' }\n | { readonly action: 'rebuild'; readonly sourceKey: string; readonly reason: string }\n | { readonly action: 'cold-cook'; readonly sourceKey: string; readonly reason: string }\n | { readonly action: 'retry'; readonly sourceKey: string; readonly reason: string };\n\nfunction nonNegativeInteger(name: string, value: number): number {\n if (!Number.isInteger(value) || value < 0)\n throw new Error(`${name} must be a non-negative integer`);\n return value;\n}\n\nfunction copyError(error: LodOcclusionInspectionError): LodOcclusionInspectionError {\n return Object.freeze({\n code: error.code,\n expected: error.expected,\n hint: error.hint,\n ...(error.detail === undefined ? {} : { detail: Object.freeze({ ...error.detail }) }),\n });\n}\n\nfunction copyFallback(fallback: LodOcclusionFallback): LodOcclusionFallback {\n return fallback.active\n ? Object.freeze({ ...fallback, error: copyError(fallback.error) })\n : Object.freeze({ active: false });\n}\n\nfunction copySamples(\n samples: readonly LodOcclusionInspectionSample[],\n): readonly LodOcclusionInspectionSample[] {\n return Object.freeze(\n [...samples]\n .sort((left, right) => left.primitiveSlot - right.primitiveSlot)\n .slice(0, MAX_INSPECTION_SAMPLES)\n .map((sample) =>\n Object.freeze({\n primitiveSlot: nonNegativeInteger('sample.primitiveSlot', sample.primitiveSlot),\n level: nonNegativeInteger('sample.level', sample.level),\n visible: sample.visible,\n }),\n ),\n );\n}\n\nfunction copyWorldAttribution(\n attribution: LodOcclusionWorldAttribution | undefined,\n): LodOcclusionWorldAttribution {\n if (attribution === undefined) {\n return Object.freeze({ status: 'unavailable', reason: 'projection-only' });\n }\n if (attribution.status === 'same-submit') {\n if (typeof attribution.submit.build !== 'string' || attribution.submit.build.length === 0) {\n throw new Error('world.attribution.submit.build must be a non-empty string');\n }\n nonNegativeInteger('world.attribution.submit.frameId', attribution.submit.frameId);\n nonNegativeInteger(\n 'world.attribution.submit.deviceGeneration',\n attribution.submit.deviceGeneration,\n );\n return Object.freeze({\n status: 'same-submit',\n submit: Object.freeze({ ...attribution.submit }),\n });\n }\n if (attribution.status !== 'unavailable' || attribution.reason !== 'projection-only') {\n throw new Error('world.attribution must declare same-submit or projection-only');\n }\n return Object.freeze({ status: 'unavailable', reason: 'projection-only' });\n}\n\nfunction copyRow(row: LodOcclusionInspectionRow): LodOcclusionInspectionRow {\n for (const [name, value] of Object.entries({\n generation: row.generation,\n candidates: row.count.candidates,\n visible: row.count.visible,\n occluded: row.count.occluded,\n median: row.queryLatencyUs.median,\n p95: row.queryLatencyUs.p95,\n last: row.queryLatencyUs.last,\n pageUsed: row.pagePressure.used,\n pageCapacity: row.pagePressure.capacity,\n }))\n nonNegativeInteger(`inspection.${name}`, value);\n if (\n row.view.cameraEntity < 0 ||\n row.view.viewGeneration < 0 ||\n row.slot.primitiveSlot < 0 ||\n row.slot.slotGeneration < 0\n ) {\n throw new Error('inspection identity values must be non-negative');\n }\n if (row.pagePressure.used > row.pagePressure.capacity) {\n throw new Error('inspection page pressure exceeds capacity');\n }\n return Object.freeze({\n root: Object.freeze({ ...row.root }),\n view: Object.freeze({ ...row.view }),\n slot: Object.freeze({ ...row.slot }),\n generation: row.generation,\n count: Object.freeze({ ...row.count }),\n lodHistogram: Object.freeze(\n row.lodHistogram.map((histogram) =>\n Object.freeze({\n level: nonNegativeInteger('histogram.level', histogram.level),\n count: nonNegativeInteger('histogram.count', histogram.count),\n }),\n ),\n ),\n queryLatencyUs: Object.freeze({ ...row.queryLatencyUs }),\n pagePressure: Object.freeze({ ...row.pagePressure }),\n fallback: copyFallback(row.fallback),\n degradation: Object.freeze({ ...row.degradation }),\n samples: copySamples(row.samples),\n });\n}\n\nfunction copyWorlds(\n worlds: readonly LodOcclusionWorldInspectionInput[] | undefined,\n fallback: LodOcclusionInspectionRow,\n): readonly LodOcclusionWorldInspection[] {\n const source = worlds ?? [{ attachmentId: fallback.view.attachmentId, rows: [fallback] }];\n return Object.freeze(\n source.map((world) =>\n Object.freeze({\n attachmentId: world.attachmentId,\n rows: Object.freeze(world.rows.map((row) => copyRow(row))),\n attribution: copyWorldAttribution(world.attribution),\n }),\n ),\n );\n}\n\nexport function inspectLodOcclusion(input: LodOcclusionInspectionInput): LodOcclusionInspection {\n const row = copyRow(input);\n const defaultBudget = createVisibilityBudget();\n const budget = input.budget ?? {\n configuredQueryBudget: defaultBudget.configuredQueryBudget,\n effectiveQueryBudget: defaultBudget.effectiveQueryBudget,\n settleSubmits: defaultBudget.settleSubmits,\n retestSubmits: defaultBudget.retestSubmits,\n expirySubmits: defaultBudget.expirySubmits,\n };\n for (const [name, value] of Object.entries(budget))\n nonNegativeInteger(`inspection.budget.${name}`, value);\n const submit = input.submit ?? {\n frameId: input.generation,\n build: 'unknown',\n deviceGeneration: 0,\n };\n nonNegativeInteger('inspection.submit.frameId', submit.frameId);\n nonNegativeInteger('inspection.submit.deviceGeneration', submit.deviceGeneration);\n if (typeof submit.build !== 'string' || submit.build.length === 0) {\n throw new Error('inspection.submit.build must be a non-empty string');\n }\n const worlds = copyWorlds(input.worlds, row);\n for (const world of worlds) {\n if (\n world.attribution.status === 'same-submit' &&\n (world.attribution.submit.frameId !== submit.frameId ||\n world.attribution.submit.build !== submit.build ||\n world.attribution.submit.deviceGeneration !== submit.deviceGeneration)\n ) {\n throw new Error('world attribution must reference the parent inspection submit');\n }\n }\n const inspection: LodOcclusionInspection = Object.freeze({\n schema: LOD_OCCLUSION_INSPECTION_SCHEMA,\n ...row,\n submit: Object.freeze({ ...submit }),\n budget: Object.freeze({ ...budget }),\n worlds,\n });\n if (JSON.stringify(inspection).length > LOD_OCCLUSION_INSPECTION_MAX_BYTES) {\n throw new Error(`LOD occlusion inspection exceeds ${LOD_OCCLUSION_INSPECTION_MAX_BYTES} bytes`);\n }\n return inspection;\n}\n\nexport function serializeLodOcclusionInspection(inspection: LodOcclusionInspection): string {\n const serialized = JSON.stringify(inspection);\n if (serialized.length > LOD_OCCLUSION_INSPECTION_MAX_BYTES) {\n throw new Error(`LOD occlusion inspection exceeds ${LOD_OCCLUSION_INSPECTION_MAX_BYTES} bytes`);\n }\n return serialized;\n}\n\nexport function consumeLodOcclusionInspection(\n inspection: LodOcclusionInspection,\n): LodOcclusionInspectionAction {\n if (!inspection.fallback.active) return { action: 'none' };\n const { reason, error } = inspection.fallback;\n const action =\n error.code.startsWith('asset-') || reason === 'producer-failed'\n ? 'rebuild'\n : reason === 'query-failed' || reason === 'page-exhausted' || reason === 'device-loss'\n ? 'retry'\n : 'cold-cook';\n return { action, sourceKey: inspection.root.sourceKey, reason };\n}\n","// @forgeax/engine-render - bounded SSR spatial inspection projection.\n\nimport type { ScreenSpaceReflectionData } from '../components/screen-space-reflection';\nimport type { ReflectionFallbackSource } from '../inspection-types';\nimport type { SsrSpatialAdmission, SsrSpatialLane, SsrSpatialWork } from './admission';\nimport type { SsrConfigInvalidError, SsrUnavailableError } from './errors';\nimport type { SsrHistoryState } from './history';\n\nexport type SsrSpatialInspectionFailure = SsrConfigInvalidError | SsrUnavailableError;\n\nexport interface SsrSpatialHistoryInspection {\n readonly state: 'not-owned' | SsrHistoryState;\n readonly bytes: number;\n readonly resetCount: number;\n}\n\nexport interface SsrSpatialInspectionProjection {\n readonly status?: SsrSpatialInspection['status'];\n readonly coverage?: Partial<SsrSpatialInspection['coverage']>;\n readonly history?: SsrSpatialHistoryInspection;\n readonly passRoster?: readonly string[];\n readonly fallbackSource?: ReflectionFallbackSource;\n readonly failure?: SsrSpatialInspectionFailure;\n}\n\n/** Keep the public projection bounded even if a graph owner supplies a bad list. */\nexport const SSR_INSPECTION_MAX_PASSES = 64 as const;\n\nfunction nonNegativeSafeInteger(name: string, value: number): number {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw new Error(`${name} must be a non-negative safe integer`);\n }\n return value;\n}\n\nfunction copyHistory(history: SsrSpatialHistoryInspection): SsrSpatialHistoryInspection {\n nonNegativeSafeInteger('SSR inspection history.bytes', history.bytes);\n nonNegativeSafeInteger('SSR inspection history.resetCount', history.resetCount);\n return Object.freeze({\n state: history.state,\n bytes: history.bytes,\n resetCount: history.resetCount,\n });\n}\n\nfunction copyCoverage(\n coverage: Partial<SsrSpatialInspection['coverage']> | undefined,\n): SsrSpatialInspection['coverage'] {\n const result = {\n hitCount: coverage?.hitCount ?? null,\n fallbackCount: coverage?.fallbackCount ?? null,\n excludedCount: coverage?.excludedCount ?? null,\n };\n for (const [key, value] of Object.entries(result)) {\n if (value !== null) nonNegativeSafeInteger(`SSR inspection coverage.${key}`, value);\n }\n return Object.freeze(result);\n}\n\nfunction copyPassRoster(passRoster: readonly string[] | undefined): readonly string[] {\n return Object.freeze(\n [...(passRoster ?? [])].slice(0, SSR_INSPECTION_MAX_PASSES).map((name, index) => {\n if (typeof name !== 'string' || name.length === 0) {\n throw new Error(`SSR inspection passRoster[${index}] must be a non-empty string`);\n }\n return name;\n }),\n );\n}\n\nexport interface SsrSpatialInspection {\n readonly status: 'not-requested' | 'requested' | 'admitted' | 'fallback-only' | 'structural-only';\n readonly lane: SsrSpatialLane;\n readonly config: ScreenSpaceReflectionData | undefined;\n readonly viewRange: number;\n readonly coverage: {\n /** Null means no GPU coverage measurement is available for this frame. */\n readonly hitCount: number | null;\n readonly fallbackCount: number | null;\n readonly excludedCount: number | null;\n };\n readonly history: SsrSpatialHistoryInspection;\n readonly work: SsrSpatialWork;\n readonly passRoster: readonly string[];\n readonly fallbackSource: ReflectionFallbackSource | undefined;\n readonly failure: SsrSpatialInspectionFailure | undefined;\n}\n\n/** Project only detached, bounded facts from the spatial admission result. */\nexport function projectSsrSpatialInspection(\n admission: SsrSpatialAdmission,\n projection: SsrSpatialInspectionProjection = {},\n): SsrSpatialInspection {\n const config = admission.config;\n return Object.freeze({\n status: projection.status ?? admission.status,\n lane: admission.lane,\n config:\n config === undefined\n ? undefined\n : Object.freeze({\n maxDistance: config.maxDistance,\n thickness: config.thickness,\n maxRoughness: config.maxRoughness,\n }),\n viewRange: admission.viewRange,\n coverage: copyCoverage(projection.coverage),\n history: copyHistory(\n projection.history ?? {\n state: 'not-owned' as const,\n bytes: 0,\n resetCount: 0,\n },\n ),\n work: Object.freeze({ ...admission.work }),\n passRoster: copyPassRoster(projection.passRoster),\n fallbackSource: projection.fallbackSource,\n failure: projection.failure ?? admission.failure,\n });\n}\n\nexport function serializeSsrSpatialInspection(inspection: SsrSpatialInspection): string {\n return JSON.stringify(inspection);\n}\n","import type { Handle, MeshAsset } from '@forgeax/engine-types';\nimport { err, ok, type Result } from '@forgeax/engine-types';\n\n/** A standard MeshAsset candidate prepared for one attached World generation. */\nexport interface DynamicGeometryPrepareInput {\n readonly world: object;\n /** Live ECS entity carrying MeshFilter + MeshRenderer on the attached World. */\n readonly entity?: number;\n /** Optional derived-physics entity whose fixed-step publication gates draw. */\n readonly physicsEntity?: number;\n readonly mesh: MeshAsset;\n /** Existing World.sharedRefs handle whose standard GPU residency is prepared. */\n readonly meshHandle?: Handle<'MeshAsset', 'shared'>;\n readonly revision: number;\n /** Material identity is a consumer fact; MaterialAsset stays in the World. */\n readonly materialIdentity?: string;\n /** Topology changes invalidate motion/history consumers. */\n readonly topologyRevision?: number;\n /** Captured by the Renderer host from the World FixedTime resource. */\n readonly fixedStep?: number;\n}\n\n/** Explicit ECS/fixed-step ordering proof used by Renderer admission. */\nexport interface DynamicGeometryOrdering {\n readonly world: object;\n readonly fixedStep: number;\n}\n\nexport type DynamicGeometryCandidateState =\n | 'prepared'\n | 'accepted'\n | 'published'\n | 'cancelled'\n | 'retired';\n\nexport interface DynamicGeometryCandidate {\n readonly candidateId: string;\n readonly generation: number;\n readonly owner: object;\n readonly world: object;\n readonly entity?: number;\n readonly physicsEntity?: number;\n /** False when the pure lifecycle was used without a shared MeshAsset handle. */\n readonly gpuReady: boolean;\n /** CPU/GPU geometry bytes reserved by this candidate budget. */\n readonly meshBytes: number;\n readonly revision: number;\n readonly topologyRevision: number;\n readonly materialIdentity?: string;\n readonly meshHandle?: Handle<'MeshAsset', 'shared'>;\n readonly fixedStep?: number;\n readonly mesh: MeshAsset;\n readonly state: DynamicGeometryCandidateState;\n}\n\n/** Record-stage lane that consumed a published dynamic-geometry candidate. */\nexport type DynamicGeometryRecordStageLane = 'cpu' | 'gpu' | 'mixed';\n\n/** Receipt that ties candidate publication to the sole Renderer FrameReceipt. */\nexport interface DynamicGeometryReceipt {\n readonly candidateId: string;\n readonly generation: number;\n readonly revision: number;\n readonly topologyRevision: number;\n readonly fixedStep?: number;\n readonly frameId: number;\n readonly deviceGeneration: number;\n readonly frame: {\n readonly frameId: number;\n readonly deviceGeneration: number;\n readonly completed?: Promise<unknown>;\n };\n /** Whether the Renderer record stage consumed this candidate for this frame. */\n readonly recordStageConsumed: boolean;\n /** Lane evidence from the exact submitted record stage, when attached. */\n readonly recordStageLane?: DynamicGeometryRecordStageLane;\n /** Actual frame fixed step; may be newer than the preparation step. */\n readonly publicationFixedStep?: number;\n}\n\nexport interface DynamicGeometryInspection {\n readonly generation: number;\n readonly prepared: number;\n readonly accepted: number;\n readonly published: number;\n readonly retired: number;\n readonly latestRevision?: number;\n readonly latestFrameId?: number;\n readonly historyInvalidations: number;\n readonly invalidated: number;\n readonly meshBytes: number;\n readonly maxMeshBytes: number;\n}\n\nexport type DynamicGeometryErrorCode =\n | 'dynamic-geometry-disposed'\n | 'dynamic-geometry-world-not-attached'\n | 'dynamic-geometry-invalid'\n | 'dynamic-geometry-gpu-failed'\n | 'dynamic-geometry-gpu-not-ready'\n | 'dynamic-geometry-budget-exceeded'\n | 'dynamic-geometry-stale'\n | 'dynamic-geometry-generation-mismatch'\n | 'dynamic-geometry-candidate-not-found'\n | 'dynamic-geometry-candidate-state'\n | 'dynamic-geometry-receipt-mismatch'\n | 'dynamic-geometry-ordering-required';\n\nexport interface DynamicGeometryErrorDetail {\n readonly code: DynamicGeometryErrorCode;\n readonly candidateId?: string;\n readonly revision?: number;\n readonly generation?: number;\n readonly actual?: unknown;\n}\n\nexport class DynamicGeometryError extends Error {\n readonly code: DynamicGeometryErrorCode;\n readonly expected: string;\n readonly hint: string;\n readonly detail: DynamicGeometryErrorDetail;\n\n constructor(\n code: DynamicGeometryErrorCode,\n expected: string,\n hint: string,\n detail: Omit<DynamicGeometryErrorDetail, 'code'> = {},\n ) {\n super(`${code}: ${expected}`);\n this.name = 'DynamicGeometryError';\n this.code = code;\n this.expected = expected;\n this.hint = hint;\n this.detail = Object.freeze({ code, ...detail });\n }\n}\n\ninterface CandidateRecord {\n readonly world: object;\n candidate: DynamicGeometryCandidate;\n /** Published history remains queryable for its completion fence, but a\n * newer topology must prevent that history from being consumed again. */\n historyInvalidated: boolean;\n acceptedFrame?: { readonly frameId: number; readonly deviceGeneration: number };\n}\n\n/**\n * A public candidate is a credential, not a mutable state object. Keep the\n * owner/world check in `current` cheap, then compare every scalar admission\n * fact before a caller can cancel, retire, or inspect another record by\n * copying its candidate id. The renderer-owned MeshAsset copy remains the\n * content source for the actual draw.\n */\nexport function sameCandidateCredential(\n candidate: DynamicGeometryCandidate,\n committed: DynamicGeometryCandidate,\n): boolean {\n return (\n candidate.candidateId === committed.candidateId &&\n candidate.owner === committed.owner &&\n candidate.world === committed.world &&\n candidate.generation === committed.generation &&\n candidate.entity === committed.entity &&\n candidate.physicsEntity === committed.physicsEntity &&\n candidate.gpuReady === committed.gpuReady &&\n candidate.meshBytes === committed.meshBytes &&\n candidate.revision === committed.revision &&\n candidate.topologyRevision === committed.topologyRevision &&\n candidate.materialIdentity === committed.materialIdentity &&\n candidate.meshHandle === committed.meshHandle &&\n candidate.fixedStep === committed.fixedStep\n );\n}\n\nfunction cloneTypedArray<T extends Float32Array | Uint16Array | Uint32Array>(value: T): T {\n return new (value.constructor as new (source: T) => T)(value);\n}\n\nfunction cloneMesh(mesh: MeshAsset): MeshAsset {\n const attributes = Object.fromEntries(\n Object.entries(mesh.attributes).map(([key, value]) => [\n key,\n value instanceof ArrayBuffer\n ? value.slice(0)\n : value === undefined\n ? undefined\n : cloneTypedArray(value as never),\n ]),\n ) as MeshAsset['attributes'];\n return Object.freeze({\n ...mesh,\n vertices: new Float32Array(mesh.vertices),\n ...(mesh.indices === undefined ? {} : { indices: cloneTypedArray(mesh.indices) }),\n attributes,\n ...(mesh.aabb === undefined ? {} : { aabb: new Float32Array(mesh.aabb) }),\n submeshes: Object.freeze(mesh.submeshes.map((submesh) => Object.freeze({ ...submesh }))),\n materialSlots: Object.freeze(mesh.materialSlots.map((slot) => Object.freeze({ ...slot }))),\n });\n}\n\nfunction cloneCandidate(candidate: DynamicGeometryCandidate): DynamicGeometryCandidate {\n return Object.freeze({ ...candidate, mesh: cloneMesh(candidate.mesh) });\n}\n\nfunction validateMesh(mesh: MeshAsset): string | undefined {\n if (mesh.kind !== 'mesh') return 'MeshAsset.kind must be mesh';\n if (!(mesh.vertices instanceof Float32Array) || mesh.vertices.length === 0) {\n return 'MeshAsset.vertices must be a non-empty Float32Array';\n }\n // vertices may be interleaved. Attribute layout validation belongs to the\n // mesh producer/residency path; this gate must not assume an xyz-only stride.\n if (\n mesh.indices !== undefined &&\n !(mesh.indices instanceof Uint16Array || mesh.indices instanceof Uint32Array)\n ) {\n return 'MeshAsset.indices must be Uint16Array or Uint32Array';\n }\n if (mesh.submeshes.length === 0)\n return 'MeshAsset.submeshes must contain at least one topology range';\n if (\n mesh.submeshes.some(\n (submesh) =>\n !Number.isSafeInteger(submesh.materialSlot) ||\n submesh.materialSlot < 0 ||\n submesh.materialSlot >= mesh.materialSlots.length,\n )\n ) {\n return 'MeshAsset.materialSlots must cover every referenced materialSlot';\n }\n if (mesh.vertices.some((value) => !Number.isFinite(value)))\n return 'MeshAsset.vertices must be finite';\n return undefined;\n}\n\nfunction meshByteSize(mesh: MeshAsset): number {\n let bytes = mesh.vertices.byteLength + (mesh.indices?.byteLength ?? 0);\n for (const value of Object.values(mesh.attributes)) {\n if (value instanceof ArrayBuffer) bytes += value.byteLength;\n else if (value !== undefined && ArrayBuffer.isView(value)) bytes += value.byteLength;\n }\n if (mesh.aabb !== undefined) bytes += mesh.aabb.byteLength;\n // Submesh/material metadata is intentionally bounded by the candidate\n // count. The reserved byte budget is for typed geometry and GPU upload\n // inputs, which are the resources that can exhaust the renderer.\n return bytes;\n}\n\n/**\n * Renderer-owned lifecycle for standard MeshAsset candidates. It deliberately\n * has no device, buffer, queue, or frame clock; the host supplies generation\n * and FrameReceipt facts at the boundaries below.\n */\nexport interface DynamicGeometryLifecycle {\n prepare(\n input: DynamicGeometryPrepareInput,\n generation: number,\n ): Result<DynamicGeometryCandidate, DynamicGeometryError>;\n accept(\n candidate: DynamicGeometryCandidate,\n ordering?: DynamicGeometryOrdering,\n ): Result<DynamicGeometryCandidate, DynamicGeometryError>;\n cancel(\n candidate: DynamicGeometryCandidate,\n completion?: Promise<unknown>,\n ): Result<void, DynamicGeometryError>;\n retire(candidate: DynamicGeometryCandidate): Result<void, DynamicGeometryError>;\n /** Release the count/byte budget after receipt-bound GPU cleanup completes. */\n finalizeRetirement(candidate: DynamicGeometryCandidate): Result<void, DynamicGeometryError>;\n receipt(candidate: DynamicGeometryCandidate): DynamicGeometryReceipt | undefined;\n publishFrame(\n frame: {\n readonly frameId: number;\n readonly deviceGeneration: number;\n readonly completed?: Promise<unknown>;\n },\n worlds?: readonly object[],\n fixedStep?: number,\n canPublish?: (candidate: DynamicGeometryCandidate) => boolean,\n recordStageLane?: (\n candidate: DynamicGeometryCandidate,\n ) => DynamicGeometryRecordStageLane | undefined,\n ): readonly DynamicGeometryReceipt[];\n invalidateWorld(world: object, completion?: Promise<unknown>): void;\n invalidateGeneration(generation: number): void;\n inspect(): DynamicGeometryInspection;\n dispose(): void;\n}\n\nexport function createDynamicGeometryLifecycle(\n maxCandidates = 32,\n maxMeshBytes = 64 * 1024 * 1024,\n): DynamicGeometryLifecycle {\n const records = new Map<string, CandidateRecord>();\n const owner = {};\n let sequence = 0;\n let currentGeneration = 0;\n let disposed = false;\n let historyInvalidations = 0;\n let latestRevision: number | undefined;\n let latestFrameId: number | undefined;\n let retired = 0;\n let invalidated = 0;\n let meshBytes = 0;\n const latestRevisionByWorld = new WeakMap<object, Map<number | undefined, number>>();\n const latestTopologyRevisionByWorld = new WeakMap<object, Map<number | undefined, number>>();\n const publishedReceipts = new Map<string, DynamicGeometryReceipt>();\n\n const failure = (\n code: DynamicGeometryErrorCode,\n expected: string,\n hint: string,\n detail: Omit<DynamicGeometryErrorDetail, 'code'> = {},\n ): Result<never, DynamicGeometryError> =>\n err(new DynamicGeometryError(code, expected, hint, detail));\n\n const current = (candidate: DynamicGeometryCandidate): CandidateRecord | undefined => {\n const record = records.get(candidate.candidateId);\n if (\n record === undefined ||\n candidate.owner !== owner ||\n record.candidate.owner !== candidate.owner ||\n record.candidate.world !== candidate.world ||\n record.candidate.generation !== candidate.generation\n )\n return undefined;\n return record;\n };\n\n return {\n prepare(input, generation) {\n if (disposed)\n return failure('dynamic-geometry-disposed', 'renderer is alive', 'rebuild the Renderer');\n if (input.world === null || typeof input.world !== 'object') {\n return failure(\n 'dynamic-geometry-world-not-attached',\n 'candidate belongs to an attached World',\n 'attach the World before preparing geometry',\n );\n }\n if (!Number.isInteger(input.revision) || input.revision < 0) {\n return failure(\n 'dynamic-geometry-invalid',\n 'geometry revision is a non-negative integer',\n 'advance the consumer revision monotonically',\n { revision: input.revision },\n );\n }\n if (generation !== currentGeneration && currentGeneration !== 0) {\n return failure(\n 'dynamic-geometry-generation-mismatch',\n 'candidate uses the active renderer generation',\n 'discard stale generation work and prepare again',\n { generation, actual: currentGeneration },\n );\n }\n if (records.size >= maxCandidates) {\n return failure(\n 'dynamic-geometry-budget-exceeded',\n 'candidate count remains within the bounded renderer budget',\n 'cancel or retire an earlier candidate before retrying',\n { actual: records.size },\n );\n }\n const invalid = validateMesh(input.mesh);\n if (invalid !== undefined)\n return failure(\n 'dynamic-geometry-invalid',\n 'MeshAsset satisfies the standard geometry contract',\n invalid,\n );\n const candidateBytes = meshByteSize(input.mesh);\n if (\n !Number.isSafeInteger(candidateBytes) ||\n candidateBytes < 0 ||\n meshBytes > maxMeshBytes - candidateBytes\n ) {\n return failure(\n 'dynamic-geometry-budget-exceeded',\n 'candidate mesh bytes remain within the bounded renderer resource budget',\n 'cancel or retire an earlier candidate before retrying',\n { actual: { meshBytes, candidateBytes, maxMeshBytes } },\n );\n }\n const candidateId = `mesh:${generation}:${++sequence}:${input.revision}`;\n const candidate: DynamicGeometryCandidate = Object.freeze({\n candidateId,\n generation,\n owner,\n world: input.world,\n ...(input.entity === undefined ? {} : { entity: input.entity }),\n ...(input.physicsEntity === undefined ? {} : { physicsEntity: input.physicsEntity }),\n gpuReady: input.meshHandle !== undefined,\n meshBytes: candidateBytes,\n revision: input.revision,\n topologyRevision: input.topologyRevision ?? input.revision,\n ...(input.materialIdentity === undefined\n ? {}\n : { materialIdentity: input.materialIdentity }),\n ...(input.meshHandle === undefined ? {} : { meshHandle: input.meshHandle }),\n ...(input.fixedStep === undefined ? {} : { fixedStep: input.fixedStep }),\n mesh: cloneMesh(input.mesh),\n state: 'prepared',\n });\n records.set(candidateId, {\n world: input.world,\n candidate,\n historyInvalidated: false,\n });\n meshBytes += candidateBytes;\n currentGeneration = generation;\n // Keep the credential handed to the consumer separate from the\n // renderer-owned copy. Mesh typed arrays remain mutable at runtime even\n // when exposed through a readonly TypeScript field.\n return ok(cloneCandidate(candidate));\n },\n accept(candidate, ordering) {\n if (disposed)\n return failure('dynamic-geometry-disposed', 'renderer is alive', 'rebuild the Renderer');\n const record = current(candidate);\n if (record === undefined)\n return failure(\n 'dynamic-geometry-candidate-not-found',\n 'candidate is owned by this renderer',\n 'discard the stale credential',\n );\n if (candidate.generation !== currentGeneration) {\n return failure(\n 'dynamic-geometry-generation-mismatch',\n 'candidate generation matches the active renderer generation',\n 'prepare against the current renderer generation',\n { candidateId: candidate.candidateId },\n );\n }\n if (record.candidate.state !== 'prepared') {\n return failure(\n 'dynamic-geometry-candidate-state',\n 'candidate is prepared exactly once before acceptance',\n 'retain the accepted or published receipt',\n { candidateId: candidate.candidateId },\n );\n }\n if (!sameCandidateCredential(candidate, record.candidate)) {\n return failure(\n 'dynamic-geometry-receipt-mismatch',\n 'acceptance uses the exact prepared candidate credential',\n 'discard the altered credential and use the value returned by prepare',\n { candidateId: candidate.candidateId },\n );\n }\n if (ordering !== undefined) {\n if (\n ordering.world !== record.world ||\n !Number.isInteger(ordering.fixedStep) ||\n ordering.fixedStep < 0\n ) {\n return failure(\n 'dynamic-geometry-ordering-required',\n 'acceptance ordering names the candidate World and a non-negative fixed step',\n 'submit the PhysicsWorld publication ordering for the same attached World',\n { candidateId: candidate.candidateId, actual: ordering },\n );\n }\n }\n const newest = [...records.values()]\n .filter(\n (entry) =>\n entry.candidate.candidateId !== candidate.candidateId &&\n entry.world === record.world &&\n entry.candidate.entity === record.candidate.entity &&\n (entry.candidate.state === 'prepared' || entry.candidate.state === 'accepted'),\n )\n .map((entry) => entry.candidate.revision)\n .concat(latestRevisionByWorld.get(record.world)?.get(record.candidate.entity) ?? -1)\n .sort((a, b) => b - a)[0];\n if (newest !== undefined && record.candidate.revision <= newest) {\n return failure(\n 'dynamic-geometry-stale',\n 'accepted geometry revision is newer than the active candidate',\n 'advance topology revision before accepting',\n { candidateId: candidate.candidateId },\n );\n }\n const accepted = Object.freeze({\n ...record.candidate,\n ...(ordering === undefined ? {} : { fixedStep: ordering.fixedStep }),\n state: 'accepted' as const,\n });\n const previousTopologies = [...records.values()]\n .filter(\n (entry) =>\n entry.candidate.candidateId !== candidate.candidateId &&\n entry.world === record.world &&\n entry.candidate.entity === record.candidate.entity,\n )\n .map((entry) => entry.candidate.topologyRevision);\n const previousLatestTopology = latestTopologyRevisionByWorld\n .get(record.world)\n ?.get(record.candidate.entity);\n const newestTopology = previousTopologies\n .concat(previousLatestTopology === undefined ? [] : [previousLatestTopology])\n .sort((a, b) => b - a)[0];\n if (newestTopology !== undefined && accepted.topologyRevision < newestTopology) {\n return failure(\n 'dynamic-geometry-stale',\n 'accepted topology revision is not older than the active geometry history',\n 'advance topology revision before accepting a replacement candidate',\n { candidateId: candidate.candidateId },\n );\n }\n if (newestTopology !== undefined && accepted.topologyRevision > newestTopology) {\n historyInvalidations += 1;\n // Invalidate publication eligibility, not resource ownership. The host\n // cancels superseded candidates with their allocation completion fence.\n for (const previous of records.values()) {\n if (\n previous.world !== record.world ||\n previous.candidate.entity !== record.candidate.entity ||\n previous.candidate.candidateId === candidate.candidateId ||\n previous.candidate.topologyRevision >= accepted.topologyRevision\n )\n continue;\n if (!previous.historyInvalidated) {\n previous.historyInvalidated = true;\n invalidated += 1;\n }\n }\n }\n record.candidate = accepted;\n return ok(cloneCandidate(accepted));\n },\n cancel(candidate, completion) {\n const record = current(candidate);\n if (record === undefined)\n return failure(\n 'dynamic-geometry-candidate-not-found',\n 'candidate is owned by this renderer',\n 'discard the stale credential',\n );\n if (!sameCandidateCredential(candidate, record.candidate))\n return failure(\n 'dynamic-geometry-receipt-mismatch',\n 'cancellation uses the exact prepared candidate credential',\n 'discard the altered credential and use the value returned by prepare',\n { candidateId: candidate.candidateId },\n );\n if (record.candidate.state !== 'prepared' && record.candidate.state !== 'accepted') {\n return failure(\n 'dynamic-geometry-candidate-state',\n 'only prepared or accepted geometry can be cancelled once',\n 'retire published geometry or await the existing terminal cleanup',\n );\n }\n record.candidate = Object.freeze({ ...record.candidate, state: 'cancelled' as const });\n const release = (): void => {\n if (records.get(candidate.candidateId) !== record) return;\n records.delete(candidate.candidateId);\n meshBytes = Math.max(0, meshBytes - record.candidate.meshBytes);\n };\n if (completion === undefined) release();\n else void completion.then(release, release);\n return ok(undefined);\n },\n retire(candidate) {\n const record = current(candidate);\n if (record === undefined)\n return failure(\n 'dynamic-geometry-candidate-not-found',\n 'retirement uses a published candidate owned by this renderer',\n 'discard the stale credential and do not evict any unrelated mesh',\n { candidateId: candidate.candidateId },\n );\n if (!sameCandidateCredential(candidate, record.candidate))\n return failure(\n 'dynamic-geometry-receipt-mismatch',\n 'retirement uses the exact published candidate credential',\n 'discard the altered credential and use the value returned by publish',\n { candidateId: candidate.candidateId },\n );\n if (record.candidate.state !== 'published') {\n return failure(\n 'dynamic-geometry-candidate-state',\n 'only published geometry can enter receipt-bound retirement',\n 'publish the candidate from a submitted frame first',\n );\n }\n record.candidate = Object.freeze({ ...record.candidate, state: 'retired' as const });\n publishedReceipts.delete(candidate.candidateId);\n retired += 1;\n // Retiring is the logical state transition. Keep the candidate record\n // and its typed bytes until the owner calls `finalizeRetirement` after\n // every record-stage completion fence and GPU lease are gone. This is\n // what makes the declared count/byte budget include in-flight work.\n return ok(undefined);\n },\n finalizeRetirement(candidate) {\n const record = current(candidate);\n if (record === undefined)\n return failure(\n 'dynamic-geometry-candidate-not-found',\n 'retirement finalization uses a candidate retained by this lifecycle',\n 'discard the stale credential or finish the current receipt-bound retirement',\n );\n if (!sameCandidateCredential(candidate, record.candidate))\n return failure(\n 'dynamic-geometry-receipt-mismatch',\n 'retirement finalization uses the exact published candidate credential',\n 'discard the altered credential and use the value returned by publication',\n { candidateId: candidate.candidateId },\n );\n if (record.candidate.state !== 'retired')\n return failure(\n 'dynamic-geometry-candidate-state',\n 'only a retired candidate can release its deferred budget',\n 'retire the published candidate before finalizing its receipt-bound cleanup',\n { candidateId: candidate.candidateId },\n );\n records.delete(candidate.candidateId);\n meshBytes = Math.max(0, meshBytes - record.candidate.meshBytes);\n return ok(undefined);\n },\n publishFrame(frame, worlds, fixedStep, canPublish, recordStageLane) {\n if (disposed || frame.deviceGeneration !== currentGeneration) return [];\n const receipts: DynamicGeometryReceipt[] = [];\n for (const record of records.values()) {\n const canRepeatPublished =\n record.candidate.state === 'published' &&\n // Attached Renderer publication revalidates the entity binding in\n // `canPublish`, so a history-invalidated candidate can still record\n // a real draw for its live entity. Detached lifecycle publication\n // remains one-shot once that history is invalidated.\n (canPublish !== undefined || !record.historyInvalidated);\n if (record.candidate.state !== 'accepted' && !canRepeatPublished) continue;\n if (worlds !== undefined && !worlds.includes(record.world)) continue;\n if (\n record.candidate.fixedStep !== undefined &&\n (fixedStep === undefined || record.candidate.fixedStep > fixedStep)\n ) {\n continue;\n }\n if (canPublish !== undefined && !canPublish(record.candidate)) continue;\n const consumedLane =\n canPublish === undefined ? undefined : recordStageLane?.(record.candidate);\n record.candidate = Object.freeze({ ...record.candidate, state: 'published' as const });\n const receipt = Object.freeze({\n candidateId: record.candidate.candidateId,\n generation: record.candidate.generation,\n revision: record.candidate.revision,\n topologyRevision: record.candidate.topologyRevision,\n ...(record.candidate.fixedStep === undefined\n ? {}\n : { fixedStep: record.candidate.fixedStep }),\n frameId: frame.frameId,\n deviceGeneration: frame.deviceGeneration,\n recordStageConsumed: canPublish !== undefined,\n ...(consumedLane === undefined ? {} : { recordStageLane: consumedLane }),\n ...(fixedStep === undefined ? {} : { publicationFixedStep: fixedStep }),\n frame: Object.freeze({ ...frame }),\n });\n receipts.push(receipt);\n publishedReceipts.set(record.candidate.candidateId, receipt);\n latestRevision = record.candidate.revision;\n latestFrameId = frame.frameId;\n if (!latestRevisionByWorld.has(record.world))\n latestRevisionByWorld.set(record.world, new Map());\n latestRevisionByWorld\n .get(record.world)\n ?.set(record.candidate.entity, record.candidate.revision);\n if (!latestTopologyRevisionByWorld.has(record.world))\n latestTopologyRevisionByWorld.set(record.world, new Map());\n latestTopologyRevisionByWorld\n .get(record.world)\n ?.set(record.candidate.entity, record.candidate.topologyRevision);\n }\n return receipts;\n },\n invalidateWorld(world, completion) {\n for (const [id, record] of records) {\n if (record.world !== world) continue;\n // An earlier terminal operation already owns this reservation's fence.\n if (record.candidate.state === 'cancelled' || record.candidate.state === 'retired')\n continue;\n publishedReceipts.delete(id);\n record.candidate = Object.freeze({ ...record.candidate, state: 'cancelled' as const });\n const release = (): void => {\n if (records.get(id) !== record) return;\n records.delete(id);\n meshBytes = Math.max(0, meshBytes - record.candidate.meshBytes);\n };\n if (completion === undefined) release();\n else void completion.then(release, release);\n invalidated += 1;\n }\n latestRevisionByWorld.delete(world);\n latestTopologyRevisionByWorld.delete(world);\n },\n invalidateGeneration(generation) {\n if (generation === currentGeneration) return;\n currentGeneration = generation;\n const invalidatedWorlds = new Set<object>();\n for (const [id, record] of records) {\n if (record.candidate.generation !== generation) {\n records.delete(id);\n publishedReceipts.delete(id);\n meshBytes = Math.max(0, meshBytes - record.candidate.meshBytes);\n invalidatedWorlds.add(record.world);\n invalidated += 1;\n }\n }\n for (const world of invalidatedWorlds) {\n latestRevisionByWorld.delete(world);\n latestTopologyRevisionByWorld.delete(world);\n }\n },\n receipt(candidate) {\n const receipt = publishedReceipts.get(candidate.candidateId);\n const record = records.get(candidate.candidateId);\n if (record === undefined || !sameCandidateCredential(candidate, record.candidate)) {\n return undefined;\n }\n return receipt?.generation === candidate.generation ? receipt : undefined;\n },\n inspect() {\n let prepared = 0;\n let accepted = 0;\n let published = 0;\n for (const record of records.values()) {\n if (record.candidate.state === 'prepared') prepared += 1;\n else if (record.candidate.state === 'accepted') accepted += 1;\n else if (record.candidate.state === 'published') published += 1;\n }\n return Object.freeze({\n generation: currentGeneration,\n prepared,\n accepted,\n published,\n retired,\n ...(latestRevision === undefined ? {} : { latestRevision }),\n ...(latestFrameId === undefined ? {} : { latestFrameId }),\n historyInvalidations,\n invalidated,\n meshBytes,\n maxMeshBytes,\n });\n },\n dispose() {\n disposed = true;\n records.clear();\n publishedReceipts.clear();\n meshBytes = 0;\n },\n };\n}\n","import type { Handle } from '@forgeax/engine-types';\nimport type { ExtractedFrame, RenderableSnapshot } from '../render-system-extract';\n\n/** One asset closure for source publication and receiver admission. */\nexport function publicationDependencies(\n row: Pick<RenderableSnapshot, 'assetHandle' | 'materials'>,\n): Handle<string, 'shared'>[] {\n const handles = new Set<Handle<string, 'shared'>>([row.assetHandle as Handle<string, 'shared'>]);\n for (const material of row.materials) {\n for (const handle of [\n material.materialHandle,\n material.baseColorTexture,\n material.metallicRoughnessTexture,\n material.normalTexture,\n material.emissiveTexture,\n material.occlusionTexture,\n ]) {\n if (handle) handles.add(handle as Handle<string, 'shared'>);\n }\n for (const handle of material.textureHandles?.values() ?? []) handles.add(handle);\n for (const handle of material.samplerHandles?.values() ?? []) handles.add(handle);\n }\n return [...handles];\n}\n\n/** Resources selected once for the frame rather than attached to geometry. */\nexport function publicationFrameDependencies(\n frame: Pick<\n ExtractedFrame,\n 'cameras' | 'auxiliaryCameras' | 'skylight' | 'skybox' | 'lights' | 'volumetricFog'\n >,\n): Handle<string, 'shared'>[] {\n const handles = new Set<Handle<string, 'shared'>>();\n const add = (handle: number | undefined) => {\n if (handle) handles.add(handle as Handle<string, 'shared'>);\n };\n add(frame.skylight?.equirectHandle);\n add(frame.skybox?.equirectHandle);\n for (const camera of [...frame.cameras, ...frame.auxiliaryCameras]) add(camera.output?.colorLut);\n for (const light of frame.lights.spot) {\n add(light.iesProfileHandle);\n add(light.cookieHandle);\n add(light.projectorHandle);\n }\n const fogs =\n frame.volumetricFog === undefined\n ? []\n : [frame.volumetricFog, ...(frame.volumetricFog.additional ?? [])];\n for (const fog of fogs) {\n add(fog.densityHandle);\n add(fog.projectorHandle);\n }\n return [...handles];\n}\n","// @forgeax/engine-runtime - tilemap-chunk-extract-system.\n//\n// Walks every TileLayer attached to a Tilemap via ChildOf; when a layer is\n// dirty (or has never been extracted), purges its previously-spawned derived\n// per-cell entities and re-spawns one ECS entity per non-zero cell. Each\n// derived entity carries Transform + MeshFilter (HANDLE_QUAD) + MeshRenderer\n// + Layer + ChildOf { parent: layerEntity }. The ChildOf edge lets\n// `world.despawn(tilemapEntity)` cascade-despawn the entire subtree\n// (Tilemap -> TileLayer -> derived render entities) via the engine's\n// default `linkedSpawn: true` (tweak-20260714 M2, requirements AC-02/03/04).\n//\n// M0 baseline: unit-cell 1x1 form, single-atlas, no UV inset.\n// M2 extension (plan-strategy §D-2 + §D-7 step 3):\n// M3 extension (plan-strategy §D-7 step 2 + §D-12):\n// - resolveTilesetMaterial walks the 3-hop chain\n// `tile.regionIndex -> regions[i].atlasIndex ?? 0 -> atlases[idx]`\n// so multi-atlas tilesets route each region to the correct GPU\n// texture handle (requirements AC-04 / AC-11). Cache key stays\n// binary `(atlasHandle, regionIndex)` -- atlasHandle already\n// encodes the atlas pick.\n// - spawnDerivedRenderEntities scales the quad by widthCells x\n// heightCells (defaults 1 x 1) and offsets the centre so the pivot\n// lands at the (pivotX, pivotY) location inside the anchor cell.\n// - basePivotForX = D ? pivotY : pivotX (and dually for Y), so the\n// 90deg CW z-rotation correctly swaps which atlas-axis pivot maps\n// to which world axis.\n// - effectivePivotX = H ? (1 - basePivotForX) : basePivotForX (and\n// dually for Y). The anchor pivot under H flip lands at the\n// mirrored cell position (charter P4 - same semantics as Tiled's\n// \"pivot stays in atlas-local coords, flips with the texel grid\").\n// - posX = (cellX + effectivePivotX + (0.5 - effectivePivotX) * widthCells)\n// * tileSizeX\n// posY analogous with effectivePivotY + heightCells.\n// - scaleX/scaleY: signed by H/V flip; magnitude is widthCells *\n// tileSizeX / heightCells * tileSizeY (multi-cell scale).\n// - resolveTilesetMaterial inset-shrinks the region UV rectangle by\n// half a texel on every edge so GPU bilinear filtering at the\n// atlas-tile boundary never bleeds into the adjacent tile\n// (charter P3 - default behaviour avoids visual defects).\n//\n// M3 boundary: per-entity sort key with effectivePivotY is wired in\n// render-system-extract (m3-t5), not here.\n//\n// Cache key for resolveTilesetMaterial is BINARY: (atlasHandle, regionIndex).\n// AI users widthCells / pivot variations share the same material handle\n// (charter P4 consistent abstraction; plan-strategy §D-9 / §D-12).\n//\n// Anchors: plan-tasks m0-t10 / m2-t2 / m2-t4; plan-strategy §D-1 +\n// §D-2 (multi-cell + flip x pivot) + §D-5 (M0 baseline file-by-file\n// ECS API adaptation) + §D-7 step 3 (half-texel UV inset).\n\nimport {\n HANDLE_QUAD,\n resolveTilesetRuntime,\n type TilesetAtlasLookup,\n} from '@forgeax/engine-assets-runtime';\nimport type { EntityHandle, World } from '@forgeax/engine-ecs';\nimport { decodeTileBits } from '@forgeax/engine-graphics-extras';\nimport { type box3, frustum, mat4 } from '@forgeax/engine-math';\nimport { ChildOf, Children, GlobalTransform, Transform } from '@forgeax/engine-scene';\nimport {\n type Handle,\n type MaterialAsset,\n type TilesetAsset,\n type TilesetRegion,\n type TilesetTileEntry,\n toShared,\n unwrapHandle,\n} from '@forgeax/engine-types';\nimport {\n CAMERA_PROJECTION_ORTHOGRAPHIC,\n Camera,\n decodeSortScope,\n Layer,\n MeshFilter,\n MeshRenderer,\n type SortScope,\n SpriteInstances,\n TileLayer,\n Tilemap,\n} from './components';\nimport { SPRITE_PREMULTIPLIED_ALPHA_BLEND } from './materials';\n\n// Module-scoped caches (charter P5 — engine-side memoisation; AI users\n// never reach in). Test harness can flush them via the reset helpers.\n//\n// Two material caches coexist because the extract system produces two\n// kinds of derived entities, each with a different material-key granularity:\n//\n// 1. `atlasMaterialCache` — key `${atlasId}|${regionIndex}` → per-region\n// material with the UV rectangle baked into `values.region`.\n// Used by the per-cell entity path (sortScope='per-cell' object\n// layers). Each tile graphic gets a distinct MaterialAsset.\n//\n// 2. `atlasOnlyMaterialCache` — key `${atlasId}` → per-atlas material\n// with `values.region: [0,0,1,1]` placeholder. Used by the\n// SpriteInstances batched path (sortScope='layer' terrain layers).\n// The shader's PER_INSTANCE_REGION=true variant reads per-instance\n// UV from the instance buffer, not from the material UBO, so the\n// placeholder is ignored at draw time.\nlet atlasMaterialCache = new WeakMap<World, Map<string, Handle<'MaterialAsset', 'shared'>>>();\nlet atlasOnlyMaterialCache = new WeakMap<World, Map<string, Handle<'MaterialAsset', 'shared'>>>();\n// tweak-20260714 M3 (plan-strategy §2 D-3): the terrain (sortScope='layer')\n// derived-entity tracker Map + first-frame-heuristic Set that used to live\n// alongside these material caches were retired once every derived entity\n// was attached as `ChildOf` child of its TileLayer (M2). The reverse\n// mirror `Children.entities` on the TileLayer is now the SSOT for\n// \"which derived entities belong to this layer\" — engine-maintained on\n// `world.addComponent(ChildOf) / world.despawn`, deriving-not-duplicating\n// (architecture-principles §2). `purgeDerivedEntities` reads that mirror\n// directly; the \"already built\" gate uses `Children.entities.length > 0`,\n// which naturally handles both first frames (empty ⇒ rebuild) and steady\n// state (populated ⇒ skip) without a second parallel ledger.\n\n// ─── Chunk-streaming state for sortScope='per-cell' (object) layers ───────\n//\n// Object layers stream per-chunk: only chunks whose world AABB intersects the\n// camera frustum have per-cell entities alive in the ECS world. This keeps\n// extractFrame's entity count proportional to visible tile count rather than\n// total map tile count (charter P5: engine-side memoisation / streaming).\n//\n// Design: one WeakMap entry per World owns three bounded maps:\n// layers : layerKey → pre-bucketed specs by chunkIndex (built once\n// from bucketTileLayer, rebuilt on dirty). Avoids re-reading\n// the full tileset and re-materialising every frame.\n// chunkEntities : \"${layerKey}:${chunkIdx}\" → spawned entity ids\n// for that chunk (purged when chunk leaves frustum).\n// activeChunks : layerKey → Set<chunkIdx> currently spawned.\n//\n// bug-20260703-tilemap-chunk-stale-frustum-and-cull-overhang (D2): each entry\n// stores the ACTUAL world-space bounding box (union of every tile's post-TRS\n// footprint from `computeTileTrs`) rather than a tile-aligned grid box.\n// Multi-cell tiles (`widthCells` / `heightCells > 1`) and non-central pivots\n// let a tile extend beyond its anchor chunk's grid; the grid box would\n// despawn the anchor chunk while overhanging tiles were still on screen,\n// causing edge-of-chunk flicker as the camera pans. Bounds are computed once\n// per (dirty | first-time) rebuild, so the per-frame visibility test stays a\n// single `frustum.intersectsBox` call (plan-strategy §2 D-3).\ninterface ChunkStreamEntry {\n readonly specs: readonly DerivedSpawnSpec[];\n readonly bounds: box3.Box3Like;\n}\ninterface StreamLayerCache {\n readonly byChunk: ReadonlyMap<number, ChunkStreamEntry>;\n readonly tilemap: {\n readonly cols: number;\n readonly rows: number;\n readonly tileSize: ArrayLike<number>;\n readonly chunkSize: number;\n };\n readonly layerOrder: number;\n readonly sortScope: SortScope;\n}\ninterface PerWorldStreamingCache {\n readonly layers: Map<string, StreamLayerCache>;\n readonly chunkEntities: Map<string, EntityHandle[]>;\n readonly activeChunks: Map<string, Set<number>>;\n}\n\nlet streamingCacheByWorld = new WeakMap<World, PerWorldStreamingCache>();\n\nfunction streamingCache(world: World): PerWorldStreamingCache {\n let cache = streamingCacheByWorld.get(world);\n if (cache === undefined) {\n cache = {\n layers: new Map(),\n chunkEntities: new Map(),\n activeChunks: new Map(),\n };\n streamingCacheByWorld.set(world, cache);\n }\n return cache;\n}\n\n/**\n * Flush both material caches. Useful in test harnesses + after a\n * TilesetAsset reload.\n */\nexport function resetTilemapChunkExtractCache(): void {\n atlasMaterialCache = new WeakMap<World, Map<string, Handle<'MaterialAsset', 'shared'>>>();\n atlasOnlyMaterialCache = new WeakMap<World, Map<string, Handle<'MaterialAsset', 'shared'>>>();\n}\n\n/**\n * Flush the per-cell streaming caches. Useful in test harnesses + when\n * the World is re-created.\n *\n * Signature preserved (AC-08 hard constraint) after tweak-20260714 M3\n * retired the terrain-side tracker Map + first-frame heuristic Set:\n * terrain layers now derive their \"already-built\" state from\n * `Children.entities` on the TileLayer (mirror of ChildOf, engine-\n * maintained), so the tracker only needs to clear the 3 streaming\n * caches (plan-strategy §2 D-3 + §2 D-5).\n */\nexport function resetTilemapDerivedEntityTracker(): void {\n streamingCacheByWorld = new WeakMap<World, PerWorldStreamingCache>();\n}\n\n/**\n * @internal Test-only helper for AC-11 (tweak-20260714 M4). Returns the\n * union of `layerKey`s currently referenced by the three per-cell\n * streaming caches. Post-diff-cleanup, an evicted layerKey MUST NOT\n * appear here; a slot subsequently reused for a fresh TileLayer sees\n * empty caches and rebuilds from zero (plan-strategy §2 D-4).\n *\n * Parsing the per-World `chunkEntities` key format `${entity}:${chunkIdx}`\n * is intentional so callers observe cleanup on all three maps without\n * depending on the invariant `activeSet ↔ chunkEntities\n * keys are paired` — the test then also cross-checks that invariant.\n */\nexport function _peekPerCellStreamingLayerKeys(world: World): readonly number[] {\n const cache = streamingCacheByWorld.get(world);\n if (cache === undefined) return [];\n const out = new Set<number>();\n for (const layerKey of cache.layers.keys()) {\n if (Number.isFinite(Number(layerKey))) out.add(Number(layerKey));\n }\n for (const layerKey of cache.activeChunks.keys()) {\n if (Number.isFinite(Number(layerKey))) out.add(Number(layerKey));\n }\n for (const key of cache.chunkEntities.keys()) {\n const parts = key.split(':');\n const entity = parts[0];\n if (entity !== undefined && Number.isFinite(Number(entity))) out.add(Number(entity));\n }\n return Array.from(out);\n}\n\n/**\n * Compute the per-layer / per-chunk packed value carried in `Layer.value`\n * on derived entities. `sortScope` is the closed string union from\n * `TileLayer.sortScope`:\n * - `'layer'` (default): `(layerOrder << 20) | (chunkIndex & 0xFFFFF)` —\n * terrain semantics, layerOrder dominates with chunkIndex\n * tiebreak within the layer.\n * - `'per-cell'`: returns `(layerOrder << 20)` (chunkIndex folded to 0)\n * so every derived entity in the layer shares one\n * Layer.value and can Y-interleave with sprite entities\n * carrying the same value (e.g. a player sprite riding\n * `SPRITE_LAYER_VALUE = layerOrder << 20`).\n *\n * Round-2 rename (D-V-3): the third arg was `ySort: boolean` before the\n * sortScope union landed; it is now the closed `SortScope` union with\n * default `'layer'`. The 0x200000 / chunked-bits semantics for the two\n * arms are preserved exactly so existing pixel-parity baselines stay\n * stable (only the AI-user surface widens to a self-documenting literal).\n */\nexport function encodeTilemapLayerValue(\n layerOrder: number,\n chunkIndex: number,\n sortScope: SortScope = 'layer',\n): number {\n if (sortScope === 'per-cell') return (layerOrder << 20) | 0;\n return (layerOrder << 20) | (chunkIndex & 0xfffff) | 0;\n}\n\n/**\n * Resolve (regionIndex) into a per-tile sprite material handle by walking\n * the 3-hop chain:\n *\n * tile.regionIndex -> regions[regionIndex] -> region.atlasIndex ?? 0\n * -> atlases[atlasIndex]\n *\n * (plan-strategy §D-7 step 2 + requirements §AC-04 / §AC-11). Caches the\n * resulting MaterialAsset handle so repeated lookups hit a single\n * registered material per atlas-region pair; the cache key stays the\n * binary tuple `(atlasHandle, regionIndex)` -- atlasHandle already\n * encodes the atlasIndex pick so widening to a 3-tuple key would only\n * inflate the SSOT without adding signal (charter P4 + plan-strategy\n * §D-12). atlasIndex out-of-range is caught at register time by\n * `validateTilesetPayload` (m1-t6); the runtime resolver falls through\n * to handle 0 when an atlas slot is unexpectedly empty so the renderer\n * skips the draw rather than silently sampling the wrong texture\n * (charter P3 fail-safe).\n *\n * The shader is `forgeax::sprite`; values are filled with the atlas\n * texture handle + a UV region rectangle covering the supplied\n * TilesetRegion (half-texel inset added in m2-t4).\n */\nfunction resolveTilesetMaterial(\n world: World,\n tileset: TilesetAsset,\n regionIndex: number,\n lookup: (guid: string) => TilesetAtlasLookup,\n): Handle<'MaterialAsset', 'shared'> {\n const region = tileset.regions[regionIndex];\n if (region === undefined) return toShared<'MaterialAsset'>(0);\n // 3-hop walk: regions[i].atlasIndex (default 0) -> atlases[atlasIndex].\n // atlasIndex out-of-range is register-time fail-fast via\n // `validateTilesetPayload` (m1-t6); the runtime resolver still bails\n // when the slot is unexpectedly empty (charter P3 fail-safe).\n const atlasIndex = region.atlasIndex ?? 0;\n const atlasGuid = tileset.atlases[atlasIndex];\n if (atlasGuid === undefined) return toShared<'MaterialAsset'>(0);\n const atlas = resolveTilesetRuntime(world, atlasGuid, lookup);\n if (!atlas.ok) return toShared<'MaterialAsset'>(0);\n const atlasHandle = atlas.value.handle;\n const atlasId = unwrapHandle(atlasHandle);\n const cacheKey = `${atlasId}|${regionIndex}`;\n const cache =\n atlasMaterialCache.get(world) ?? new Map<string, Handle<'MaterialAsset', 'shared'>>();\n atlasMaterialCache.set(world, cache);\n const cached = cache.get(cacheKey);\n if (cached !== undefined) return cached;\n\n // Atlas-space rectangle -> normalised UV. M2 adds a half-texel inset\n // on every edge (plan-strategy §D-7 step 3) so GPU bilinear filtering\n // at the region boundary never samples the adjacent atlas tile. Atlas\n // pixel extent comes from atlasSizes[atlasIndex] when present (exact\n // per-atlas pixel dimensions); falls back to columns * tileWidth for\n // single-atlas or legacy callers.\n const atlasSize = tileset.atlasSizes?.[atlasIndex];\n const atlasWidth = Math.max(\n 1,\n atlasSize !== undefined ? atlasSize.pixelWidth : tileset.columns * tileset.tileWidth,\n );\n const atlasHeight = Math.max(\n 1,\n atlasSize !== undefined ? atlasSize.pixelHeight : tileset.rows * tileset.tileHeight,\n );\n const halfTexelU = 0.5 / atlasWidth;\n const halfTexelV = 0.5 / atlasHeight;\n const u = region.x / atlasWidth + halfTexelU;\n const v = region.y / atlasHeight + halfTexelV;\n const w = region.width / atlasWidth - 2 * halfTexelU;\n const h = region.height / atlasHeight - 2 * halfTexelV;\n\n const matPayload: MaterialAsset = {\n kind: 'material',\n passes: [\n {\n name: 'Forward',\n program: { module: 'forgeax::sprite' },\n renderState: {\n ...{ blend: SPRITE_PREMULTIPLIED_ALPHA_BLEND },\n tags: { LightMode: 'Forward' },\n queue: 3000,\n },\n },\n ],\n values: {\n colorTint: [1.0, 1.0, 1.0, 1.0],\n baseColorTexture: atlasHandle,\n region: [u, v, w, h],\n pivotAndSize: [0.5, 0.5, 1.0, 1.0],\n flipY: 1.0,\n },\n };\n const matHandle = world.allocSharedRef<'MaterialAsset', MaterialAsset>(\n 'MaterialAsset',\n matPayload,\n );\n cache.set(cacheKey, matHandle);\n return matHandle;\n}\n\n/**\n * Resolve an atlas-only sprite material (no baked-in UV region). One\n * material per atlas — used by the SpriteInstances batched draw path\n * (sortScope='layer'). The per-instance UV region rectangle lives in the\n * `SpriteInstances.regions` buffer instead of in the material UBO.\n *\n * `values.region` is a `[0, 0, 1, 1]` placeholder. The sprite shader's\n * `PER_INSTANCE_REGION=true` variant reads region from\n * `instances[idx].region` and ignores the material slot; selecting that\n * variant is the record stage's responsibility (see\n * `render-system-record.ts` sprite pass pipeline selection).\n *\n * Returns the registered MaterialAsset slot id (unwrapped Handle u32) or\n * 0 if the atlas slot is empty (charter P3 fail-safe; mirrors\n * `resolveTilesetMaterial`).\n */\nfunction resolveAtlasOnlyMaterial(\n world: World,\n tileset: TilesetAsset,\n atlasIndex: number,\n lookup: (guid: string) => TilesetAtlasLookup,\n): Handle<'MaterialAsset', 'shared'> {\n const atlasGuid = tileset.atlases[atlasIndex];\n if (atlasGuid === undefined) return toShared<'MaterialAsset'>(0);\n const atlas = resolveTilesetRuntime(world, atlasGuid, lookup);\n if (!atlas.ok) return toShared<'MaterialAsset'>(0);\n const atlasHandle = atlas.value.handle;\n const atlasId = unwrapHandle(atlasHandle);\n const cacheKey = String(atlasId);\n const cache =\n atlasOnlyMaterialCache.get(world) ?? new Map<string, Handle<'MaterialAsset', 'shared'>>();\n atlasOnlyMaterialCache.set(world, cache);\n const cached = cache.get(cacheKey);\n if (cached !== undefined) return cached;\n\n const matPayload: MaterialAsset = {\n kind: 'material',\n passes: [\n {\n name: 'Forward',\n program: { module: 'forgeax::sprite' },\n renderState: {\n ...{ blend: SPRITE_PREMULTIPLIED_ALPHA_BLEND },\n tags: { LightMode: 'Forward' },\n queue: 3000,\n },\n },\n ],\n values: {\n colorTint: [1.0, 1.0, 1.0, 1.0],\n baseColorTexture: atlasHandle,\n region: [0.0, 0.0, 1.0, 1.0],\n pivotAndSize: [0.5, 0.5, 1.0, 1.0],\n flipY: 1.0,\n },\n };\n const matHandle = world.allocSharedRef<'MaterialAsset', MaterialAsset>(\n 'MaterialAsset',\n matPayload,\n );\n cache.set(cacheKey, matHandle);\n return matHandle;\n}\n\n/**\n * Compute the half-texel-inset normalised UV rectangle for a TilesetRegion\n * (atlas-space pixels → atlas-normalised [u, v, w, h]). Mirrors the inset\n * computation inside `resolveTilesetMaterial` so the per-instance region\n * data fed into `SpriteInstances.regions` produces pixel-identical sampling\n * to the per-region material path (charter P4 consistent abstraction).\n */\nfunction computeRegionUv(\n tileset: TilesetAsset,\n region: TilesetRegion,\n atlasIndex: number,\n): [u: number, v: number, w: number, h: number] {\n const atlasSize = tileset.atlasSizes?.[atlasIndex];\n const atlasWidth = Math.max(\n 1,\n atlasSize !== undefined ? atlasSize.pixelWidth : tileset.columns * tileset.tileWidth,\n );\n const atlasHeight = Math.max(\n 1,\n atlasSize !== undefined ? atlasSize.pixelHeight : tileset.rows * tileset.tileHeight,\n );\n const halfTexelU = 0.5 / atlasWidth;\n const halfTexelV = 0.5 / atlasHeight;\n return [\n region.x / atlasWidth + halfTexelU,\n region.y / atlasHeight + halfTexelV,\n region.width / atlasWidth - 2 * halfTexelU,\n region.height / atlasHeight - 2 * halfTexelV,\n ];\n}\n\ninterface DerivedSpawnSpec {\n readonly cellX: number;\n readonly cellY: number;\n readonly tileId: number;\n readonly packedTile: number;\n readonly materialHandle: Handle<'MaterialAsset', 'shared'>;\n readonly chunkIndex: number;\n // M2: multi-cell footprint + custom pivot land per-tile via TilesetTileEntry.\n readonly widthCells: number;\n readonly heightCells: number;\n readonly pivotX: number;\n readonly pivotY: number;\n // Atlas + region indices retained so the SpriteInstances (sortScope=\n // 'layer') path can group cells by atlas and look up per-instance UV\n // without re-walking the 3-hop chain `tileId → regions → atlasIndex`.\n readonly atlasIndex: number;\n readonly regionIndex: number;\n}\n\nconst SQRT1_2 = Math.SQRT1_2;\n\n/**\n * Compute the post-flip \"effective pivot Y\" for a tilemap tile entry.\n *\n * Mirrors the D-2 first-line composition used by `spawnDerivedRenderEntities`:\n *\n * basePivotForY = flipDiagonal ? pivotX : pivotY\n * effectivePivotY = flipV ? (1 - basePivotForY) : basePivotForY\n *\n * Exported so the render-system-extract sprite-bucket sort key path can\n * reproduce the *same* per-entity pivot value that landed on\n * `Transform.posY` -- otherwise the foot-Y formula\n * `posY - effectivePivotY * |scaleY|` would drift on flipped tiles\n * (charter P4 single-source pivot SSOT; plan-strategy §D-1 + §D-2 +\n * requirements §AC-12 / §AC-13).\n */\nexport function effectivePivotYForTilemapFlip(\n pivotY: number,\n pivotX: number,\n flipV: boolean,\n flipDiagonal: boolean,\n): number {\n const base = flipDiagonal ? pivotX : pivotY;\n return flipV ? 1 - base : base;\n}\n\n/**\n * Compute the per-cell derived spawn spec for one non-zero cell. Carries\n * widthCells / heightCells / pivotX / pivotY from the TilesetTileEntry so\n * `spawnDerivedRenderEntities` can apply the D-2 geometric correction\n * without re-reading the asset registry.\n */\nfunction specFor(\n layerCols: number,\n chunkSize: number,\n cellIndex: number,\n packedTile: number,\n materialHandle: Handle<'MaterialAsset', 'shared'>,\n entry: TilesetTileEntry,\n atlasIndex: number,\n): DerivedSpawnSpec {\n const cellX = cellIndex % layerCols;\n const cellY = Math.floor(cellIndex / layerCols);\n const chunkX = Math.floor(cellX / chunkSize);\n const chunkY = Math.floor(cellY / chunkSize);\n const chunksPerRow = Math.max(1, Math.ceil(layerCols / chunkSize));\n const chunkIndex = chunkY * chunksPerRow + chunkX;\n const { tileId } = decodeTileBits(packedTile);\n return {\n cellX,\n cellY,\n tileId,\n packedTile,\n materialHandle,\n chunkIndex,\n widthCells: entry.widthCells ?? 1,\n heightCells: entry.heightCells ?? 1,\n pivotX: entry.pivotX ?? 0.5,\n pivotY: entry.pivotY ?? 0.5,\n atlasIndex,\n regionIndex: entry.regionIndex,\n };\n}\n\n/**\n * Compute the post-flip TRS components for one tile cell. The plan-strategy\n * §D-2 multi-cell + flip x pivot composite formula (first-line form):\n *\n * basePivotForX = D ? pivotY : pivotX\n * basePivotForY = D ? pivotX : pivotY\n * effectivePivotX = H ? (1 - basePivotForX) : basePivotForX\n * effectivePivotY = V ? (1 - basePivotForY) : basePivotForY\n * posX = (cellX + effectivePivotX + (0.5 - effectivePivotX) * widthCells)\n * * tileSizeX\n * posY = (cellY + effectivePivotY + (0.5 - effectivePivotY) * heightCells)\n * * tileSizeY\n * scaleX = (H ? -1 : 1) * widthCells * tileSizeX\n * scaleY = (V ? -1 : 1) * heightCells * tileSizeY\n * quatZ = D ? Math.SQRT1_2 : 0\n * quatW = D ? Math.SQRT1_2 : 1\n *\n * Single SSOT consumed by both the per-cell entity spawn path and the\n * SpriteInstances batched path so the two routes produce pixel-identical\n * world transforms (charter P4 consistent abstraction).\n */\nfunction computeTileTrs(\n tilemap: { tileSize: ArrayLike<number> },\n spec: DerivedSpawnSpec,\n packedTile: number,\n): {\n posX: number;\n posY: number;\n scaleX: number;\n scaleY: number;\n quatZ: number;\n quatW: number;\n} {\n const { flipH, flipV, flipDiagonal } = decodeTileBits(packedTile);\n const basePivotForX = flipDiagonal ? spec.pivotY : spec.pivotX;\n const effectivePivotX = flipH ? 1 - basePivotForX : basePivotForX;\n const effectivePivotY = effectivePivotYForTilemapFlip(\n spec.pivotY,\n spec.pivotX,\n flipV,\n flipDiagonal,\n );\n const tileSizeX = tilemap.tileSize[0] ?? 1;\n const tileSizeY = tilemap.tileSize[1] ?? 1;\n return {\n posX: (spec.cellX + effectivePivotX + (0.5 - effectivePivotX) * spec.widthCells) * tileSizeX,\n posY: (spec.cellY + effectivePivotY + (0.5 - effectivePivotY) * spec.heightCells) * tileSizeY,\n scaleX: (flipH ? -1 : 1) * spec.widthCells * tileSizeX,\n scaleY: (flipV ? -1 : 1) * spec.heightCells * tileSizeY,\n quatZ: flipDiagonal ? SQRT1_2 : 0,\n quatW: flipDiagonal ? SQRT1_2 : 1,\n };\n}\n\n/**\n * Spawn a single derived per-cell render entity. Used by the per-cell\n * sortScope path (`sortScope='per-cell'`, object layers) where each cell\n * needs an independent Y-sort position to interleave with sprite entities\n * (e.g. player) at arbitrary Y positions.\n *\n * `layerEntity` becomes the derived entity's `ChildOf.parent`, so\n * `world.despawn(layerEntity)` cascade-despawns every derived cell entity\n * via the engine's `linkedSpawn: true` default (feat-20260616). Combined\n * with the Tilemap -> TileLayer ChildOf edge, a single\n * `world.despawn(tilemapEntity)` unwinds the entire subtree without a\n * bespoke tilemap-scoped cleanup pass (requirements AC-02 / AC-03).\n */\nfunction spawnDerivedRenderEntities(\n world: World,\n tilemap: { tileSize: ArrayLike<number> },\n layerEntity: EntityHandle,\n layerOrder: number,\n spec: DerivedSpawnSpec,\n packedTile: number,\n sortScope: SortScope = 'layer',\n): EntityHandle {\n const { posX, posY, scaleX, scaleY, quatZ, quatW } = computeTileTrs(tilemap, spec, packedTile);\n const layerValue = encodeTilemapLayerValue(layerOrder, spec.chunkIndex, sortScope);\n return world\n .spawn(\n {\n component: Transform,\n data: {\n pos: [posX, posY, 0],\n quat: [0, 0, quatZ, quatW],\n scale: [scaleX, scaleY, 1],\n },\n },\n { component: MeshFilter, data: { assetHandle: HANDLE_QUAD } },\n {\n component: MeshRenderer,\n data: {\n materials: [spec.materialHandle],\n },\n },\n { component: Layer, data: { value: layerValue } },\n { component: ChildOf, data: { parent: layerEntity } },\n )\n .unwrap();\n}\n\n/**\n * Spawn one batched SpriteInstances entity per (TileLayer, chunk, atlas)\n * group. Used by the `sortScope='layer'` path (terrain layers): every\n * cell in the group becomes one instance in the same drawIndexed call.\n *\n * The chunk grid is the unit declared by `Tilemap.chunkSize` (default\n * 16x16). One SpriteInstances entity per (chunk, atlas) pair keeps each\n * GPU instance buffer small (256 cells x 80B = 20KB worst case) and lets\n * downstream frustum culling / incremental rebuild operate at chunk\n * granularity (industry standard: Godot quadrant_size, Bevy ChunkSize,\n * Tiled TMX chunks).\n *\n * Layout:\n * - Transform: identity (the per-instance mat4 carries world-space TRS).\n * - MeshFilter: HANDLE_QUAD.\n * - MeshRenderer: atlas-only sprite material (region placeholder; shader\n * reads per-instance UV from SpriteInstances.regions under the\n * PER_INSTANCE_REGION=true variant — selected at record stage).\n * - SpriteInstances: { transforms: Float32Array(N*16),\n * regions: Float32Array(N*4) }.\n * - Layer: encodeTilemapLayerValue(layerOrder, chunkIndex, 'layer').\n * chunkIndex distinguishes adjacent chunks of the same layer in the\n * transparent-sort key so the back-to-front ordering between chunks\n * remains stable (chunks within a layer don't visually overlap in\n * normal tilemap scenes; the chunkIndex tiebreaker is byte-exact\n * with the per-cell path's encoding).\n *\n * Returns the spawned EntityHandle. Empty groups (zero cells) short-circuit\n * and return `undefined`.\n */\nfunction spawnSpriteInstancesGroup(\n world: World,\n tilemap: { cols: number; tileSize: ArrayLike<number>; chunkSize: number },\n tileset: TilesetAsset,\n layerEntity: EntityHandle,\n layerOrder: number,\n chunkIndex: number,\n atlasIndex: number,\n materialHandle: Handle<'MaterialAsset', 'shared'>,\n cellSpecs: readonly DerivedSpawnSpec[],\n): EntityHandle | undefined {\n if (cellSpecs.length === 0) return undefined;\n const N = cellSpecs.length;\n const transforms = new Float32Array(N * 16);\n const regions = new Float32Array(N * 4);\n const tmpMat = mat4.create();\n const tmpT: [number, number, number] = [0, 0, 0];\n const tmpR: [number, number, number, number] = [0, 0, 0, 1];\n const tmpS: [number, number, number] = [1, 1, 1];\n\n // Per-chunk frustum cull: entity Transform = chunk world center + chunk\n // extents (scaleX/Y). The frustum culler reads the entity AABB (HANDLE_QUAD\n // local [-0.5, 0.5]² expanded by entity scale/pos) → world AABB exactly\n // covers the chunk footprint.\n //\n // Per-instance transforms become chunk-local: inv_chunk * world_tile.\n // inv_chunk is a pure TRS-inverse (no rotation), so for each column c of\n // the world mat W:\n // local[c*4+0] = (W[c*4+0] - chunkCenterX * W[c*4+3]) * invSX\n // local[c*4+1] = (W[c*4+1] - chunkCenterY * W[c*4+3]) * invSY\n // local[c*4+2] = W[c*4+2]\n // local[c*4+3] = W[c*4+3]\n // The sprite shader then produces:\n // world = chunk_TRS * local_tile * pos_local\n // = chunk_TRS * (inv_chunk * world_tile) * pos_local\n // = world_tile * pos_local ✓ (pixel-identical to identity path)\n //\n // Tiles whose widthCells/heightCells straddle a chunk boundary will have\n // instance transforms that exceed the chunk AABB; the entity is still drawn\n // (conservative cull only skips when the chunk AABB is fully outside).\n const chunksPerRow = Math.max(1, Math.ceil(tilemap.cols / tilemap.chunkSize));\n const chunkX = chunkIndex % chunksPerRow;\n const chunkY = Math.floor(chunkIndex / chunksPerRow);\n const chunkScaleX = tilemap.chunkSize * (tilemap.tileSize[0] ?? 1);\n const chunkScaleY = tilemap.chunkSize * (tilemap.tileSize[1] ?? 1);\n const chunkCenterX = (chunkX + 0.5) * chunkScaleX;\n const chunkCenterY = (chunkY + 0.5) * chunkScaleY;\n const invSX = chunkScaleX > 0 ? 1 / chunkScaleX : 1;\n const invSY = chunkScaleY > 0 ? 1 / chunkScaleY : 1;\n\n for (let i = 0; i < N; i++) {\n const spec = cellSpecs[i] as DerivedSpawnSpec;\n const { posX, posY, scaleX, scaleY, quatZ, quatW } = computeTileTrs(\n tilemap,\n spec,\n spec.packedTile,\n );\n tmpT[0] = posX;\n tmpT[1] = posY;\n tmpT[2] = 0;\n tmpR[0] = 0;\n tmpR[1] = 0;\n tmpR[2] = quatZ;\n tmpR[3] = quatW;\n tmpS[0] = scaleX;\n tmpS[1] = scaleY;\n tmpS[2] = 1;\n mat4.compose(tmpMat, tmpT, tmpR, tmpS);\n\n // Write chunk-local transform: inv_chunk * world_tile (see formula above).\n const dst = i * 16;\n for (let c = 0; c < 4; c++) {\n const base = c * 4;\n const w3 = tmpMat[base + 3] ?? 0;\n transforms[dst + base + 0] = ((tmpMat[base + 0] ?? 0) - chunkCenterX * w3) * invSX;\n transforms[dst + base + 1] = ((tmpMat[base + 1] ?? 0) - chunkCenterY * w3) * invSY;\n transforms[dst + base + 2] = tmpMat[base + 2] ?? 0;\n transforms[dst + base + 3] = w3;\n }\n\n const region = tileset.regions[spec.regionIndex];\n if (region !== undefined) {\n const [u, v, w, h] = computeRegionUv(tileset, region, atlasIndex);\n regions[i * 4 + 0] = u;\n regions[i * 4 + 1] = v;\n regions[i * 4 + 2] = w;\n regions[i * 4 + 3] = h;\n }\n }\n\n const layerValue = encodeTilemapLayerValue(layerOrder, chunkIndex, 'layer');\n // plan-strategy D-2: the SpriteInstances entity's Transform.posY is set\n // to `chunkCenterY` (becomes `world[13]` in the entity's local-to-world\n // matrix). This is the LAYER_Y fold sort key — terrain rows share a\n // chunk Y, so per-chunk Y resolution is exactly the granularity the\n // fold pass needs. Per-tile world[13] (instance-level) is intentionally\n // _not_ used; instances live in the chunk-local space anchored at\n // chunkCenterY (see line 601-647 above). This is intentional, not a bug.\n return world\n .spawn(\n {\n component: Transform,\n data: {\n pos: [chunkCenterX, chunkCenterY, 0],\n quat: [0, 0, 0, 1],\n scale: [chunkScaleX, chunkScaleY, 1],\n },\n },\n { component: MeshFilter, data: { assetHandle: HANDLE_QUAD } },\n {\n component: MeshRenderer,\n data: {\n materials: [materialHandle],\n },\n },\n { component: SpriteInstances, data: { transforms, regions } },\n { component: Layer, data: { value: layerValue } },\n { component: ChildOf, data: { parent: layerEntity } },\n )\n .unwrap();\n}\n\n/**\n * Bucket a single layer's tiles into per-non-zero-cell spawn specs.\n * Returns the parent Tilemap metadata + the resolved spawn specs.\n */\nfunction bucketTileLayer(\n world: World,\n layerEntity: EntityHandle,\n parentEntity: EntityHandle,\n lookup: (guid: string) => TilesetAtlasLookup,\n):\n | {\n readonly tilemap: {\n cols: number;\n rows: number;\n tileSize: ArrayLike<number>;\n chunkSize: number;\n };\n readonly layerOrder: number;\n readonly sortScope: SortScope;\n readonly tileset: TilesetAsset;\n readonly specs: readonly DerivedSpawnSpec[];\n }\n | undefined {\n const tilemapRes = world.get(parentEntity, Tilemap);\n if (!tilemapRes.ok) return undefined;\n const tilemap = tilemapRes.value;\n const tilesetPayload = lookup(tilemap.tileset);\n if (tilesetPayload === undefined || 'code' in tilesetPayload) return undefined;\n if (tilesetPayload.kind !== 'tileset') return undefined;\n const tileset = tilesetPayload;\n\n const layerRes = world.get(layerEntity, TileLayer);\n if (!layerRes.ok) return undefined;\n const layer = layerRes.value;\n const tiles = layer.tiles as Uint32Array;\n const sortScope = decodeSortScope(layer.sortScope);\n\n // sortScope='layer' (terrain) uses the SpriteInstances batched path which\n // groups cells by atlas under an atlas-only material; sortScope='per-cell'\n // (object) keeps the per-cell entity path with per-region materials so\n // each cell can interleave with sprites by foot-Y. The material resolver\n // selection here keeps the spec's `materialHandle` in the correct\n // granularity for whichever spawn path consumes it downstream.\n const useSpriteInstances = sortScope === 'layer';\n\n const specs: DerivedSpawnSpec[] = [];\n for (let i = 0; i < tiles.length; i++) {\n const packed = tiles[i] ?? 0;\n if (packed === 0) continue;\n const { tileId } = decodeTileBits(packed);\n if (tileId === 0) continue;\n const entry = tileset.tiles[tileId - 1];\n if (entry === undefined) continue;\n const region = tileset.regions[entry.regionIndex];\n if (region === undefined) continue;\n const atlasIndex = region.atlasIndex ?? 0;\n const materialHandle = useSpriteInstances\n ? resolveAtlasOnlyMaterial(world, tileset, atlasIndex, lookup)\n : resolveTilesetMaterial(world, tileset, entry.regionIndex, lookup);\n const spec = specFor(\n tilemap.cols,\n tilemap.chunkSize,\n i,\n packed,\n materialHandle,\n entry,\n atlasIndex,\n );\n specs.push(spec);\n }\n return {\n tilemap,\n layerOrder: layer.layerOrder,\n sortScope,\n tileset,\n specs,\n };\n}\n\n/**\n * Compute the camera frustum planes for the first Camera + Transform entity\n * found in the world. Returns null when no camera exists or the projection\n * parameters are degenerate (callers treat null as always-visible).\n *\n * Mirrors the frustum-plane computation in render-system-extract so both\n * cull paths use byte-identical planes (charter P4 consistent abstraction).\n */\nfunction buildCameraFrustumPlanes(world: World): frustum.Frustum | null {\n const query = world.query({ with: [Camera, Transform, GlobalTransform] }).unwrap();\n let result: frustum.Frustum | null = null;\n for (const row of query) {\n const camEntity = row.entity;\n\n const camRes = world.get(camEntity, Camera);\n const trRes = world.get(camEntity, GlobalTransform);\n if (!camRes.ok || !trRes.ok) continue;\n\n const cam = camRes.value;\n const tr = trRes.value;\n\n const { near, far } = cam;\n if (near >= far) continue;\n\n const proj = mat4.create();\n if (cam.projection === CAMERA_PROJECTION_ORTHOGRAPHIC) {\n mat4.orthographic(\n proj as Parameters<typeof mat4.orthographic>[0],\n cam.left,\n cam.right,\n cam.top,\n cam.bottom,\n near,\n far,\n );\n } else {\n mat4.perspective(\n proj as Parameters<typeof mat4.perspective>[0],\n cam.fov,\n cam.aspect,\n near,\n far,\n );\n }\n const view = mat4.create();\n mat4.invert(\n view as Parameters<typeof mat4.invert>[0],\n tr.world as Parameters<typeof mat4.invert>[1],\n );\n const vp = mat4.create();\n mat4.multiply(\n vp as Parameters<typeof mat4.multiply>[0],\n proj as Parameters<typeof mat4.multiply>[1],\n view as Parameters<typeof mat4.multiply>[2],\n );\n const f = frustum.create();\n frustum.fromViewProjection(f, vp as Parameters<typeof frustum.fromViewProjection>[1]);\n result = f;\n break;\n }\n return result;\n}\n\n/**\n * bug-20260703-tilemap-chunk-stale-frustum-and-cull-overhang (D2): compute\n * the world-space AABB that tightly encloses every tile inside a chunk\n * after post-TRS placement (`computeTileTrs` applied per spec, SSOT shared\n * with the per-cell spawn path and SpriteInstances batched path). This is\n * the SSOT the streaming visibility test uses to decide whether a chunk's\n * tiles could still be visible; using it instead of the tile-aligned grid\n * box makes multi-cell / non-central-pivot overhang round-trip correctly,\n * so an overhanging tile no longer disappears when its anchor chunk goes\n * off-screen (plan-strategy §2 D-2).\n *\n * Empty spec list -> inverted `Number.MAX_VALUE` sentinel (plan-strategy\n * §2 D-4). `bucketTileLayer` filters empty cells before the byChunk map\n * is built, so this branch should never trigger in production; the\n * sentinel is an explicit \"no visible pixels\" value that\n * `frustum.intersectsBox` rejects immediately, avoiding a silent NaN\n * propagation path (charter P3 explicit failure).\n *\n * Note: `frustum.intersectsBox` picks a p-vertex per plane and computes\n * `dot(normal, p) + d`. When normal has a zero component, multiplying by\n * `Infinity` yields `NaN` (`NaN < 0 === false` -> false positive\n * intersection). The sentinel uses finite `Number.MAX_VALUE` on the axes\n * we want inverted so `0 * MAX_VALUE === 0` and the non-zero-normal axis\n * dominates, driving `dot` to `-Infinity` and correctly rejecting.\n *\n * Z is expanded to +/- 1 so flat sprite geometry (`pos_local.z === 0`) is\n * never degenerate against the frustum's near/far planes.\n *\n * @internal exported for M2 overhang / empty-chunk sentinel unit tests\n * (plan-strategy §5.3); not part of the AI user surface.\n */\nexport function computeChunkStreamBounds(\n tilemap: { tileSize: ArrayLike<number> },\n specs: readonly DerivedSpawnSpec[],\n): box3.Box3Like {\n let minX = Number.MAX_VALUE;\n let minY = Number.MAX_VALUE;\n let maxX = -Number.MAX_VALUE;\n let maxY = -Number.MAX_VALUE;\n for (const spec of specs) {\n const { posX, posY, scaleX, scaleY } = computeTileTrs(tilemap, spec, spec.packedTile);\n const halfW = Math.abs(scaleX) * 0.5;\n const halfH = Math.abs(scaleY) * 0.5;\n const x0 = posX - halfW;\n const x1 = posX + halfW;\n const y0 = posY - halfH;\n const y1 = posY + halfH;\n if (x0 < minX) minX = x0;\n if (y0 < minY) minY = y0;\n if (x1 > maxX) maxX = x1;\n if (y1 > maxY) maxY = y1;\n }\n return [minX, minY, -1, maxX, maxY, 1];\n}\n\n/**\n * Despawn every derived render entity currently attached to `layerEntity`.\n *\n * After tweak-20260714 M3 the terrain path locates its previously-spawned\n * children via `Children.entities` on the TileLayer (mirror of ChildOf,\n * engine-maintained via the relationship hook) rather than a module-level\n * tracker Map — SSOT collapse per architecture-principles §2 (Derive,\n * Don't Duplicate). The snapshot returned by\n * `world.get(layerEntity, Children).entities` is a fresh read-only\n * Uint32Array that is stable across the iteration even though each\n * despawn prunes the mirror in place.\n *\n * Empty children (never-built layer, or already-purged) trivially\n * short-circuits — this is the \"empty array no-op\" equivalence to the\n * old first-frame-heuristic guard (plan-strategy §2 D-3 edge case 3).\n */\nfunction purgeDerivedEntities(world: World, layerEntity: EntityHandle): void {\n const r = world.get(layerEntity, Children);\n if (!r.ok) return;\n const snap = r.value.entities;\n for (let i = 0; i < snap.length; i++) {\n const e = snap[i];\n if (e !== undefined) world.despawn(e as EntityHandle);\n }\n}\n\n/**\n * Snapshot of a single TileLayer's per-frame work item — populated by the\n * main-loop query and consumed both by the per-cell diff-cleanup preamble\n * (`evictDeadPerCellStreamingCaches`) and the per-layer processing branches.\n */\ninterface LayerWork {\n readonly layerEntity: EntityHandle;\n readonly parentEntity: EntityHandle;\n readonly dirty: number;\n readonly sortScopeRaw: number;\n}\n\n/**\n * tweak-20260714 M4 diff-cleanup preamble (plan-strategy §2 D-4 +\n * requirements §5 AC-11 + §8 edge case #4).\n *\n * The per-cell streaming maps are owned by one weak World entry and outlive\n * individual TileLayer entities while that World is alive. When a TileLayer\n * is despawned (or cascade-collected via `world.despawn(tilemapEntity)`) the\n * ECS mirrors clean up entities and `Children.entities`, but these maps retain\n * the dead layer's entries until this diff. On slot reuse, the stale entries\n * would corrupt rebuild: `activeSet` still lists old\n * chunkIndexes, and the rebuild branch would attempt to despawn stale\n * entity IDs before repopulating.\n *\n * Fix: at the top of each frame, diff this World's cached layer keys against\n * the fresh query. The set\n * difference names layers that vanished since the previous call; evict\n * their entries from all three Maps. `activeSet` is the SSOT for \"which\n * chunkIndexes have entries under this layer\" (each insertion / removal\n * pairs a `chunkEntities` set/delete with an `activeSet` add/delete), so\n * cleanup iterates `activeSet` rather than scanning `chunkEntities.keys()` —\n * O(chunks-per-dead-layer) instead\n * of O(total-cache-keys).\n *\n * Cross-world isolation is structural: the WeakMap key is the World object.\n * No duplicated World id is retained in every layer/chunk key.\n *\n * Per-frame cost (OOS-3 invariant): the two `keys()` iterations scan\n * O(cache_size) ≤ O(all-ever-seen-layers-for-this-worldId). Typical\n * scenes have ≤ 10 layers so this is a handful of Map lookups; no\n * matrix arithmetic. Actual eviction work only runs on frames where a\n * layer vanished — steady-state frames pay only the diff scan.\n */\nfunction evictDeadPerCellStreamingCaches(work: readonly LayerWork[], world: World): void {\n const cache = streamingCache(world);\n const aliveLayerKeys = new Set<string>();\n for (const w of work) {\n aliveLayerKeys.add(String(w.layerEntity));\n }\n const deadLayerKeys = new Set<string>();\n for (const layerKey of cache.activeChunks.keys()) {\n if (!aliveLayerKeys.has(layerKey)) deadLayerKeys.add(layerKey);\n }\n for (const layerKey of cache.layers.keys()) {\n if (!aliveLayerKeys.has(layerKey)) deadLayerKeys.add(layerKey);\n }\n for (const deadKey of deadLayerKeys) {\n const activeSet = cache.activeChunks.get(deadKey);\n if (activeSet !== undefined) {\n for (const chunkIdx of activeSet) {\n cache.chunkEntities.delete(`${deadKey}:${chunkIdx}`);\n }\n cache.activeChunks.delete(deadKey);\n }\n cache.layers.delete(deadKey);\n }\n}\n\n/**\n * Walk every TileLayer ChildOf-ing a Tilemap, extract its non-zero cells\n * into derived render entities. A Renderer attaches this system to FrameEnd;\n * World's final publication then resolves newly-created GlobalTransform.world values before the\n * read-only render walk begins.\n *\n * Two paths based on `TileLayer.sortScope`:\n *\n * `'layer'` (terrain, default):\n * Batched SpriteInstances path — spawned once, reused until dirty. Each\n * (chunk, atlas) pair becomes one SpriteInstances entity whose Transform\n * covers the chunk footprint, so the frustum culler rejects off-screen\n * chunks at entity granularity.\n *\n * `'per-cell'` (object layers):\n * Chunk-streaming path — specs are bucketed by chunkIndex once (rebuilt\n * on dirty) and the live entity set is updated every frame to match the\n * camera frustum. Only chunks whose world AABB intersects the frustum\n * have ECS entities alive, keeping `extractFrame` iteration proportional\n * to visible tile count rather than total map tile count.\n */\nexport function tilemapChunkExtractSystem(\n world: World,\n lookup: (guid: string) => TilesetAtlasLookup = () => undefined,\n): void {\n const streaming = streamingCache(world);\n const work: LayerWork[] = [];\n const tileLayerQuery = world.query({ read: [TileLayer, ChildOf] }).unwrap();\n for (const row of tileLayerQuery) {\n const layer = row.get(TileLayer);\n const parent = row.get(ChildOf).parent;\n if (parent === null) continue;\n work.push({\n layerEntity: row.entity,\n parentEntity: parent,\n dirty: layer.dirty,\n sortScopeRaw: layer.sortScope,\n });\n }\n\n evictDeadPerCellStreamingCaches(work, world);\n\n // Compute the camera frustum once per frame — only needed when at least\n // one streaming (per-cell) layer exists. Null = always-visible fallback.\n let frustumPlanes: frustum.Frustum | null | undefined;\n\n for (const w of work) {\n // The outer WeakMap owns World identity; this generation-bearing packed\n // entity handle prevents aliasing when an ECS slot is reused.\n const layerKey = String(w.layerEntity);\n // AC-04: decode via the canonical SortScope union; avoid relying on the\n // raw encoding (0='layer', 1='per-cell') leaking through this call site.\n // `decodeSortScope` is the SSOT used throughout `bucketTileLayer` (see\n // line 730); this main-loop branch is the last remaining numeric check.\n const isStreaming = decodeSortScope(w.sortScopeRaw) === 'per-cell';\n\n if (!isStreaming) {\n // ── Terrain batched path (sortScope='layer') ──────────────────────\n // Spawn once per dirty; entity AABB covers the chunk footprint for\n // entity-level frustum culling in render-system-extract.\n //\n // \"already built\" is derived from Children.entities (mirror of\n // ChildOf, engine-maintained). Empty children ⇒ never built (or\n // just purged) ⇒ don't skip. Populated children + dirty=0 ⇒\n // steady state ⇒ skip. Populated + dirty=1 ⇒ purge + rebuild.\n // architecture-principles §2 (Derive, Don't Duplicate): the\n // former module-level \"ever-built\" Set was a second copy of\n // information that Children.entities already carries.\n const childrenRes = world.get(w.layerEntity, Children);\n const childCount = childrenRes.ok ? childrenRes.value.entities.length : 0;\n if (childCount > 0 && w.dirty === 0) continue;\n\n purgeDerivedEntities(world, w.layerEntity);\n\n const bucket = bucketTileLayer(world, w.layerEntity, w.parentEntity, lookup);\n if (bucket === undefined) continue;\n\n const byChunkAtlas = new Map<number, DerivedSpawnSpec[]>();\n for (const spec of bucket.specs) {\n const key = ((spec.chunkIndex & 0xfffff) << 16) | (spec.atlasIndex & 0xffff);\n const list = byChunkAtlas.get(key);\n if (list === undefined) {\n byChunkAtlas.set(key, [spec]);\n } else {\n list.push(spec);\n }\n }\n for (const groupSpecs of byChunkAtlas.values()) {\n const first = groupSpecs[0];\n if (first === undefined) continue;\n spawnSpriteInstancesGroup(\n world,\n bucket.tilemap,\n bucket.tileset,\n w.layerEntity,\n bucket.layerOrder,\n first.chunkIndex,\n first.atlasIndex,\n first.materialHandle,\n groupSpecs,\n );\n }\n if (w.dirty !== 0) {\n world.set(w.layerEntity, TileLayer, { dirty: 0 }).unwrap();\n }\n continue;\n }\n\n // ── Object streaming path (sortScope='per-cell') ───────────────────\n // Step 1: rebuild specs cache when dirty or first time.\n if (w.dirty !== 0 || !streaming.layers.has(layerKey)) {\n // Despawn all currently-active chunks for this layer.\n const activeSet = streaming.activeChunks.get(layerKey);\n if (activeSet !== undefined) {\n for (const chunkIdx of activeSet) {\n const key = `${layerKey}:${chunkIdx}`;\n const entities = streaming.chunkEntities.get(key);\n if (entities !== undefined) {\n for (const e of entities) world.despawn(e as EntityHandle);\n streaming.chunkEntities.delete(key);\n }\n }\n activeSet.clear();\n }\n streaming.layers.delete(layerKey);\n\n const bucket = bucketTileLayer(world, w.layerEntity, w.parentEntity, lookup);\n if (bucket !== undefined) {\n const byChunkSpecs = new Map<number, DerivedSpawnSpec[]>();\n for (const spec of bucket.specs) {\n const list = byChunkSpecs.get(spec.chunkIndex);\n if (list === undefined) {\n byChunkSpecs.set(spec.chunkIndex, [spec]);\n } else {\n list.push(spec);\n }\n }\n // bug-20260703 D2: promote each chunk's bucket to a ChunkStreamEntry\n // carrying the world-space bounds that enclose every tile's actual\n // footprint (not the tile-aligned grid box). The visibility test\n // then rejects the chunk only when its TRUE pixels are all\n // off-screen, so multi-cell / off-pivot tiles no longer flicker at\n // chunk-boundary crossings (plan-strategy §2 D-2 / D-3).\n const byChunk = new Map<number, ChunkStreamEntry>();\n for (const [chunkIdx, specs] of byChunkSpecs) {\n byChunk.set(chunkIdx, {\n specs,\n bounds: computeChunkStreamBounds(bucket.tilemap, specs),\n });\n }\n streaming.layers.set(layerKey, {\n byChunk,\n tilemap: bucket.tilemap,\n layerOrder: bucket.layerOrder,\n sortScope: bucket.sortScope,\n });\n }\n if (w.dirty !== 0) {\n world.set(w.layerEntity, TileLayer, { dirty: 0 }).unwrap();\n }\n }\n\n const cache = streaming.layers.get(layerKey);\n if (cache === undefined) continue;\n\n // Step 2: lazy-compute camera frustum on first streaming layer.\n if (frustumPlanes === undefined) {\n frustumPlanes = buildCameraFrustumPlanes(world);\n }\n\n // Step 3: diff visible chunks against active set.\n const activeSet = streaming.activeChunks.get(layerKey) ?? new Set<number>();\n streaming.activeChunks.set(layerKey, activeSet);\n const { tilemap } = cache;\n\n for (const [chunkIdx, entry] of cache.byChunk) {\n const { specs, bounds } = entry;\n const visible = frustumPlanes === null || frustum.intersectsBox(frustumPlanes, bounds);\n const wasActive = activeSet.has(chunkIdx);\n\n if (visible && !wasActive) {\n // Spawn per-cell entities for this newly-visible chunk.\n const spawned: EntityHandle[] = [];\n for (const spec of specs) {\n const e = spawnDerivedRenderEntities(\n world,\n tilemap,\n w.layerEntity,\n cache.layerOrder,\n spec,\n spec.packedTile,\n cache.sortScope,\n );\n spawned.push(e);\n }\n streaming.chunkEntities.set(`${layerKey}:${chunkIdx}`, spawned);\n activeSet.add(chunkIdx);\n } else if (!visible && wasActive) {\n // Despawn per-cell entities for this newly-invisible chunk.\n const key = `${layerKey}:${chunkIdx}`;\n const entities = streaming.chunkEntities.get(key);\n if (entities !== undefined) {\n for (const e of entities) world.despawn(e);\n streaming.chunkEntities.delete(key);\n }\n activeSet.delete(chunkIdx);\n }\n }\n }\n}\n","import type { AssetRegistry } from '@forgeax/engine-assets-runtime';\nimport { Update, type World } from '@forgeax/engine-ecs';\nimport { registerPropagateTransforms } from '@forgeax/engine-scene';\nimport type { GpuResidencyCache } from '../device/gpu-residency';\nimport { glyphTextLayoutSystem } from '../glyph-text-layout-system';\nimport { tilemapChunkExtractSystem } from '../tilemap-chunk-extract-system';\n\nlet nextId = 0;\n/** Derived authoring stays beside World; only completed mesh data reaches the Renderer. */\nexport function registerRenderSourceSystems(\n world: World,\n assets: AssetRegistry,\n meshes: Pick<GpuResidencyCache, 'updateMesh'>,\n): () => void {\n const releaseTransforms = registerPropagateTransforms(world);\n const name = `renderDerived:${++nextId}`;\n const result = world.addSystem(Update, {\n name,\n queries: [],\n fn: (world) => {\n tilemapChunkExtractSystem(world, (guid) => assets.lookup(guid));\n glyphTextLayoutSystem(world, meshes).unwrap();\n },\n });\n if (!result.ok) {\n releaseTransforms();\n throw result.error;\n }\n return () => {\n world.removeSystem(Update, name).unwrap();\n releaseTransforms();\n };\n}\n","import type { MaterialCookProgramContext } from '@forgeax/engine-pack/material-cook';\nimport type { RhiCaps } from '@forgeax/engine-rhi';\n\n/** The receiving device selects the immutable material program domain. */\nexport function renderMaterialContext(caps: Pick<RhiCaps, 'backendKind' | 'storageBuffer'>): {\n readonly materialContext?: MaterialCookProgramContext;\n} {\n if (caps.backendKind === 'null') return {};\n return {\n materialContext: {\n backend: caps.backendKind === 'wgpu-webgl2' ? 'webgl2' : caps.backendKind,\n capability: caps.storageBuffer ? 'storage-buffer' : 'uniform-fallback',\n pipeline: 'forward',\n geometry: 'mesh',\n pass: 'forward',\n profile: 'forgeax-material-wgsl-v1',\n toolchain: 'naga-oil',\n instrumentation: 'none',\n },\n };\n}\n","import { RuntimeMaterialValue, RuntimeMeshVertices } from '@forgeax/engine-assets-runtime';\nimport type { Component, EntityHandle, Query, World } from '@forgeax/engine-ecs';\nimport { createStateProjection } from '@forgeax/engine-ecs/projection';\nimport { ChildOf, GlobalTransform, MorphWeights, Transform } from '@forgeax/engine-scene';\nimport { Skin } from '@forgeax/engine-skinning';\nimport {\n Instances,\n Layer,\n Lines,\n MeshFilter,\n MeshRenderer,\n Points,\n SortKey,\n SpriteInstances,\n SpriteRegionOverride,\n Visibility,\n} from '../components';\nexport type GlobalTransformChangeQuery = Query<readonly [typeof GlobalTransform]>;\n\n// Retained geometry consumes these component changes. Camera, lighting and\n// environment facts are freshly extracted by deriveFramePlan on every draw;\n// their edits must not recreate unrelated geometry or its submission history.\nexport const RENDERABLE_SOURCE_COMPONENTS = [\n ChildOf,\n MeshFilter,\n MeshRenderer,\n Instances,\n SpriteInstances,\n SpriteRegionOverride,\n Skin,\n Layer,\n Visibility,\n MorphWeights,\n Points,\n Lines,\n SortKey,\n] as const;\nexport function createGlobalTransformChangeQuery(world: World): GlobalTransformChangeQuery {\n const result = world.query({ read: [GlobalTransform], changed: [GlobalTransform] });\n if (!result.ok) throw result.error;\n const query = result.value as GlobalTransformChangeQuery;\n for (const _span of query.spans().unwrap()) {\n // The full rebuild consumed these values; establish the observation baseline.\n }\n return query;\n}\n\nexport function createRenderSourceState(world: World, additional: readonly Component[] = []) {\n // Numerical poses already have one span reader. Keep their table membership\n // in this projection, without scanning their changed rows a second time.\n const components = [\n ...RENDERABLE_SOURCE_COMPONENTS,\n RuntimeMaterialValue,\n RuntimeMeshVertices,\n ...additional,\n ];\n const projection = createStateProjection(world, components, [\n ...components,\n Transform,\n GlobalTransform,\n ]);\n const entities = new Map<number, EntityHandle>();\n const contentHandles = new Map<number, readonly number[]>();\n const batch = projection.read();\n for (const index of batch.indices) {\n const entity = projection.entity(index);\n if (entity !== undefined) {\n entities.set(index, entity);\n const handles: number[] = [];\n const material = world.hasComponent(entity, RuntimeMaterialValue)\n ? world.get(entity, RuntimeMaterialValue)\n : undefined;\n const mesh = world.hasComponent(entity, RuntimeMeshVertices)\n ? world.get(entity, RuntimeMeshVertices)\n : undefined;\n if (material?.ok) handles.push(Number(material.value.asset));\n if (mesh?.ok) handles.push(Number(mesh.value.asset));\n if (handles.length > 0) contentHandles.set(index, handles);\n }\n }\n return { projection, entities, contentHandles, batch };\n}\n\nexport function isRenderableMember(world: World, entity: number): boolean {\n return (\n world.hasComponent(entity as EntityHandle, MeshRenderer) &&\n world.hasComponent(entity as EntityHandle, Transform) &&\n world.hasComponent(entity as EntityHandle, MeshFilter)\n );\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/publication/contract.ts","../src/typed-shadow-atlas.ts","../src/record/frame-targets.ts","../src/targets/contracts.ts","../src/targets/owner.ts","../src/targets/readback.ts","../src/assembly/render-target-host.ts","../src/publication/targets.ts","../src/features/barrel-distortion.ts","../src/cloud/density.ts","../src/cloud/inspection.ts","../src/cloud/resources.ts","../src/cloud/optics.ts","../src/cloud/shadow.ts","../src/cloud/temporal.ts","../src/cloud/feature.ts","../src/surface/gpu-driven.ts","../src/points-lines/admission.ts","../src/point-shadow-inspection.ts","../src/ssr/admission.ts","../src/volume/inspection.ts","../src/surface/dynamic-input.ts","../src/reflection/filter.ts","../src/reflection/gpu-table.ts","../src/reflection/inspection.ts","../src/reflection/projection.ts","../src/scene/visibility/inspection.ts","../src/ssr/inspection.ts","../src/dynamic-geometry.ts","../src/publication/dependencies.ts","../src/tilemap-chunk-extract-system.ts","../src/scene/source-systems.ts","../src/extract/material-context.ts","../src/scene/render-source.ts"],"names":["mipCount","invalid","token","wrapped","ok","x0","y0","z0","x1","y1","z1","fx","fy","fz","smoothstep","normalize","err","pass","failure","resourceStage","ERROR_POLICY","primitiveKey","activeSet","world","Ch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,IAAA,IAAI,WAAW,MAAA,EAAW;AACxB,MAAA,QAAA,CAAS,GAAA,CAAI,OAAO,MAAM,CAAA;AAC1B,MAAA,MAAM,UAAoB,EAAC;AAC3B,MAAA,MAAM,QAAA,GAAW,KAAA,CAAM,YAAA,CAAa,MAAA,EAAQ,oBAAoB,IAC5D,KAAA,CAAM,GAAA,CAAI,MAAA,EAAQ,oBAAoB,CAAA,GACtC,MAAA;AACJ,MAAA,MAAM,IAAA,GAAO,KAAA,CAAM,YAAA,CAAa,MAAA,EAAQ,mBAAmB,IACvD,KAAA,CAAM,GAAA,CAAI,MAAA,EAAQ,mBAAmB,CAAA,GACrC,MAAA;AACJ,MAAA,IAAI,QAAA,EAAU,IAAI,OAAA,CAAQ,IAAA,CAAK,OAAO,QAAA,CAAS,KAAA,CAAM,KAAK,CAAC,CAAA;AAC3D,MAAA,IAAI,IAAA,EAAM,IAAI,OAAA,CAAQ,IAAA,CAAK,OAAO,IAAA,CAAK,KAAA,CAAM,KAAK,CAAC,CAAA;AACnD,MAAA,IAAI,QAAQ,MAAA,GAAS,CAAA,EAAG,cAAA,CAAe,GAAA,CAAI,OAAO,OAAO,CAAA;AAAA,IAC3D;AAAA,EACF;AACA,EAAA,OAAO,EAAE,UAAA,EAAY,QAAA,EAAU,cAAA,EAAgB,KAAA,EAAM;AACvD;AAEO,SAAS,kBAAA,CAAmB,OAAc,MAAA,EAAyB;AACxE,EAAA,OACE,KAAA,CAAM,YAAA,CAAa,MAAA,EAAwB,YAAY,CAAA,IACvD,KAAA,CAAM,YAAA,CAAa,MAAA,EAAwBC,SAAS,CAAA,IACpD,KAAA,CAAM,YAAA,CAAa,QAAwB,UAAU,CAAA;AAEzD","file":"chunk-OEYKKMXG.mjs","sourcesContent":["import type { TimeResource } from '@forgeax/engine-ecs';\nimport type { MaterialRuntimeArtifact, MaterialShaderEntry } from '@forgeax/engine-shader';\nimport type { Asset, Handle } from '@forgeax/engine-types';\nimport type { DispatchEntry, ExtractedFrame, RenderableSnapshot } from '../render-system-extract';\nimport type { TransparentSortConfig } from '../systems/transparent-sort-config';\nimport type { PublishedRenderTarget, PublishedRenderTargetSource } from './targets';\n\n/** Chosen by App before creating the receiver; never inferred from the first packet. */\nexport interface RenderPublicationIdentity {\n readonly source: string;\n readonly epoch: number;\n}\n\nexport type RenderPublicationMetadata = Omit<\n ExtractedFrame,\n | 'renderables'\n | 'dispatch'\n | 'visibilitySnapshots'\n | 'featureVisibilitySnapshots'\n | 'hiddenEntityReports'\n | 'shadowCasterEntityKeys'\n | 'shadowCasterDrawKeys'\n | 'shadowCasterMembership'\n>;\n\nexport interface RenderPublicationTemplate {\n readonly snapshot: Omit<RenderableSnapshot, 'worldId' | 'entityKey' | 'transform'>;\n readonly dispatch: readonly Omit<DispatchEntry, 'entityIndex' | 'renderableIndex'>[];\n}\n\n/** Numeric storage is publisher-owned; no ECS or asset buffer is transferred. */\nexport interface RenderPublication extends RenderPublicationIdentity {\n readonly revision: number;\n readonly base: number;\n readonly baseline: boolean;\n readonly time: TimeResource;\n readonly sampleTimeSeconds: number;\n readonly temporalReset: boolean;\n readonly transparentSort: TransparentSortConfig;\n readonly metadata: RenderPublicationMetadata;\n readonly templates: readonly RenderPublicationTemplate[];\n readonly videoFrames: readonly {\n readonly entity: number;\n readonly clip: number;\n readonly frame: VideoFrame;\n }[];\n readonly targets: readonly PublishedRenderTarget[];\n readonly targetSources: readonly PublishedRenderTargetSource[];\n readonly features: readonly { readonly identity: string; readonly data: unknown }[];\n readonly programs: readonly {\n readonly key: string;\n readonly shader: MaterialShaderEntry;\n readonly artifact?: MaterialRuntimeArtifact;\n }[];\n /** entity, template index pairs. A publication source owns one World. */\n readonly upserts: Uint32Array;\n readonly removed: Uint32Array;\n readonly transformEntities: Uint32Array;\n readonly transforms: Float32Array;\n readonly assets: readonly {\n readonly handle: Handle<string, 'shared'>;\n readonly guid?: string;\n readonly value: Asset;\n }[];\n readonly retiredAssets: readonly Handle<string, 'shared'>[];\n readonly invalidatedAssets: readonly Handle<string, 'shared'>[];\n}\n\nexport interface PublishedRenderFrameInput {\n readonly publication: RenderPublication;\n /** Realm-local adapter invoked only after the feature's graph is submitted. */\n readonly onFeatureSourceSubmitted?: (identity: string, feedback: unknown) => void;\n}\n\nexport function renderPublicationTransfers(packet: RenderPublication): ArrayBuffer[] {\n return [\n packet.upserts.buffer,\n packet.removed.buffer,\n packet.transformEntities.buffer,\n packet.transforms.buffer,\n ] as ArrayBuffer[];\n}\n\nexport type RenderPublicationFailure =\n | 'identity'\n | 'base'\n | 'revision'\n | 'shape'\n | 'unsupported'\n | 'in-flight'\n | 'disposed';\n\nexport class RenderPublicationError extends Error {\n readonly code = 'render-publication-invalid' as const;\n readonly expected = 'one valid publication for the bound source session and accepted base';\n readonly hint =\n 'inspect detail.reason; repair the source or start a new session with a complete current baseline';\n constructor(\n readonly detail: { readonly reason: RenderPublicationFailure; readonly subject: string },\n ) {\n super(`render-publication-invalid: ${detail.reason}: ${detail.subject}`);\n this.name = 'RenderPublicationError';\n }\n}\n","export interface DirectionalShadowAtlasGrid {\n readonly columns: 1 | 2;\n readonly rows: 1 | 2;\n}\n\n/**\n * The directional CSM atlas layout is one compact contract for raster writes\n * and shader reads: 1 -> 1x1, 2 -> 2x1, and 3/4 -> 2x2.\n */\nexport function resolveDirectionalShadowAtlasGrid(\n cascadeCount: number,\n): DirectionalShadowAtlasGrid {\n const count = Math.max(1, Math.min(4, Math.round(cascadeCount)));\n if (count === 1) return { columns: 1, rows: 1 };\n if (count === 2) return { columns: 2, rows: 1 };\n return { columns: 2, rows: 2 };\n}\n","import type { RhiCanvasContext, Texture, TextureView } from '@forgeax/engine-rhi';\nimport type { RenderGraphExecutionPhase } from '../render-contract';\nimport type { ExtractedLights } from '../render-system-extract';\nimport type { RenderTargetDescriptor } from '../targets/contracts';\nimport { resolveDirectionalShadowAtlasGrid } from '../typed-shadow-atlas';\nimport { configureSurface, type PipelineState, type RenderSystemInternals } from './render-context';\n\nexport function graphExecutionPhase(passName: string): RenderGraphExecutionPhase {\n if (passName.startsWith('shadowCascade')) return 'record/graph-execute/shadow';\n if (passName.startsWith('point-shadow')) return 'record/graph-execute/point-shadow';\n if (passName.startsWith('spot-shadow')) return 'record/graph-execute/spot-shadow';\n if (passName === 'ssr-hiz-seed' || passName.startsWith('ssr-hiz-reduce-')) {\n return 'record/graph-execute/ssr-hiz';\n }\n if (passName === 'ssr-trace') return 'record/graph-execute/ssr-trace';\n if (passName === 'ssr-temporal') return 'record/graph-execute/ssr-temporal';\n if (passName.startsWith('ssr-reflection-mip-')) {\n return 'record/graph-execute/ssr-reflection-mip';\n }\n if (passName === 'ssr-compose') return 'record/graph-execute/ssr-compose';\n if (passName.startsWith('bloom-downsample-')) {\n return 'record/graph-execute/bloom-downsample';\n }\n if (passName.startsWith('bloom-upsample-')) {\n return 'record/graph-execute/bloom-upsample';\n }\n switch (passName) {\n case 'cluster-binner-upload':\n case 'cluster-membership-producer':\n return 'record/graph-execute/cluster-binner-upload';\n case 'g-buffer':\n return 'record/graph-execute/g-buffer';\n case 'ssao-calc':\n return 'record/graph-execute/ssao-calc';\n case 'ssao-blur':\n return 'record/graph-execute/ssao-blur';\n case 'lighting':\n return 'record/graph-execute/lighting';\n case 'forward':\n case 'transmission-forward':\n return 'record/graph-execute/forward';\n case 'output-transform':\n return 'record/graph-execute/output-transform';\n case 'present':\n return 'record/graph-execute/present';\n case 'debug-overlay':\n return 'record/graph-execute/debug-overlay';\n case 'shadow':\n return 'record/graph-execute/shadow';\n case 'skybox':\n return 'record/graph-execute/skybox';\n case 'main':\n return 'record/graph-execute/main';\n case 'fxaa':\n return 'record/graph-execute/fxaa';\n case 'bloom-downsample':\n return 'record/graph-execute/bloom-downsample';\n case 'bloom-upsample':\n return 'record/graph-execute/bloom-upsample';\n case 'bloom-composite':\n return 'record/graph-execute/bloom-composite';\n default:\n return 'record/graph-execute/other';\n }\n}\n\nexport function resolveRenderTargetMipExtent(\n descriptor: RenderTargetDescriptor,\n mipLevel: number,\n): { readonly width: number; readonly height: number } {\n const mipCount =\n descriptor.mipLevels === 1\n ? 1\n : Math.floor(Math.log2(Math.max(descriptor.width, descriptor.height))) + 1;\n const level = Math.max(0, Math.min(mipLevel, mipCount - 1));\n return {\n width: Math.max(1, descriptor.width >> level),\n height: Math.max(1, descriptor.height >> level),\n };\n}\n\nexport function acquireSwapChainTarget(\n internals: RenderSystemInternals,\n pipelineState: PipelineState,\n): { currentTexture: Texture; view: TextureView; targetW: number; targetH: number } | null {\n const canvasContext: RhiCanvasContext | null = internals.context;\n if (canvasContext === null) return null;\n\n let currentTextureResult = canvasContext.getCurrentTexture();\n if (!currentTextureResult.ok) {\n const configuredDevice = internals.resolveSurfaceDevice?.(internals.device);\n if (configuredDevice !== undefined && !configuredDevice.ok) {\n internals.errorRegistry.fire(configuredDevice.error);\n internals.healthRegistry.fire({\n reason: 'internal-fault',\n detail: { message: 'surface device resolution failed; current frame skipped' },\n recoverable: true,\n });\n return null;\n }\n const configured = configureSurface(\n canvasContext,\n configuredDevice?.value ?? internals.device,\n pipelineState.format,\n pipelineState.colorAttachmentFormat,\n );\n if (!configured.ok) {\n internals.errorRegistry.fire(configured.error);\n internals.healthRegistry.fire({\n reason: 'internal-fault',\n detail: { message: 'surface configure candidate failed; current frame skipped' },\n recoverable: true,\n });\n return null;\n }\n pipelineState.perPassResources.configured = true;\n (globalThis as Record<string, unknown>).__forgeaxSwapChainFormat = pipelineState.format;\n const retry = canvasContext.getCurrentTexture();\n if (!retry.ok) {\n internals.errorRegistry.fire(retry.error);\n internals.healthRegistry.fire({\n reason: 'internal-fault',\n detail: {\n message:\n 'surface-configure-failed after retry: getCurrentTexture failed twice consecutively',\n },\n recoverable: false,\n });\n return null;\n }\n currentTextureResult = retry;\n }\n const viewDescriptor =\n pipelineState.colorAttachmentFormat === pipelineState.format\n ? {}\n : { format: pipelineState.colorAttachmentFormat as GPUTextureFormat };\n const viewResult = internals.device.createTextureView(currentTextureResult.value, viewDescriptor);\n if (!viewResult.ok) {\n internals.errorRegistry.fire(viewResult.error);\n return null;\n }\n return {\n currentTexture: currentTextureResult.value,\n view: viewResult.value,\n targetW: internals.canvas.width | 0,\n targetH: internals.canvas.height | 0,\n };\n}\n\nexport function resolveShadowMapSize(\n internals: RenderSystemInternals,\n lights: ExtractedLights,\n): number | undefined {\n if (lights.cascadeCount === undefined) return undefined;\n const requested = lights.shadowMapSize;\n if (!(requested !== undefined && requested > 0)) return requested;\n const cascades = Math.max(1, Math.min(4, Math.round(lights.cascadeCount ?? 1)));\n const atlasGrid = resolveDirectionalShadowAtlasGrid(cascades);\n const maxDimension = internals.device.limits.maxTextureDimension2D;\n if (!(maxDimension > 0)) return Math.floor(requested);\n const depthTextureDimension =\n internals.device.caps?.backendKind === 'wgpu-webgl2'\n ? Math.max(1, Math.floor(maxDimension / 2))\n : maxDimension;\n const maxPerTile = Math.max(\n 1,\n Math.floor(depthTextureDimension / Math.max(atlasGrid.columns, atlasGrid.rows)),\n );\n return Math.max(1, Math.min(Math.floor(requested), maxPerTile));\n}\n\n/**\n * Resolve the per-tile size for the graph-owned spot atlas when a frame has\n * no directional shadow map. The typed spot pass still needs a non-zero\n * viewport in a spot-only world; the directional resolver cannot provide\n * that because it intentionally follows only the directional shadow lane.\n */\nexport function resolveSpotShadowMapSize(\n internals: RenderSystemInternals,\n lights: ExtractedLights,\n): number | undefined {\n const requested = lights.spot.find(\n (spot) => spot.shadowAtlasTile >= 0 && spot.lightViewProj !== undefined,\n )?.mapSize;\n if (!(requested !== undefined && requested > 0)) return requested;\n const maxDimension = internals.device.limits.maxTextureDimension2D;\n if (!(maxDimension > 0)) return Math.floor(requested);\n const maxPerTile = Math.max(1, Math.floor(maxDimension / 2));\n return Math.max(1, Math.min(Math.floor(requested), maxPerTile));\n}\n","import type { RenderError } from '../errors/render';\nimport {\n RenderTargetCapabilityMissingError,\n RenderTargetDescriptorInvalidError,\n} from '../errors/render';\nimport type { RenderResult } from '../render-contract';\n\nexport type RenderTargetFormat = 'rgba16float' | 'rgba8unorm' | 'rgba8unorm-srgb';\nexport type RenderTargetShape = '2d' | 'cube';\nexport type RenderTargetMipLevels = 1 | 'full';\nexport type RenderTargetSampleCount = 1 | 4;\nexport type RenderTargetDepthFormat = 'depth24plus-stencil8' | 'depth32float';\n\nexport interface RenderTargetDescriptor {\n readonly shape: RenderTargetShape;\n readonly width: number;\n readonly height: number;\n readonly format: RenderTargetFormat;\n readonly mipLevels: RenderTargetMipLevels;\n readonly sampleCount: RenderTargetSampleCount;\n readonly depth?: RenderTargetDepthFormat;\n readonly sampled: boolean;\n readonly readback: boolean;\n}\n\ndeclare const RenderTargetBrand: unique symbol;\ndeclare const RenderTargetTextureSourceBrand: unique symbol;\ndeclare const RenderTargetReadbackTicketBrand: unique symbol;\n\n/** Opaque logical target lease owned by one Renderer. */\nexport interface RenderTarget {\n readonly [RenderTargetBrand]: 'RenderTarget';\n}\n\nexport type RenderTargetTextureAspect = 'color';\n\nexport interface RenderTargetTextureSourceOptions {\n readonly aspect: RenderTargetTextureAspect;\n readonly dimension: RenderTargetShape;\n readonly mipLevel: number;\n}\n\n/** Renderer-local runtime material source; it is not an asset handle. */\nexport interface RenderTargetTextureSource {\n readonly [RenderTargetTextureSourceBrand]: 'RenderTargetTextureSource';\n}\n\nexport interface RenderTargetReadbackRequest {\n readonly mipLevel: number;\n /** Cube array layer to copy; 2D targets accept only the omitted form. */\n readonly face?: number;\n}\n\n/** One-shot readback request bound to a future matching FrameReceipt. */\nexport interface RenderTargetReadbackTicket {\n readonly [RenderTargetReadbackTicketBrand]: 'RenderTargetReadbackTicket';\n}\n\n/** Bytes released by observe after the ticket's matching frame completes. */\nexport interface RenderTargetReadbackData {\n readonly ticket: RenderTargetReadbackTicket;\n readonly bytes: Uint8Array;\n readonly frameId: number;\n readonly deviceGeneration: number;\n readonly mipLevel: number;\n readonly face?: number;\n readonly bytesPerRow: number;\n readonly byteLength: number;\n}\n\nexport interface RenderTargetAdmissionLimits {\n readonly maxTextureDimension2D: number;\n readonly maxBytesPerTarget: number;\n readonly renderableFormats: readonly RenderTargetFormat[];\n readonly sampleCounts: readonly RenderTargetSampleCount[];\n readonly depthFormats: readonly RenderTargetDepthFormat[];\n}\n\nconst FORMAT_BYTES: Readonly<Record<RenderTargetFormat, number>> = {\n rgba16float: 8,\n rgba8unorm: 4,\n 'rgba8unorm-srgb': 4,\n};\n\nfunction mipFactor(mipLevels: RenderTargetMipLevels): number {\n return mipLevels === 'full' ? 4 / 3 : 1;\n}\n\nfunction estimatedBytes(descriptor: RenderTargetDescriptor): number {\n const layers = descriptor.shape === 'cube' ? 6 : 1;\n const samples = descriptor.sampleCount;\n const depthBytes = descriptor.depth === undefined ? 0 : 4;\n return Math.ceil(\n descriptor.width *\n descriptor.height *\n FORMAT_BYTES[descriptor.format] *\n layers *\n samples *\n mipFactor(descriptor.mipLevels) +\n descriptor.width *\n descriptor.height *\n depthBytes *\n layers *\n samples *\n mipFactor(descriptor.mipLevels),\n );\n}\n\nfunction invalid(\n field: string,\n value: unknown,\n expected: string,\n): RenderResult<never, RenderError> {\n return {\n ok: false,\n error: new RenderTargetDescriptorInvalidError({ field, value, expected }),\n };\n}\n\n/** Validate descriptor facts before a renderer allocates a physical target. */\nexport function admitRenderTargetDescriptor(\n descriptor: RenderTargetDescriptor,\n limits: RenderTargetAdmissionLimits,\n): RenderResult<RenderTargetDescriptor, RenderError> {\n if (!Number.isInteger(descriptor.width) || descriptor.width < 1) {\n return invalid('width', descriptor.width, 'an integer >= 1');\n }\n if (!Number.isInteger(descriptor.height) || descriptor.height < 1) {\n return invalid('height', descriptor.height, 'an integer >= 1');\n }\n if (\n descriptor.width > limits.maxTextureDimension2D ||\n descriptor.height > limits.maxTextureDimension2D\n ) {\n return invalid(\n 'extent',\n { width: descriptor.width, height: descriptor.height },\n `width and height <= ${limits.maxTextureDimension2D}`,\n );\n }\n if (descriptor.shape === 'cube' && descriptor.width !== descriptor.height) {\n return invalid('shape', descriptor.shape, 'cube width === height');\n }\n if (!limits.renderableFormats.includes(descriptor.format)) {\n return {\n ok: false,\n error: new RenderTargetCapabilityMissingError({\n operation: 'create',\n requested: descriptor.format,\n capability: 'renderableFormats',\n actual: limits.renderableFormats.join(', '),\n }),\n };\n }\n if (!limits.sampleCounts.includes(descriptor.sampleCount)) {\n return {\n ok: false,\n error: new RenderTargetCapabilityMissingError({\n operation: 'create',\n requested: String(descriptor.sampleCount),\n capability: 'sampleCounts',\n actual: limits.sampleCounts.join(', '),\n }),\n };\n }\n if (descriptor.depth !== undefined && !limits.depthFormats.includes(descriptor.depth)) {\n return {\n ok: false,\n error: new RenderTargetCapabilityMissingError({\n operation: 'create',\n requested: descriptor.depth,\n capability: 'depthFormats',\n actual: limits.depthFormats.join(', '),\n }),\n };\n }\n const bytes = estimatedBytes(descriptor);\n if (bytes > limits.maxBytesPerTarget) {\n return invalid('bytes', bytes, `estimated allocation <= ${limits.maxBytesPerTarget}`);\n }\n return { ok: true, value: descriptor };\n}\n","import type { RenderError } from '../errors/render';\nimport { RenderTargetOperationFailedError, RenderTargetStateInvalidError } from '../errors/render';\nimport type { RenderResult } from '../render-contract';\nimport type { RenderTarget, RenderTargetDescriptor } from './contracts';\n\nexport type RenderTargetOwnerState =\n | 'uninitialized'\n | 'candidate'\n | 'active'\n | 'rebuilding'\n | 'destroyed';\n\nexport interface RenderTargetPhysicalCandidate {\n readonly generation: number;\n readonly descriptor: RenderTargetDescriptor;\n}\n\nexport interface RenderTargetOwnerInspection {\n readonly token: RenderTarget;\n readonly state: RenderTargetOwnerState;\n readonly generation: number;\n readonly descriptor: RenderTargetDescriptor;\n readonly candidate?: RenderTargetPhysicalCandidate;\n}\n\nexport interface RenderTargetOwnerOptions {\n readonly rendererId: symbol;\n readonly initialGeneration: number;\n}\n\nexport interface RenderTargetOwner {\n create(descriptor: RenderTargetDescriptor): RenderResult<RenderTarget, RenderError>;\n stage(\n target: RenderTarget,\n descriptor?: RenderTargetDescriptor,\n ): RenderResult<RenderTargetPhysicalCandidate, RenderError>;\n promote(target: RenderTarget, generation: number): RenderResult<void, RenderError>;\n rejectCandidate(\n target: RenderTarget,\n generation: number,\n stage: 'allocation' | 'compile' | 'write' | 'submit',\n ): RenderResult<void, RenderError>;\n beginRecovery(target: RenderTarget, generation: number): RenderResult<void, RenderError>;\n finishRecovery(target: RenderTarget): RenderResult<void, RenderError>;\n retire(target: RenderTarget, generation: number): RenderResult<void, RenderError>;\n destroy(target: RenderTarget): RenderResult<void, RenderError>;\n inspect(target: RenderTarget): RenderResult<RenderTargetOwnerInspection, RenderError>;\n}\n\ninterface TargetState {\n readonly target: RenderTarget;\n readonly rendererId: symbol;\n state: RenderTargetOwnerState;\n generation: number;\n descriptor: RenderTargetDescriptor;\n candidate: RenderTargetPhysicalCandidate | undefined;\n retiredGenerations: Set<number>;\n}\n\nfunction frozenDescriptor(descriptor: RenderTargetDescriptor): RenderTargetDescriptor {\n return Object.freeze({ ...descriptor });\n}\n\nfunction invalid(\n operation: 'inspect' | 'resize' | 'source' | 'readback' | 'destroy',\n reason: 'foreign-renderer' | 'destroyed' | 'uninitialized' | 'generation-mismatch',\n state: RenderTargetOwnerState,\n generation: number,\n): RenderResult<never, RenderError> {\n return {\n ok: false,\n error: new RenderTargetStateInvalidError({ operation, reason, state, generation }),\n };\n}\n\nfunction token(): RenderTarget {\n return Object.freeze({}) as RenderTarget;\n}\n\nexport function createRenderTargetOwner(options: RenderTargetOwnerOptions): RenderTargetOwner {\n const targets = new WeakMap<object, TargetState>();\n const requireTarget = (\n target: RenderTarget,\n operation: 'inspect' | 'resize' | 'source' | 'readback' | 'destroy',\n ): RenderResult<TargetState, RenderError> => {\n const state = targets.get(target as object);\n if (state === undefined) return invalid(operation, 'foreign-renderer', 'destroyed', 0);\n if (state.rendererId !== options.rendererId) {\n return invalid(operation, 'foreign-renderer', state.state, state.generation);\n }\n if (state.state === 'destroyed') {\n return invalid(operation, 'destroyed', state.state, state.generation);\n }\n return { ok: true, value: state };\n };\n\n return {\n create(descriptor) {\n const target = token();\n targets.set(target as object, {\n target,\n rendererId: options.rendererId,\n state: 'uninitialized',\n generation: 0,\n descriptor: frozenDescriptor(descriptor),\n candidate: undefined,\n retiredGenerations: new Set(),\n });\n return { ok: true, value: target };\n },\n stage(target, descriptor) {\n const found = requireTarget(target, 'resize');\n if (!found.ok) return found;\n const state = found.value;\n if (state.state === 'rebuilding') {\n return invalid('resize', 'generation-mismatch', state.state, state.generation);\n }\n const candidate = Object.freeze({\n generation: state.state === 'uninitialized' ? options.initialGeneration : state.generation,\n descriptor: frozenDescriptor(descriptor ?? state.descriptor),\n });\n state.candidate = candidate;\n state.state = 'candidate';\n return { ok: true, value: candidate };\n },\n promote(target, generation) {\n const found = requireTarget(target, 'resize');\n if (!found.ok) return found;\n const state = found.value;\n if (state.candidate?.generation !== generation) {\n return invalid('resize', 'generation-mismatch', state.state, state.generation);\n }\n state.descriptor = state.candidate.descriptor;\n state.generation = generation;\n state.candidate = undefined;\n state.state = 'active';\n return { ok: true, value: undefined };\n },\n rejectCandidate(target, generation, stage) {\n const found = requireTarget(target, 'resize');\n if (!found.ok) return found;\n const state = found.value;\n if (state.candidate?.generation !== generation) {\n return invalid('resize', 'generation-mismatch', state.state, state.generation);\n }\n state.candidate = undefined;\n state.state = state.generation === 0 ? 'uninitialized' : 'active';\n return {\n ok: false,\n error: new RenderTargetOperationFailedError({\n operation: 'resize',\n stage,\n generation,\n cause: new Error(`candidate ${generation} failed during ${stage}`),\n recovery: state.generation === 0 ? 'retry' : 'retain-last-known-good',\n }),\n };\n },\n beginRecovery(target, generation) {\n const found = requireTarget(target, 'resize');\n if (!found.ok) return found;\n const state = found.value;\n if (state.state !== 'active' || generation <= state.generation) {\n return invalid('resize', 'generation-mismatch', state.state, state.generation);\n }\n state.generation = generation;\n state.candidate = undefined;\n state.state = 'rebuilding';\n return { ok: true, value: undefined };\n },\n finishRecovery(target) {\n const found = requireTarget(target, 'resize');\n if (!found.ok) return found;\n const state = found.value;\n if (state.state !== 'rebuilding') {\n return invalid('resize', 'generation-mismatch', state.state, state.generation);\n }\n state.state = 'uninitialized';\n return { ok: true, value: undefined };\n },\n retire(target, generation) {\n const found = requireTarget(target, 'destroy');\n if (!found.ok) return found;\n found.value.retiredGenerations.add(generation);\n return { ok: true, value: undefined };\n },\n destroy(target) {\n const state = targets.get(target as object);\n if (state === undefined) return invalid('destroy', 'foreign-renderer', 'destroyed', 0);\n if (state.rendererId !== options.rendererId) {\n return invalid('destroy', 'foreign-renderer', state.state, state.generation);\n }\n if (state.state === 'destroyed') return { ok: true, value: undefined };\n state.candidate = undefined;\n state.state = 'destroyed';\n return { ok: true, value: undefined };\n },\n inspect(target) {\n const found = requireTarget(target, 'inspect');\n if (!found.ok) return found;\n const state = found.value;\n return {\n ok: true,\n value: Object.freeze({\n token: state.target,\n state: state.state,\n generation: state.generation,\n descriptor: state.descriptor,\n ...(state.candidate === undefined ? {} : { candidate: state.candidate }),\n }),\n };\n },\n };\n}\n","import type { RenderError } from '../errors/render';\nimport { RenderTargetOperationFailedError, RenderTargetStateInvalidError } from '../errors/render';\nimport type { RenderResult } from '../render-contract';\nimport type { RenderTarget } from './contracts';\n\nexport interface RenderTargetReadbackReceipt {\n readonly frameId: number;\n readonly deviceGeneration: number;\n}\n\nexport interface RenderTargetReadbackTicketInput {\n readonly frameId?: number;\n deviceGeneration: number;\n readonly mipLevel: number;\n readonly face?: number;\n readonly width: number;\n readonly height: number;\n readonly bytesPerPixel: number;\n}\n\nexport interface RenderTargetReadbackTicket {\n readonly target: RenderTarget;\n frameId: number | undefined;\n deviceGeneration: number;\n readonly mipLevel: number;\n readonly face?: number;\n readonly width: number;\n readonly height: number;\n readonly bytesPerRow: number;\n readonly byteLength: number;\n consumed: boolean;\n}\n\nexport interface RenderTargetReadbackResult {\n readonly bytes: Uint8Array;\n readonly frameId: number;\n readonly deviceGeneration: number;\n readonly mipLevel: number;\n readonly face?: number;\n}\n\nfunction invalidTicket(\n ticket: RenderTargetReadbackTicket,\n reason: 'uninitialized' | 'generation-mismatch' | 'destroyed',\n): RenderResult<never, RenderError> {\n return {\n ok: false,\n error: new RenderTargetStateInvalidError({\n operation: 'readback',\n reason,\n state: reason === 'destroyed' ? 'destroyed' : 'active',\n generation: ticket.deviceGeneration,\n }),\n };\n}\n\nexport function bindRenderTargetReadbackTicket(\n ticket: RenderTargetReadbackTicket,\n receipt: RenderTargetReadbackReceipt,\n): RenderResult<void, RenderError> {\n if (ticket.consumed) return invalidTicket(ticket, 'destroyed');\n if (ticket.frameId !== undefined) {\n return invalidTicket(ticket, 'generation-mismatch');\n }\n ticket.frameId = receipt.frameId;\n ticket.deviceGeneration = receipt.deviceGeneration;\n return { ok: true, value: undefined };\n}\n\nexport function createRenderTargetReadbackTicket(\n target: RenderTarget,\n input: RenderTargetReadbackTicketInput,\n): RenderResult<RenderTargetReadbackTicket, RenderError> {\n if (\n (input.frameId !== undefined && (!Number.isInteger(input.frameId) || input.frameId < 0)) ||\n !Number.isInteger(input.deviceGeneration) ||\n input.deviceGeneration < 0 ||\n !Number.isInteger(input.mipLevel) ||\n input.mipLevel < 0 ||\n !Number.isInteger(input.width) ||\n input.width < 1 ||\n !Number.isInteger(input.height) ||\n input.height < 1 ||\n !Number.isInteger(input.bytesPerPixel) ||\n input.bytesPerPixel < 1\n ) {\n return {\n ok: false,\n error: new RenderTargetOperationFailedError({\n operation: 'readback',\n stage: 'copy',\n generation: input.deviceGeneration,\n cause: new Error('readback dimensions and identity must be non-negative integers'),\n recovery: 'retry',\n }),\n };\n }\n const unalignedRowBytes = input.width * input.bytesPerPixel;\n const bytesPerRow = Math.ceil(unalignedRowBytes / 256) * 256;\n return {\n ok: true,\n value: {\n target,\n frameId: input.frameId,\n deviceGeneration: input.deviceGeneration,\n mipLevel: input.mipLevel,\n ...(input.face === undefined ? {} : { face: input.face }),\n width: input.width,\n height: input.height,\n bytesPerRow,\n byteLength: bytesPerRow * input.height,\n consumed: false,\n },\n };\n}\n\nexport function completeRenderTargetReadback(\n ticket: RenderTargetReadbackTicket,\n receipt: RenderTargetReadbackReceipt,\n bytes: Uint8Array,\n): RenderResult<RenderTargetReadbackResult, RenderError> {\n if (ticket.consumed) return invalidTicket(ticket, 'destroyed');\n if (\n ticket.frameId === undefined ||\n receipt.frameId !== ticket.frameId ||\n receipt.deviceGeneration !== ticket.deviceGeneration\n ) {\n return invalidTicket(ticket, 'generation-mismatch');\n }\n if (bytes.byteLength !== ticket.byteLength) {\n return {\n ok: false,\n error: new RenderTargetOperationFailedError({\n operation: 'readback',\n stage: 'copy',\n generation: ticket.deviceGeneration,\n cause: new Error(`expected ${ticket.byteLength} bytes, received ${bytes.byteLength}`),\n recovery: 'retry',\n }),\n };\n }\n ticket.consumed = true;\n return {\n ok: true,\n value: {\n bytes,\n frameId: ticket.frameId,\n deviceGeneration: ticket.deviceGeneration,\n mipLevel: ticket.mipLevel,\n ...(ticket.face === undefined ? {} : { face: ticket.face }),\n },\n };\n}\n","import type {\n Buffer,\n RhiCommandEncoder,\n RhiDevice,\n Texture,\n TextureView,\n} from '@forgeax/engine-rhi';\nimport type { RenderError } from '../errors/render';\nimport {\n RenderTargetCapabilityMissingError,\n RenderTargetDescriptorInvalidError,\n RenderTargetOperationFailedError,\n RenderTargetStateInvalidError,\n} from '../errors/render';\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 { GPU_BUFFER_USAGE_COPY_DST, GPU_BUFFER_USAGE_MAP_READ } from '../gpu-usage';\nimport { resolveRenderTargetMipExtent } from '../record/frame-targets';\nimport type { RenderResult } from '../render-contract';\nimport {\n admitRenderTargetDescriptor,\n type RenderTarget,\n type RenderTargetAdmissionLimits,\n type RenderTargetDescriptor,\n type RenderTargetReadbackData,\n type RenderTargetReadbackRequest,\n type RenderTargetReadbackTicket,\n type RenderTargetTextureSource,\n type RenderTargetTextureSourceOptions,\n} from '../targets/contracts';\nimport {\n createRenderTargetMaterialSource,\n type RenderTargetMaterialSourceBinding,\n resolveRenderTargetMaterialSource,\n} from '../targets/material-source';\nimport { createRenderTargetOwner, type RenderTargetOwner } from '../targets/owner';\nimport type { RenderTargetPhysical } from '../targets/physical';\nimport {\n bindRenderTargetReadbackTicket,\n completeRenderTargetReadback,\n createRenderTargetReadbackTicket,\n type RenderTargetReadbackTicket as InternalReadbackTicket,\n type RenderTargetReadbackReceipt,\n} from '../targets/readback';\n\nexport interface RenderTargetHostOptions {\n readonly rendererId?: symbol;\n readonly initialGeneration?: number;\n readonly getGeneration?: () => number;\n readonly limits?: RenderTargetAdmissionLimits;\n readonly getDevice?: () => RhiDevice;\n /**\n * Renderer-owned candidate publication gate. Progressive cube capture keeps\n * a target candidate across face submissions and returns true only after the\n * capture scheduler has committed all faces for the matching fence.\n */\n readonly canPromoteTarget?: (target: RenderTarget) => boolean;\n}\n\nconst DEFAULT_LIMITS: RenderTargetAdmissionLimits = {\n maxTextureDimension2D: 8192,\n maxBytesPerTarget: 256 * 1024 * 1024,\n renderableFormats: ['rgba16float', 'rgba8unorm', 'rgba8unorm-srgb'],\n sampleCounts: [1, 4],\n depthFormats: ['depth24plus-stencil8', 'depth32float'],\n};\n\ninterface ReadbackRecord {\n readonly target: RenderTarget;\n readonly request: RenderTargetReadbackRequest;\n readonly ticket: InternalReadbackTicket;\n readonly buffer?: Buffer;\n encoded: boolean;\n}\n\nexport interface RenderTargetHost {\n /** The logical owner for every target lifecycle operation. */\n readonly owner: 'renderer';\n /** Logical descriptions for the source publication boundary; no physical state escapes. */\n descriptions(): readonly {\n readonly target: RenderTarget;\n readonly descriptor: RenderTargetDescriptor;\n }[];\n createRenderTarget(descriptor: RenderTargetDescriptor): RenderResult<RenderTarget, RenderError>;\n resizeRenderTarget(\n target: RenderTarget,\n descriptor: RenderTargetDescriptor,\n ): RenderResult<void, RenderError>;\n createRenderTargetTextureSource(\n target: RenderTarget,\n options: RenderTargetTextureSourceOptions,\n ): RenderResult<RenderTargetTextureSource, RenderError>;\n /** @internal Resolve a source for the existing material projection path. */\n resolveRenderTargetTextureSource(\n source: RenderTargetTextureSource,\n ): RenderTargetMaterialSourceBinding | undefined;\n requestTargetReadback(\n target: RenderTarget,\n request: RenderTargetReadbackRequest,\n ): RenderResult<RenderTargetReadbackTicket, RenderError>;\n observeTargetReadbacks(\n receipt: RenderTargetReadbackReceipt,\n tickets: readonly RenderTargetReadbackTicket[],\n ): Promise<RenderResult<readonly RenderTargetReadbackData[], RenderError>>;\n /** @internal Physical target used by the active Standard frame. */\n getPhysicalTarget(target: RenderTarget): RenderTargetPhysical | undefined;\n /** @internal Add pending target copies to the frame's sole encoder. */\n encodePendingReadbacks(encoder: RhiCommandEncoder, faces?: readonly number[]): void;\n destroyRenderTarget(target: RenderTarget): RenderResult<void, RenderError>;\n /** Called immediately before the existing Standard frame is interpreted. */\n beginFrame(): void;\n /** Called only after the existing Renderer frame submission is accepted. */\n onFrameSubmitted(completed?: Promise<RenderResult<void, RenderError>>): void;\n /** Called after a replacement DeviceScope generation becomes active. */\n recover(): void;\n /** Called before Renderer-owned physical resources are released. */\n dispose(): void;\n}\n\nfunction opaqueTicket(): RenderTargetReadbackTicket {\n return Object.freeze({}) as RenderTargetReadbackTicket;\n}\n\nfunction bytesPerPixel(format: RenderTargetDescriptor['format']): number {\n return format === 'rgba16float' ? 8 : 4;\n}\n\nfunction mipCount(descriptor: RenderTargetDescriptor): number {\n return descriptor.mipLevels === 1\n ? 1\n : Math.floor(Math.log2(Math.max(descriptor.width, descriptor.height))) + 1;\n}\n\nfunction makePhysical(\n device: RhiDevice,\n descriptor: RenderTargetDescriptor,\n generation: number,\n): RenderResult<RenderTargetPhysical, RenderError> {\n const layers = descriptor.shape === 'cube' ? 6 : 1;\n const usage =\n GPU_TEXTURE_USAGE_RENDER_ATTACHMENT |\n (descriptor.sampled ? GPU_TEXTURE_USAGE_TEXTURE_BINDING : 0) |\n (descriptor.readback ? GPU_TEXTURE_USAGE_COPY_SRC : 0);\n const created = device.createTexture({\n label: `render-target.${generation}`,\n size: { width: descriptor.width, height: descriptor.height, depthOrArrayLayers: layers },\n format: descriptor.format,\n mipLevelCount: mipCount(descriptor),\n // WebGPU forbids multisampled array textures. The cube is always the\n // single-sample resolve destination; MSAA capture uses one depth=1 color\n // texture per face below.\n sampleCount: 1,\n dimension: '2d',\n usage,\n viewFormats: undefined,\n textureBindingViewDimension: descriptor.shape === 'cube' ? 'cube' : undefined,\n });\n if (!created.ok)\n return {\n ok: false,\n error: new RenderTargetOperationFailedError({\n operation: 'create',\n stage: 'allocation',\n generation,\n cause: created.error,\n recovery: 'retry',\n }),\n };\n const texture = created.value;\n const view = device.createTextureView(texture, {\n dimension: descriptor.shape,\n baseMipLevel: 0,\n mipLevelCount: mipCount(descriptor),\n baseArrayLayer: 0,\n arrayLayerCount: layers,\n });\n if (!view.ok)\n return {\n ok: false,\n error: new RenderTargetOperationFailedError({\n operation: 'create',\n stage: 'allocation',\n generation,\n cause: view.error,\n recovery: 'retry',\n }),\n };\n const mipViews: TextureView[] = [];\n for (let mip = 0; mip < mipCount(descriptor); mip += 1) {\n const mipView = device.createTextureView(texture, {\n dimension: descriptor.shape,\n baseMipLevel: mip,\n mipLevelCount: 1,\n baseArrayLayer: 0,\n arrayLayerCount: layers,\n });\n if (!mipView.ok)\n return {\n ok: false,\n error: new RenderTargetOperationFailedError({\n operation: 'create',\n stage: 'allocation',\n generation,\n cause: mipView.error,\n recovery: 'retry',\n }),\n };\n mipViews.push(mipView.value);\n }\n const resolveFaceViews: TextureView[] = [];\n for (let face = 0; face < layers; face += 1) {\n const faceView = device.createTextureView(texture, {\n dimension: '2d',\n baseMipLevel: 0,\n mipLevelCount: 1,\n baseArrayLayer: face,\n arrayLayerCount: 1,\n });\n if (!faceView.ok)\n return {\n ok: false,\n error: new RenderTargetOperationFailedError({\n operation: 'create',\n stage: 'allocation',\n generation,\n cause: faceView.error,\n recovery: 'retry',\n }),\n };\n resolveFaceViews.push(faceView.value);\n }\n const colorTextures: Texture[] = [];\n const faceViews: TextureView[] = [];\n const depthTextures: Texture[] = [];\n const depthViews: TextureView[] = [];\n for (let face = 0; face < layers; face += 1) {\n const depth = device.createTexture({\n label: `render-target.${generation}.depth.${face}`,\n size: {\n width: descriptor.width,\n height: descriptor.height,\n depthOrArrayLayers: descriptor.sampleCount === 4 ? 1 : layers,\n },\n mipLevelCount: 1,\n sampleCount: descriptor.sampleCount,\n dimension: '2d',\n format: 'depth24plus-stencil8',\n usage: GPU_TEXTURE_USAGE_RENDER_ATTACHMENT,\n viewFormats: undefined,\n textureBindingViewDimension: undefined,\n });\n if (!depth.ok)\n return {\n ok: false,\n error: new RenderTargetOperationFailedError({\n operation: 'create',\n stage: 'allocation',\n generation,\n cause: depth.error,\n recovery: 'retry',\n }),\n };\n const depthView = device.createTextureView(depth.value, {\n dimension: '2d',\n baseArrayLayer: descriptor.sampleCount === 4 ? 0 : face,\n arrayLayerCount: 1,\n });\n if (!depthView.ok)\n return {\n ok: false,\n error: new RenderTargetOperationFailedError({\n operation: 'create',\n stage: 'allocation',\n generation,\n cause: depthView.error,\n recovery: 'retry',\n }),\n };\n depthTextures.push(depth.value);\n depthViews.push(depthView.value);\n }\n if (descriptor.sampleCount === 4) {\n for (let face = 0; face < layers; face += 1) {\n const msaa = device.createTexture({\n label: `render-target.${generation}.msaa.${face}`,\n size: { width: descriptor.width, height: descriptor.height, depthOrArrayLayers: 1 },\n format: descriptor.format,\n mipLevelCount: 1,\n sampleCount: 4,\n dimension: '2d',\n usage: GPU_TEXTURE_USAGE_RENDER_ATTACHMENT,\n viewFormats: undefined,\n textureBindingViewDimension: undefined,\n });\n if (!msaa.ok)\n return {\n ok: false,\n error: new RenderTargetOperationFailedError({\n operation: 'create',\n stage: 'allocation',\n generation,\n cause: msaa.error,\n recovery: 'retry',\n }),\n };\n const msaaView = device.createTextureView(msaa.value, {\n dimension: '2d',\n baseMipLevel: 0,\n mipLevelCount: 1,\n baseArrayLayer: 0,\n arrayLayerCount: 1,\n });\n if (!msaaView.ok)\n return {\n ok: false,\n error: new RenderTargetOperationFailedError({\n operation: 'create',\n stage: 'allocation',\n generation,\n cause: msaaView.error,\n recovery: 'retry',\n }),\n };\n colorTextures.push(msaa.value);\n faceViews.push(msaaView.value);\n }\n } else {\n for (let face = 0; face < layers; face += 1) {\n colorTextures.push(texture);\n faceViews.push(resolveFaceViews[face] ?? view.value);\n }\n }\n return {\n ok: true,\n value: {\n generation,\n descriptor,\n texture,\n view: view.value,\n mipViews,\n colorTextures,\n faceViews,\n depthTextures,\n depthViews,\n ...(descriptor.sampleCount === 4 ? { resolveTexture: texture } : {}),\n resolveView: view.value,\n resolveFaceViews,\n },\n };\n}\n\nfunction destroyPhysical(\n device: RhiDevice | undefined,\n physical: RenderTargetPhysical | undefined,\n): void {\n if (device === undefined || physical === undefined) return;\n const textures = new Set<Texture>();\n textures.add(physical.texture);\n if (physical.resolveTexture !== undefined) textures.add(physical.resolveTexture);\n for (const texture of physical.colorTextures) textures.add(texture);\n for (const texture of physical.depthTextures) textures.add(texture);\n for (const texture of textures) device.destroyTexture(texture);\n}\n\nexport function createRenderTargetHost(options: RenderTargetHostOptions = {}): RenderTargetHost {\n let disposed = false;\n const limits = options.limits ?? DEFAULT_LIMITS;\n const owner: RenderTargetOwner = createRenderTargetOwner({\n rendererId: options.rendererId ?? Symbol('renderer'),\n initialGeneration: options.initialGeneration ?? 0,\n });\n const targets = new Set<RenderTarget>();\n const staged = new Set<RenderTarget>();\n const activePhysical = new WeakMap<object, RenderTargetPhysical>();\n const candidatePhysical = new WeakMap<object, RenderTargetPhysical>();\n const sources = new WeakMap<object, RenderTargetMaterialSourceBinding>();\n const readbacks = new WeakMap<object, ReadbackRecord>();\n const readbackRecords = new Set<ReadbackRecord>();\n const currentGeneration = (): number =>\n options.getGeneration?.() ?? options.initialGeneration ?? 0;\n const stagePhysical = (\n target: RenderTarget,\n descriptor?: RenderTargetDescriptor,\n ): RenderResult<void, RenderError> => {\n const stagedTarget = owner.stage(target, descriptor);\n if (!stagedTarget.ok) return stagedTarget;\n const device = options.getDevice?.();\n if (device === undefined) {\n staged.add(target);\n return { ok: true, value: undefined };\n }\n const physical = makePhysical(\n device,\n stagedTarget.value.descriptor,\n stagedTarget.value.generation,\n );\n if (!physical.ok) {\n owner.rejectCandidate(target, stagedTarget.value.generation, 'allocation');\n return physical;\n }\n candidatePhysical.set(target as object, physical.value);\n staged.add(target);\n return { ok: true, value: undefined };\n };\n\n return Object.freeze({\n owner: 'renderer' as const,\n descriptions() {\n return [...targets].map((target) => {\n const state = owner.inspect(target);\n if (!state.ok) throw state.error;\n return { target, descriptor: state.value.candidate?.descriptor ?? state.value.descriptor };\n });\n },\n createRenderTarget(\n descriptor: RenderTargetDescriptor,\n ): RenderResult<RenderTarget, RenderError> {\n if (disposed) {\n return {\n ok: false,\n error: new RenderTargetStateInvalidError({\n operation: 'inspect',\n reason: 'destroyed',\n state: 'destroyed',\n generation: currentGeneration(),\n }),\n };\n }\n const admitted = admitRenderTargetDescriptor(descriptor, limits);\n if (!admitted.ok) return admitted;\n const created = owner.create(admitted.value);\n if (created.ok) targets.add(created.value);\n return created;\n },\n resizeRenderTarget(\n target: RenderTarget,\n descriptor: RenderTargetDescriptor,\n ): RenderResult<void, RenderError> {\n const admitted = admitRenderTargetDescriptor(descriptor, limits);\n if (!admitted.ok) return admitted;\n return stagePhysical(target, admitted.value);\n },\n createRenderTargetTextureSource(\n target: RenderTarget,\n sourceOptions: RenderTargetTextureSourceOptions,\n ): RenderResult<RenderTargetTextureSource, RenderError> {\n const inspected = owner.inspect(target);\n if (!inspected.ok) return inspected;\n if (!inspected.value.descriptor.sampled) {\n return {\n ok: false,\n error: new RenderTargetCapabilityMissingError({\n operation: 'source',\n requested: 'sampled=true',\n capability: 'sampled',\n actual: 'false',\n }),\n };\n }\n if (sourceOptions.dimension !== inspected.value.descriptor.shape) {\n return {\n ok: false,\n error: new RenderTargetDescriptorInvalidError({\n field: 'dimension',\n value: sourceOptions.dimension,\n expected: `dimension matches ${inspected.value.descriptor.shape}`,\n }),\n };\n }\n if (\n !Number.isInteger(sourceOptions.mipLevel) ||\n sourceOptions.mipLevel < 0 ||\n (inspected.value.descriptor.mipLevels === 1 && sourceOptions.mipLevel !== 0)\n ) {\n return {\n ok: false,\n error: new RenderTargetDescriptorInvalidError({\n field: 'mipLevel',\n value: sourceOptions.mipLevel,\n expected: 'an admitted mip level for the target',\n }),\n };\n }\n const binding = createRenderTargetMaterialSource(target, inspected.value.descriptor, {\n ...sourceOptions,\n generation: inspected.value.generation,\n });\n if (!binding.ok) return binding;\n sources.set(binding.value.source as object, binding.value);\n return { ok: true, value: binding.value.source };\n },\n resolveRenderTargetTextureSource(source: RenderTargetTextureSource) {\n const binding = sources.get(source as object) ?? resolveRenderTargetMaterialSource(source);\n if (binding === undefined) return undefined;\n const physical = activePhysical.get(binding.target as object);\n if (physical === undefined) return binding;\n const view =\n physical.mipViews[binding.view.mipLevel] ??\n (binding.shape === 'cube' ? physical.view : physical.resolveView);\n if (binding.generation !== physical.generation) return binding;\n return { ...binding, textureView: view };\n },\n requestTargetReadback(\n target: RenderTarget,\n request: RenderTargetReadbackRequest,\n ): RenderResult<RenderTargetReadbackTicket, RenderError> {\n const inspected = owner.inspect(target);\n if (!inspected.ok) return inspected;\n if (!inspected.value.descriptor.readback) {\n return {\n ok: false,\n error: new RenderTargetCapabilityMissingError({\n operation: 'readback',\n requested: 'readback=true',\n capability: 'readback',\n actual: 'false',\n }),\n };\n }\n if (!Number.isInteger(request.mipLevel) || request.mipLevel < 0) {\n return {\n ok: false,\n error: new RenderTargetDescriptorInvalidError({\n field: 'mipLevel',\n value: request.mipLevel,\n expected: 'a non-negative integer',\n }),\n };\n }\n const mipCount =\n inspected.value.descriptor.mipLevels === 1\n ? 1\n : Math.floor(\n Math.log2(\n Math.max(inspected.value.descriptor.width, inspected.value.descriptor.height),\n ),\n ) + 1;\n if (request.mipLevel >= mipCount) {\n return {\n ok: false,\n error: new RenderTargetDescriptorInvalidError({\n field: 'mipLevel',\n value: request.mipLevel,\n expected: `mipLevel < ${mipCount}`,\n }),\n };\n }\n if (\n request.face !== undefined &&\n (!Number.isInteger(request.face) ||\n request.face < 0 ||\n request.face > 5 ||\n inspected.value.descriptor.shape !== 'cube')\n ) {\n return {\n ok: false,\n error: new RenderTargetDescriptorInvalidError({\n field: 'face',\n value: request.face,\n expected:\n inspected.value.descriptor.shape === 'cube'\n ? 'an integer in [0, 5]'\n : 'omitted for a 2d target',\n }),\n };\n }\n const ticket = opaqueTicket();\n const extent = resolveRenderTargetMipExtent(inspected.value.descriptor, request.mipLevel);\n const buffer = options.getDevice?.()?.createBuffer({\n label: `render-target-readback.${request.mipLevel}.${request.face ?? 0}`,\n size:\n Math.ceil((extent.width * bytesPerPixel(inspected.value.descriptor.format)) / 256) *\n 256 *\n extent.height,\n usage: GPU_BUFFER_USAGE_COPY_DST | GPU_BUFFER_USAGE_MAP_READ,\n mappedAtCreation: false,\n });\n if (buffer !== undefined && !buffer.ok) {\n return {\n ok: false,\n error: new RenderTargetOperationFailedError({\n operation: 'readback',\n stage: 'allocation',\n generation: inspected.value.generation,\n cause: buffer.error,\n recovery: 'retry',\n }),\n };\n }\n const internalTicket = createRenderTargetReadbackTicket(target, {\n deviceGeneration: inspected.value.generation,\n mipLevel: request.mipLevel,\n ...(request.face === undefined ? {} : { face: request.face }),\n width: extent.width,\n height: extent.height,\n bytesPerPixel: bytesPerPixel(inspected.value.descriptor.format),\n });\n if (!internalTicket.ok) return internalTicket;\n const record = {\n target,\n request,\n ticket: internalTicket.value,\n ...(buffer === undefined ? {} : { buffer: buffer.value }),\n encoded: false,\n } satisfies ReadbackRecord;\n readbacks.set(ticket as object, record);\n readbackRecords.add(record);\n return { ok: true, value: ticket };\n },\n async observeTargetReadbacks(\n receipt: RenderTargetReadbackReceipt,\n tickets: readonly RenderTargetReadbackTicket[],\n ): Promise<RenderResult<readonly RenderTargetReadbackData[], RenderError>> {\n const results: RenderTargetReadbackData[] = [];\n for (const publicTicket of tickets) {\n const record = readbacks.get(publicTicket as object);\n if (record === undefined) {\n return {\n ok: false,\n error: new RenderTargetStateInvalidError({\n operation: 'readback',\n reason: 'foreign-renderer',\n state: 'destroyed',\n generation: receipt.deviceGeneration,\n }),\n };\n }\n const inspected = owner.inspect(record.target);\n if (!inspected.ok) return inspected;\n if (inspected.value.state !== 'active') {\n return {\n ok: false,\n error: new RenderTargetStateInvalidError({\n operation: 'readback',\n reason: 'uninitialized',\n state: inspected.value.state,\n generation: inspected.value.generation,\n }),\n };\n }\n if (inspected.value.generation !== receipt.deviceGeneration) {\n return {\n ok: false,\n error: new RenderTargetStateInvalidError({\n operation: 'readback',\n reason: 'generation-mismatch',\n state: inspected.value.state,\n generation: inspected.value.generation,\n }),\n };\n }\n const bound = bindRenderTargetReadbackTicket(record.ticket, receipt);\n if (!bound.ok) return bound;\n let bytes = new Uint8Array(record.ticket.byteLength);\n if (record.buffer !== undefined && typeof record.buffer.mapAsync === 'function') {\n const mapped = await record.buffer.mapAsync(1);\n if (!mapped.ok) {\n return {\n ok: false,\n error: new RenderTargetOperationFailedError({\n operation: 'readback',\n stage: 'copy',\n generation: receipt.deviceGeneration,\n cause: mapped.error,\n recovery: 'retry',\n }),\n };\n }\n const range = mapped.value.getMappedRange();\n if (!range.ok) {\n return {\n ok: false,\n error: new RenderTargetOperationFailedError({\n operation: 'readback',\n stage: 'copy',\n generation: receipt.deviceGeneration,\n cause: range.error,\n recovery: 'retry',\n }),\n };\n }\n bytes = new Uint8Array(range.value.slice(0));\n mapped.value.unmap();\n }\n const completed = completeRenderTargetReadback(record.ticket, receipt, bytes);\n if (!completed.ok) return completed;\n results.push({\n ticket: publicTicket,\n bytes: completed.value.bytes,\n frameId: completed.value.frameId,\n deviceGeneration: completed.value.deviceGeneration,\n mipLevel: completed.value.mipLevel,\n ...(completed.value.face === undefined ? {} : { face: completed.value.face }),\n bytesPerRow: record.ticket.bytesPerRow,\n byteLength: record.ticket.byteLength,\n });\n }\n return { ok: true, value: Object.freeze(results) };\n },\n destroyRenderTarget(target: RenderTarget): RenderResult<void, RenderError> {\n const destroyed = owner.destroy(target);\n if (destroyed.ok) {\n destroyPhysical(options.getDevice?.(), activePhysical.get(target as object));\n destroyPhysical(options.getDevice?.(), candidatePhysical.get(target as object));\n activePhysical.delete(target as object);\n candidatePhysical.delete(target as object);\n for (const record of readbackRecords) {\n if (record.target !== target) continue;\n if (record.buffer !== undefined) options.getDevice?.()?.destroyBuffer(record.buffer);\n readbacks.delete(record.ticket as object);\n readbackRecords.delete(record);\n }\n targets.delete(target);\n }\n return destroyed;\n },\n beginFrame(): void {\n if (disposed) return;\n for (const target of targets) {\n const inspected = owner.inspect(target);\n if (\n !inspected.ok ||\n inspected.value.state === 'active' ||\n inspected.value.state === 'candidate'\n ) {\n continue;\n }\n stagePhysical(target);\n }\n },\n onFrameSubmitted(completed = Promise.resolve({ ok: true, value: undefined } as const)): void {\n if (disposed) return;\n const submittedTargets = [...staged];\n staged.clear();\n void completed.then((result) => {\n for (const target of submittedTargets) {\n const candidate = owner.inspect(target);\n if (!candidate.ok || candidate.value.candidate === undefined) continue;\n if (!result.ok) {\n owner.rejectCandidate(target, candidate.value.candidate.generation, 'submit');\n destroyPhysical(options.getDevice?.(), candidatePhysical.get(target as object));\n candidatePhysical.delete(target as object);\n continue;\n }\n // A progressive CubeCamera writes several faces into one physical\n // candidate across multiple submissions. Do not publish that\n // partially-written generation as active: the next face would then\n // bind the same texture as both a sampled source and an attachment.\n // Keep the target in the staged queue so the next accepted frame (or\n // this same completion callback after the final face) retries the\n // publication check.\n if (options.canPromoteTarget?.(target) === false) {\n staged.add(target);\n continue;\n }\n const generation = candidate.value.candidate.generation;\n const physical = candidatePhysical.get(target as object);\n if (physical === undefined) {\n owner.rejectCandidate(target, generation, 'submit');\n continue;\n }\n const promoted = owner.promote(target, generation);\n if (!promoted.ok) {\n destroyPhysical(options.getDevice?.(), physical);\n candidatePhysical.delete(target as object);\n continue;\n }\n const previous = activePhysical.get(target as object);\n activePhysical.set(target as object, physical as RenderTargetPhysical);\n candidatePhysical.delete(target as object);\n destroyPhysical(options.getDevice?.(), previous);\n }\n });\n },\n getPhysicalTarget(target: RenderTarget): RenderTargetPhysical | undefined {\n return candidatePhysical.get(target as object) ?? activePhysical.get(target as object);\n },\n encodePendingReadbacks(encoder: RhiCommandEncoder, faces?: readonly number[]): void {\n for (const record of readbackRecords) {\n if (record.encoded || record.buffer === undefined) continue;\n if (\n faces !== undefined &&\n record.ticket.face !== undefined &&\n !faces.includes(record.ticket.face)\n ) {\n continue;\n }\n const candidate = candidatePhysical.get(record.target as object);\n const physical =\n faces !== undefined &&\n candidate !== undefined &&\n record.ticket.face !== undefined &&\n faces.includes(record.ticket.face)\n ? candidate\n : activePhysical.get(record.target as object);\n if (physical === undefined) continue;\n const source = physical.resolveTexture ?? physical.texture;\n encoder.copyTextureToBuffer(\n {\n texture: source,\n mipLevel: record.ticket.mipLevel,\n origin: { x: 0, y: 0, z: record.ticket.face ?? 0 },\n },\n {\n buffer: record.buffer,\n bytesPerRow: record.ticket.bytesPerRow,\n rowsPerImage: record.ticket.height,\n },\n [record.ticket.width, record.ticket.height, 1],\n );\n record.encoded = true;\n }\n },\n recover(): void {\n if (disposed) return;\n const generation = currentGeneration();\n for (const target of targets) {\n const inspected = owner.inspect(target);\n if (!inspected.ok || inspected.value.state !== 'active') continue;\n destroyPhysical(options.getDevice?.(), activePhysical.get(target as object));\n destroyPhysical(options.getDevice?.(), candidatePhysical.get(target as object));\n activePhysical.delete(target as object);\n candidatePhysical.delete(target as object);\n for (const record of readbackRecords) {\n if (record.target !== target) continue;\n if (record.buffer !== undefined) options.getDevice?.()?.destroyBuffer(record.buffer);\n readbacks.delete(record.ticket as object);\n readbackRecords.delete(record);\n }\n const begun = owner.beginRecovery(target, generation);\n if (begun.ok) owner.finishRecovery(target);\n }\n },\n dispose(): void {\n disposed = true;\n for (const target of [...targets]) {\n destroyPhysical(options.getDevice?.(), activePhysical.get(target as object));\n destroyPhysical(options.getDevice?.(), candidatePhysical.get(target as object));\n for (const record of readbackRecords) {\n if (record.target !== target) continue;\n if (record.buffer !== undefined) options.getDevice?.()?.destroyBuffer(record.buffer);\n readbacks.delete(record.ticket as object);\n readbackRecords.delete(record);\n }\n activePhysical.delete(target as object);\n candidatePhysical.delete(target as object);\n owner.destroy(target);\n }\n targets.clear();\n staged.clear();\n readbackRecords.clear();\n },\n });\n}\n","import { createRenderTargetHost, type RenderTargetHost } from '../assembly/render-target-host';\nimport type {\n RenderTarget,\n RenderTargetDescriptor,\n RenderTargetTextureSource,\n RenderTargetTextureSourceOptions,\n} from '../targets/contracts';\nimport { resolveRenderTargetMaterialSource } from '../targets/material-source';\nimport type { RenderPublicationTemplate } from './contract';\nimport { RenderPublicationError } from './contract';\nimport type { PreparedRenderPublication } from './receiver';\n\n/** Author descriptions synchronously; the consuming Renderer owns physical resources. */\nexport type RenderTargetAuthoring = Pick<\n RenderTargetHost,\n | 'createRenderTarget'\n | 'resizeRenderTarget'\n | 'createRenderTargetTextureSource'\n | 'destroyRenderTarget'\n>;\nexport interface PublishedRenderTarget {\n readonly id: number;\n readonly token: RenderTarget;\n readonly descriptor: RenderTargetDescriptor;\n}\nexport interface PublishedRenderTargetSource {\n readonly token: RenderTargetTextureSource;\n readonly target: RenderTarget;\n readonly options: RenderTargetTextureSourceOptions;\n}\nexport class RenderPublicationTargetOwner {\n private readonly host = createRenderTargetHost();\n private readonly ids = new WeakMap<object, number>();\n private nextId = 0;\n readonly authoring: RenderTargetAuthoring = this.host;\n snapshot(): readonly PublishedRenderTarget[] {\n return this.host.descriptions().map(({ target, descriptor }) => {\n let id = this.ids.get(target);\n if (id === undefined) {\n id = ++this.nextId;\n this.ids.set(target, id);\n }\n return { id, token: target, descriptor };\n });\n }\n dispose(): void {\n this.host.dispose();\n }\n}\n\nexport function publicationTargetSources(\n templates: readonly RenderPublicationTemplate[],\n): readonly PublishedRenderTargetSource[] {\n const sources = new Map<RenderTargetTextureSource, PublishedRenderTargetSource>();\n for (const template of templates)\n for (const material of template.snapshot.materials) {\n for (const source of material.textureSources?.values() ?? []) {\n if (sources.has(source)) continue;\n const binding = resolveRenderTargetMaterialSource(source);\n if (binding === undefined)\n throw new RenderPublicationError({\n reason: 'shape',\n subject: 'unknown material target source',\n });\n sources.set(source, {\n token: source,\n target: binding.target,\n options: {\n aspect: 'color',\n dimension: binding.view.dimension,\n mipLevel: binding.view.mipLevel,\n },\n });\n }\n }\n return [...sources.values()];\n}\n\ninterface ReceivedTarget {\n readonly target: RenderTarget;\n descriptor: RenderTargetDescriptor;\n readonly sources: Map<string, RenderTargetTextureSource>;\n}\n\n/** Translate logical references once at receive time; no source GPU handle crosses realms. */\nexport class RenderPublicationTargetReceiver {\n private readonly targets = new Map<number, ReceivedTarget>();\n constructor(private readonly host: RenderTargetAuthoring) {}\n apply(input: PreparedRenderPublication): PreparedRenderPublication {\n const packet = input.packet;\n if (packet.targets.length === 0 && packet.targetSources.length === 0 && this.targets.size === 0)\n return input;\n const tokens = new Map<RenderTarget, RenderTarget>();\n const records = new Map<RenderTarget, ReceivedTarget>();\n const active = new Set(packet.targets.map((row) => row.id));\n for (const [id, record] of this.targets)\n if (!active.has(id)) {\n const destroyed = this.host.destroyRenderTarget(record.target);\n if (!destroyed.ok) throw destroyed.error;\n this.targets.delete(id);\n }\n for (const row of packet.targets) {\n let record = this.targets.get(row.id);\n if (record === undefined) {\n const created = this.host.createRenderTarget(row.descriptor);\n if (!created.ok) throw created.error;\n record = { target: created.value, descriptor: row.descriptor, sources: new Map() };\n this.targets.set(row.id, record);\n } else if (JSON.stringify(record.descriptor) !== JSON.stringify(row.descriptor)) {\n const resized = this.host.resizeRenderTarget(record.target, row.descriptor);\n if (!resized.ok) throw resized.error;\n record.descriptor = row.descriptor;\n record.sources.clear();\n }\n tokens.set(row.token, record.target);\n records.set(row.token, record);\n }\n const resolve = (token: RenderTarget): RenderTarget => {\n const target = tokens.get(token);\n if (target === undefined)\n throw new RenderPublicationError({ reason: 'shape', subject: 'missing target descriptor' });\n return target;\n };\n const sources = new Map<RenderTargetTextureSource, RenderTargetTextureSource>();\n for (const row of packet.targetSources) {\n const record = records.get(row.target);\n if (record === undefined)\n throw new RenderPublicationError({ reason: 'shape', subject: 'missing material target' });\n const key = JSON.stringify(row.options);\n let source = record.sources.get(key);\n if (source === undefined) {\n const created = this.host.createRenderTargetTextureSource(record.target, row.options);\n if (!created.ok) throw created.error;\n source = created.value;\n record.sources.set(key, source);\n }\n sources.set(row.token, source);\n }\n const camera = <T extends { readonly target?: RenderTarget }>(row: T): T =>\n row.target === undefined ? row : { ...row, target: resolve(row.target) };\n const renderables = input.frame.renderables.map((row) => {\n const materials = row.materials.map((material) => {\n if (material.textureSources === undefined) return material;\n const textureSources = new Map(\n [...material.textureSources].map(([name, token]) => {\n const source = sources.get(token);\n if (source === undefined)\n throw new RenderPublicationError({\n reason: 'shape',\n subject: 'missing material target source',\n });\n return [name, source] as const;\n }),\n );\n return { ...material, textureSources };\n });\n const first = row.materials.indexOf(row.material);\n return { ...row, materials, material: materials[Math.max(0, first)] ?? row.material };\n });\n const snapshots = new Map(renderables.map((row) => [row.entityKey, row]));\n return {\n ...input,\n frame: {\n ...input.frame,\n renderables,\n cameras: input.frame.cameras.map(camera),\n auxiliaryCameras: input.frame.auxiliaryCameras.map(camera),\n cubeCameras: input.frame.cubeCameras.map(camera),\n },\n operations: input.operations.map((operation) => {\n if (operation.kind === 'remove' || operation.snapshot === undefined) return operation;\n const snapshot = snapshots.get(operation.entityKey);\n if (snapshot === undefined)\n throw new RenderPublicationError({\n reason: 'shape',\n subject: 'missing remapped snapshot',\n });\n return { ...operation, snapshot };\n }),\n };\n }\n}\n","/** One graph-valid identity for the barrel stage, feature and shader prewarm. */\nexport const BARREL_DISTORTION_POST_PROCESS_ID = 'fullscreen.forgeax.barrel-distortion';\nexport const BARREL_DISTORTION_FEATURE_IDENTITY = BARREL_DISTORTION_POST_PROCESS_ID;\n\nimport { ok, type Result } from '@forgeax/engine-types';\nimport type { RenderError } from '../errors/render';\nimport type { RenderFeaturePlan } from './plan';\nimport type { RenderFeature, RenderFeatureExtractContext, RenderFeaturePlanContext } from './types';\n\n/**\n * The coordinate function is exported beside the production shader so a real\n * f32 device probe can compile exactly the same implementation. Keeping the\n * probe source here avoids a second test-only equation that could drift from\n * the Standard pass.\n */\nexport const BARREL_DISTORTION_WGSL_COORDINATE = /* wgsl */ `\nstruct BarrelDistortionParams {\n strength : f32,\n centerX : f32,\n centerY : f32,\n radiusSquared : f32,\n};\n\nfn barrel_distortion_display_to_scene_uv(\n inputUv : vec2<f32>,\n params : BarrelDistortionParams,\n dimensions : vec2<f32>,\n) -> vec2<f32> {\n let aspect = dimensions.x / max(dimensions.y, 1.0);\n let p = vec2<f32>(\n 2.0 * aspect * (inputUv.x - params.centerX),\n 2.0 * (inputUv.y - params.centerY),\n );\n let t = dot(p, p) / max(params.radiusSquared, 1e-6);\n let scale = (1.0 - params.strength) / (1.0 - params.strength * t);\n return clamp(\n vec2<f32>(\n params.centerX + (inputUv.x - params.centerX) * scale,\n params.centerY + (inputUv.y - params.centerY) * scale,\n ),\n vec2<f32>(0.0),\n vec2<f32>(1.0),\n );\n}\n`;\n\n/**\n * Manifest-equivalent WGSL for the bounded analytic model. The Standard\n * owner registers this source once and keeps the graph, encoder, and submit\n * lifecycle shared with every other fullscreen stage.\n */\nexport const BARREL_DISTORTION_WGSL = /* wgsl */ `${BARREL_DISTORTION_WGSL_COORDINATE}\nstruct FullscreenOutput {\n @builtin(position) position : vec4<f32>,\n @location(0) uv : vec2<f32>,\n};\n\nfn fullscreen_triangle(vertex_index : u32) -> FullscreenOutput {\n var x : f32 = -1.0;\n var y : f32 = -1.0;\n if (vertex_index == 1u) { x = 3.0; }\n if (vertex_index == 2u) { y = 3.0; }\n let u : f32 = (x + 1.0) * 0.5;\n let v : f32 = 1.0 - (y + 1.0) * 0.5;\n var out : FullscreenOutput;\n out.position = vec4<f32>(x, y, 0.0, 1.0);\n out.uv = vec2<f32>(u, v);\n return out;\n}\n\n@group(1) @binding(0) var sceneColor : texture_2d<f32>;\n@group(1) @binding(1) var sceneSampler : sampler;\n\n@group(1) @binding(2) var<uniform> params : BarrelDistortionParams;\n\n@vertex\nfn vs_main(@builtin(vertex_index) vertex_index : u32) -> FullscreenOutput {\n return fullscreen_triangle(vertex_index);\n}\n\n@fragment\nfn fs_main(input : FullscreenOutput) -> @location(0) vec4<f32> {\n let dimensions = vec2<f32>(textureDimensions(sceneColor));\n let sampleUv = barrel_distortion_display_to_scene_uv(input.uv, params, dimensions);\n return textureSampleLevel(sceneColor, sceneSampler, sampleUv, 0.0);\n}\n`;\n\n/**\n * Ordinary feature registration for the Standard linear-LDR stage.\n * Standard still allocates the stage targets and chooses its position in the\n * post chain; this feature owns the executable fullscreen declaration that is\n * projected into that slot by the existing graph/encoder/submit path.\n */\nexport interface BarrelDistortionFeatureFrame {\n /** True only when the extracted camera requires a spatial warp this frame. */\n readonly active: boolean;\n}\n\nexport function createBarrelDistortionRenderFeature(): RenderFeature<BarrelDistortionFeatureFrame> {\n return Object.freeze({\n identity: BARREL_DISTORTION_FEATURE_IDENTITY,\n requiredCapabilities: ['rgba16floatRenderable'] as const,\n requiredFullscreenPostProcesses: [\n { identity: BARREL_DISTORTION_POST_PROCESS_ID, source: BARREL_DISTORTION_WGSL },\n ],\n extract: (\n context: RenderFeatureExtractContext,\n ): Result<BarrelDistortionFeatureFrame, RenderError> =>\n ok({ active: (context.selectedCamera?.barrelDistortion?.strength ?? 0) > 0 }),\n plan: (\n data: BarrelDistortionFeatureFrame,\n _context: RenderFeaturePlanContext,\n ): Result<RenderFeaturePlan, RenderError> =>\n ok({\n resources: data.active\n ? [\n {\n kind: 'fullscreen-program' as const,\n name: BARREL_DISTORTION_POST_PROCESS_ID,\n source: BARREL_DISTORTION_WGSL,\n reads: ['ldrColor'],\n params: { byteSize: 16, defaultValue: new Uint8Array(16) },\n },\n {\n kind: 'graphics-program' as const,\n name: 'barrel-distortion-pipeline',\n program: {\n shader: BARREL_DISTORTION_POST_PROCESS_ID,\n vertexLayout: 'none',\n colorFormats: ['rgba16float'],\n sampleCount: 1,\n },\n },\n {\n kind: 'graphics-bindings' as const,\n name: 'barrel-distortion-bindings',\n program: 'barrel-distortion-pipeline',\n values: {\n group: 1,\n fullscreen: true,\n shader: BARREL_DISTORTION_POST_PROCESS_ID,\n input: 'barrel-input',\n },\n logicalTargets: { input: 'barrel-input' },\n },\n ]\n : [],\n passes: data.active\n ? [\n {\n kind: 'raster' as const,\n name: 'barrel-distortion',\n colorAttachments: [\n { target: 'barrel-output', loadOp: 'clear' as const, storeOp: 'store' as const },\n ],\n sampledTargets: ['barrel-input'],\n draws: [\n {\n program: 'barrel-distortion-pipeline',\n bindings: ['barrel-distortion-bindings'],\n vertexData: [],\n vertexLayout: 'none' as const,\n draw: { kind: 'draw' as const, vertexCount: 3, instanceCount: 1 },\n },\n ],\n },\n ]\n : [],\n }),\n });\n}\n","import { err, ok, type Result } from '@forgeax/engine-types';\nimport { CloudLayerCacheInvalidError, type CloudLayerError } from '../errors/cloud';\nimport {\n CLOUD_QUALITY_PROFILES,\n type CloudQualityProfile,\n cloudLayerFormationKey,\n type ValidatedCloudLayer,\n} from './parameters';\n\nexport interface CloudDensityCache {\n readonly sourceKey: string;\n readonly resolution: number;\n /** R8 normalized density values in z-major, y, x order. */\n readonly data: Uint8Array;\n /**\n * Weather, body and erosion bases in three contiguous R8 planes. `data` is\n * retained as a diagnostic projection for callers that still need the\n * composed density; runtime sampling uses these formation planes so coverage,\n * density and wind remain evaluation controls.\n */\n readonly formationData: Uint8Array;\n readonly formationByteLength: number;\n /** Bytes uploaded for the reusable formation planes. */\n readonly byteLength: number;\n readonly digest: string;\n}\n\nexport interface CloudDensityCacheSnapshot {\n readonly sourceKey: string;\n readonly resolution: number;\n readonly data: Uint8Array;\n readonly formationData?: Uint8Array;\n readonly digest: string;\n}\n\nexport interface CloudDensitySample {\n readonly density: number;\n readonly heightFraction: number;\n readonly noise: number;\n readonly weather?: number;\n readonly body?: number;\n readonly erosion?: number;\n}\n\nexport interface CloudFormationSample {\n readonly weather: number;\n readonly body: number;\n readonly erosion: number;\n readonly noise: number;\n}\n\n/**\n * The cache is one world-space period. Keep several lattice cells inside that\n * period so a street view sees separate cloud bodies instead of one broad\n * slab. The lattice wraps at the same boundary as the cache, which prevents\n * the old seam from turning into a repeated horizontal band.\n */\nconst CLOUD_SHAPE_CELLS = 4;\nconst CLOUD_WEATHER_CELLS = 2;\nconst CLOUD_DETAIL_CELLS = CLOUD_SHAPE_CELLS * 3;\n// One advective cache period contains four horizontal and two vertical body cells.\n// Integer periods on every axis make the formation continuous when wind wraps\n// through the cache boundary instead of introducing a seam at y = 0/1.\nexport const CLOUD_VERTICAL_CELLS = 1;\n// The cache keeps one advective period, while the formation itself gets two\n// smooth vertical lobes inside that period so the street view does not read as\n// a single sheet. Both are integer-period fields, so the cache seam remains\n// exact.\nconst CLOUD_VERTICAL_NOISE_CELLS = 2;\nconst CLOUD_DETAIL_VERTICAL_CELLS = 3;\n\nfunction saturate(value: number): number {\n return Math.min(1, Math.max(0, value));\n}\n\nfunction smoothstep(edge0: number, edge1: number, value: number): number {\n const t = saturate((value - edge0) / Math.max(1e-6, edge1 - edge0));\n return t * t * (3 - 2 * t);\n}\n\nfunction fract(value: number): number {\n return value - Math.floor(value);\n}\n\nfunction wrapInteger(value: number, period: number): number {\n const wrapped = value % period;\n return wrapped < 0 ? wrapped + period : wrapped;\n}\n\n/** Deterministic integer hash. Every octave uses the same seeded function. */\nfunction hash3(x: number, y: number, z: number, seed: number): number {\n let value = Math.imul(x | 0, 0x45d9f3b);\n value = Math.imul(value ^ Math.imul(y | 0, 0x119de1f3), 0x45d9f3b);\n value = Math.imul(value ^ Math.imul(z | 0, 0x3449f), 0x45d9f3b);\n value ^= seed | 0;\n value = Math.imul(value ^ (value >>> 16), 0x45d9f3b);\n value = Math.imul(value ^ (value >>> 13), 0x27d4eb2d);\n return ((value ^ (value >>> 16)) >>> 0) / 0x100000000;\n}\n\nfunction valueNoise(\n x: number,\n y: number,\n z: number,\n seed: number,\n periodX = 0,\n periodY = 0,\n periodZ = 0,\n): number {\n const ix = Math.floor(x);\n const iy = Math.floor(y);\n const iz = Math.floor(z);\n const fx = x - ix;\n const fy = y - iy;\n const fz = z - iz;\n const ux = fx * fx * (3 - 2 * fx);\n const uy = fy * fy * (3 - 2 * fy);\n const uz = fz * fz * (3 - 2 * fz);\n const lattice = (cellX: number, cellY: number, cellZ: number): number =>\n hash3(\n periodX > 0 ? wrapInteger(cellX, periodX) : cellX,\n periodY > 0 ? wrapInteger(cellY, periodY) : cellY,\n periodZ > 0 ? wrapInteger(cellZ, periodZ) : cellZ,\n seed,\n );\n const c000 = lattice(ix, iy, iz);\n const c100 = lattice(ix + 1, iy, iz);\n const c010 = lattice(ix, iy + 1, iz);\n const c110 = lattice(ix + 1, iy + 1, iz);\n const c001 = lattice(ix, iy, iz + 1);\n const c101 = lattice(ix + 1, iy, iz + 1);\n const c011 = lattice(ix, iy + 1, iz + 1);\n const c111 = lattice(ix + 1, iy + 1, iz + 1);\n const x00 = c000 + (c100 - c000) * ux;\n const x10 = c010 + (c110 - c010) * ux;\n const x01 = c001 + (c101 - c001) * ux;\n const x11 = c011 + (c111 - c011) * ux;\n return x00 + (x10 - x00) * uy + (x01 + (x11 - x01) * uy - (x00 + (x10 - x00) * uy)) * uz;\n}\n\n/** Bounded Worley-like cellular term used to erode the high frequency field. */\nfunction cellularNoise(\n x: number,\n y: number,\n z: number,\n seed: number,\n periodXZ = CLOUD_DETAIL_CELLS,\n periodY = 0,\n): number {\n const ix = Math.floor(x);\n const iy = Math.floor(y);\n const iz = Math.floor(z);\n const fx = x - ix;\n const fy = y - iy;\n const fz = z - iz;\n let nearest = Number.POSITIVE_INFINITY;\n for (let dz = -1; dz <= 1; dz += 1) {\n for (let dy = -1; dy <= 1; dy += 1) {\n for (let dx = -1; dx <= 1; dx += 1) {\n const random = hash3(\n wrapInteger(ix + dx, periodXZ),\n periodY > 0 ? wrapInteger(iy + dy, periodY) : iy + dy,\n wrapInteger(iz + dz, periodXZ),\n seed ^ 0x9e3779b9,\n );\n const px = dx + fract(random * 17.0) - fx;\n const py = dy + fract(random * 31.0) - fy;\n const pz = dz + fract(random * 47.0) - fz;\n nearest = Math.min(nearest, px * px + py * py + pz * pz);\n }\n }\n }\n return 1 - saturate(Math.sqrt(nearest) * 1.25);\n}\n\nfunction heightEnvelope(height: number, body: number, weather: number): number {\n // Let each body choose its own crown height. A fixed upper edge reads as a\n // horizontal slab from the street camera; tying the crown to the cached body\n // makes dense cells grow upward while sparse cells dissolve earlier.\n const lowerEdge = 0.05 + (1 - body) * 0.1;\n const crownEdge = Math.min(0.96, 0.6 + body * 0.3 + weather * 0.08);\n return (\n smoothstep(lowerEdge, Math.min(1, lowerEdge + 0.12), height) *\n (1 - smoothstep(crownEdge, Math.min(1, crownEdge + 0.14), height))\n );\n}\n\n/** Coverage shapes the macro body; detail removes material only at its boundary. */\nfunction composeCloudDensity(\n height: number,\n formation: CloudFormationSample,\n coverage: number,\n): number {\n const threshold = 1 - coverage * (0.45 + formation.weather * 0.55);\n const covered = smoothstep(0, 0.4, (formation.body - threshold) / Math.max(0.001, 1 - threshold));\n const shaped = covered * heightEnvelope(height, formation.body, formation.weather);\n const erosion = (1 - formation.erosion) * 0.18;\n return saturate((shaped - erosion) / (1 - erosion));\n}\n\nfunction formationField(\n x: number,\n y: number,\n z: number,\n seed: number,\n detailRepeat = 1,\n): CloudFormationSample {\n // A low-frequency height-aware warp breaks axis-aligned horizontal sheets\n // while keeping the cache periodic on every axis. The warp is evaluated once while\n // the reusable formation cache is built, so runtime ray steps pay no extra\n // noise cost.\n const macroWarpX =\n valueNoise(\n x * CLOUD_WEATHER_CELLS,\n y * CLOUD_VERTICAL_NOISE_CELLS + 3.0,\n z * CLOUD_WEATHER_CELLS,\n seed + 41023,\n CLOUD_WEATHER_CELLS,\n 2,\n CLOUD_WEATHER_CELLS,\n ) - 0.5;\n const macroWarpZ =\n valueNoise(\n x * CLOUD_WEATHER_CELLS + 5.0,\n y * CLOUD_VERTICAL_NOISE_CELLS - 7.0,\n z * CLOUD_WEATHER_CELLS,\n seed + 41023,\n CLOUD_WEATHER_CELLS,\n 2,\n CLOUD_WEATHER_CELLS,\n ) - 0.5;\n const bodyX = x + macroWarpX * 0.3;\n const bodyZ = z + macroWarpZ * 0.3;\n let amplitude = 0.5;\n let frequency = 1;\n let sum = 0;\n let weight = 0;\n for (let octave = 0; octave < 4; octave += 1) {\n const tilePeriod = CLOUD_SHAPE_CELLS * frequency;\n sum +=\n valueNoise(\n bodyX * tilePeriod,\n y * frequency * CLOUD_VERTICAL_NOISE_CELLS,\n bodyZ * tilePeriod,\n seed + octave * 1013,\n tilePeriod,\n frequency * CLOUD_VERTICAL_NOISE_CELLS,\n tilePeriod,\n ) * amplitude;\n weight += amplitude;\n amplitude *= 0.4;\n frequency *= 2;\n }\n // Perlin-Worley-style body remapping: the broad fBm controls the volume and\n // the cellular field only breaks its boundary. Keeping these values\n // separate is what lets a runtime coverage edit preserve the authored cloud\n // bodies instead of regenerating a final alpha volume.\n const broad = sum / weight;\n // Periodic Worley cells provide bounded breakup. The broad field remains\n // dominant so one cache period reads as a few connected formations instead\n // of a repeated grid of small spheres.\n const cells = cellularNoise(\n bodyX * CLOUD_SHAPE_CELLS,\n y * CLOUD_VERTICAL_NOISE_CELLS,\n bodyZ * CLOUD_SHAPE_CELLS,\n seed + 5011,\n CLOUD_SHAPE_CELLS,\n CLOUD_VERTICAL_NOISE_CELLS,\n );\n // Let the broad field carry the silhouette and use cellular noise as a\n // bounded breakup term. A broad-dominant mix keeps the same cache and ray\n // budget while yielding fewer, wider and less spherical cumulus masses.\n const body = saturate(broad * 0.85 + cells * 0.15 + 0.15);\n const weather = smoothstep(\n 0.34,\n 0.66,\n valueNoise(\n x * CLOUD_WEATHER_CELLS,\n 0.37,\n z * CLOUD_WEATHER_CELLS,\n seed + 17041,\n CLOUD_WEATHER_CELLS,\n 1,\n CLOUD_WEATHER_CELLS,\n ),\n );\n const detailX = x * detailRepeat;\n const detailY = y * detailRepeat;\n const detailZ = z * detailRepeat;\n const warpX =\n valueNoise(\n detailX * CLOUD_WEATHER_CELLS,\n detailY * 2 + 11.0,\n detailZ * CLOUD_WEATHER_CELLS,\n seed + 29011,\n CLOUD_WEATHER_CELLS,\n 2,\n CLOUD_WEATHER_CELLS,\n ) - 0.5;\n const warpZ =\n valueNoise(\n detailX * CLOUD_WEATHER_CELLS + 7.0,\n detailY * 2 - 5.0,\n detailZ * CLOUD_WEATHER_CELLS,\n seed + 29011,\n CLOUD_WEATHER_CELLS,\n 2,\n CLOUD_WEATHER_CELLS,\n ) - 0.5;\n const erosion = cellularNoise(\n (detailX + warpX * 0.22) * CLOUD_DETAIL_CELLS,\n detailY * CLOUD_DETAIL_VERTICAL_CELLS,\n (detailZ + warpZ * 0.22) * CLOUD_DETAIL_CELLS,\n seed + 7919,\n CLOUD_DETAIL_CELLS,\n CLOUD_DETAIL_VERTICAL_CELLS,\n );\n const noise = body;\n return { weather, body, erosion, noise };\n}\n\n/** Evaluate the reusable weather/body/erosion bases at one world position. */\nexport function evaluateCloudFormation(\n params: ValidatedCloudLayer,\n position: ArrayLike<number>,\n timeSeconds = 0,\n): CloudFormationSample {\n const windX = (params.wind[0] ?? 0) * timeSeconds;\n const windY = (params.wind[1] ?? 0) * timeSeconds;\n const windZ = (params.wind[2] ?? 0) * timeSeconds;\n const relativeHeight =\n ((position[1] ?? 0) - params.baseHeight) / Math.max(1e-6, params.thickness);\n const advectedHeight =\n relativeHeight + (windY * params.scale) / Math.max(1e-6, CLOUD_VERTICAL_CELLS);\n return formationField(\n ((position[0] ?? 0) + windX) * params.scale,\n fract(advectedHeight) * CLOUD_VERTICAL_CELLS,\n ((position[2] ?? 0) + windZ) * params.scale,\n params.seed,\n );\n}\n\n/** Analytic field used for cache generation, CPU diagnostics and recovery. */\nexport function evaluateCloudDensity(\n params: ValidatedCloudLayer,\n position: ArrayLike<number>,\n timeSeconds = 0,\n): CloudDensitySample {\n const relativeHeight =\n ((position[1] ?? 0) - params.baseHeight) / Math.max(1e-6, params.thickness);\n if (relativeHeight <= 0 || relativeHeight >= 1 || params.density <= 0 || params.coverage <= 0) {\n return { density: 0, heightFraction: saturate(relativeHeight), noise: 0 };\n }\n const windX = (params.wind[0] ?? 0) * timeSeconds;\n const windY = (params.wind[1] ?? 0) * timeSeconds;\n const windZ = (params.wind[2] ?? 0) * timeSeconds;\n const x = ((position[0] ?? 0) + windX) * params.scale;\n const advectedHeight =\n relativeHeight + (windY * params.scale) / Math.max(1e-6, CLOUD_VERTICAL_CELLS);\n const y = fract(advectedHeight) * CLOUD_VERTICAL_CELLS;\n const z = ((position[2] ?? 0) + windZ) * params.scale;\n const formation = formationField(x, y, z, params.seed, 3);\n const noise = formation.noise;\n return {\n density: composeCloudDensity(relativeHeight, formation, params.coverage) * params.density,\n heightFraction: relativeHeight,\n noise,\n weather: formation.weather,\n body: formation.body,\n erosion: formation.erosion,\n };\n}\n\nfunction cacheIndex(resolution: number, x: number, y: number, z: number): number {\n return z * resolution * resolution + y * resolution + x;\n}\n\nfunction digestBytes(data: Uint8Array): string {\n // FNV-1a is stable and intentionally cheap; this is an identity receipt,\n // not a cryptographic integrity boundary.\n let hash = 0x811c9dc5;\n for (const byte of data) {\n hash ^= byte;\n hash = Math.imul(hash, 0x01000193);\n }\n return (hash >>> 0).toString(16).padStart(8, '0');\n}\n\n/** Build one canonical, periodic formation cache. */\nexport function buildCloudDensityCache(\n params: ValidatedCloudLayer,\n profile: CloudQualityProfile = CLOUD_QUALITY_PROFILES[params.quality],\n): CloudDensityCache {\n const resolution = Math.max(4, Math.floor(profile.cacheResolution));\n const data = new Uint8Array(resolution * resolution * resolution);\n const formationData = new Uint8Array(data.byteLength * 3);\n const position = [0, 0, 0];\n for (let z = 0; z < resolution; z += 1) {\n for (let y = 0; y < resolution; y += 1) {\n position[1] = params.baseHeight + ((y + 0.5) / resolution) * params.thickness;\n for (let x = 0; x < resolution; x += 1) {\n // One cache period is one noise period in world space. This makes the\n // x/z addressing periodic and lets advection wrap without seams.\n position[0] = (x + 0.5) / resolution / params.scale;\n position[2] = (z + 0.5) / resolution / params.scale;\n const index = cacheIndex(resolution, x, y, z);\n const formation = evaluateCloudFormation(params, position, 0);\n formationData[index] = Math.round(saturate(formation.weather) * 255);\n formationData[data.byteLength + index] = Math.round(saturate(formation.body) * 255);\n formationData[data.byteLength * 2 + index] = Math.round(saturate(formation.erosion) * 255);\n }\n }\n }\n const cache: CloudDensityCache = {\n sourceKey: cloudLayerFormationKey(params),\n resolution,\n data,\n formationData,\n formationByteLength: formationData.byteLength,\n byteLength: formationData.byteLength,\n digest: digestBytes(formationData),\n };\n for (let z = 0; z < resolution; z++) {\n for (let y = 0; y < resolution; y++) {\n for (let x = 0; x < resolution; x++) {\n position[0] = (x + 0.5) / resolution / params.scale;\n position[1] = params.baseHeight + ((y + 0.5) / resolution) * params.thickness;\n position[2] = (z + 0.5) / resolution / params.scale;\n data[cacheIndex(resolution, x, y, z)] = Math.round(\n saturate(sampleCloudDensity(cache, params, position)) * 255,\n );\n }\n }\n }\n return Object.freeze(cache);\n}\n\n/** Export a detached snapshot suitable for persistence or a worker boundary. */\nexport function snapshotCloudDensityCache(cache: CloudDensityCache): CloudDensityCacheSnapshot {\n return Object.freeze({\n sourceKey: cache.sourceKey,\n resolution: cache.resolution,\n data: new Uint8Array(cache.data),\n formationData: new Uint8Array(cache.formationData),\n digest: cache.digest,\n });\n}\n\n/** Reconstruct a cache without running the procedural generator again. */\nexport function reconstructCloudDensityCache(\n params: ValidatedCloudLayer,\n snapshot: CloudDensityCacheSnapshot,\n): Result<CloudDensityCache, CloudLayerError> {\n const expectedKey = cloudLayerFormationKey(params);\n if (snapshot.sourceKey !== expectedKey) {\n return err(new CloudLayerCacheInvalidError(snapshot.sourceKey, 'source key mismatch'));\n }\n if (\n !Number.isInteger(snapshot.resolution) ||\n snapshot.resolution < 4 ||\n snapshot.resolution > 256 ||\n snapshot.data.byteLength !== snapshot.resolution ** 3 ||\n (snapshot.formationData !== undefined &&\n snapshot.formationData.byteLength !== snapshot.resolution ** 3 * 3)\n ) {\n return err(\n new CloudLayerCacheInvalidError(snapshot.sourceKey, 'resolution and payload length mismatch'),\n );\n }\n const formationData =\n snapshot.formationData === undefined\n ? new Uint8Array(snapshot.data.length * 3).fill(0)\n : new Uint8Array(snapshot.formationData);\n const digest = digestBytes(formationData);\n if (digest !== snapshot.digest) {\n return err(new CloudLayerCacheInvalidError(snapshot.sourceKey, 'payload digest mismatch'));\n }\n const data = new Uint8Array(snapshot.data);\n return ok(\n Object.freeze({\n sourceKey: snapshot.sourceKey,\n resolution: snapshot.resolution,\n data,\n formationData,\n formationByteLength: formationData.byteLength,\n byteLength: formationData.byteLength,\n digest,\n }),\n );\n}\n\nfunction wrapped(value: number, resolution: number): number {\n const result = value - Math.floor(value);\n return Math.min(resolution - 1e-6, Math.max(0, result * resolution));\n}\n\n/** Sample the cached field with periodic x/z addressing and wind advection. */\nexport function sampleCloudDensity(\n cache: CloudDensityCache,\n params: ValidatedCloudLayer,\n position: ArrayLike<number>,\n timeSeconds = 0,\n): number {\n const height = ((position[1] ?? 0) - params.baseHeight) / Math.max(1e-6, params.thickness);\n if (height <= 0 || height >= 1 || params.coverage <= 0 || params.density <= 0) return 0;\n const period = 1 / Math.max(1e-6, params.scale);\n const x = wrapped(\n ((position[0] ?? 0) + (params.wind[0] ?? 0) * timeSeconds) / period - 0.5 / cache.resolution,\n cache.resolution,\n );\n const z = wrapped(\n ((position[2] ?? 0) + (params.wind[2] ?? 0) * timeSeconds) / period - 0.5 / cache.resolution,\n cache.resolution,\n );\n // The cache's y axis stores the normalized formation coordinate before\n // vertical advection. Map the authored noise shift back through the same\n // vertical cell aspect used by formationField; the world-space envelope\n // below remains anchored to the current receiver height.\n const advectedHeight =\n height +\n ((params.wind[1] ?? 0) * timeSeconds * params.scale) / Math.max(1e-6, CLOUD_VERTICAL_CELLS);\n const y = wrapped(advectedHeight - 0.5 / cache.resolution, cache.resolution);\n const x0 = Math.floor(x);\n const y0 = Math.floor(y);\n const z0 = Math.floor(z);\n const x1 = (x0 + 1) % cache.resolution;\n const y1 = (y0 + 1) % cache.resolution;\n const z1 = (z0 + 1) % cache.resolution;\n const fx = x - x0;\n const fy = y - y0;\n const fz = z - z0;\n const stride = cache.resolution ** 3;\n if (cache.formationData === undefined || cache.formationData.byteLength < stride * 3) {\n const sampleLegacy = (sx: number, sy: number, sz: number): number =>\n (cache.data[cacheIndex(cache.resolution, sx, sy, sz)] ?? 0) / 255;\n const c00 =\n sampleLegacy(x0, y0, z0) + (sampleLegacy(x1, y0, z0) - sampleLegacy(x0, y0, z0)) * fx;\n const c10 =\n sampleLegacy(x0, y1, z0) + (sampleLegacy(x1, y1, z0) - sampleLegacy(x0, y1, z0)) * fx;\n const c01 =\n sampleLegacy(x0, y0, z1) + (sampleLegacy(x1, y0, z1) - sampleLegacy(x0, y0, z1)) * fx;\n const c11 =\n sampleLegacy(x0, y1, z1) + (sampleLegacy(x1, y1, z1) - sampleLegacy(x0, y1, z1)) * fx;\n return (\n (c00 + (c10 - c00) * fy + (c01 + (c11 - c01) * fy - (c00 + (c10 - c00) * fy)) * fz) *\n heightEnvelope(height, 1, 0.5) *\n params.density\n );\n }\n const samplePlane = (plane: number, sx: number, sy: number, sz: number): number => {\n const payload = cache.formationData;\n const offset = plane * stride + cacheIndex(cache.resolution, sx, sy, sz);\n return (payload[offset] ?? 0) / 255;\n };\n const sample = (plane: number): number => {\n const repeat = plane === 2 ? 3 : 1;\n const sx = wrapped(\n ((x + 0.5) / cache.resolution) * repeat - 0.5 / cache.resolution,\n cache.resolution,\n );\n const sy = wrapped(\n ((y + 0.5) / cache.resolution) * repeat - 0.5 / cache.resolution,\n cache.resolution,\n );\n const sz = wrapped(\n ((z + 0.5) / cache.resolution) * repeat - 0.5 / cache.resolution,\n cache.resolution,\n );\n const x0 = Math.floor(sx),\n y0 = Math.floor(sy),\n z0 = Math.floor(sz);\n const x1 = (x0 + 1) % cache.resolution,\n y1 = (y0 + 1) % cache.resolution,\n z1 = (z0 + 1) % cache.resolution;\n const fx = sx - x0,\n fy = sy - y0,\n fz = sz - z0;\n\n const c00 =\n samplePlane(plane, x0, y0, z0) +\n (samplePlane(plane, x1, y0, z0) - samplePlane(plane, x0, y0, z0)) * fx;\n const c10 =\n samplePlane(plane, x0, y1, z0) +\n (samplePlane(plane, x1, y1, z0) - samplePlane(plane, x0, y1, z0)) * fx;\n const c01 =\n samplePlane(plane, x0, y0, z1) +\n (samplePlane(plane, x1, y0, z1) - samplePlane(plane, x0, y0, z1)) * fx;\n const c11 =\n samplePlane(plane, x0, y1, z1) +\n (samplePlane(plane, x1, y1, z1) - samplePlane(plane, x0, y1, z1)) * fx;\n return c00 + (c10 - c00) * fy + (c01 + (c11 - c01) * fy - (c00 + (c10 - c00) * fy)) * fz;\n };\n const weather = sample(0);\n const body = sample(1);\n const erosion = sample(2);\n return (\n composeCloudDensity(height, { weather, body, erosion, noise: body }, params.coverage) *\n params.density\n );\n}\n","import type { RhiCaps } from '@forgeax/engine-rhi';\nimport type { CloudLayerResourceFacts } from './resources';\nimport type { CloudTemporalResetReason } from './temporal';\n\nexport type CloudLayerInspectionStatus = 'off' | 'available' | 'unavailable' | 'degraded';\nexport type CloudLayerResourceStage = 'none' | 'candidate' | 'accepted' | 'lkg' | 'recovering';\n/** Physical-adapter evidence is explicit; RHI backend labels cannot prove it. */\nexport type CloudPhysicalGpuEvidence = 'unknown' | 'available' | 'unavailable';\n\nexport interface CloudLayerBudgetObservation {\n readonly measured: boolean;\n readonly physicalGpu: CloudPhysicalGpuEvidence;\n readonly gpuTimestamp: boolean;\n readonly quality: 'low' | 'medium' | 'high' | undefined;\n readonly warmupFrames: number;\n readonly sampleFrames: number;\n readonly p50GpuMs: number | undefined;\n readonly p95GpuMs: number | undefined;\n readonly coldGenerationMs: number | undefined;\n readonly frameBudgetMs: number | undefined;\n readonly reason?: string;\n}\n\nexport interface CloudLayerInspection {\n readonly status: CloudLayerInspectionStatus;\n readonly resourceStage: CloudLayerResourceStage;\n readonly sourceKey: string | undefined;\n readonly generation: number | undefined;\n readonly candidateGeneration: number | undefined;\n readonly lkgGeneration: number | undefined;\n readonly shadowRevision: number | undefined;\n readonly temporalResets: number;\n readonly lastTemporalReset: CloudTemporalResetReason | undefined;\n readonly resourceFacts: CloudLayerResourceFacts | undefined;\n readonly capability: {\n readonly compute: boolean;\n readonly storageBuffer: boolean;\n readonly rgba16floatRenderable: boolean;\n readonly physicalGpu: CloudPhysicalGpuEvidence;\n readonly timestampQuery: boolean;\n };\n readonly budget: CloudLayerBudgetObservation;\n}\n\nexport interface CloudLayerInspectionInput {\n readonly authored: boolean;\n readonly sourceKey?: string;\n readonly generation?: number;\n readonly candidateGeneration?: number;\n readonly lkgGeneration?: number;\n readonly shadowRevision?: number;\n readonly temporalResets?: number;\n readonly lastTemporalReset?: CloudTemporalResetReason;\n readonly resourceFacts?: CloudLayerResourceFacts;\n readonly capability?: Partial<CloudLayerInspection['capability']>;\n readonly degraded?: boolean;\n readonly budget?: Partial<CloudLayerBudgetObservation>;\n}\n\nfunction resourceStage(input: CloudLayerInspectionInput): CloudLayerResourceStage {\n if (!input.authored || input.generation === undefined) return 'none';\n if (input.candidateGeneration !== undefined) return 'candidate';\n if (input.degraded === true || input.lkgGeneration !== undefined) return 'lkg';\n return 'accepted';\n}\n\n/** Capability and lifecycle facts are inspectable even when the lane is unavailable. */\nexport function inspectCloudLayer(input: CloudLayerInspectionInput): CloudLayerInspection {\n const capability = {\n compute: input.capability?.compute ?? false,\n storageBuffer: input.capability?.storageBuffer ?? false,\n rgba16floatRenderable: input.capability?.rgba16floatRenderable ?? false,\n physicalGpu: input.capability?.physicalGpu ?? 'unknown',\n timestampQuery: input.capability?.timestampQuery ?? false,\n };\n const budget: CloudLayerBudgetObservation = {\n measured: input.budget?.measured ?? false,\n physicalGpu: input.budget?.physicalGpu ?? capability.physicalGpu,\n gpuTimestamp: input.budget?.gpuTimestamp ?? capability.timestampQuery,\n quality: input.budget?.quality,\n warmupFrames: input.budget?.warmupFrames ?? 0,\n sampleFrames: input.budget?.sampleFrames ?? 0,\n p50GpuMs: input.budget?.p50GpuMs,\n p95GpuMs: input.budget?.p95GpuMs,\n coldGenerationMs: input.budget?.coldGenerationMs,\n frameBudgetMs: input.budget?.frameBudgetMs,\n ...(input.budget?.reason === undefined ? {} : { reason: input.budget.reason }),\n };\n // CloudLayer's production plan allocates an HDR shadow/composite target and\n // therefore requires the complete feature capability tuple. Reporting\n // `available` from compute/storage alone lets inspection lie while the graph\n // admission correctly disables the feature on LDR-only adapters.\n const available =\n capability.compute && capability.storageBuffer && capability.rgba16floatRenderable;\n return Object.freeze({\n status: !input.authored\n ? 'off'\n : !available\n ? 'unavailable'\n : input.degraded === true\n ? 'degraded'\n : 'available',\n resourceStage: resourceStage(input),\n sourceKey: input.sourceKey,\n generation: input.generation,\n candidateGeneration: input.candidateGeneration,\n lkgGeneration: input.lkgGeneration,\n shadowRevision: input.shadowRevision,\n temporalResets: input.temporalResets ?? 0,\n lastTemporalReset: input.lastTemporalReset,\n resourceFacts: input.resourceFacts,\n capability,\n budget,\n });\n}\n\n/** Convert RHI facts without letting inspection invent physical measurements. */\nexport function cloudCapabilitiesFromRhi(\n caps: Readonly<RhiCaps>,\n): CloudLayerInspection['capability'] {\n return Object.freeze({\n compute: caps.compute === true,\n storageBuffer: caps.storageBuffer === true,\n rgba16floatRenderable: caps.rgba16floatRenderable === true,\n // RHI caps intentionally do not claim a physical adapter. A browser or\n // Dawn receipt must promote this fact to available/unavailable.\n physicalGpu: 'unknown',\n timestampQuery: caps.timestampQuery === true,\n });\n}\n","import type { CloudDensityCache } from './density';\nimport type { CloudShadowProjection } from './shadow';\nimport type { CloudHistory } from './temporal';\n\n/** Evidence level for bytes owned by the prepared GPU path. */\nexport type CloudGpuResourceEvidence = 'unavailable' | 'declared' | 'measured';\n\n/** rgba16float is four 16-bit channels (8 bytes per texel). */\nexport const CLOUD_RGBA16FLOAT_BYTES_PER_TEXEL = 8;\n/** Two ping-pong surfaces for each of radiance/transmittance/depth. */\nexport const CLOUD_HISTORY_SURFACE_COUNT = 6;\n\nexport interface CloudLayerResourceFacts {\n readonly generation: number;\n /** CPU-side packed formation payload; this is not GPU residency. */\n readonly cacheBytes: number;\n /** Measured GPU bytes, or zero when no prepared-owner receipt was supplied. */\n readonly shadowBytes: number;\n readonly historyBytes: number;\n readonly inFlightBytes: number;\n readonly residentBytes: number;\n readonly resourceCount: number;\n /** Whether the GPU byte fields are measured, only graph-declared, or unknown. */\n readonly gpuEvidence: CloudGpuResourceEvidence;\n /** Descriptor-derived allocation sizes, independent from physical residency. */\n readonly declaredShadowBytes: number;\n readonly declaredHistoryBytes: number;\n readonly declaredResidentBytes: number;\n readonly declaredResourceCount: number;\n /** Measured GPU resource count, kept separate from logical declarations. */\n readonly measuredGpuResourceCount: number;\n readonly cacheResolution: number;\n readonly shadowResolution: number;\n}\n\nexport interface CloudLayerResourceInputs {\n readonly generation: number;\n readonly cache?: CloudDensityCache;\n readonly shadow?: CloudShadowProjection;\n readonly history?: CloudHistory;\n /** Bytes reported by the prepared GPU owner; absent means unavailable. */\n readonly shadowBytes?: number;\n readonly historyBytes?: number;\n readonly inFlightBytes?: number;\n}\n\n/** Derive one inspection receipt from the resources owned by the current generation. */\nexport function inspectCloudLayerResources(\n input: CloudLayerResourceInputs,\n): CloudLayerResourceFacts {\n const cacheBytes = input.cache?.byteLength ?? 0;\n const shadowResolution = input.shadow?.resolution ?? 0;\n const declaredShadowBytes =\n shadowResolution * shadowResolution * CLOUD_RGBA16FLOAT_BYTES_PER_TEXEL;\n const historyWidth = input.history?.width ?? 0;\n const historyHeight = input.history?.height ?? 0;\n const declaredHistoryBytes =\n historyWidth * historyHeight * CLOUD_HISTORY_SURFACE_COUNT * CLOUD_RGBA16FLOAT_BYTES_PER_TEXEL;\n const shadowBytes = input.shadowBytes ?? 0;\n const historyBytes = input.historyBytes ?? 0;\n const inFlightBytes = Math.max(0, input.inFlightBytes ?? 0);\n const residentBytes = cacheBytes + shadowBytes + historyBytes;\n const measuredGpuResourceCount =\n Number(input.shadowBytes !== undefined) + Number(input.historyBytes !== undefined);\n const gpuEvidence: CloudGpuResourceEvidence =\n measuredGpuResourceCount > 0 || input.inFlightBytes !== undefined\n ? 'measured'\n : input.shadow !== undefined || input.history !== undefined\n ? 'declared'\n : 'unavailable';\n const resourceCount =\n Number(input.cache !== undefined) +\n Number(input.shadow !== undefined) +\n Number(input.history !== undefined);\n return Object.freeze({\n generation: input.generation,\n cacheBytes,\n shadowBytes,\n historyBytes,\n inFlightBytes,\n residentBytes,\n resourceCount,\n gpuEvidence,\n declaredShadowBytes,\n declaredHistoryBytes,\n declaredResidentBytes: cacheBytes + declaredShadowBytes + declaredHistoryBytes,\n declaredResourceCount: resourceCount,\n measuredGpuResourceCount,\n cacheResolution: input.cache?.resolution ?? 0,\n shadowResolution,\n });\n}\n\nexport interface CloudLayerGeneration {\n readonly generation: number;\n readonly sourceKey: string;\n readonly resourceFacts: CloudLayerResourceFacts;\n readonly status: 'candidate' | 'active' | 'lkg' | 'retiring';\n}\n\n/** Candidate -> active transition used by the renderer's existing graph owner. */\nexport function acceptCloudLayerGeneration(\n candidate: CloudLayerGeneration,\n previous: CloudLayerGeneration | undefined,\n): { readonly active: CloudLayerGeneration; readonly lkg: CloudLayerGeneration | undefined } {\n return Object.freeze({\n active: Object.freeze({ ...candidate, status: 'active' as const }),\n lkg:\n previous === undefined ? undefined : Object.freeze({ ...previous, status: 'lkg' as const }),\n });\n}\n\n/** A failed candidate never replaces the LKG; retirement is fence-owned by Render. */\nexport function retainCloudLayerAfterFailure(\n active: CloudLayerGeneration | undefined,\n candidate: CloudLayerGeneration,\n): { readonly active: CloudLayerGeneration | undefined; readonly retiring: CloudLayerGeneration } {\n return Object.freeze({\n active,\n retiring: Object.freeze({ ...candidate, status: 'retiring' as const }),\n });\n}\n","import type { CloudDensityCache } from './density';\nimport { evaluateCloudDensity, sampleCloudDensity } from './density';\nimport { CLOUD_EXTINCTION_COEFFICIENT, type ValidatedCloudLayer } from './parameters';\n\nexport type CloudOpticalPath = 'camera' | 'solar-column' | 'cloud-interior';\n\nexport interface CloudRay {\n readonly origin: readonly [number, number, number];\n readonly direction: readonly [number, number, number];\n readonly maxDistance: number;\n}\n\nexport interface CloudOpticalResult {\n readonly path: CloudOpticalPath;\n readonly transmittance: number;\n readonly scattering: readonly [number, number, number];\n readonly opticalDepth: number;\n readonly representativeDepth: number;\n readonly steps: number;\n readonly entered: boolean;\n readonly exited: boolean;\n}\n\nexport interface CloudInteriorLighting {\n readonly sunRadiance: readonly [number, number, number];\n readonly sunDirection: readonly [number, number, number];\n readonly phaseG?: number;\n}\n\nexport interface CloudOpticsInput {\n readonly params: ValidatedCloudLayer;\n readonly ray: CloudRay;\n readonly path: CloudOpticalPath;\n readonly timeSeconds?: number;\n readonly cache?: CloudDensityCache;\n readonly steps?: number;\n readonly lighting?: CloudInteriorLighting;\n}\n\nconst EMPTY_SCATTERING: readonly [number, number, number] = [0, 0, 0];\n\nfunction normalize(vector: ArrayLike<number>): readonly [number, number, number] {\n const x = vector[0] ?? 0;\n const y = vector[1] ?? 0;\n const z = vector[2] ?? 0;\n const length = Math.hypot(x, y, z);\n return length <= 1e-8 ? [0, 1, 0] : [x / length, y / length, z / length];\n}\n\nfunction rayBoxInterval(\n ray: CloudRay,\n params: ValidatedCloudLayer,\n): { readonly start: number; readonly end: number } | undefined {\n const min = [Number.NEGATIVE_INFINITY, params.baseHeight, Number.NEGATIVE_INFINITY];\n const max = [\n Number.POSITIVE_INFINITY,\n params.baseHeight + params.thickness,\n Number.POSITIVE_INFINITY,\n ];\n let start = 0;\n let end = Math.max(0, ray.maxDistance);\n for (let axis = 0; axis < 3; axis += 1) {\n const origin = ray.origin[axis] ?? 0;\n const direction = ray.direction[axis] ?? 0;\n const lower = min[axis] ?? 0;\n const upper = max[axis] ?? 0;\n if (Math.abs(direction) < 1e-8) {\n if (origin < lower || origin > upper) return undefined;\n continue;\n }\n const a = (lower - origin) / direction;\n const b = (upper - origin) / direction;\n start = Math.max(start, Math.min(a, b));\n end = Math.min(end, Math.max(a, b));\n if (end <= start) return undefined;\n }\n return end > start ? { start, end } : undefined;\n}\n\nexport function intersectCloudLayer(\n ray: CloudRay,\n params: ValidatedCloudLayer,\n): { readonly start: number; readonly end: number } | undefined {\n return rayBoxInterval(ray, params);\n}\n\nfunction phaseFunction(cosTheta: number, g: number): number {\n const boundedG = Math.max(-0.95, Math.min(0.95, g));\n const denominator = Math.max(1e-4, 1 + boundedG * boundedG - 2 * boundedG * cosTheta);\n return ((1 - boundedG * boundedG) / denominator ** 1.5) * (1 / (4 * Math.PI));\n}\n\nfunction cloudPhase(cosTheta: number, forwardG: number): number {\n // Match the bounded dual-lobe phase used by the fullscreen WGSL path.\n return phaseFunction(cosTheta, forwardG) * 0.8 + phaseFunction(cosTheta, -0.2) * 0.2;\n}\n\nfunction smoothstep(edge0: number, edge1: number, value: number): number {\n const t = Math.max(0, Math.min(1, (value - edge0) / Math.max(1e-6, edge1 - edge0)));\n return t * t * (3 - 2 * t);\n}\n\n/** Unit-sun incident light, using the same phase basis as production volumes. */\nexport function cloudIncidentLight(\n solarT: number,\n cosTheta: number,\n height: number,\n forwardG = 0.55,\n): readonly [number, number, number] {\n const direct = solarT * cloudPhase(cosTheta, forwardG);\n const multiple = (0.5 * Math.sqrt(solarT) + 0.25 * solarT ** 0.25) / (4 * Math.PI);\n const energy = (direct + multiple) * (4 * Math.PI);\n const skyFill = 0.025 + 0.05 * smoothstep(0.1, 0.85, height);\n return [energy + 0.72 * skyFill, energy + 0.84 * skyFill, energy + skyFill];\n}\n\nfunction densityAt(input: CloudOpticsInput, position: readonly [number, number, number]): number {\n return input.cache === undefined\n ? evaluateCloudDensity(input.params, position, input.timeSeconds ?? 0).density\n : sampleCloudDensity(input.cache, input.params, position, input.timeSeconds ?? 0);\n}\n\n/**\n * Integrate one explicitly named optical path through the layer.\n *\n * Camera, solar-column and cloud-interior paths are intentionally separate\n * call sites. A caller cannot accidentally use a camera interval as the\n * light interval and apply the same cloud attenuation twice.\n */\nexport function integrateCloudPath(input: CloudOpticsInput): CloudOpticalResult {\n const direction = normalize(input.ray.direction);\n const interval = rayBoxInterval({ ...input.ray, direction }, input.params);\n if (interval === undefined || input.params.density <= 0) {\n return {\n path: input.path,\n transmittance: 1,\n scattering: EMPTY_SCATTERING,\n opticalDepth: 0,\n representativeDepth: input.ray.maxDistance,\n steps: 0,\n entered: false,\n exited: false,\n };\n }\n const steps = Math.max(1, Math.floor(input.steps ?? 32));\n const length = interval.end - interval.start;\n const stepLength = length / steps;\n let opticalDepth = 0;\n const scattering: [number, number, number] = [0, 0, 0];\n let weightedDepth = 0;\n let scatteringWeight = 0;\n const lighting = input.lighting;\n const lightDirection = lighting === undefined ? undefined : normalize(lighting.sunDirection);\n const viewDirection = normalize(input.ray.direction);\n for (let index = 0; index < steps; index += 1) {\n const distance = interval.start + (index + 0.5) * stepLength;\n const position: [number, number, number] = [\n (input.ray.origin[0] ?? 0) + direction[0] * distance,\n (input.ray.origin[1] ?? 0) + direction[1] * distance,\n (input.ray.origin[2] ?? 0) + direction[2] * distance,\n ];\n const localDensity = Math.max(0, densityAt(input, position));\n const extinction = localDensity * CLOUD_EXTINCTION_COEFFICIENT * stepLength;\n const transmittanceBefore = Math.exp(-opticalDepth);\n opticalDepth += extinction;\n if (lighting !== undefined && lightDirection !== undefined && localDensity > 0) {\n const localShadow = integrateCloudPath({\n params: input.params,\n path: 'solar-column',\n ray: {\n origin: position,\n direction: lightDirection,\n maxDistance: input.params.shadowRange,\n },\n steps: Math.max(4, Math.ceil((input.steps ?? 32) * 0.5)),\n ...(input.timeSeconds === undefined ? {} : { timeSeconds: input.timeSeconds }),\n ...(input.cache === undefined ? {} : { cache: input.cache }),\n });\n const cosTheta =\n viewDirection[0] * lightDirection[0] +\n viewDirection[1] * lightDirection[1] +\n viewDirection[2] * lightDirection[2];\n const segmentWeight = transmittanceBefore * (1 - Math.exp(-extinction));\n const heightFraction = Math.max(\n 0,\n Math.min(1, ((position[1] ?? 0) - input.params.baseHeight) / input.params.thickness),\n );\n const incident = cloudIncidentLight(\n localShadow.transmittance,\n cosTheta,\n heightFraction,\n lighting.phaseG,\n );\n for (let channel = 0; channel < 3; channel++) {\n scattering[channel] =\n (scattering[channel] ?? 0) +\n (lighting.sunRadiance[channel] ?? 0) * (incident[channel] ?? 0) * segmentWeight;\n }\n const weight = segmentWeight;\n scatteringWeight += weight;\n weightedDepth += distance * weight;\n }\n }\n const transmittance = Math.exp(-opticalDepth);\n return {\n path: input.path,\n transmittance,\n scattering,\n opticalDepth,\n representativeDepth:\n scatteringWeight > 1e-6 ? weightedDepth / scatteringWeight : interval.start,\n steps,\n entered: true,\n exited: interval.end < input.ray.maxDistance,\n };\n}\n\nexport function integrateCloudCameraPath(\n params: ValidatedCloudLayer,\n ray: CloudRay,\n options: Omit<CloudOpticsInput, 'params' | 'ray' | 'path'> = {},\n): CloudOpticalResult {\n return integrateCloudPath({ ...options, params, ray, path: 'camera' });\n}\n\nexport function integrateCloudSolarColumn(\n params: ValidatedCloudLayer,\n origin: readonly [number, number, number],\n sunDirection: readonly [number, number, number],\n options: Omit<CloudOpticsInput, 'params' | 'ray' | 'path'> & {\n readonly maxDistance?: number;\n } = {},\n): CloudOpticalResult {\n return integrateCloudPath({\n ...options,\n params,\n path: 'solar-column',\n ray: {\n origin,\n direction: sunDirection,\n maxDistance: options.maxDistance ?? params.shadowRange,\n },\n });\n}\n\nexport function integrateCloudInterior(\n params: ValidatedCloudLayer,\n ray: CloudRay,\n lighting: CloudInteriorLighting,\n options: Omit<CloudOpticsInput, 'params' | 'ray' | 'path' | 'lighting'> = {},\n): CloudOpticalResult {\n return integrateCloudPath({ ...options, params, ray, path: 'cloud-interior', lighting });\n}\n\n/** Standard's one selected sun term consumes this factor exactly once. */\nexport function applyCloudSolarTransmittance(\n directSunRadiance: readonly [number, number, number],\n cloudTransmittance: number,\n meshVisibility = 1,\n): readonly [number, number, number] {\n const factor =\n Math.min(1, Math.max(0, cloudTransmittance)) * Math.min(1, Math.max(0, meshVisibility));\n return [\n (directSunRadiance[0] ?? 0) * factor,\n (directSunRadiance[1] ?? 0) * factor,\n (directSunRadiance[2] ?? 0) * factor,\n ];\n}\n\n/** Scene-linear HDR composition at the cloud interval/depth boundary. */\nexport function compositeCloudRadiance(\n sceneLinearHdr: readonly [number, number, number, number],\n cloud: CloudOpticalResult,\n sceneDepth: number,\n cloudDepth = cloud.representativeDepth,\n): readonly [number, number, number, number] {\n if (!Number.isFinite(sceneDepth) || cloudDepth > sceneDepth) return sceneLinearHdr;\n const transmittance = Math.min(1, Math.max(0, cloud.transmittance));\n return [\n (sceneLinearHdr[0] ?? 0) * transmittance + (cloud.scattering[0] ?? 0),\n (sceneLinearHdr[1] ?? 0) * transmittance + (cloud.scattering[1] ?? 0),\n (sceneLinearHdr[2] ?? 0) * transmittance + (cloud.scattering[2] ?? 0),\n 1,\n ];\n}\n","import type { CloudDensityCache } from './density';\nimport { integrateCloudSolarColumn } from './optics';\nimport type { ValidatedCloudLayer } from './parameters';\n\nexport interface CloudShadowProjection {\n readonly revision: number;\n readonly resolution: number;\n readonly range: number;\n readonly texelSize: number;\n readonly center: readonly [number, number, number];\n readonly origin: readonly [number, number, number];\n readonly right: readonly [number, number, number];\n readonly up: readonly [number, number, number];\n readonly sunDirection: readonly [number, number, number];\n readonly lowSun: boolean;\n}\n\nexport interface CloudShadowSample {\n readonly transmittance: number;\n readonly uv: readonly [number, number] | undefined;\n readonly valid: boolean;\n readonly fallback: 'none' | 'low-sun' | 'outside-range' | 'empty-coverage';\n readonly revision: number;\n}\n\nfunction normalize(vector: ArrayLike<number>): readonly [number, number, number] {\n const x = vector[0] ?? 0;\n const y = vector[1] ?? 0;\n const z = vector[2] ?? 0;\n const length = Math.hypot(x, y, z);\n return length <= 1e-8 ? [0, 1, 0] : [x / length, y / length, z / length];\n}\n\nfunction cross(\n a: readonly [number, number, number],\n b: readonly [number, number, number],\n): readonly [number, number, number] {\n return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];\n}\n\nfunction dot(a: ArrayLike<number>, b: ArrayLike<number>): number {\n return (a[0] ?? 0) * (b[0] ?? 0) + (a[1] ?? 0) * (b[1] ?? 0) + (a[2] ?? 0) * (b[2] ?? 0);\n}\n\nfunction stableRevision(input: {\n readonly center: readonly [number, number, number];\n readonly sunDirection: readonly [number, number, number];\n readonly range: number;\n readonly resolution: number;\n}): number {\n let hash = 2166136261;\n const values = [...input.center, ...input.sunDirection, input.range, input.resolution];\n for (const value of values) {\n const bits = new Float32Array([value]);\n const bytes = new Uint8Array(bits.buffer);\n for (const byte of bytes) hash = Math.imul(hash ^ byte, 16777619);\n }\n return hash >>> 0;\n}\n\n/**\n * Build a camera-independent light-space projection. The center is a world\n * anchor chosen by Render (usually the active scene bounds), and is snapped to\n * one texel so camera motion cannot crawl the cloud shadow.\n */\nexport function createCloudShadowProjection(input: {\n readonly center: readonly [number, number, number];\n readonly sunDirection: readonly [number, number, number];\n readonly range: number;\n readonly resolution?: number;\n}): CloudShadowProjection {\n const sunDirection = normalize(input.sunDirection);\n const resolution = Math.max(16, Math.floor(input.resolution ?? 1024));\n const range = Math.max(1, input.range);\n const texelSize = range / resolution;\n const reference = Math.abs(sunDirection[1]) < 0.95 ? ([0, 1, 0] as const) : ([1, 0, 0] as const);\n const right = normalize(cross(reference, sunDirection));\n const up = normalize(cross(sunDirection, right));\n const center = input.center;\n const lightX = dot(center, right);\n const lightY = dot(center, up);\n const lightZ = dot(center, sunDirection);\n const snappedX = Math.floor(lightX / texelSize + 0.5) * texelSize;\n const snappedY = Math.floor(lightY / texelSize + 0.5) * texelSize;\n const origin: [number, number, number] = [\n right[0] * snappedX + up[0] * snappedY + sunDirection[0] * lightZ,\n right[1] * snappedX + up[1] * snappedY + sunDirection[1] * lightZ,\n right[2] * snappedX + up[2] * snappedY + sunDirection[2] * lightZ,\n ];\n return Object.freeze({\n revision: stableRevision({ center, sunDirection, range, resolution }),\n resolution,\n range,\n texelSize,\n center: Object.freeze([...center] as [number, number, number]),\n origin: Object.freeze(origin),\n right,\n up,\n sunDirection,\n lowSun: sunDirection[1] <= 0.08,\n });\n}\n\nexport function projectCloudShadowUv(\n projection: CloudShadowProjection,\n position: readonly [number, number, number],\n): { readonly uv: readonly [number, number]; readonly inRange: boolean } {\n const relative: [number, number, number] = [\n position[0] - projection.origin[0],\n position[1] - projection.origin[1],\n position[2] - projection.origin[2],\n ];\n const x = dot(relative, projection.right);\n const y = dot(relative, projection.up);\n const uv: [number, number] = [0.5 + x / projection.range, 0.5 + y / projection.range];\n return { uv, inRange: uv[0] >= 0 && uv[0] <= 1 && uv[1] >= 0 && uv[1] <= 1 };\n}\n\n/** Evaluate the stable world-space shadow term used by surface and volume sun paths. */\nexport function sampleCloudShadow(\n params: ValidatedCloudLayer,\n projection: CloudShadowProjection,\n worldPosition: readonly [number, number, number],\n options: { readonly cache?: CloudDensityCache; readonly timeSeconds?: number } = {},\n): CloudShadowSample {\n const projected = projectCloudShadowUv(projection, worldPosition);\n if (projection.lowSun) {\n return {\n transmittance: 1,\n uv: projected.uv,\n valid: false,\n fallback: 'low-sun',\n revision: projection.revision,\n };\n }\n if (!projected.inRange) {\n return {\n transmittance: 1,\n uv: projected.uv,\n valid: false,\n fallback: 'outside-range',\n revision: projection.revision,\n };\n }\n if (params.coverage >= 1 || params.density <= 0) {\n return {\n transmittance: 1,\n uv: projected.uv,\n valid: false,\n fallback: 'empty-coverage',\n revision: projection.revision,\n };\n }\n const integrated = integrateCloudSolarColumn(params, worldPosition, projection.sunDirection, {\n steps: 20,\n maxDistance: projection.range,\n ...(options.cache === undefined ? {} : { cache: options.cache }),\n ...(options.timeSeconds === undefined ? {} : { timeSeconds: options.timeSeconds }),\n });\n return {\n transmittance: integrated.transmittance,\n uv: projected.uv,\n valid: integrated.entered,\n fallback: 'none',\n revision: projection.revision,\n };\n}\n","import type { CloudQuality } from '../components/cloud-layer';\n\nexport type CloudTemporalResetReason =\n | 'authoring-generation'\n | 'camera-cut'\n | 'resize'\n | 'recovery'\n | 'time-discontinuity'\n | 'cloud-shadow-revision'\n | 'device-generation'\n | 'history-missing'\n | 'reprojection-outside'\n | 'scene-depth-disocclusion';\n\nexport interface CloudTemporalSignature {\n readonly sourceKey: string;\n readonly viewId: string;\n readonly authoringGeneration: number;\n readonly cloudShadowRevision: number;\n readonly cameraRevision: number;\n readonly deviceGeneration: number;\n readonly width: number;\n readonly height: number;\n readonly timeSeconds: number;\n readonly quality: CloudQuality;\n /** Scene-depth producer revision used to reject disoccluded history. */\n readonly sceneDepthVersion?: number;\n}\n\nexport interface CloudHistory {\n readonly width: number;\n readonly height: number;\n readonly signature: string;\n readonly temporal: CloudTemporalSignature;\n readonly generation: number;\n readonly valid: boolean;\n}\n\nexport interface CloudTemporalDecision {\n readonly reset: boolean;\n readonly reasons: readonly CloudTemporalResetReason[];\n readonly signature: string;\n readonly history: CloudHistory | undefined;\n}\n\nexport interface CloudTemporalFrame {\n readonly signature: CloudTemporalSignature;\n readonly history: CloudHistory | undefined;\n readonly reset: boolean;\n readonly reasons: readonly CloudTemporalResetReason[];\n}\n\nexport interface CloudHistoryReprojectionInput {\n readonly currentDepth: number;\n readonly historyDepth: number;\n readonly motion: readonly [number, number];\n readonly currentPixel: readonly [number, number];\n readonly historySize: readonly [number, number];\n readonly depthTolerance?: number;\n}\n\nexport interface CloudHistoryReprojection {\n readonly accepted: boolean;\n readonly historyUv: readonly [number, number];\n readonly weight: number;\n readonly reason: 'accepted' | 'outside' | 'depth-disocclusion';\n}\n\nexport function cloudTemporalSignature(input: CloudTemporalSignature): string {\n return [\n 'cloud-temporal-v1',\n input.viewId,\n input.sourceKey,\n input.authoringGeneration,\n input.cloudShadowRevision,\n input.cameraRevision,\n input.deviceGeneration,\n input.width,\n input.height,\n input.timeSeconds,\n input.quality,\n input.sceneDepthVersion ?? 0,\n ].join(':');\n}\n\nfunction sameLayout(left: CloudTemporalSignature, right: CloudTemporalSignature): boolean {\n return left.viewId === right.viewId && left.width === right.width && left.height === right.height;\n}\n\n/** Compare the facts that make a cloud history safe to reuse. */\nexport function cloudTemporalResetReasons(\n previous: CloudTemporalSignature | undefined,\n next: CloudTemporalSignature,\n options: { readonly cameraCut?: boolean; readonly recovery?: boolean } = {},\n): readonly CloudTemporalResetReason[] {\n if (previous === undefined) return ['history-missing'];\n const reasons: CloudTemporalResetReason[] = [];\n if (\n previous.sourceKey !== next.sourceKey ||\n previous.authoringGeneration !== next.authoringGeneration\n ) {\n reasons.push('authoring-generation');\n }\n if (previous.cloudShadowRevision !== next.cloudShadowRevision)\n reasons.push('cloud-shadow-revision');\n if (previous.deviceGeneration !== next.deviceGeneration) reasons.push('device-generation');\n if (\n previous.sceneDepthVersion !== undefined &&\n next.sceneDepthVersion !== undefined &&\n previous.sceneDepthVersion !== next.sceneDepthVersion\n ) {\n reasons.push('scene-depth-disocclusion');\n }\n if (!sameLayout(previous, next)) reasons.push('resize');\n if (options.cameraCut === true || previous.cameraRevision !== next.cameraRevision)\n reasons.push('camera-cut');\n const dt = next.timeSeconds - previous.timeSeconds;\n if (!Number.isFinite(dt) || dt < 0 || dt > 0.5) reasons.push('time-discontinuity');\n if (options.recovery === true) reasons.push('recovery');\n return Object.freeze(reasons);\n}\n\nexport function createCloudHistory(\n signature: CloudTemporalSignature,\n generation: number,\n valid = false,\n): CloudHistory {\n return Object.freeze({\n width: Math.max(1, Math.floor(signature.width)),\n height: Math.max(1, Math.floor(signature.height)),\n signature: cloudTemporalSignature(signature),\n temporal: Object.freeze({ ...signature }),\n generation,\n valid,\n });\n}\n\n/** Per-view histories are keyed by the renderer's view identity. */\nexport class CloudHistoryStore {\n private readonly maxViews: number;\n private readonly entries = new Map<\n string,\n { readonly history: CloudHistory; readonly signature: CloudTemporalSignature }\n >();\n\n constructor(maxViews = 4) {\n this.maxViews = Math.max(1, Math.floor(maxViews));\n }\n\n begin(\n signature: CloudTemporalSignature,\n options: { readonly cameraCut?: boolean; readonly recovery?: boolean } = {},\n ): CloudTemporalDecision {\n const key = signature.viewId;\n const previousEntry = this.entries.get(key);\n const previous = previousEntry?.history;\n const reasons = cloudTemporalResetReasons(previousEntry?.signature, signature, options);\n const reset = reasons.length > 0;\n return Object.freeze({\n reset,\n reasons,\n signature: cloudTemporalSignature(signature),\n history: reset ? undefined : previous,\n });\n }\n\n commit(signature: CloudTemporalSignature, history: CloudHistory): void {\n if (\n history.width !== Math.max(1, Math.floor(signature.width)) ||\n history.height !== Math.max(1, Math.floor(signature.height))\n ) {\n this.entries.delete(signature.viewId);\n return;\n }\n this.entries.set(signature.viewId, { history, signature: Object.freeze({ ...signature }) });\n while (this.entries.size > this.maxViews) {\n const oldest = this.entries.keys().next().value as string | undefined;\n if (oldest === undefined) break;\n this.entries.delete(oldest);\n }\n }\n\n reset(viewId?: string): void {\n if (viewId === undefined) this.entries.clear();\n else this.entries.delete(viewId);\n }\n\n get(viewId: string): CloudHistory | undefined {\n return this.entries.get(viewId)?.history;\n }\n\n dispose(): void {\n this.entries.clear();\n }\n}\n\n/** Project one current pixel into the previous cloud history. */\nexport function reprojectCloudHistory(\n input: CloudHistoryReprojectionInput,\n historyWeight = 0.9,\n): CloudHistoryReprojection {\n const width = Math.max(1, input.historySize[0] ?? 1);\n const height = Math.max(1, input.historySize[1] ?? 1);\n const uv: [number, number] = [\n ((input.currentPixel[0] ?? 0) - (input.motion[0] ?? 0)) / width,\n ((input.currentPixel[1] ?? 0) - (input.motion[1] ?? 0)) / height,\n ];\n if (uv[0] < 0 || uv[0] > 1 || uv[1] < 0 || uv[1] > 1) {\n return { accepted: false, historyUv: uv, weight: 0, reason: 'outside' };\n }\n const depthTolerance =\n input.depthTolerance ?? Math.max(0.01, Math.abs(input.currentDepth) * 0.02);\n if (\n !Number.isFinite(input.currentDepth) ||\n !Number.isFinite(input.historyDepth) ||\n Math.abs(input.currentDepth - input.historyDepth) > depthTolerance\n ) {\n return { accepted: false, historyUv: uv, weight: 0, reason: 'depth-disocclusion' };\n }\n return {\n accepted: true,\n historyUv: uv,\n weight: Math.min(0.99, Math.max(0, historyWeight)),\n reason: 'accepted',\n };\n}\n","import { ok, type Result } from '@forgeax/engine-types';\nimport type { RenderError } from '../errors/render';\nimport type { RenderFeaturePlan, RenderFeaturePlanContext } from '../features/plan';\nimport type { RenderFeature, RenderFeatureExtractContext } from '../features/types';\nimport { buildCloudDensityCache, CLOUD_VERTICAL_CELLS, type CloudDensityCache } from './density';\nimport {\n type CloudLayerInspection,\n cloudCapabilitiesFromRhi,\n inspectCloudLayer,\n} from './inspection';\nimport {\n CLOUD_EXTINCTION_COEFFICIENT,\n CLOUD_QUALITY_PROFILES,\n cloudLayerFormationKey,\n cloudShadowResolutionForQuality,\n cloudViewDistanceForQuality,\n type ValidatedCloudLayer,\n} from './parameters';\nimport { inspectCloudLayerResources } from './resources';\nimport { type CloudShadowProjection, createCloudShadowProjection } from './shadow';\nimport {\n CloudHistoryStore,\n type CloudTemporalFrame,\n type CloudTemporalSignature,\n createCloudHistory,\n} from './temporal';\n\nexport const CLOUD_LAYER_FEATURE_IDENTITY = 'forgeax.cloud-layer';\nexport const CLOUD_LAYER_DENSITY_PROGRAM = 'cloud-layer-density';\nexport const CLOUD_LAYER_DENSITY_BINDINGS = 'cloud-layer-density-bindings';\nexport const CLOUD_LAYER_DENSITY_CACHE = 'cloud-layer-density-cache';\nexport const CLOUD_LAYER_DENSITY_OUTPUT = 'cloud-layer-density-output';\n\nconst COMPUTE_STAGE = 0x4;\nconst CLOUD_WORKGROUP_SIZE = 64;\n// 24 vec4/u32 lanes: authored field, sun, integration mode and the\n// renderer-owned stable light-space shadow projection. The same POD is used by\n// the display and shadow entry points so they cannot drift in their density or\n// cache addressing contract.\n// The final lane carries temporal validity/reset/blend. Keep the payload\n// explicitly 16-byte aligned so the public schema, prepared UBO and WGSL stay\n// one contract.\nexport const CLOUD_VIEW_PARAMS_BYTES = 176;\n\n/** R8 cache bytes are packed into little-endian u32 storage elements. */\nfunction packCloudDensityCache(cache: CloudDensityCache): Uint32Array {\n const packed = new Uint32Array(Math.max(1, Math.ceil(cache.formationData.byteLength / 4)));\n for (let index = 0; index < cache.formationData.byteLength; index += 1) {\n const wordIndex = index >>> 2;\n packed[wordIndex] =\n (packed[wordIndex] ?? 0) | ((cache.formationData[index] ?? 0) << ((index & 3) * 8));\n }\n return packed;\n}\n\n/** Minimal copy compute; one invocation owns one packed u32 cache element. */\nexport const CLOUD_DENSITY_COMPUTE_WGSL = /* wgsl */ `\nstruct CloudCacheParams { count: u32, }\n@group(0) @binding(0) var<storage, read> sourceDensity: array<u32>;\n@group(0) @binding(1) var<storage, read_write> cachedDensity: array<u32>;\n@group(0) @binding(2) var<uniform> params: CloudCacheParams;\n@compute @workgroup_size(64)\nfn cloud_density_cache(@builtin(global_invocation_id) id: vec3<u32>) {\n if (id.x >= params.count) { return; }\n cachedDensity[id.x] = sourceDensity[id.x];\n}\n`;\n\n/**\n * Cloud view transport. The View group is the renderer-owned camera/light\n * source of truth; group(1) carries frame-local cloud parameters, depth and\n * the bounded packed 3D cache. Camera, solar-column and cloud-interior\n * integration all call cloud_density(), so wind only changes the sample\n * coordinate and never the authored field.\n */\nexport const CLOUD_VIEW_FULLSCREEN_WGSL = /* wgsl */ `\nconst CLOUD_VERTICAL_CELLS: f32 = ${CLOUD_VERTICAL_CELLS};\nconst CLOUD_VERTICAL_NOISE_CELLS: f32 = 2.0;\n\nstruct CloudCameraView {\n worldViewProj: mat4x4<f32>,\n lightDir: vec3<f32>,\n lightColor: vec3<f32>,\n cameraPos: vec3<f32>,\n lightViewProj_A: mat4x4<f32>,\n inverseViewProj: mat4x4<f32>,\n lightViewProj_B: mat4x4<f32>,\n lightViewProj_C: mat4x4<f32>,\n lightViewProj_D: mat4x4<f32>,\n splitPlanes: array<vec4<f32>, 4>,\n cascadeCount: f32,\n cascadeBlend: f32,\n depthBias: f32,\n normalBias: f32,\n directionalShadowFilter: vec4<f32>,\n spotLightViewProj: array<mat4x4<f32>, 4>,\n temporalCurrentViewProj: mat4x4<f32>,\n temporalPreviousViewProj: mat4x4<f32>,\n temporalProjection: vec4<f32>,\n temporalPreviousCameraPos: vec4<f32>,\n ssrParams: vec4<f32>,\n};\n\nstruct CloudViewParams {\n layer: vec4<f32>, // baseHeight, thickness, scale, density\n field: vec4<f32>, // coverage, timeSeconds, maxDistance, seed\n wind: vec4<f32>, // xyz m/s\n sunDirection: vec4<f32>,\n sunRadiance: vec4<f32>,\n integration: vec4<u32>, // cacheResolution, viewSteps, solarSteps, reserved\n shadowOrigin: vec4<f32>,\n shadowRight: vec4<f32>,\n shadowUp: vec4<f32>,\n shadowProjection: vec4<f32>, // range, valid, lowSun, texelSize\n temporal: vec4<f32>, // valid, reset, historyWeight, reserved\n};\n\n@group(0) @binding(0) var<uniform> view: CloudCameraView;\n@group(1) @binding(0) var sceneColor: texture_2d<f32>;\n@group(1) @binding(1) var sceneSampler: sampler;\n@group(1) @binding(2) var<uniform> cloud: CloudViewParams;\n@group(1) @binding(3) var sceneDepth: texture_depth_2d;\n@group(1) @binding(4) var depthSampler: sampler;\n@group(1) @binding(5) var previousRadiance: texture_2d<f32>;\n@group(1) @binding(6) var previousTransmittance: texture_2d<f32>;\n@group(1) @binding(7) var previousDepth: texture_2d<f32>;\n@group(1) @binding(8) var<storage, read> densityCache: array<u32>;\n\nstruct CloudViewOut {\n @builtin(position) position: vec4<f32>,\n @location(0) uv: vec2<f32>,\n};\n\nfn cloud_hash3(cell: vec3<i32>, seed: u32) -> f32 {\n var h = bitcast<u32>(cell.x) * 0x45d9f3bu;\n h = (h ^ (bitcast<u32>(cell.y) * 0x119de1f3u)) * 0x45d9f3bu;\n h = (h ^ (bitcast<u32>(cell.z) * 0x3449fu)) * 0x45d9f3bu;\n h = h ^ seed;\n h = (h ^ (h >> 16u)) * 0x45d9f3bu;\n h = (h ^ (h >> 13u)) * 0x27d4eb2du;\n return f32(h ^ (h >> 16u)) / 4294967296.0;\n}\n\nfn cloud_wrap_cell(value: i32, period: i32) -> i32 {\n let wrapped = value % period;\n return select(wrapped, wrapped + period, wrapped < 0);\n}\n\nfn cloud_hash3_periodic(\n cell: vec3<i32>,\n seed: u32,\n periodX: i32,\n periodY: i32,\n periodZ: i32,\n) -> f32 {\n return cloud_hash3(\n vec3<i32>(\n cloud_wrap_cell(cell.x, periodX),\n cloud_wrap_cell(cell.y, periodY),\n cloud_wrap_cell(cell.z, periodZ),\n ),\n seed,\n );\n}\n\nfn cloud_value_noise(\n position: vec3<f32>,\n seed: u32,\n periodX: i32,\n periodY: i32,\n periodZ: i32,\n) -> f32 {\n let cell = vec3<i32>(floor(position));\n let fraction = fract(position);\n let smoothFraction = fraction * fraction * (3.0 - 2.0 * fraction);\n let c000 = cloud_hash3_periodic(cell + vec3<i32>(0, 0, 0), seed, periodX, periodY, periodZ);\n let c100 = cloud_hash3_periodic(cell + vec3<i32>(1, 0, 0), seed, periodX, periodY, periodZ);\n let c010 = cloud_hash3_periodic(cell + vec3<i32>(0, 1, 0), seed, periodX, periodY, periodZ);\n let c110 = cloud_hash3_periodic(cell + vec3<i32>(1, 1, 0), seed, periodX, periodY, periodZ);\n let c001 = cloud_hash3_periodic(cell + vec3<i32>(0, 0, 1), seed, periodX, periodY, periodZ);\n let c101 = cloud_hash3_periodic(cell + vec3<i32>(1, 0, 1), seed, periodX, periodY, periodZ);\n let c011 = cloud_hash3_periodic(cell + vec3<i32>(0, 1, 1), seed, periodX, periodY, periodZ);\n let c111 = cloud_hash3_periodic(cell + vec3<i32>(1, 1, 1), seed, periodX, periodY, periodZ);\n let x00 = mix(c000, c100, smoothFraction.x);\n let x10 = mix(c010, c110, smoothFraction.x);\n let x01 = mix(c001, c101, smoothFraction.x);\n let x11 = mix(c011, c111, smoothFraction.x);\n return mix(mix(x00, x10, smoothFraction.y), mix(x01, x11, smoothFraction.y), smoothFraction.z);\n}\n\nfn cloud_cellular_noise(position: vec3<f32>, seed: u32, periodXZ: i32, periodY: i32) -> f32 {\n let cell = vec3<i32>(floor(position));\n let fraction = fract(position);\n var nearest = 1e9;\n var dz: i32 = -1;\n loop {\n var dy: i32 = -1;\n loop {\n var dx: i32 = -1;\n loop {\n let random = cloud_hash3_periodic(\n cell + vec3<i32>(dx, dy, dz),\n seed ^ 0x9e3779b9u,\n periodXZ,\n periodY,\n periodXZ,\n );\n let point = vec3<f32>(\n f32(dx) + fract(random * 17.0) - fraction.x,\n f32(dy) + fract(random * 31.0) - fraction.y,\n f32(dz) + fract(random * 47.0) - fraction.z,\n );\n nearest = min(nearest, dot(point, point));\n if (dx >= 1) { break; }\n dx = dx + 1;\n }\n if (dy >= 1) { break; }\n dy = dy + 1;\n }\n if (dz >= 1) { break; }\n dz = dz + 1;\n }\n return 1.0 - clamp(sqrt(nearest) * 1.25, 0.0, 1.0);\n}\n\nfn cloud_weather_field(position: vec3<f32>, seed: u32) -> f32 {\n return smoothstep(\n 0.34,\n 0.66,\n cloud_value_noise(\n vec3<f32>(position.x * 2.0, 0.37, position.z * 2.0),\n seed + 17041u,\n 2,\n 1,\n 2,\n ),\n );\n}\n\nfn cloud_formation_field(position: vec3<f32>, seed: u32) -> vec3<f32> {\n let macroWarpX = cloud_value_noise(\n vec3<f32>(position.x * 2.0, position.y * CLOUD_VERTICAL_NOISE_CELLS + 3.0, position.z * 2.0),\n seed + 41023u,\n 2,\n 2,\n 2,\n ) - 0.5;\n let macroWarpZ = cloud_value_noise(\n vec3<f32>(position.x * 2.0 + 5.0, position.y * CLOUD_VERTICAL_NOISE_CELLS - 7.0, position.z * 2.0),\n seed + 41023u,\n 2,\n 2,\n 2,\n ) - 0.5;\n let bodyX = position.x + macroWarpX * 0.3;\n let bodyZ = position.z + macroWarpZ * 0.3;\n var noise = 0.0;\n var weight = 0.0;\n var amplitude = 0.5;\n var frequency = 1.0;\n for (var octave = 0u; octave < 4u; octave = octave + 1u) {\n let tilePeriod = 4.0 * frequency;\n noise = noise + cloud_value_noise(\n vec3<f32>(bodyX * tilePeriod, position.y * frequency * CLOUD_VERTICAL_NOISE_CELLS, bodyZ * tilePeriod),\n seed + octave * 1013u,\n i32(tilePeriod),\n i32(frequency * CLOUD_VERTICAL_NOISE_CELLS),\n i32(tilePeriod),\n ) * amplitude;\n weight = weight + amplitude;\n amplitude = amplitude * 0.4;\n frequency = frequency * 2.0;\n }\n let broad = noise / max(0.0001, weight);\n let cells = cloud_cellular_noise(\n vec3<f32>(bodyX * 4.0, position.y * CLOUD_VERTICAL_NOISE_CELLS, bodyZ * 4.0),\n seed + 5011u,\n 4,\n i32(CLOUD_VERTICAL_NOISE_CELLS),\n );\n // Keep the broad field responsible for the cloud silhouette and use the\n // cellular term as bounded breakup. A broad-dominant mix reads as fewer,\n // wider formations instead of evenly spaced foam balls.\n let base = clamp(broad * 0.85 + cells * 0.15 + 0.15, 0.0, 1.0);\n let weather = cloud_weather_field(position, seed);\n let detailPosition = position * 3.0;\n let warpX = cloud_value_noise(\n vec3<f32>(detailPosition.x * 2.0, detailPosition.y * 2.0 + 11.0, detailPosition.z * 2.0),\n seed + 29011u,\n 2,\n 2,\n 2,\n ) - 0.5;\n let warpZ = cloud_value_noise(\n vec3<f32>(detailPosition.x * 2.0 + 7.0, detailPosition.y * 2.0 - 5.0, detailPosition.z * 2.0),\n seed + 29011u,\n 2,\n 2,\n 2,\n ) - 0.5;\n let erosion = cloud_cellular_noise(\n vec3<f32>(\n (detailPosition.x + warpX * 0.22) * 12.0,\n detailPosition.y * 3.0,\n (detailPosition.z + warpZ * 0.22) * 12.0,\n ),\n seed + 7919u,\n 12,\n 3,\n );\n return vec3<f32>(weather, base, erosion);\n}\n\nfn cloud_height_profile(height: f32, body: f32, weather: f32) -> f32 {\n // A body-dependent crown breaks the fixed horizontal slab silhouette while\n // keeping the profile smooth enough for the bounded ray step budget.\n let lowerEdge = 0.05 + (1.0 - body) * 0.1;\n let crownEdge = min(0.96, 0.6 + body * 0.3 + weather * 0.08);\n let lower = smoothstep(lowerEdge, min(1.0, lowerEdge + 0.12), height);\n let upper = 1.0 - smoothstep(crownEdge, min(1.0, crownEdge + 0.14), height);\n return lower * upper;\n}\n\nfn cloud_compose_density(height: f32, formation: vec3<f32>, coverage: f32) -> f32 {\n let threshold = 1.0 - coverage * (0.45 + formation.x * 0.55);\n let covered = smoothstep(0.0, 0.4, (formation.y - threshold) / max(0.001, 1.0 - threshold));\n let shaped = covered * cloud_height_profile(height, formation.y, formation.x);\n let erosion = (1.0 - formation.z) * 0.18;\n return clamp((shaped - erosion) / (1.0 - erosion), 0.0, 1.0);\n}\n\nfn cloud_analytic_density(position: vec3<f32>) -> f32 {\n let height = (position.y - cloud.layer.x) / max(0.000001, cloud.layer.y);\n if (height <= 0.0 || height >= 1.0 || cloud.layer.w <= 0.0 || cloud.field.x <= 0.0) { return 0.0; }\n let advected = position + cloud.wind.xyz * cloud.field.y;\n let advectedHeight = height +\n cloud.wind.y * cloud.field.y * cloud.layer.z / max(CLOUD_VERTICAL_CELLS, 0.000001);\n let p = vec3<f32>(\n advected.x * cloud.layer.z,\n fract(advectedHeight) * CLOUD_VERTICAL_CELLS,\n advected.z * cloud.layer.z,\n );\n let formation = cloud_formation_field(p, u32(round(cloud.field.w)));\n return cloud_compose_density(height, formation, cloud.field.x) * cloud.layer.w;\n}\n\nfn cloud_cache_byte(index: u32) -> f32 {\n let word = densityCache[index >> 2u];\n let shift = (index & 3u) * 8u;\n return f32((word >> shift) & 255u) / 255.0;\n}\n\nfn cloud_cache_component(plane: u32, index: u32, stride: u32) -> f32 {\n return cloud_cache_byte(plane * stride + index);\n}\n\nfn cloud_cache_trilinear(\n plane: u32,\n resolution: u32,\n x0: u32,\n x1: u32,\n y0: u32,\n y1: u32,\n z0: u32,\n z1: u32,\n fx: f32,\n fy: f32,\n fz: f32,\n) -> f32 {\n let stride = resolution * resolution * resolution;\n let layer = resolution * resolution;\n let c000 = cloud_cache_component(plane, z0 * layer + y0 * resolution + x0, stride);\n let c100 = cloud_cache_component(plane, z0 * layer + y0 * resolution + x1, stride);\n let c010 = cloud_cache_component(plane, z0 * layer + y1 * resolution + x0, stride);\n let c110 = cloud_cache_component(plane, z0 * layer + y1 * resolution + x1, stride);\n let c001 = cloud_cache_component(plane, z1 * layer + y0 * resolution + x0, stride);\n let c101 = cloud_cache_component(plane, z1 * layer + y0 * resolution + x1, stride);\n let c011 = cloud_cache_component(plane, z1 * layer + y1 * resolution + x0, stride);\n let c111 = cloud_cache_component(plane, z1 * layer + y1 * resolution + x1, stride);\n let x00 = mix(c000, c100, fx);\n let x10 = mix(c010, c110, fx);\n let x01 = mix(c001, c101, fx);\n let x11 = mix(c011, c111, fx);\n return mix(mix(x00, x10, fy), mix(x01, x11, fy), fz);\n}\n\nfn cloud_density(position: vec3<f32>) -> f32 {\n let height = (position.y - cloud.layer.x) / max(0.000001, cloud.layer.y);\n if (height <= 0.0 || height >= 1.0 || cloud.layer.w <= 0.0 || cloud.field.x <= 0.0) { return 0.0; }\n let resolution = cloud.integration.x;\n if (resolution < 4u) { return max(cloud_analytic_density(position), 0.0); }\n let periodCoordinate = fract((position.xz + cloud.wind.xz * cloud.field.y) * cloud.layer.z);\n let x = fract(periodCoordinate.x - 0.5 / f32(resolution)) * f32(resolution);\n let z = fract(periodCoordinate.y - 0.5 / f32(resolution)) * f32(resolution);\n let advectedHeight = height +\n cloud.wind.y * cloud.field.y * cloud.layer.z / max(CLOUD_VERTICAL_CELLS, 0.000001);\n let y = fract(advectedHeight - 0.5 / f32(resolution)) * f32(resolution);\n let x0 = u32(floor(x));\n let y0 = u32(floor(y));\n let z0 = u32(floor(z));\n let x1 = (x0 + 1u) % resolution;\n let y1 = (y0 + 1u) % resolution;\n let z1 = (z0 + 1u) % resolution;\n let fx = x - f32(x0);\n let fy = y - f32(y0);\n let fz = z - f32(z0);\n let weather = cloud_cache_trilinear(0u, resolution, x0, x1, y0, y1, z0, z1, fx, fy, fz);\n let body = cloud_cache_trilinear(1u, resolution, x0, x1, y0, y1, z0, z1, fx, fy, fz);\n // Repeat only the independent erosion plane: fine boundary structure with\n // the same eight packed reads and the same cache allocation.\n let detail = fract(vec3<f32>(periodCoordinate.x, advectedHeight, periodCoordinate.y) * 3.0 - vec3<f32>(0.5 / f32(resolution))) * f32(resolution);\n let d0 = vec3<u32>(floor(detail));\n let d1 = (d0 + vec3<u32>(1u)) % vec3<u32>(resolution);\n let df = fract(detail);\n let erosion = cloud_cache_trilinear(2u, resolution, d0.x, d1.x, d0.y, d1.y, d0.z, d1.z, df.x, df.y, df.z);\n return cloud_compose_density(height, vec3<f32>(weather, body, erosion), cloud.field.x) * cloud.layer.w;\n}\n\nfn cloud_layer_interval(origin: vec3<f32>, direction: vec3<f32>, maxDistance: f32) -> vec2<f32> {\n if (abs(direction.y) < 0.000001) {\n if (origin.y < cloud.layer.x || origin.y > cloud.layer.x + cloud.layer.y) {\n return vec2<f32>(1.0, 0.0);\n }\n return vec2<f32>(0.0, maxDistance);\n }\n let lower = (cloud.layer.x - origin.y) / direction.y;\n let upper = (cloud.layer.x + cloud.layer.y - origin.y) / direction.y;\n return vec2<f32>(\n max(0.0, min(lower, upper)),\n min(maxDistance, max(lower, upper)),\n );\n}\n\nfn cloud_solar_transmittance(position: vec3<f32>) -> f32 {\n let sunDirection = normalize(-view.lightDir);\n let solarDistance = select(cloud.field.z, cloud.shadowProjection.x, cloud.shadowProjection.x > 0.0);\n let interval = cloud_layer_interval(position, sunDirection, solarDistance);\n if (interval.y <= interval.x) { return 1.0; }\n let steps = min(cloud.integration.z, 64u);\n let stepLength = (interval.y - interval.x) / max(1.0, f32(steps));\n var opticalDepth = 0.0;\n let solarJitter = cloud_solar_jitter(position);\n for (var index = 0u; index < 64u; index = index + 1u) {\n if (index >= steps) { break; }\n let samplePosition = position + sunDirection * (interval.x + (f32(index) + solarJitter) * stepLength);\n opticalDepth = opticalDepth + cloud_density(samplePosition) * ${CLOUD_EXTINCTION_COEFFICIENT} * stepLength;\n }\n return exp(-max(opticalDepth, 0.0));\n}\n\nfn cloud_henyey_greenstein(cosTheta: f32, g: f32) -> f32 {\n let denominator = max(0.0001, 1.0 + g * g - 2.0 * g * cosTheta);\n return (1.0 - g * g) / (denominator * sqrt(denominator)) * 0.0795774715;\n}\n\nfn cloud_phase(cosTheta: f32) -> f32 {\n // A bounded dual lobe gives a readable forward highlight and a small\n // back-scatter rim without another solar march.\n return cloud_henyey_greenstein(cosTheta, 0.55) * 0.8 +\n cloud_henyey_greenstein(cosTheta, -0.2) * 0.2;\n}\n\n// Reuse the same remaining-path optical depth for two bounded scattering\n// orders. This adds arithmetic only; no extra density or light-ray samples.\nfn cloud_incident_light(solarT: f32, cosTheta: f32, height: f32) -> vec3<f32> {\n let direct = solarT * cloud_phase(cosTheta);\n let multiple = (0.5 * pow(solarT, 0.5) + 0.25 * pow(solarT, 0.25)) * 0.0795774715;\n let skyFill = mix(0.025, 0.075, smoothstep(0.1, 0.85, height));\n // Match volume-integrate: the shared DirectionalLight value uses the\n // unnormalized phase convention. Convert the normalized HG basis once.\n return cloud.sunRadiance.xyz *\n (vec3<f32>((direct + multiple) * 12.5663706144) + vec3<f32>(0.72, 0.84, 1.0) * skyFill);\n}\n\nfn cloud_ray_jitter(pixel: vec2<f32>) -> f32 {\n // A stable per-pixel offset removes view-step contour bands without adding\n // a frame-varying noise source that would fight temporal reprojection.\n return fract(sin(dot(pixel, vec2<f32>(12.9898, 78.233))) * 43758.5453);\n}\n\nfn cloud_solar_jitter(position: vec3<f32>) -> f32 {\n // Dither the light-column samples in world space so low shadow-step\n // profiles do not paint parallel contour bands across cloud bases.\n return fract(sin(dot(position.xz, vec2<f32>(19.193, 47.117))) * 15731.743);\n}\n\nfn reconstruct_world(uv: vec2<f32>, depth: f32) -> vec3<f32> {\n let ndc = vec4<f32>(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, depth, 1.0);\n let world = view.inverseViewProj * ndc;\n return world.xyz / max(abs(world.w), 0.00001);\n}\n\n@vertex\nfn vs_main(@builtin(vertex_index) index: u32) -> CloudViewOut {\n var positions = array<vec2<f32>, 3>(\n vec2<f32>(-1.0, -1.0),\n vec2<f32>(3.0, -1.0),\n vec2<f32>(-1.0, 3.0),\n );\n var output: CloudViewOut;\n output.position = vec4<f32>(positions[index], 0.0, 1.0);\n // WebGPU clip-space Y grows upward while sampled framebuffer rows and the\n // depth texture use a top-left origin. Keep this one top-left UV for color,\n // depth and inverse-projection reconstruction; flipping only the final\n // color would leave the camera ray and depth cut mirrored.\n output.uv = vec2<f32>(\n positions[index].x * 0.5 + 0.5,\n 1.0 - (positions[index].y * 0.5 + 0.5),\n );\n return output;\n}\n\n@fragment\nfn fs_main(input: CloudViewOut) -> @location(0) vec4<f32> {\n // The shadow producer uses this same production density/cache contract but\n // rasterizes a camera-independent, texel-snapped light-space map. It does\n // not consume scene colour; the generic fullscreen host still supplies the\n // input binding to keep the feature binding ABI single and validated.\n if (cloud.integration.w == 1u) {\n let projection = cloud.shadowProjection;\n if (projection.y < 0.5 || projection.z > 0.5 || projection.x <= 0.0) {\n return vec4<f32>(1.0);\n }\n let offset = (input.uv - vec2<f32>(0.5)) * projection.x;\n let receiver = cloud.shadowOrigin.xyz +\n cloud.shadowRight.xyz * offset.x + cloud.shadowUp.xyz * offset.y;\n let sunDirection = normalize(-view.lightDir);\n let interval = cloud_layer_interval(receiver, sunDirection, projection.x);\n if (interval.y <= interval.x) { return vec4<f32>(1.0); }\n let steps = min(cloud.integration.z, 64u);\n let stepLength = (interval.y - interval.x) / max(1.0, f32(steps));\n var opticalDepth = 0.0;\n var firstHeight = 1.0;\n var lastHeight = 0.0;\n var occupied = false;\n let solarJitter = cloud_solar_jitter(receiver);\n for (var index = 0u; index < 64u; index = index + 1u) {\n if (index >= steps) { break; }\n let samplePosition = receiver + sunDirection *\n (interval.x + (f32(index) + solarJitter) * stepLength);\n let localDensity = cloud_density(samplePosition);\n opticalDepth = opticalDepth + localDensity * ${CLOUD_EXTINCTION_COEFFICIENT} * stepLength;\n if (localDensity > 0.0001) {\n let sampleHeight = clamp(\n (samplePosition.y - cloud.layer.x) / max(0.0001, cloud.layer.y),\n 0.0,\n 1.0,\n );\n if (!occupied) { firstHeight = sampleHeight; }\n lastHeight = sampleHeight;\n occupied = true;\n }\n }\n let transmittance = exp(-max(opticalDepth, 0.0));\n // R stores full-column transmittance. G/B preserve the first/last\n // occupied normalized layer heights so interior samples can estimate the\n // remaining segment without pretending optical depth is uniform through\n // the whole layer. A stores the integrated optical depth and distinguishes\n // an empty projected column from a valid, nearly-clear one.\n return vec4<f32>(\n transmittance,\n select(1.0, firstHeight, occupied),\n select(0.0, lastHeight, occupied),\n select(0.0, opticalDepth, occupied),\n );\n }\n // The shadow producer branch above is per-fragment (its light-space\n // interval depends on the rasterized receiver), so derivative-based\n // sampling here would violate WGSL uniform-control-flow rules. The cloud\n // scene path already owns an explicit level-0 sampler contract.\n // Keep point semantics for the current full-resolution scene path. The\n // half-resolution transport contract is introduced with its own resolve\n // shader so this path retains the established depth convention.\n let depthPixel = vec2<i32>(input.position.xy);\n let depth = textureLoad(sceneDepth, depthPixel, 0);\n let farWorld = reconstruct_world(input.uv, 1.0);\n let sceneWorld = reconstruct_world(input.uv, clamp(depth, 0.0, 1.0));\n let ray = normalize(farWorld - view.cameraPos);\n let rayJitter = cloud_ray_jitter(input.position.xy);\n let sceneDistance = select(cloud.field.z, length(sceneWorld - view.cameraPos), depth < 0.999999);\n let interval = cloud_layer_interval(view.cameraPos, ray, sceneDistance);\n\n // The depth producer shares the same camera ray, interval and density\n // contract as the display path. It writes a cloud representative world\n // position and a validity bit so history remains comparable after camera\n // translation or rotation and never uses an opaque scene distance as a\n // proxy for a participating medium.\n if (cloud.integration.w == 2u) {\n if (interval.y <= interval.x) { return vec4<f32>(sceneWorld, 0.0); }\n let depthSteps = min(cloud.integration.y, 64u);\n let depthStepLength = (interval.y - interval.x) / max(1.0, f32(depthSteps));\n var depthTransmittance = 1.0;\n var weightedDistance = 0.0;\n var opticalWeight = 0.0;\n for (var depthIndex = 0u; depthIndex < 64u; depthIndex = depthIndex + 1u) {\n if (depthIndex >= depthSteps) { break; }\n let sampleDistance = interval.x + (f32(depthIndex) + rayJitter) * depthStepLength;\n let samplePosition = view.cameraPos + ray * sampleDistance;\n let localDensity = cloud_density(samplePosition);\n let localTransmittance = exp(-max(localDensity * ${CLOUD_EXTINCTION_COEFFICIENT} * depthStepLength, 0.0));\n let weight = depthTransmittance * (1.0 - localTransmittance);\n weightedDistance = weightedDistance + sampleDistance * weight;\n opticalWeight = opticalWeight + weight;\n depthTransmittance = depthTransmittance * localTransmittance;\n }\n let hasCloud = opticalWeight > 0.00001;\n let representativeDistance = select(sceneDistance, weightedDistance / opticalWeight, hasCloud);\n let representativeWorld = view.cameraPos + ray * representativeDistance;\n return vec4<f32>(representativeWorld, select(0.0, 1.0, hasCloud));\n }\n\n let scene = textureSampleLevel(sceneColor, sceneSampler, input.uv, 0.0);\n if (interval.y <= interval.x) { return scene; }\n let steps = min(cloud.integration.y, 64u);\n let stepLength = (interval.y - interval.x) / max(1.0, f32(steps));\n var transmittance = 1.0;\n var scattering = vec3<f32>(0.0);\n var weightedDistance = 0.0;\n var opticalWeight = 0.0;\n let sunDirection = normalize(-view.lightDir);\n for (var index = 0u; index < 64u; index = index + 1u) {\n if (index >= steps) { break; }\n let distance = interval.x + (f32(index) + rayJitter) * stepLength;\n let samplePosition = view.cameraPos + ray * distance;\n let localDensity = cloud_density(samplePosition);\n let extinction = localDensity * ${CLOUD_EXTINCTION_COEFFICIENT} * stepLength;\n let localTransmittance = exp(-max(extinction, 0.0));\n let depthWeight = transmittance * (1.0 - localTransmittance);\n weightedDistance = weightedDistance + distance * depthWeight;\n opticalWeight = opticalWeight + depthWeight;\n // Empty samples are common in the separated-cloud field. Avoid a nested\n // solar march for them and stop once the camera path is effectively opaque.\n if (localDensity > 0.0001 && transmittance > 0.01) {\n let solarTransmittance = cloud_solar_transmittance(samplePosition);\n let cloudHeight = clamp(\n (samplePosition.y - cloud.layer.x) / max(0.0001, cloud.layer.y), 0.0, 1.0,\n );\n scattering = scattering + cloud_incident_light(\n solarTransmittance, dot(ray, sunDirection), cloudHeight,\n ) * depthWeight;\n }\n transmittance = transmittance * localTransmittance;\n if (transmittance < 0.01) { break; }\n }\n let hasCloud = opticalWeight > 0.00001;\n let representativeDistance = select(sceneDistance, weightedDistance / opticalWeight, hasCloud);\n let representativeWorld = view.cameraPos + ray * representativeDistance;\n // Wind is an advective coordinate change. Reproject the cloud point into\n // the previous frame's world before applying the previous camera matrix;\n // authored field values remain immutable.\n let windDelta = cloud.wind.xyz * max(0.0, cloud.field.y - cloud.temporal.w);\n // cloud_density evaluates the authored field at position + wind*time.\n // Keeping the same field sample in the previous frame therefore advances\n // the previous world point by the elapsed wind delta as well.\n let previousCloudWorld = representativeWorld + windDelta;\n let previousCloudClip = view.temporalPreviousViewProj * vec4<f32>(previousCloudWorld, 1.0);\n let previousCloudNdc = previousCloudClip.xyz / max(abs(previousCloudClip.w), 0.00001);\n let previousCloudUv = vec2<f32>(\n previousCloudNdc.x * 0.5 + 0.5,\n 1.0 - (previousCloudNdc.y * 0.5 + 0.5),\n );\n let cloudInBounds = all(previousCloudUv >= vec2<f32>(0.0)) && all(previousCloudUv <= vec2<f32>(1.0));\n let cloudHistoryUv = clamp(previousCloudUv, vec2<f32>(0.0), vec2<f32>(1.0));\n let cloudHistoryDepthSample = textureSampleLevel(previousDepth, depthSampler, cloudHistoryUv, 0.0);\n let cloudHistoryWorld = cloudHistoryDepthSample.xyz;\n let previous = textureSampleLevel(previousRadiance, sceneSampler, cloudHistoryUv, 0.0);\n let previousTransport = textureSampleLevel(\n previousTransmittance,\n sceneSampler,\n cloudHistoryUv,\n 0.0,\n );\n let worldTolerance = max(0.05, length(previousCloudWorld - view.cameraPos) * 0.02);\n let depthAccepted = cloudHistoryDepthSample.a > 0.5 &&\n distance(cloudHistoryWorld, previousCloudWorld) <= worldTolerance;\n let accepted =\n hasCloud && cloud.temporal.x > 0.5 && cloud.temporal.y < 0.5 && cloudInBounds &&\n depthAccepted && previousTransport.a > 0.0;\n let historyWeight = select(0.0, clamp(cloud.temporal.z, 0.0, 0.95), accepted);\n let cloudRadiance = mix(scattering, previous.rgb, historyWeight);\n // Preserve scene-linear HDR output for the downstream material lane. The\n // history owner receives cloudRadiance separately through the history pass.\n return vec4<f32>(scene.rgb * transmittance + cloudRadiance, transmittance);\n}\n\n// The light-space shadow producer already paid for a bounded column integral.\n// Reuse that texel for camera samples instead of starting a full solar march\n// for every occupied camera step. Outside the occupied interval the cached\n// full-column transmittance is exact for the projected column. Inside the\n// interval, the cache supplies the stable projection/bounds and a short\n// residual march resolves the non-uniform density that a linear optical-depth\n// interpolation would lose. Invalid/out-of-range projections retain the\n// analytic path as an explicit fallback.\nfn cloud_solar_cached_transmittance(position: vec3<f32>) -> f32 {\n let projection = cloud.shadowProjection;\n if (projection.y < 0.5 || projection.x <= 0.0) {\n return cloud_solar_transmittance(position);\n }\n let relative = position - cloud.shadowOrigin.xyz;\n let uv = vec2<f32>(\n dot(relative, cloud.shadowRight.xyz) / projection.x + 0.5,\n dot(relative, cloud.shadowUp.xyz) / projection.x + 0.5,\n );\n if (any(uv < vec2<f32>(0.0)) || any(uv > vec2<f32>(1.0))) {\n return cloud_solar_transmittance(position);\n }\n let cachedShadow = textureSampleLevel(previousRadiance, sceneSampler, uv, 0.0);\n let cachedOpticalDepth = max(cachedShadow.a, 0.0);\n let layerHeight = clamp(\n (position.y - cloud.layer.x) / max(0.0001, cloud.layer.y),\n 0.0,\n 1.0,\n );\n if (cachedOpticalDepth <= 0.0001) { return 1.0; }\n let firstHeight = clamp(cachedShadow.g, 0.0, 1.0);\n let lastHeight = clamp(cachedShadow.b, 0.0, 1.0);\n let occupiedMin = min(firstHeight, lastHeight);\n let occupiedMax = max(firstHeight, lastHeight);\n let sunDirection = normalize(-view.lightDir);\n // G/B are ordered along the light ray, not necessarily bottom-to-top. Only\n // use the cached full/empty fast paths when the light has enough vertical\n // component to make that ordering meaningful; grazing light stays on the\n // residual path so a low-sun column cannot invert the cache bounds.\n if (abs(sunDirection.y) > 0.2) {\n if (sunDirection.y > 0.0) {\n if (layerHeight <= occupiedMin) { return exp(-cachedOpticalDepth); }\n if (layerHeight >= occupiedMax) { return 1.0; }\n } else {\n if (layerHeight >= occupiedMax) { return exp(-cachedOpticalDepth); }\n if (layerHeight <= occupiedMin) { return 1.0; }\n }\n }\n\n // A short residual march is only paid for samples inside the projected\n // cloud span. Vertical light uses twelve taps, oblique light sixteen, and\n // grazing light up to thirty-two because the same layer projects across a\n // much longer solar segment. This removes the large error caused by\n // assuming optical depth is uniform between the first and last occupied\n // heights while keeping the normal camera path far below a second full\n // solar integration.\n let solarDistance = select(cloud.field.z, projection.x, projection.x > 0.0);\n let interval = cloud_layer_interval(position, sunDirection, solarDistance);\n if (interval.y <= interval.x) { return 1.0; }\n let absLightY = abs(sunDirection.y);\n let directionBudget = select(\n 32u,\n select(16u, 12u, absLightY > 0.5),\n absLightY > 0.2,\n );\n let residualSteps = min(directionBudget, max(8u, cloud.integration.z * 3u));\n let stepLength = (interval.y - interval.x) / max(1.0, f32(residualSteps));\n var opticalDepth = 0.0;\n let solarJitter = cloud_solar_jitter(position);\n for (var index = 0u; index < 32u; index = index + 1u) {\n if (index >= residualSteps) { break; }\n let samplePosition = position + sunDirection *\n (interval.x + (f32(index) + solarJitter) * stepLength);\n opticalDepth = opticalDepth + cloud_density(samplePosition) *\n ${CLOUD_EXTINCTION_COEFFICIENT} * stepLength;\n }\n return exp(-max(opticalDepth, 0.0));\n}\n\nstruct CloudTransportOutput {\n @location(0) radiance: vec4<f32>,\n @location(1) transmittance: vec4<f32>,\n @location(2) depth: vec4<f32>,\n};\n\n// One half-resolution transport pass writes all three reusable cloud fields.\n// The full-resolution resolve below reconstructs colour and applies temporal\n// history; no second full raymarch exists solely to obtain cloud depth.\n@fragment\nfn fs_transport(input: CloudViewOut) -> CloudTransportOutput {\n let depth = textureSampleLevel(sceneDepth, depthSampler, input.uv, 0u);\n let farWorld = reconstruct_world(input.uv, 1.0);\n let sceneWorld = reconstruct_world(input.uv, clamp(depth, 0.0, 1.0));\n let ray = normalize(farWorld - view.cameraPos);\n let rayJitter = cloud_ray_jitter(input.position.xy);\n let sceneDistance = select(cloud.field.z, length(sceneWorld - view.cameraPos), depth < 0.999999);\n let interval = cloud_layer_interval(view.cameraPos, ray, sceneDistance);\n var output: CloudTransportOutput;\n output.radiance = vec4<f32>(0.0, 0.0, 0.0, 0.0);\n output.transmittance = vec4<f32>(1.0, 1.0, 1.0, 1.0);\n output.depth = vec4<f32>(sceneWorld, 0.0);\n if (interval.y <= interval.x) { return output; }\n\n let steps = min(cloud.integration.y, 64u);\n let stepLength = (interval.y - interval.x) / max(1.0, f32(steps));\n var transmittance = 1.0;\n var scattering = vec3<f32>(0.0);\n var weightedDistance = 0.0;\n var opticalWeight = 0.0;\n let sunDirection = normalize(-view.lightDir);\n for (var index = 0u; index < 64u; index = index + 1u) {\n if (index >= steps) { break; }\n let distance = interval.x + (f32(index) + rayJitter) * stepLength;\n let samplePosition = view.cameraPos + ray * distance;\n let localDensity = cloud_density(samplePosition);\n let extinction = localDensity * ${CLOUD_EXTINCTION_COEFFICIENT} * stepLength;\n let localTransmittance = exp(-max(extinction, 0.0));\n let depthWeight = transmittance * (1.0 - localTransmittance);\n weightedDistance = weightedDistance + distance * depthWeight;\n opticalWeight = opticalWeight + depthWeight;\n if (localDensity > 0.0001 && transmittance > 0.01) {\n let solarTransmittance = cloud_solar_cached_transmittance(samplePosition);\n let cloudHeight = clamp(\n (samplePosition.y - cloud.layer.x) / max(0.0001, cloud.layer.y), 0.0, 1.0,\n );\n scattering = scattering + cloud_incident_light(\n solarTransmittance, dot(ray, sunDirection), cloudHeight,\n ) * depthWeight;\n }\n transmittance = transmittance * localTransmittance;\n if (transmittance < 0.01) { break; }\n }\n let hasCloud = opticalWeight > 0.00001;\n let representativeDistance = select(sceneDistance, weightedDistance / max(opticalWeight, 0.00001), hasCloud);\n output.radiance = vec4<f32>(scattering, select(0.0, 1.0, hasCloud));\n output.transmittance = vec4<f32>(transmittance, transmittance, transmittance, 1.0);\n output.depth = vec4<f32>(view.cameraPos + ray * representativeDistance, select(0.0, 1.0, hasCloud));\n return output;\n}\n`;\n\n/** Shared cloud transport module; `fs_transport` is selected by the MRT PSO. */\nexport const CLOUD_TRANSPORT_FULLSCREEN_WGSL = CLOUD_VIEW_FULLSCREEN_WGSL;\n/** Analytic fallback for adapters without a projected cloud-shadow target. */\nexport const CLOUD_TRANSPORT_ANALYTIC_FULLSCREEN_WGSL = CLOUD_VIEW_FULLSCREEN_WGSL.replace(\n 'cloud_solar_cached_transmittance(samplePosition)',\n 'cloud_solar_transmittance(samplePosition)',\n);\n\n/**\n * History writer. It is a separate MRT pass so the cloud composite remains a\n * normal scene-linear color producer while the renderer owns the ping-pong\n * radiance/transmittance/depth attachments and advances them only on submit.\n */\nexport const CLOUD_HISTORY_FULLSCREEN_WGSL = /* wgsl */ `\nstruct CloudCameraView {\n worldViewProj: mat4x4<f32>,\n lightDir: vec3<f32>,\n lightColor: vec3<f32>,\n cameraPos: vec3<f32>,\n lightViewProj_A: mat4x4<f32>,\n inverseViewProj: mat4x4<f32>,\n lightViewProj_B: mat4x4<f32>,\n lightViewProj_C: mat4x4<f32>,\n lightViewProj_D: mat4x4<f32>,\n splitPlanes: array<vec4<f32>, 4>,\n cascadeCount: f32,\n cascadeBlend: f32,\n depthBias: f32,\n normalBias: f32,\n directionalShadowFilter: vec4<f32>,\n spotLightViewProj: array<mat4x4<f32>, 4>,\n temporalCurrentViewProj: mat4x4<f32>,\n temporalPreviousViewProj: mat4x4<f32>,\n temporalProjection: vec4<f32>,\n temporalPreviousCameraPos: vec4<f32>,\n ssrParams: vec4<f32>,\n};\n\nstruct CloudHistoryParams {\n temporal: vec4<f32>, // valid, reset, historyWeight, reserved\n windTime: vec4<f32>, // wind.xyz, elapsed seconds since previous submit\n};\n\n@group(0) @binding(0) var<uniform> view: CloudCameraView;\n@group(1) @binding(0) var currentRadiance: texture_2d<f32>;\n@group(1) @binding(1) var sceneSampler: sampler;\n@group(1) @binding(2) var<uniform> params: CloudHistoryParams;\n@group(1) @binding(3) var sceneDepth: texture_depth_2d;\n@group(1) @binding(4) var depthSampler: sampler;\n@group(1) @binding(5) var currentCloudDepth: texture_2d<f32>;\n@group(1) @binding(6) var sceneBackground: texture_2d<f32>;\n\nstruct CloudHistoryInput {\n @builtin(position) position: vec4<f32>,\n @location(0) uv: vec2<f32>,\n};\n\nstruct CloudHistoryOutput {\n @location(0) radiance: vec4<f32>,\n @location(1) transmittance: vec4<f32>,\n};\n\nfn reconstruct_world(uv: vec2<f32>, depth: f32) -> vec3<f32> {\n let ndc = vec4<f32>(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, depth, 1.0);\n let world = view.inverseViewProj * ndc;\n return world.xyz / max(abs(world.w), 0.00001);\n}\n\n@vertex\nfn vs_main(@builtin(vertex_index) index: u32) -> CloudHistoryInput {\n var positions = array<vec2<f32>, 3>(\n vec2<f32>(-1.0, -1.0),\n vec2<f32>(3.0, -1.0),\n vec2<f32>(-1.0, 3.0),\n );\n var output: CloudHistoryInput;\n output.position = vec4<f32>(positions[index], 0.0, 1.0);\n output.uv = vec2<f32>(\n positions[index].x * 0.5 + 0.5,\n 1.0 - (positions[index].y * 0.5 + 0.5),\n );\n return output;\n}\n\n@fragment\nfn fs_main(input: CloudHistoryInput) -> CloudHistoryOutput {\n let current = textureSampleLevel(currentRadiance, sceneSampler, input.uv, 0.0);\n let background = textureSampleLevel(sceneBackground, sceneSampler, input.uv, 0.0);\n let cloudDepth = textureSampleLevel(currentCloudDepth, depthSampler, input.uv, 0.0);\n let currentValid = cloudDepth.a > 0.5;\n // currentRadiance is the scene-linear cloud composite. Remove the\n // unchanged scene background before writing history so the persistent owner\n // stores raw cloud radiance only. The view pass is the sole temporal blend\n // owner; blending here as well would accumulate history twice per frame.\n let currentCloudRadiance = max(current.rgb - background.rgb * current.a, vec3<f32>(0.0));\n let currentTransmittance = vec4<f32>(current.a, current.a, current.a, 1.0);\n var output: CloudHistoryOutput;\n output.radiance = vec4<f32>(currentCloudRadiance, select(0.0, 1.0, currentValid));\n output.transmittance = currentTransmittance;\n return output;\n}\n`;\n\n/** Full-resolution resolve for the half-resolution transport MRT. */\nexport const CLOUD_RESOLVE_FULLSCREEN_WGSL = /* wgsl */ `\nstruct CloudCameraView {\n worldViewProj: mat4x4<f32>,\n lightDir: vec3<f32>,\n lightColor: vec3<f32>,\n cameraPos: vec3<f32>,\n lightViewProj_A: mat4x4<f32>,\n inverseViewProj: mat4x4<f32>,\n lightViewProj_B: mat4x4<f32>,\n lightViewProj_C: mat4x4<f32>,\n lightViewProj_D: mat4x4<f32>,\n splitPlanes: array<vec4<f32>, 4>,\n cascadeCount: f32,\n cascadeBlend: f32,\n depthBias: f32,\n normalBias: f32,\n directionalShadowFilter: vec4<f32>,\n spotLightViewProj: array<mat4x4<f32>, 4>,\n temporalCurrentViewProj: mat4x4<f32>,\n temporalPreviousViewProj: mat4x4<f32>,\n temporalProjection: vec4<f32>,\n temporalPreviousCameraPos: vec4<f32>,\n ssrParams: vec4<f32>,\n};\n\nstruct CloudResolveParams {\n layer: vec4<f32>,\n field: vec4<f32>,\n wind: vec4<f32>,\n sunDirection: vec4<f32>,\n sunRadiance: vec4<f32>,\n integration: vec4<u32>,\n shadowOrigin: vec4<f32>,\n shadowRight: vec4<f32>,\n shadowUp: vec4<f32>,\n shadowProjection: vec4<f32>,\n temporal: vec4<f32>,\n};\n\n@group(0) @binding(0) var<uniform> view: CloudCameraView;\n@group(1) @binding(0) var sceneColor: texture_2d<f32>;\n@group(1) @binding(1) var sceneSampler: sampler;\n@group(1) @binding(2) var<uniform> cloud: CloudResolveParams;\n@group(1) @binding(3) var sceneDepth: texture_depth_2d;\n@group(1) @binding(4) var depthSampler: sampler;\n@group(1) @binding(5) var currentRadiance: texture_2d<f32>;\n@group(1) @binding(6) var currentTransmittance: texture_2d<f32>;\n@group(1) @binding(7) var currentDepth: texture_2d<f32>;\n@group(1) @binding(8) var previousRadiance: texture_2d<f32>;\n@group(1) @binding(9) var previousTransmittance: texture_2d<f32>;\n@group(1) @binding(10) var previousDepth: texture_2d<f32>;\n\nstruct CloudResolveInput {\n @builtin(position) position: vec4<f32>,\n @location(0) uv: vec2<f32>,\n};\n\nfn reconstruct_world(uv: vec2<f32>, depth: f32) -> vec3<f32> {\n let ndc = vec4<f32>(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, depth, 1.0);\n let world = view.inverseViewProj * ndc;\n return world.xyz / max(abs(world.w), 0.00001);\n}\n\n@vertex\nfn vs_main(@builtin(vertex_index) index: u32) -> CloudResolveInput {\n var positions = array<vec2<f32>, 3>(\n vec2<f32>(-1.0, -1.0),\n vec2<f32>(3.0, -1.0),\n vec2<f32>(-1.0, 3.0),\n );\n var output: CloudResolveInput;\n output.position = vec4<f32>(positions[index], 0.0, 1.0);\n output.uv = vec2<f32>(\n positions[index].x * 0.5 + 0.5,\n 1.0 - (positions[index].y * 0.5 + 0.5),\n );\n return output;\n}\n\n@fragment\nfn fs_main(input: CloudResolveInput) -> @location(0) vec4<f32> {\n let scene = textureSampleLevel(sceneColor, sceneSampler, input.uv, 0.0);\n // The resolve owns the full-resolution foreground test. Reject the current\n // low-resolution transport before any history or radiance is composited;\n // gating history alone still lets a newly sampled cloud bleed over geometry.\n let sceneDepthValue = textureLoad(sceneDepth, vec2<i32>(input.position.xy), 0);\n let sceneWorld = reconstruct_world(input.uv, clamp(sceneDepthValue, 0.0, 1.0));\n let sceneDistance = length(sceneWorld - view.cameraPos);\n let transport = textureSampleLevel(currentRadiance, sceneSampler, input.uv, 0.0);\n let transportT = textureSampleLevel(currentTransmittance, sceneSampler, input.uv, 0.0);\n // The transport depth is an rgba16float color attachment, not the scene's\n // depth texture. Sample it with the filtering color sampler; binding the\n // non-filtering scene-depth sampler here makes the shader contract depend on\n // an incompatible sampler/texture pair on strict WebGPU implementations.\n let cloudDepth = textureSampleLevel(currentDepth, sceneSampler, input.uv, 0.0);\n let currentValid = transport.a > 0.5 && cloudDepth.a > 0.5;\n let cloudDistance = length(cloudDepth.xyz - view.cameraPos);\n let foregroundAccepted = sceneDepthValue >= 0.999999 ||\n cloudDistance <= sceneDistance + max(0.05, sceneDistance * 0.01);\n if (!currentValid || !foregroundAccepted) { return scene; }\n\n let previousClip = view.temporalPreviousViewProj * vec4<f32>(\n cloudDepth.xyz + cloud.wind.xyz * max(0.0, cloud.field.y - cloud.temporal.w),\n 1.0,\n );\n let previousNdc = previousClip.xyz / max(abs(previousClip.w), 0.00001);\n let previousUv = vec2<f32>(\n previousNdc.x * 0.5 + 0.5,\n 1.0 - (previousNdc.y * 0.5 + 0.5),\n );\n let inBounds = all(previousUv >= vec2<f32>(0.0)) && all(previousUv <= vec2<f32>(1.0));\n let historyUv = clamp(previousUv, vec2<f32>(0.0), vec2<f32>(1.0));\n let historyDepth = textureSampleLevel(previousDepth, sceneSampler, historyUv, 0.0);\n let previous = textureSampleLevel(previousRadiance, sceneSampler, historyUv, 0.0);\n let previousTransport = textureSampleLevel(previousTransmittance, sceneSampler, historyUv, 0.0);\n let dims = vec2<f32>(textureDimensions(previousRadiance));\n let texel = 1.0 / max(dims, vec2<f32>(1.0));\n // Clamp reprojected history against the current low-resolution transport\n // neighborhood. Using only previous-frame neighbors (and including the\n // previous center in both extrema) is a no-op and lets stale bright cloud\n // pixels leak across a newly exposed edge.\n let c0 = transport.rgb;\n let c1 = textureSampleLevel(currentRadiance, sceneSampler, clamp(input.uv + vec2<f32>(-texel.x, 0.0), vec2<f32>(0.0), vec2<f32>(1.0)), 0.0).rgb;\n let c2 = textureSampleLevel(currentRadiance, sceneSampler, clamp(input.uv + vec2<f32>(texel.x, 0.0), vec2<f32>(0.0), vec2<f32>(1.0)), 0.0).rgb;\n let c3 = textureSampleLevel(currentRadiance, sceneSampler, clamp(input.uv + vec2<f32>(0.0, -texel.y), vec2<f32>(0.0), vec2<f32>(1.0)), 0.0).rgb;\n let c4 = textureSampleLevel(currentRadiance, sceneSampler, clamp(input.uv + vec2<f32>(0.0, texel.y), vec2<f32>(0.0), vec2<f32>(1.0)), 0.0).rgb;\n let minRadiance = min(c0, min(min(c1, c2), min(c3, c4)));\n let maxRadiance = max(c0, max(max(c1, c2), max(c3, c4)));\n let t1 = textureSampleLevel(currentTransmittance, sceneSampler, clamp(input.uv + vec2<f32>(-texel.x, 0.0), vec2<f32>(0.0), vec2<f32>(1.0)), 0.0).r;\n let t2 = textureSampleLevel(currentTransmittance, sceneSampler, clamp(input.uv + vec2<f32>(texel.x, 0.0), vec2<f32>(0.0), vec2<f32>(1.0)), 0.0).r;\n let t3 = textureSampleLevel(currentTransmittance, sceneSampler, clamp(input.uv + vec2<f32>(0.0, -texel.y), vec2<f32>(0.0), vec2<f32>(1.0)), 0.0).r;\n let t4 = textureSampleLevel(currentTransmittance, sceneSampler, clamp(input.uv + vec2<f32>(0.0, texel.y), vec2<f32>(0.0), vec2<f32>(1.0)), 0.0).r;\n let minTransport = min(transportT.r, min(min(t1, t2), min(t3, t4)));\n let maxTransport = max(transportT.r, max(max(t1, t2), max(t3, t4)));\n let worldTolerance = max(0.05, distance(cloudDepth.xyz, view.cameraPos) * 0.02);\n let depthAccepted = historyDepth.a > 0.5 && distance(historyDepth.xyz, cloudDepth.xyz) <= worldTolerance;\n let accepted = cloud.temporal.x > 0.5 && cloud.temporal.y < 0.5 && inBounds && depthAccepted;\n let historyWeight = select(0.0, clamp(cloud.temporal.z, 0.0, 0.92), accepted);\n let stableHistory = clamp(previous.rgb, minRadiance, maxRadiance);\n let stableTransport = clamp(previousTransport.r, minTransport, maxTransport);\n let radiance = mix(transport.rgb, stableHistory, historyWeight);\n let transmittance = mix(transportT.r, stableTransport, historyWeight);\n return vec4<f32>(scene.rgb * transmittance + radiance, transmittance);\n}\n`;\n\nexport interface CloudLayerFeatureFrame {\n readonly params: ValidatedCloudLayer | undefined;\n readonly cache: CloudDensityCache | undefined;\n readonly sourceKey: string | undefined;\n readonly timeSeconds: number;\n readonly sunDirection: readonly [number, number, number] | undefined;\n readonly sunRadiance: readonly [number, number, number] | undefined;\n readonly shadowProjection: CloudShadowProjection | undefined;\n readonly temporal: CloudTemporalFrame | undefined;\n readonly generation: number;\n readonly inspection: CloudLayerInspection;\n}\n\nexport interface CloudLayerFeatureOptions {\n /** Disable the renderer-owned CloudLayer projection while retaining the component. */\n readonly enabled?: boolean;\n}\n\nfunction makeCloudViewParams(\n frame: CloudLayerFeatureFrame,\n cache: CloudDensityCache,\n mode: 0 | 1 | 2 = 0,\n): Uint8Array {\n const params = new ArrayBuffer(CLOUD_VIEW_PARAMS_BYTES);\n const floats = new Float32Array(params);\n const integers = new Uint32Array(params);\n const profile = CLOUD_QUALITY_PROFILES[frame.params?.quality ?? 'medium'];\n const authored = frame.params;\n floats[0] = authored?.baseHeight ?? 0;\n floats[1] = authored?.thickness ?? 1;\n floats[2] = authored?.scale ?? 1;\n floats[3] = authored?.density ?? 0;\n floats[4] = authored?.coverage ?? 1;\n floats[5] = frame.timeSeconds;\n floats[6] =\n mode === 1\n ? (authored?.shadowRange ?? 0)\n : cloudViewDistanceForQuality(authored?.quality ?? 'medium');\n floats[7] = authored?.seed ?? 0;\n floats[8] = authored?.wind[0] ?? 0;\n floats[9] = authored?.wind[1] ?? 0;\n floats[10] = authored?.wind[2] ?? 0;\n floats[12] = frame.sunDirection?.[0] ?? 0;\n floats[13] = frame.sunDirection?.[1] ?? -1;\n floats[14] = frame.sunDirection?.[2] ?? 0;\n floats[15] = 0.2;\n floats[16] = frame.sunRadiance?.[0] ?? 0;\n floats[17] = frame.sunRadiance?.[1] ?? 0;\n floats[18] = frame.sunRadiance?.[2] ?? 0;\n integers[20] = cache.resolution;\n integers[21] = Math.max(1, Math.min(64, Math.floor(profile.viewSteps)));\n integers[22] = Math.max(1, Math.min(64, Math.floor(profile.shadowSteps)));\n integers[23] = mode;\n const projection = frame.shadowProjection;\n if (projection !== undefined) {\n floats[24] = projection.origin[0];\n floats[25] = projection.origin[1];\n floats[26] = projection.origin[2];\n floats[28] = projection.right[0];\n floats[29] = projection.right[1];\n floats[30] = projection.right[2];\n floats[32] = projection.up[0];\n floats[33] = projection.up[1];\n floats[34] = projection.up[2];\n floats[36] = projection.range;\n floats[37] = projection.lowSun ? 0 : 1;\n floats[38] = projection.lowSun ? 1 : 0;\n floats[39] = projection.texelSize;\n }\n const temporal = frame.temporal;\n floats[40] = temporal !== undefined && temporal.reset === false ? 1 : 0;\n floats[41] = temporal?.reset === true ? 1 : 0;\n floats[42] = temporal === undefined ? 0 : profile.historyWeight;\n // The history entry is the last successfully submitted signature. Carry its\n // timestamp so the shader can advect the representative cloud point by the\n // exact elapsed time during reprojection.\n floats[43] = temporal?.history?.temporal.timeSeconds ?? frame.timeSeconds;\n return new Uint8Array(params);\n}\n\nfunction planCloudDensity(\n frame: CloudLayerFeatureFrame,\n packedCache: Uint32Array,\n context: RenderFeaturePlanContext,\n): RenderFeaturePlan {\n const cacheCount = packedCache.length;\n const params = new Uint32Array([cacheCount]);\n const inputTarget = context.targets.find((target) => target.name === 'motion-input');\n const outputTarget = context.targets.find((target) => target.name === 'motion-output');\n const historyRadiancePrevious = context.targets.find(\n (target) => target.name === 'cloud-history-radiance-previous',\n );\n const historyTransmittancePrevious = context.targets.find(\n (target) => target.name === 'cloud-history-transmittance-previous',\n );\n const historyDepthPrevious = context.targets.find(\n (target) => target.name === 'cloud-history-depth-previous',\n );\n const historyRadianceCurrent = context.targets.find(\n (target) => target.name === 'cloud-history-radiance-current',\n );\n const historyTransmittanceCurrent = context.targets.find(\n (target) => target.name === 'cloud-history-transmittance-current',\n );\n const historyDepthCurrent = context.targets.find(\n (target) => target.name === 'cloud-history-depth-current',\n );\n const hasHistoryTargets =\n historyRadiancePrevious !== undefined &&\n historyTransmittancePrevious !== undefined &&\n historyDepthPrevious !== undefined &&\n historyRadianceCurrent !== undefined &&\n historyTransmittanceCurrent !== undefined &&\n historyDepthCurrent !== undefined;\n const shadowTarget = context.targets.find((target) => target.name === 'cloud-shadow');\n const canShadow =\n shadowTarget !== undefined &&\n shadowTarget.sampleCount === 1 &&\n frame.shadowProjection !== undefined &&\n hasHistoryTargets;\n const canCompose =\n inputTarget !== undefined &&\n outputTarget !== undefined &&\n inputTarget.sampleCount === 1 &&\n outputTarget.sampleCount === 1 &&\n hasHistoryTargets;\n const transportReads = ['motion-input', { key: 'depth', sampleType: 'depth' as const }] as const;\n const transportCacheReads = [\n 'motion-input',\n 'cloud-shadow',\n { key: 'depth', sampleType: 'depth' as const },\n ] as const;\n const historyReads = [\n 'motion-input',\n 'cloud-history-radiance-previous',\n 'cloud-history-transmittance-previous',\n 'cloud-history-depth-previous',\n { key: 'depth', sampleType: 'depth' as const },\n ] as const;\n const historyAdditionalTextures = [\n 'cloud-history-radiance-previous',\n 'cloud-history-transmittance-previous',\n 'cloud-history-depth-previous',\n ] as const;\n const viewParams = makeCloudViewParams(frame, frame.cache as CloudDensityCache);\n const shadowParams = canShadow\n ? makeCloudViewParams(frame, frame.cache as CloudDensityCache, 1)\n : undefined;\n const transportUsesShadowCache = canCompose && canShadow;\n return {\n resources: [\n {\n kind: 'compute-program',\n name: CLOUD_LAYER_DENSITY_PROGRAM,\n program: {\n wgsl: CLOUD_DENSITY_COMPUTE_WGSL,\n entryPoints: ['cloud_density_cache'],\n bindings: [\n {\n label: 'forgeax.cloud-layer.cache',\n entries: [\n { binding: 0, visibility: COMPUTE_STAGE, buffer: { type: 'read-only-storage' } },\n { binding: 1, visibility: COMPUTE_STAGE, buffer: { type: 'storage' } },\n { binding: 2, visibility: COMPUTE_STAGE, buffer: { type: 'uniform' } },\n ],\n },\n ],\n },\n },\n {\n kind: 'buffer',\n name: CLOUD_LAYER_DENSITY_CACHE,\n size: packedCache.byteLength,\n usage: ['storage', 'copy-src'],\n data: packedCache,\n },\n {\n kind: 'buffer',\n name: CLOUD_LAYER_DENSITY_OUTPUT,\n size: packedCache.byteLength,\n usage: ['storage', 'copy-src'],\n },\n {\n kind: 'buffer',\n name: 'cloud-layer-density-params',\n size: params.byteLength,\n usage: ['uniform'],\n data: params,\n },\n {\n kind: 'compute-bindings',\n name: CLOUD_LAYER_DENSITY_BINDINGS,\n program: CLOUD_LAYER_DENSITY_PROGRAM,\n entries: [\n { binding: 0, resource: CLOUD_LAYER_DENSITY_CACHE },\n { binding: 1, resource: CLOUD_LAYER_DENSITY_OUTPUT },\n { binding: 2, resource: 'cloud-layer-density-params' },\n ],\n },\n {\n kind: 'fullscreen-program',\n name: 'cloud-layer-view',\n source: CLOUD_VIEW_FULLSCREEN_WGSL,\n usesView: true,\n storageBindings: [8],\n reads: historyReads,\n params: {\n byteSize: viewParams.byteLength,\n defaultValue: viewParams,\n },\n },\n ...(shadowParams === undefined\n ? []\n : [\n {\n kind: 'fullscreen-program' as const,\n name: 'cloud-layer-shadow',\n source: CLOUD_VIEW_FULLSCREEN_WGSL,\n usesView: true,\n storageBindings: [8],\n reads: historyReads,\n params: {\n byteSize: shadowParams.byteLength,\n defaultValue: shadowParams,\n },\n },\n ]),\n ...(canCompose\n ? [\n {\n kind: 'fullscreen-program' as const,\n name: 'cloud-layer-transport',\n source: transportUsesShadowCache\n ? CLOUD_TRANSPORT_FULLSCREEN_WGSL\n : CLOUD_TRANSPORT_ANALYTIC_FULLSCREEN_WGSL,\n fragmentEntryPoint: 'fs_transport',\n usesView: true,\n storageBindings: [8],\n reads: transportUsesShadowCache ? transportCacheReads : transportReads,\n params: {\n byteSize: viewParams.byteLength,\n defaultValue: viewParams,\n },\n },\n {\n kind: 'fullscreen-program' as const,\n name: 'cloud-layer-resolve',\n source: CLOUD_RESOLVE_FULLSCREEN_WGSL,\n usesView: true,\n reads: [\n 'motion-input',\n 'cloud-history-radiance-current',\n 'cloud-history-transmittance-current',\n 'cloud-history-depth-current',\n 'cloud-history-radiance-previous',\n 'cloud-history-transmittance-previous',\n 'cloud-history-depth-previous',\n { key: 'depth', sampleType: 'depth' as const },\n ],\n params: {\n byteSize: viewParams.byteLength,\n defaultValue: viewParams,\n },\n },\n ]\n : []),\n ...(canCompose\n ? [\n {\n kind: 'graphics-program' as const,\n name: 'cloud-layer-transport-pipeline',\n program: {\n shader: 'cloud-layer-transport',\n vertexLayout: 'none',\n colorFormats: [\n historyRadianceCurrent.format,\n historyTransmittanceCurrent.format,\n historyDepthCurrent.format,\n ],\n sampleCount: 1 as const,\n renderState: {\n depthWriteEnabled: false,\n depthCompare: 'always' as const,\n },\n },\n },\n {\n kind: 'graphics-bindings' as const,\n name: 'cloud-layer-transport-view-bindings',\n program: 'cloud-layer-transport-pipeline',\n values: { group: 0, view: true },\n },\n {\n kind: 'graphics-bindings' as const,\n name: 'cloud-layer-transport-bindings',\n program: 'cloud-layer-transport-pipeline',\n values: {\n group: 1,\n fullscreen: true,\n shader: 'cloud-layer-transport',\n input: 'motion-input',\n depth: 'depth',\n additionalTextures: transportUsesShadowCache ? ['cloud-shadow'] : [],\n storageBuffers: [CLOUD_LAYER_DENSITY_OUTPUT],\n },\n logicalTargets: { input: 'motion-input' },\n },\n {\n kind: 'graphics-program' as const,\n name: 'cloud-layer-resolve-pipeline',\n program: {\n shader: 'cloud-layer-resolve',\n vertexLayout: 'none',\n colorFormats: [outputTarget.format],\n sampleCount: 1 as const,\n renderState: {\n depthWriteEnabled: false,\n depthCompare: 'always' as const,\n },\n },\n },\n {\n kind: 'graphics-bindings' as const,\n name: 'cloud-layer-resolve-view-bindings',\n program: 'cloud-layer-resolve-pipeline',\n values: { group: 0, view: true },\n },\n {\n kind: 'graphics-bindings' as const,\n name: 'cloud-layer-resolve-bindings',\n program: 'cloud-layer-resolve-pipeline',\n values: {\n group: 1,\n fullscreen: true,\n shader: 'cloud-layer-resolve',\n input: 'motion-input',\n depth: 'depth',\n additionalTextures: [\n 'cloud-history-radiance-current',\n 'cloud-history-transmittance-current',\n 'cloud-history-depth-current',\n 'cloud-history-radiance-previous',\n 'cloud-history-transmittance-previous',\n 'cloud-history-depth-previous',\n ],\n },\n },\n ]\n : []),\n ...(canShadow\n ? [\n {\n kind: 'graphics-program' as const,\n name: 'cloud-layer-shadow-pipeline',\n program: {\n shader: 'cloud-layer-shadow',\n vertexLayout: 'none',\n colorFormats: [shadowTarget.format],\n sampleCount: 1 as const,\n renderState: {\n depthWriteEnabled: false,\n depthCompare: 'always' as const,\n blend: {\n color: {\n srcFactor: 'one' as const,\n dstFactor: 'zero' as const,\n operation: 'add' as const,\n },\n alpha: {\n srcFactor: 'one' as const,\n dstFactor: 'zero' as const,\n operation: 'add' as const,\n },\n },\n },\n },\n },\n {\n kind: 'graphics-bindings' as const,\n name: 'cloud-layer-shadow-view-bindings',\n program: 'cloud-layer-shadow-pipeline',\n values: { group: 0, view: true },\n },\n {\n kind: 'graphics-bindings' as const,\n name: 'cloud-layer-shadow-bindings',\n program: 'cloud-layer-shadow-pipeline',\n values: {\n group: 1,\n fullscreen: true,\n shader: 'cloud-layer-shadow',\n input: false,\n depth: 'depth',\n // The shadow branch's WGSL keeps the shared depth binding\n // shape, but its light-space path never samples scene depth.\n // Bind the renderer-owned far-depth fallback instead of\n // introducing a read-before-main graph dependency.\n depthFallback: true,\n additionalTextures: historyAdditionalTextures,\n storageBuffers: [CLOUD_LAYER_DENSITY_OUTPUT],\n },\n },\n ]\n : []),\n ],\n passes:\n context.caps.compute && context.caps.storageBuffer\n ? [\n {\n kind: 'compute' as const,\n name: 'cloud-layer-density-cache',\n program: CLOUD_LAYER_DENSITY_PROGRAM,\n bindings: CLOUD_LAYER_DENSITY_BINDINGS,\n dispatches: [\n {\n kind: 'direct' as const,\n entryPoint: 'cloud_density_cache',\n workgroups: [Math.max(1, Math.ceil(cacheCount / CLOUD_WORKGROUP_SIZE))],\n },\n ],\n },\n ...(canShadow\n ? [\n {\n kind: 'raster' as const,\n name: 'cloud-layer-shadow',\n colorAttachments: [\n {\n target: 'cloud-shadow',\n loadOp: 'clear' as const,\n storeOp: 'store' as const,\n },\n ],\n sampledTargets: [\n 'cloud-history-radiance-previous',\n 'cloud-history-transmittance-previous',\n 'cloud-history-depth-previous',\n ],\n draws: [\n {\n program: 'cloud-layer-shadow-pipeline',\n bindings: [\n 'cloud-layer-shadow-view-bindings',\n 'cloud-layer-shadow-bindings',\n ],\n vertexData: [],\n vertexLayout: 'none' as const,\n draw: { kind: 'draw' as const, vertexCount: 3, instanceCount: 1 },\n },\n ],\n },\n ]\n : []),\n ...(canCompose\n ? [\n {\n kind: 'raster' as const,\n name: 'cloud-layer-transport',\n colorAttachments: [\n {\n target: 'cloud-history-radiance-current',\n loadOp: 'clear' as const,\n storeOp: 'store' as const,\n },\n {\n target: 'cloud-history-transmittance-current',\n loadOp: 'clear' as const,\n storeOp: 'store' as const,\n },\n {\n target: 'cloud-history-depth-current',\n loadOp: 'clear' as const,\n storeOp: 'store' as const,\n },\n ],\n sampledTargets: [\n 'motion-input',\n 'depth',\n ...(transportUsesShadowCache ? ['cloud-shadow'] : []),\n ],\n draws: [\n {\n program: 'cloud-layer-transport-pipeline',\n bindings: [\n 'cloud-layer-transport-view-bindings',\n 'cloud-layer-transport-bindings',\n ],\n vertexData: [],\n vertexLayout: 'none' as const,\n draw: { kind: 'draw' as const, vertexCount: 3, instanceCount: 1 },\n },\n ],\n },\n {\n kind: 'raster' as const,\n name: 'cloud-layer-resolve',\n colorAttachments: [\n {\n target: 'motion-output',\n loadOp: 'clear' as const,\n storeOp: 'store' as const,\n },\n ],\n sampledTargets: [\n 'motion-input',\n 'depth',\n 'cloud-history-radiance-current',\n 'cloud-history-transmittance-current',\n 'cloud-history-depth-current',\n 'cloud-history-radiance-previous',\n 'cloud-history-transmittance-previous',\n 'cloud-history-depth-previous',\n ],\n draws: [\n {\n program: 'cloud-layer-resolve-pipeline',\n bindings: [\n 'cloud-layer-resolve-view-bindings',\n 'cloud-layer-resolve-bindings',\n ],\n vertexData: [],\n vertexLayout: 'none' as const,\n draw: { kind: 'draw' as const, vertexCount: 3, instanceCount: 1 },\n },\n ],\n },\n ]\n : []),\n ]\n : [],\n };\n}\n\n/**\n * Renderer-installed cloud producer. Authoring is read once from World at\n * extraction; resource preparation, graph ordering and retirement stay with\n * RenderFeatureHost.\n */\nexport function createCloudLayerFeature(\n options: CloudLayerFeatureOptions = {},\n): RenderFeature<CloudLayerFeatureFrame> {\n let cachedSourceKey: string | undefined;\n let cached: CloudDensityCache | undefined;\n let packedCache: Uint32Array | undefined;\n let generation = 0;\n const histories = new CloudHistoryStore();\n let temporalResetCount = 0;\n let lastTemporalReset: CloudTemporalFrame['reasons'][number] | undefined;\n return Object.freeze({\n identity: CLOUD_LAYER_FEATURE_IDENTITY,\n placement: 'scene' as const,\n requiredCapabilities: ['compute', 'storageBuffer', 'rgba16floatRenderable'] as const,\n // Cloud programs are generated by the feature and have no user-authored\n // manifest entry to await. Use the immediate module path so first-frame\n // feature admission does not publish a transient pending-shader failure;\n // pipeline creation remains the validation boundary for this WGSL.\n shaderModuleMode: 'immediate' as const,\n extract: (\n context: RenderFeatureExtractContext,\n ): Result<CloudLayerFeatureFrame, RenderError> => {\n if (options.enabled === false) {\n histories.reset();\n return ok({\n params: undefined,\n cache: undefined,\n sourceKey: undefined,\n timeSeconds: 0,\n sunDirection: undefined,\n sunRadiance: undefined,\n shadowProjection: undefined,\n temporal: undefined,\n generation,\n inspection: inspectCloudLayer({ authored: false }),\n });\n }\n const world = context.worlds[context.owner];\n if (world === undefined) {\n histories.reset();\n return ok({\n params: undefined,\n cache: undefined,\n sourceKey: undefined,\n timeSeconds: 0,\n sunDirection: undefined,\n sunRadiance: undefined,\n shadowProjection: undefined,\n temporal: undefined,\n generation,\n inspection: inspectCloudLayer({ authored: false }),\n });\n }\n // The normal RenderSystem extract owns World reads and selected-sun\n // resolution. Direct feature probes must provide the same frame facts;\n // this keeps the feature from growing a detached authoring callback or\n // a second per-feature ECS registry.\n const cloud = context.frame?.cloudLayer;\n const capability =\n context.caps === undefined ? undefined : cloudCapabilitiesFromRhi(context.caps);\n if (cloud === undefined) {\n histories.reset();\n return ok({\n params: undefined,\n cache: undefined,\n sourceKey: undefined,\n timeSeconds: 0,\n sunDirection: undefined,\n sunRadiance: undefined,\n shadowProjection: undefined,\n temporal: undefined,\n generation,\n inspection: inspectCloudLayer({\n authored: false,\n ...(capability === undefined ? {} : { capability }),\n }),\n });\n }\n const formationKey = cloudLayerFormationKey(cloud.params);\n if (cached === undefined || cachedSourceKey !== formationKey) {\n cached = buildCloudDensityCache(cloud.params);\n packedCache = packCloudDensityCache(cached);\n cachedSourceKey = formationKey;\n generation += 1;\n }\n const view = context.frame?.view;\n const shadowProjection =\n view === undefined || cloud.sunDirection === undefined\n ? undefined\n : createCloudShadowProjection({\n center: view.shadowAnchor ?? view.cameraPosition,\n sunDirection: cloud.sunDirection,\n range: cloud.params.shadowRange,\n resolution: cloudShadowResolutionForQuality(cloud.params.quality),\n });\n const temporalSignature: CloudTemporalSignature | undefined =\n view === undefined\n ? undefined\n : {\n sourceKey: cloud.sourceKey,\n viewId: view.identity,\n authoringGeneration: generation,\n cloudShadowRevision: shadowProjection?.revision ?? 0,\n cameraRevision: view.cameraRevision,\n deviceGeneration: view.deviceGeneration,\n width: view.width,\n height: view.height,\n timeSeconds: cloud.worldTimeSeconds,\n quality: cloud.params.quality,\n ...(view.sceneDepthVersion === undefined\n ? {}\n : { sceneDepthVersion: view.sceneDepthVersion }),\n };\n const temporal =\n temporalSignature === undefined\n ? undefined\n : (() => {\n const decision = histories.begin(temporalSignature, {\n ...(view?.cameraCut === undefined ? {} : { cameraCut: view.cameraCut }),\n ...(view?.recovery === undefined ? {} : { recovery: view.recovery }),\n });\n const history =\n decision.history ?? createCloudHistory(temporalSignature, generation, false);\n return Object.freeze({\n signature: temporalSignature,\n history,\n reset: decision.reset,\n reasons: decision.reasons,\n });\n })();\n const resourceFacts = inspectCloudLayerResources({\n generation,\n cache: cached,\n ...(shadowProjection === undefined ? {} : { shadow: shadowProjection }),\n ...(temporal?.history === undefined ? {} : { history: temporal.history }),\n });\n const temporalReset = temporal?.reasons.at(-1);\n if (temporal?.reset === true) temporalResetCount += 1;\n if (temporalReset !== undefined) lastTemporalReset = temporalReset;\n return ok({\n params: cloud.params,\n cache: cached,\n sourceKey: cloud.sourceKey,\n timeSeconds: cloud.worldTimeSeconds,\n sunDirection: cloud.sunDirection,\n sunRadiance: cloud.sunRadiance,\n shadowProjection,\n temporal,\n generation,\n inspection: inspectCloudLayer({\n authored: true,\n sourceKey: cloud.sourceKey,\n generation,\n resourceFacts,\n ...(shadowProjection === undefined ? {} : { shadowRevision: shadowProjection.revision }),\n ...(temporal === undefined\n ? {}\n : {\n temporalResets: temporalResetCount,\n ...(lastTemporalReset === undefined ? {} : { lastTemporalReset }),\n }),\n ...(capability === undefined ? {} : { capability }),\n budget: {\n quality: cloud.params.quality,\n reason:\n 'physical GPU timing and residency receipts are unavailable until a prepared adapter submits them',\n },\n }),\n });\n },\n onFrameSubmitted: (frame: CloudLayerFeatureFrame) => {\n if (frame.temporal?.history !== undefined) {\n // Advance the metadata timestamp only after submit. The next frame's\n // GPU reprojection then receives the elapsed time since this exact\n // submitted signature, while an aborted frame keeps the old entry.\n histories.commit(\n frame.temporal.signature,\n createCloudHistory(frame.temporal.signature, frame.generation, true),\n );\n }\n },\n onFrameAborted: (frame: CloudLayerFeatureFrame) => {\n // A reset candidate is committed only after queue submission. The store\n // still contains the previous entry while this frame is rejected.\n void frame;\n },\n plan: (\n frame: CloudLayerFeatureFrame,\n context: RenderFeaturePlanContext,\n ): Result<RenderFeaturePlan, RenderError> => {\n if (frame.cache === undefined || packedCache === undefined || frame.params === undefined) {\n return ok({ resources: [], passes: [] });\n }\n return ok(planCloudDensity(frame, packedCache, context));\n },\n });\n}\n","import type { RhiCaps } from '@forgeax/engine-rhi';\nimport type { MaterialProgramAbi, MaterialSurfacePassKind } from '@forgeax/engine-types';\nimport { err, ok, type Result } from '@forgeax/engine-types';\n\nexport type SurfaceGpuCapability = 'compute' | 'storageBuffer' | 'indirectDrawing';\nexport type SurfaceGpuFallbackReason = SurfaceGpuCapability;\n\nexport type SurfaceGpuSubmissionErrorCode =\n | 'surface-abi-missing'\n | 'surface-pass-missing'\n | 'surface-producer-not-ready'\n | 'surface-generation-stale';\n\nexport interface SurfaceGpuSubmissionError {\n readonly code: SurfaceGpuSubmissionErrorCode;\n readonly expected: string;\n readonly hint: string;\n readonly pass: MaterialSurfacePassKind;\n readonly owner: 'surface-producer' | 'render-scene' | 'render-generation';\n readonly actual?: unknown;\n}\n\nexport interface SurfaceGpuPassAdmission {\n readonly pass: MaterialSurfacePassKind;\n readonly lane: 'gpu-driven' | 'direct';\n readonly reason?: SurfaceGpuFallbackReason;\n}\n\nexport interface SurfaceGpuSubmissionAdmission {\n readonly model: 'single-layer-medium';\n readonly lane: 'gpu-driven' | 'direct';\n readonly passes: readonly [SurfaceGpuPassAdmission, SurfaceGpuPassAdmission];\n readonly deviceGeneration: number;\n}\n\nexport interface SurfaceGpuSubmissionInput {\n readonly abi: MaterialProgramAbi;\n readonly caps: Pick<RhiCaps, 'compute' | 'storageBuffer' | 'indirectDrawing'>;\n readonly sceneIndexReady: boolean;\n readonly resourcesReady: boolean;\n readonly dynamicInputReady: boolean;\n readonly deviceGeneration: number;\n readonly preparedDeviceGeneration: number;\n}\n\nconst ERROR_POLICY: Readonly<\n Record<SurfaceGpuSubmissionErrorCode, { readonly expected: string; readonly hint: string }>\n> = {\n 'surface-abi-missing': {\n expected: 'a producer-published single-layer-medium ABI is present',\n hint: 'compose, reflect, and publish the Surface model before preparing the draw',\n },\n 'surface-pass-missing': {\n expected: 'the published model contains both nearest-layer and color passes',\n hint: 'recook the complete model publication; do not synthesize a missing pass',\n },\n 'surface-producer-not-ready': {\n expected: 'scene-index, resources, and dynamic input facts are ready for the published model',\n hint: 'repair the owning producer publication and retry; capability fallback does not cover stale assets',\n },\n 'surface-generation-stale': {\n expected: 'prepared Surface facts belong to the current device generation',\n hint: 'rebuild the prepared surface resources for the current device generation',\n },\n};\n\nfunction failure(\n code: SurfaceGpuSubmissionErrorCode,\n pass: MaterialSurfacePassKind,\n owner: SurfaceGpuSubmissionError['owner'],\n actual?: unknown,\n): SurfaceGpuSubmissionError {\n return {\n code,\n expected: ERROR_POLICY[code].expected,\n hint: ERROR_POLICY[code].hint,\n pass,\n owner,\n ...(actual === undefined ? {} : { actual }),\n };\n}\n\nfunction capabilityFallback(\n caps: SurfaceGpuSubmissionInput['caps'],\n): SurfaceGpuFallbackReason | undefined {\n if (!caps.compute) return 'compute';\n if (!caps.storageBuffer) return 'storageBuffer';\n if (!caps.indirectDrawing) return 'indirectDrawing';\n return undefined;\n}\n\n/**\n * Admit the two Surface passes together. Capability fallback is explicit and\n * symmetric; a missing promised publication is a producer error and never a\n * silent direct fallback.\n */\nexport function admitSingleLayerMediumSubmission(\n input: SurfaceGpuSubmissionInput,\n): Result<SurfaceGpuSubmissionAdmission, SurfaceGpuSubmissionError> {\n const firstPass: MaterialSurfacePassKind = 'nearest-layer';\n const surface = input.abi.surface;\n if (surface === undefined || surface.model !== 'single-layer-medium') {\n return err(failure('surface-abi-missing', firstPass, 'surface-producer', surface));\n }\n if (!surface.passes.includes('nearest-layer') || !surface.passes.includes('color')) {\n return err(failure('surface-pass-missing', firstPass, 'surface-producer', surface.passes));\n }\n if (input.deviceGeneration !== input.preparedDeviceGeneration) {\n return err(\n failure('surface-generation-stale', firstPass, 'render-generation', {\n deviceGeneration: input.deviceGeneration,\n preparedDeviceGeneration: input.preparedDeviceGeneration,\n }),\n );\n }\n const dynamicRequired = surface.dynamicInput !== undefined;\n if (\n !input.sceneIndexReady ||\n !input.resourcesReady ||\n (dynamicRequired && !input.dynamicInputReady)\n ) {\n return err(\n failure('surface-producer-not-ready', firstPass, 'surface-producer', {\n sceneIndexReady: input.sceneIndexReady,\n resourcesReady: input.resourcesReady,\n dynamicInputReady: input.dynamicInputReady,\n }),\n );\n }\n const fallback = capabilityFallback(input.caps);\n const admitted: [SurfaceGpuPassAdmission, SurfaceGpuPassAdmission] =\n fallback === undefined\n ? [\n { pass: firstPass, lane: 'gpu-driven' },\n { pass: 'color', lane: 'gpu-driven' },\n ]\n : [\n { pass: firstPass, lane: 'direct', reason: fallback },\n { pass: 'color', lane: 'direct', reason: fallback },\n ];\n return ok({\n model: 'single-layer-medium',\n lane: fallback === undefined ? 'gpu-driven' : 'direct',\n passes: admitted,\n deviceGeneration: input.deviceGeneration,\n });\n}\n","import { err, type MaterialAsset, type MeshAsset, ok, type Result } from '@forgeax/engine-types';\nimport { type PointShape, PointShapeValue, pointShapeFromU32 } from '../components/points';\nimport type {\n PointsLinesBudgetExceededError,\n PointsLinesInvalidStyleError,\n PointsLinesMaterialUnsupportedError,\n PointsLinesStyleUnsupportedError,\n PointsLinesTopologyMismatchError,\n} from '../errors/render';\nimport {\n PointsLinesBudgetExceededError as BudgetError,\n PointsLinesInvalidStyleError as InvalidStyleError,\n PointsLinesMaterialUnsupportedError as MaterialError,\n PointsLinesStyleUnsupportedError as StyleError,\n PointsLinesTopologyMismatchError as TopologyError,\n} from '../errors/render';\n\nexport interface PointsStyleInput {\n readonly sizePx?: number;\n readonly shape?: number;\n}\n\nexport interface LinesStyleInput {\n readonly widthPx?: number;\n}\n\nexport interface PointsLinesAdmissionLimits {\n readonly maxPoints?: number;\n readonly maxSegments?: number;\n}\n\nexport interface PointsLinesAdmissionInput {\n readonly entity: number;\n readonly points?: PointsStyleInput;\n readonly lines?: LinesStyleInput;\n readonly mesh: MeshAsset;\n readonly material: MaterialAsset;\n readonly limits?: PointsLinesAdmissionLimits;\n readonly materialId?: string;\n}\n\nexport interface PointsLinesAdmission {\n readonly component: 'Points' | 'Lines';\n readonly shape?: PointShape;\n readonly sizePx?: number;\n readonly widthPx?: number;\n readonly pointCount: number;\n readonly segmentCount: number;\n readonly submeshes: readonly number[];\n}\n\nexport type PointsLinesAdmissionError =\n | PointsLinesInvalidStyleError\n | PointsLinesTopologyMismatchError\n | PointsLinesStyleUnsupportedError\n | PointsLinesMaterialUnsupportedError\n | PointsLinesBudgetExceededError;\n\nfunction invalidStyle(\n input: PointsLinesAdmissionInput,\n component: 'Points' | 'Lines' | 'Points/Lines',\n field: string,\n value: number | string | undefined,\n expected: string,\n): Result<never, PointsLinesAdmissionError> {\n return err(new InvalidStyleError({ entity: input.entity, component, field, value, expected }));\n}\n\nfunction topologyMismatch(\n input: PointsLinesAdmissionInput,\n submesh: number,\n expected: string,\n actual: string,\n): Result<never, PointsLinesAdmissionError> {\n return err(new TopologyError({ entity: input.entity, submesh, expected, actual }));\n}\n\nfunction checkStyle(\n input: PointsLinesAdmissionInput,\n): Result<\n { component: 'Points' | 'Lines'; shape?: PointShape; sizePx?: number; widthPx?: number },\n PointsLinesAdmissionError\n> {\n const hasPoints = input.points !== undefined;\n const hasLines = input.lines !== undefined;\n if (hasPoints && hasLines) {\n return invalidStyle(\n input,\n 'Points/Lines',\n 'components',\n 'Points + Lines',\n 'exactly one style component',\n );\n }\n if (!hasPoints && !hasLines) {\n return invalidStyle(input, 'Points/Lines', 'components', undefined, 'one style component');\n }\n\n if (hasPoints) {\n const sizePx = input.points?.sizePx ?? 4;\n const shapeValue = input.points?.shape ?? PointShapeValue.square;\n const shape = pointShapeFromU32(shapeValue);\n if (!Number.isFinite(sizePx) || sizePx <= 0) {\n return invalidStyle(input, 'Points', 'sizePx', sizePx, 'finite sizePx > 0');\n }\n if (shape === undefined) {\n return invalidStyle(input, 'Points', 'shape', shapeValue, \"shape is 'square' or 'circle'\");\n }\n return ok({ component: 'Points', shape, sizePx });\n }\n\n const widthPx = input.lines?.widthPx ?? 1;\n if (!Number.isFinite(widthPx) || widthPx <= 0) {\n return invalidStyle(input, 'Lines', 'widthPx', widthPx, 'finite widthPx > 0');\n }\n return ok({ component: 'Lines', widthPx });\n}\n\nfunction checkTopology(\n input: PointsLinesAdmissionInput,\n component: 'Points' | 'Lines',\n): Result<\n { pointCount: number; segmentCount: number; submeshes: readonly number[] },\n PointsLinesAdmissionError\n> {\n const expected = component === 'Points' ? 'point-list' : 'line-list';\n let pointCount = 0;\n let segmentCount = 0;\n const acceptedSubmeshes: number[] = [];\n let sawNonEmpty = false;\n\n for (const [submeshIndex, submesh] of input.mesh.submeshes.entries()) {\n const indexed = input.mesh.indices !== undefined && submesh.indexCount > 0;\n const elementCount = indexed ? submesh.indexCount : submesh.vertexCount;\n if (elementCount === 0) continue;\n sawNonEmpty = true;\n\n if (component === 'Lines' && submesh.topology === 'line-strip') {\n return err(\n new StyleError({\n lane: 'admission',\n field: 'topology',\n member: 'line-strip',\n supported: ['line-list'],\n }),\n );\n }\n if (submesh.topology !== expected) {\n return topologyMismatch(input, submeshIndex, expected, submesh.topology);\n }\n if (component === 'Lines' && elementCount % 2 !== 0) {\n return topologyMismatch(input, submeshIndex, 'line-list pairs', 'line-list odd tail');\n }\n acceptedSubmeshes.push(submeshIndex);\n if (component === 'Points') pointCount += elementCount;\n else segmentCount += elementCount / 2;\n }\n\n if (!sawNonEmpty) return topologyMismatch(input, 0, expected, 'empty-range');\n return ok({ pointCount, segmentCount, submeshes: acceptedSubmeshes });\n}\n\nfunction checkMaterial(input: PointsLinesAdmissionInput): Result<void, PointsLinesAdmissionError> {\n const passes = input.material.passes ?? [];\n const unlitModules = new Set(['forgeax_material::unlit', 'forgeax::default-unlit']);\n if (passes.length !== 1 || passes[0] === undefined) {\n const pass =\n passes.find(\n (candidate) => candidate.name === 'deferred' || candidate.name === 'shadow-caster',\n ) ?? passes[0];\n return err(\n new MaterialError({\n entity: input.entity,\n material: input.materialId ?? '<anonymous>',\n pass: pass?.name ?? '<empty>',\n module: pass?.program.module ?? '<empty>',\n reason: 'points-lines admission requires one unlit forward pass',\n }),\n );\n }\n const pass = passes[0];\n const lightMode = (pass.renderState?.tags as Record<string, unknown> | undefined)?.LightMode;\n if (\n !unlitModules.has(pass.program.module) ||\n pass.name !== 'forward' ||\n lightMode === 'ShadowCaster'\n ) {\n return err(\n new MaterialError({\n entity: input.entity,\n material: input.materialId ?? '<anonymous>',\n pass: pass.name,\n module: pass.program.module,\n reason: 'points-lines admission requires an engine-owned unlit forward pass',\n }),\n );\n }\n return ok(undefined);\n}\n\n/** Validate one complete Points/Lines candidate before any renderer publication. */\nexport function admitPointsLines(\n input: PointsLinesAdmissionInput,\n): Result<PointsLinesAdmission, PointsLinesAdmissionError> {\n const style = checkStyle(input);\n if (!style.ok) return style;\n const topology = checkTopology(input, style.value.component);\n if (!topology.ok) return topology;\n const material = checkMaterial(input);\n if (!material.ok) return material;\n\n if (style.value.component === 'Points' && input.limits?.maxPoints !== undefined) {\n if (topology.value.pointCount > input.limits.maxPoints) {\n return err(\n new BudgetError({\n lane: 'admission',\n requested: topology.value.pointCount,\n limit: input.limits.maxPoints,\n unit: 'points',\n }),\n );\n }\n }\n if (style.value.component === 'Lines' && input.limits?.maxSegments !== undefined) {\n if (topology.value.segmentCount > input.limits.maxSegments) {\n return err(\n new BudgetError({\n lane: 'admission',\n requested: topology.value.segmentCount,\n limit: input.limits.maxSegments,\n unit: 'segments',\n }),\n );\n }\n }\n\n return ok({ ...style.value, ...topology.value });\n}\n","import type { PointShadowSnapshot } from './render-system-extract';\n\n/**\n * Detached point-shadow budget facts from one completed extract/record frame.\n *\n * `requested` is the number of PointLight + PointLightShadow pairs. The\n * renderer owns the bounded cube-array atlas, so `admitted`, `shadowed`, and\n * `shadowAtlasOccupancy` are all derived from the layer sentinel emitted by\n * the same extract owner. No consumer needs to maintain a second budget\n * ledger.\n */\nexport interface PointShadowInspection {\n readonly status: 'inactive' | 'ready' | 'over-budget';\n readonly requested: number;\n readonly admitted: number;\n readonly shadowed: number;\n readonly shadowAtlasOccupancy: number;\n readonly shadowAtlasCapacity: number;\n}\n\n/** Project point-shadow snapshots to the public, JSON-safe inspection shape. */\nexport function inspectPointShadow(\n snapshots: readonly PointShadowSnapshot[],\n shadowAtlasCapacity: number,\n): PointShadowInspection {\n const requested = snapshots.length;\n const admitted = snapshots.reduce(\n (count, snapshot) =>\n snapshot.shadowAtlasLayer >= 0 && snapshot.shadowAtlasLayer < shadowAtlasCapacity\n ? count + 1\n : count,\n 0,\n );\n // Never publish a misleading `ready` state when any requested shadow owns\n // no atlas layer. The extract sentinel is the single admission projection;\n // a partial or all-sentinel frame is therefore a failed/over-budget\n // admission, not an active shadow path with incomplete output.\n const status =\n requested === 0\n ? ('inactive' as const)\n : requested > shadowAtlasCapacity || admitted !== requested\n ? ('over-budget' as const)\n : ('ready' as const);\n return Object.freeze({\n status,\n requested,\n admitted,\n // A point shadow only samples an atlas after it owns an atlas layer. Keep\n // these names explicit for AI diagnostics while deriving both from the\n // one layer projection above.\n shadowed: admitted,\n shadowAtlasOccupancy: admitted,\n shadowAtlasCapacity,\n });\n}\n","/**\n * Consumer-only SSR M0 admission.\n *\n * This module consumes detached producer receipts. It owns no capture,\n * device, graph, or recovery handle and therefore cannot repair a missing\n * producer. A complete receipt set is the only route to an admitted result.\n */\n\nimport {\n type RhiTextureFormatCapabilityReceipt,\n validateR32FloatReceipt,\n} from '@forgeax/engine-rhi';\nimport { err, ok, type Result } from '@forgeax/engine-types';\nimport type { ScreenSpaceReflectionData } from '../components/screen-space-reflection';\nimport type { ReflectionFallbackReceipt } from '../inspection-types';\nimport type {\n SsrConfigField,\n SsrConfigInvalidError,\n SsrConfigRange,\n SsrOwnerRecoveryAction,\n SsrSpatialUnavailableReason,\n SsrUnavailableError,\n} from './errors';\nimport type { SsrAdmissionIdentity } from './identity';\n\nexport const SSR_FORMAT_PROFILE = 'r32float-mip-sampled-storage' as const;\n\nexport const SSR_FORMAT_STAGES = Object.freeze([\n 'texture-create',\n 'mip-view',\n 'sampled-storage-bind-group',\n 'pipeline-bind',\n 'finish',\n 'submit',\n 'completion',\n 'readback',\n] as const);\n\nexport type { SsrAdmissionIdentity } from './identity';\n\nexport type SsrFormatStage = (typeof SSR_FORMAT_STAGES)[number];\n\n/**\n * The admission input is the real renderer owner receipt plus the one\n * integration identity supplied by the host. It deliberately does not\n * recreate submitted/source/LKG boolean flags.\n */\nexport type SsrReflectionFallbackReceipt = ReflectionFallbackReceipt & {\n readonly identity: SsrAdmissionIdentity;\n};\n\n/** RHI capability receipt with the same host-supplied integration identity. */\nexport type SsrFormatReceipt = RhiTextureFormatCapabilityReceipt & {\n readonly identity: SsrAdmissionIdentity;\n};\n\nexport interface SsrTemporalReceipt {\n readonly identity: SsrAdmissionIdentity;\n readonly successfulSubmit: true;\n readonly generation: number;\n}\n\nexport interface SsrAdmissionWork {\n readonly attachmentCount: number;\n readonly passCount: number;\n readonly bindingCount: number;\n readonly resourceCount: number;\n readonly historyCount: 0;\n readonly temporalDemand: 0;\n}\n\nexport interface SsrAdmissionBudget {\n readonly probeExecutions: 0 | 1;\n readonly resetCount: 0;\n readonly rebuildCount: 0;\n}\n\nexport interface SsrAdmissionFailure {\n readonly code:\n | 'ssr-not-requested'\n | 'ssr-reflection-fallback-unavailable'\n | 'ssr-format-unavailable'\n | 'ssr-temporal-unavailable'\n | 'ssr-receipt-identity-mismatch'\n | 'ssr-receipt-stale';\n readonly expected: string;\n readonly hint: string;\n readonly detail: Readonly<{\n readonly owner: 'producer' | 'format' | 'temporal' | 'consumer';\n /** Owner-directed action an AI consumer can take without parsing hint text. */\n readonly action: SsrOwnerRecoveryAction;\n readonly generation?: number;\n readonly identityField?: keyof SsrAdmissionIdentity;\n }>;\n}\n\nexport type SsrAdmissionResult =\n | {\n readonly status: 'admitted';\n readonly identity: SsrAdmissionIdentity | undefined;\n readonly generation: number;\n readonly work: SsrAdmissionWork;\n readonly budget: SsrAdmissionBudget;\n readonly failure?: undefined;\n }\n | {\n readonly status: 'fallback-only';\n readonly identity: SsrAdmissionIdentity | undefined;\n readonly generation: number;\n readonly work: SsrAdmissionWork;\n readonly budget: SsrAdmissionBudget;\n readonly failure: SsrAdmissionFailure;\n };\n\nexport interface SsrAdmissionInput {\n readonly requested: boolean;\n readonly identity: SsrAdmissionIdentity;\n readonly reflectionFallback?: SsrReflectionFallbackReceipt;\n readonly format?: SsrFormatReceipt;\n readonly temporal?: SsrTemporalReceipt;\n readonly previousGeneration?: number;\n}\n\n/** Public renderer projection consumed by the parent SSR feature. */\nexport interface SsrDependenciesInspection {\n readonly status: 'admitted' | 'fallback-only';\n /** Absent until the host binds an exact source/tree/lock/build identity. */\n readonly identity: SsrAdmissionIdentity | undefined;\n readonly requested: boolean;\n readonly reflectionFallback: ReflectionFallbackReceipt | undefined;\n readonly format: SsrFormatReceipt | undefined;\n readonly temporal: SsrTemporalReceipt | undefined;\n readonly admission: SsrAdmissionResult;\n readonly work: SsrAdmissionWork;\n readonly budget: SsrAdmissionBudget;\n readonly failure: SsrAdmissionFailure | undefined;\n}\n\nconst ZERO_WORK: SsrAdmissionWork = Object.freeze({\n attachmentCount: 0,\n passCount: 0,\n bindingCount: 0,\n resourceCount: 0,\n historyCount: 0,\n temporalDemand: 0,\n});\n\nconst ADMITTED_WORK: SsrAdmissionWork = Object.freeze({\n attachmentCount: 1,\n passCount: 1,\n bindingCount: 1,\n resourceCount: 1,\n historyCount: 0,\n temporalDemand: 0,\n});\n\nconst ZERO_BUDGET: SsrAdmissionBudget = Object.freeze({\n probeExecutions: 0,\n resetCount: 0,\n rebuildCount: 0,\n});\n\nconst ADMITTED_BUDGET: SsrAdmissionBudget = Object.freeze({\n probeExecutions: 1,\n resetCount: 0,\n rebuildCount: 0,\n});\n\nfunction identityFieldMismatch(\n expected: SsrAdmissionIdentity,\n actual: SsrAdmissionIdentity,\n): keyof SsrAdmissionIdentity | undefined {\n for (const field of ['sourceHead', 'sourceTree', 'lockSha256', 'buildSha256'] as const) {\n if (expected[field] !== actual[field]) return field;\n }\n return undefined;\n}\n\nfunction blocked(\n identity: SsrAdmissionIdentity | undefined,\n failure: SsrAdmissionFailure,\n generation = 0,\n): SsrAdmissionResult {\n return Object.freeze({\n status: 'fallback-only',\n identity,\n generation,\n work: ZERO_WORK,\n budget: ZERO_BUDGET,\n failure,\n });\n}\n\nfunction failure(\n code: SsrAdmissionFailure['code'],\n owner: SsrAdmissionFailure['detail']['owner'],\n hint: string,\n detail: Omit<SsrAdmissionFailure['detail'], 'owner' | 'action'> = {},\n): SsrAdmissionFailure {\n const action: SsrOwnerRecoveryAction = recoveryActionFor(code);\n return Object.freeze({\n code,\n expected: 'all producer, format, and temporal receipts share one admitted identity',\n hint,\n detail: Object.freeze({ owner, action, ...detail }),\n });\n}\n\nfunction recoveryActionFor(code: SsrAdmissionFailure['code']): SsrOwnerRecoveryAction {\n switch (code) {\n case 'ssr-reflection-fallback-unavailable':\n case 'ssr-receipt-identity-mismatch':\n return 'rebuild';\n case 'ssr-not-requested':\n case 'ssr-format-unavailable':\n case 'ssr-temporal-unavailable':\n case 'ssr-receipt-stale':\n return 'retry';\n }\n}\n\nfunction receiptFailure(\n input: SsrAdmissionInput,\n receipt: { readonly identity: SsrAdmissionIdentity },\n owner: SsrAdmissionFailure['detail']['owner'],\n): SsrAdmissionResult | undefined {\n const field = identityFieldMismatch(input.identity, receipt.identity);\n if (field === undefined) return undefined;\n return blocked(\n input.identity,\n failure('ssr-receipt-identity-mismatch', owner, 'rebuild the owner receipt for this identity', {\n identityField: field,\n }),\n );\n}\n\nfunction validFallback(receipt: SsrReflectionFallbackReceipt | undefined): boolean {\n return (\n receipt !== undefined &&\n receipt.candidateVisible === false &&\n Number.isFinite(receipt.coverage) &&\n receipt.coverage >= 0 &&\n receipt.coverage <= 1 &&\n (receipt.sourceKey === undefined || receipt.sourceKey.length > 0) &&\n (receipt.extent === undefined ||\n (receipt.extent.length === 3 &&\n receipt.extent.every((value) => Number.isFinite(value) && value > 0))) &&\n Number.isInteger(receipt.sourceGeneration) &&\n receipt.sourceGeneration >= 0 &&\n Number.isInteger(receipt.projectionGeneration) &&\n receipt.projectionGeneration >= 0 &&\n Number.isInteger(receipt.deviceGeneration) &&\n receipt.deviceGeneration >= 0 &&\n receipt.brdfSignature === 'standard-pbr-ibl-v1' &&\n ((receipt.source === 'probe' && (receipt.state === 'active' || receipt.state === 'lkg')) ||\n (receipt.source === 'skylight' && (receipt.state === 'active' || receipt.state === 'lkg')) ||\n (receipt.source === 'neutral' && receipt.state === 'neutral'))\n );\n}\n\nfunction validFormat(receipt: SsrFormatReceipt | undefined): boolean {\n if (\n receipt?.profile !== SSR_FORMAT_PROFILE ||\n receipt.verdict !== 'admitted' ||\n receipt.evidence !== 'real' ||\n !Number.isInteger(receipt.deviceGeneration) ||\n receipt.deviceGeneration < 0\n ) {\n return false;\n }\n if (\n !SSR_FORMAT_STAGES.every((stage) =>\n receipt.stages.some((entry) => entry.stage === stage && entry.verdict === 'admitted'),\n )\n ) {\n return false;\n }\n return validateR32FloatReceipt(receipt).ok;\n}\n\nfunction validTemporal(receipt: SsrTemporalReceipt | undefined): boolean {\n return (\n receipt?.successfulSubmit === true &&\n Number.isInteger(receipt.generation) &&\n receipt.generation >= 0\n );\n}\n\nexport function admitSsrM0(input: SsrAdmissionInput): SsrAdmissionResult {\n if (!input.requested) {\n return blocked(\n input.identity,\n failure('ssr-not-requested', 'consumer', 'request SSR before evaluating M0 admission'),\n );\n }\n if (input.reflectionFallback === undefined) {\n return blocked(\n input.identity,\n failure('ssr-reflection-fallback-unavailable', 'producer', 'use LKG, Skylight, or neutral'),\n );\n }\n const fallbackIdentityFailure = receiptFailure(input, input.reflectionFallback, 'producer');\n if (fallbackIdentityFailure !== undefined) return fallbackIdentityFailure;\n if (!validFallback(input.reflectionFallback)) {\n return blocked(\n input.identity,\n failure(\n 'ssr-reflection-fallback-unavailable',\n 'producer',\n 'inspect and rebuild the producer receipt',\n ),\n input.reflectionFallback.projectionGeneration,\n );\n }\n if (input.format === undefined) {\n return blocked(\n input.identity,\n failure('ssr-format-unavailable', 'format', 'probe the exact format profile for this device'),\n input.reflectionFallback.projectionGeneration,\n );\n }\n const formatIdentityFailure = receiptFailure(input, input.format, 'format');\n if (formatIdentityFailure !== undefined) return formatIdentityFailure;\n if (!validFormat(input.format)) {\n return blocked(\n input.identity,\n failure('ssr-format-unavailable', 'format', 'complete the full r32float profile probe'),\n input.reflectionFallback.projectionGeneration,\n );\n }\n // Prior submitted history is optional for fresh spatial SSR. If supplied,\n // its identity and validity still obey the temporal owner's contract.\n const temporalIdentityFailure =\n input.temporal === undefined ? undefined : receiptFailure(input, input.temporal, 'temporal');\n if (temporalIdentityFailure !== undefined) return temporalIdentityFailure;\n if (input.temporal !== undefined && !validTemporal(input.temporal)) {\n return blocked(\n input.identity,\n failure('ssr-temporal-unavailable', 'temporal', 'inspect and rebuild the temporal receipt'),\n input.reflectionFallback.projectionGeneration,\n );\n }\n if (\n input.previousGeneration !== undefined &&\n input.previousGeneration !== input.reflectionFallback.projectionGeneration\n ) {\n return blocked(\n input.identity,\n failure(\n 'ssr-receipt-stale',\n 'consumer',\n 'discard stale completion and reinspect the owners',\n {\n generation: input.reflectionFallback.projectionGeneration,\n },\n ),\n input.reflectionFallback.projectionGeneration,\n );\n }\n return Object.freeze({\n status: 'admitted',\n identity: input.identity,\n generation: input.reflectionFallback.projectionGeneration,\n work: ADMITTED_WORK,\n budget: ADMITTED_BUDGET,\n });\n}\n\n/**\n * Joins the live owner projections at the renderer boundary. The only casts\n * here add the host identity to receipts that otherwise remain canonical RHI\n * or ReflectionProbe PODs; no producer fact is copied or renamed.\n */\nexport function projectSsrDependencies(input: {\n readonly requested: boolean;\n readonly identity: SsrAdmissionIdentity | undefined;\n readonly reflectionFallback: ReflectionFallbackReceipt | undefined;\n readonly format: RhiTextureFormatCapabilityReceipt | undefined;\n readonly temporal: { readonly successfulSubmit: true; readonly generation: number } | undefined;\n readonly previousGeneration?: number;\n}): SsrDependenciesInspection {\n const identity = input.identity;\n const reflectionFallback =\n identity === undefined || input.reflectionFallback?.identity === undefined\n ? undefined\n : (input.reflectionFallback as SsrReflectionFallbackReceipt);\n const format =\n identity === undefined || input.format === undefined\n ? undefined\n : ({ ...input.format, identity } satisfies SsrFormatReceipt);\n const temporal =\n identity === undefined || input.temporal === undefined\n ? undefined\n : ({ identity, ...input.temporal } satisfies SsrTemporalReceipt);\n const admission =\n identity === undefined\n ? blocked(\n undefined,\n failure(\n input.requested ? 'ssr-receipt-identity-mismatch' : 'ssr-not-requested',\n 'consumer',\n input.requested\n ? 'bind the exact source, tree, lock, and build identity before admission'\n : 'request SSR before evaluating M0 admission',\n input.requested ? { identityField: 'sourceHead' } : {},\n ),\n )\n : admitSsrM0({\n requested: input.requested,\n identity,\n ...(reflectionFallback === undefined ? {} : { reflectionFallback }),\n ...(format === undefined ? {} : { format }),\n ...(temporal === undefined ? {} : { temporal }),\n ...(input.previousGeneration === undefined\n ? {}\n : { previousGeneration: input.previousGeneration }),\n });\n return Object.freeze({\n status: admission.status,\n identity,\n requested: input.requested,\n reflectionFallback: input.reflectionFallback,\n format,\n temporal,\n admission,\n work: admission.work,\n budget: admission.budget,\n failure: admission.failure,\n });\n}\n\nexport function zeroSsrAdmissionWork(): SsrAdmissionWork {\n return ZERO_WORK;\n}\n\n/**\n * Projects the admission decision into the existing temporal reset seam.\n * Admission never creates temporal history; only a changed committed\n * producer generation can request a reset through the coordinator.\n */\nexport function resolveSsrAdmissionGeneration(\n previousGeneration: number | undefined,\n nextGeneration: number | undefined,\n): { readonly changed: boolean; readonly generation: number | undefined } {\n return {\n changed:\n previousGeneration !== undefined &&\n nextGeneration !== undefined &&\n previousGeneration !== nextGeneration,\n generation: nextGeneration,\n };\n}\n\n/** Standard spatial lanes that may consume an SSR candidate. */\nexport type SsrSpatialLane = 'clustered' | 'deferred' | 'direct' | 'cpu-webgl2' | 'forward';\n\n/** Capability facts required by the M1 spatial path. */\nexport interface SsrSpatialCapabilities {\n readonly compute: boolean;\n readonly storageTexture: boolean;\n readonly rgba16floatRenderable: boolean;\n readonly r32floatSampledStorage: boolean;\n}\n\n/** Detached owner facts consumed by spatial admission. */\nexport interface SsrSpatialEnvironment {\n readonly lane: SsrSpatialLane;\n readonly m0: Pick<SsrAdmissionResult, 'status'>;\n readonly sceneInputs: boolean;\n /** Current-frame motion/coverage producer, not reusable previous-frame history. */\n readonly temporal: boolean;\n readonly reflectionFallback: boolean;\n readonly capabilities: SsrSpatialCapabilities;\n /** Recovery readiness is optional for callers that have no recovery fault. */\n readonly recovery?: boolean;\n}\n\n/** The only camera fields used by the spatial admission owner. */\nexport interface SsrSpatialCamera {\n readonly projection: 'perspective' | 'orthographic';\n readonly near: number;\n readonly far: number;\n readonly screenSpaceReflection?: ScreenSpaceReflectionData;\n}\n\nexport interface SsrSpatialWork {\n readonly attachmentCount: number;\n readonly passCount: number;\n readonly bindingCount: number;\n readonly resourceCount: number;\n readonly historyCount: 0;\n readonly temporalDemand: 0;\n}\n\nexport type SsrSpatialStatus =\n | 'not-requested'\n | 'requested'\n | 'admitted'\n | 'fallback-only'\n | 'structural-only';\n\nexport interface SsrSpatialAdmissionBase {\n readonly status: SsrSpatialStatus;\n readonly lane: SsrSpatialLane;\n readonly config: ScreenSpaceReflectionData | undefined;\n readonly viewRange: number;\n readonly work: SsrSpatialWork;\n}\n\nexport type SsrSpatialAdmission =\n | (SsrSpatialAdmissionBase & {\n readonly status: 'not-requested' | 'requested';\n readonly failure?: undefined;\n })\n | (SsrSpatialAdmissionBase & {\n readonly status: 'admitted';\n readonly config: ScreenSpaceReflectionData;\n readonly failure?: undefined;\n })\n | (SsrSpatialAdmissionBase & {\n readonly status: 'fallback-only' | 'structural-only';\n readonly failure: SsrConfigInvalidError | SsrUnavailableError;\n });\n\nconst ZERO_SPATIAL_WORK: SsrSpatialWork = Object.freeze({\n attachmentCount: 0,\n passCount: 0,\n bindingCount: 0,\n resourceCount: 0,\n historyCount: 0,\n temporalDemand: 0,\n});\n\nconst ADMITTED_SPATIAL_WORK: SsrSpatialWork = Object.freeze({\n attachmentCount: 3,\n passCount: 4,\n bindingCount: 4,\n resourceCount: 3,\n historyCount: 0,\n temporalDemand: 0,\n});\n\nfunction configRange(\n field: SsrConfigField,\n viewRange: number,\n maxDistance: number,\n): SsrConfigRange {\n switch (field) {\n case 'maxDistance':\n return { min: 0, minInclusive: false, max: viewRange, maxInclusive: true };\n case 'thickness':\n return { min: 0, minInclusive: false, max: maxDistance, maxInclusive: true };\n case 'maxRoughness':\n return { min: 0, minInclusive: true, max: 1, maxInclusive: true };\n }\n}\n\nfunction configError(\n field: SsrConfigField,\n value: number,\n range: SsrConfigRange,\n): SsrConfigInvalidError {\n const left = range.minInclusive ? '[' : '(';\n const right = range.maxInclusive ? ']' : ')';\n return Object.freeze({\n code: 'ssr-config-invalid',\n expected: `finite ${field} in ${left}${range.min}, ${range.max}${right}`,\n hint: `set ${field} to a finite value inside the reported range before retrying`,\n detail: Object.freeze({ field, value, range: Object.freeze(range) }),\n });\n}\n\n/** Validate one schema-derived component value against the active view. */\nexport function validateScreenSpaceReflection(\n config: ScreenSpaceReflectionData,\n input: { readonly viewRange: number },\n): Result<ScreenSpaceReflectionData, SsrConfigInvalidError> {\n const viewRange = input.viewRange;\n if (!Number.isFinite(viewRange) || viewRange <= 0) {\n return err(\n configError('maxDistance', config.maxDistance, configRange('maxDistance', viewRange, 0)),\n );\n }\n if (\n !Number.isFinite(config.maxDistance) ||\n config.maxDistance <= 0 ||\n config.maxDistance > viewRange\n ) {\n return err(\n configError(\n 'maxDistance',\n config.maxDistance,\n configRange('maxDistance', viewRange, config.maxDistance),\n ),\n );\n }\n if (\n !Number.isFinite(config.thickness) ||\n config.thickness <= 0 ||\n config.thickness > config.maxDistance\n ) {\n return err(\n configError(\n 'thickness',\n config.thickness,\n configRange('thickness', viewRange, config.maxDistance),\n ),\n );\n }\n if (!Number.isFinite(config.maxRoughness) || config.maxRoughness < 0 || config.maxRoughness > 1) {\n return err(\n configError(\n 'maxRoughness',\n config.maxRoughness,\n configRange('maxRoughness', viewRange, config.maxDistance),\n ),\n );\n }\n return ok(\n Object.freeze({\n maxDistance: config.maxDistance,\n thickness: config.thickness,\n maxRoughness: config.maxRoughness,\n }),\n );\n}\n\nfunction unavailable(\n lane: SsrSpatialLane,\n reason: SsrSpatialUnavailableReason,\n required: readonly string[],\n actual: Readonly<Record<string, boolean | number | string>>,\n): SsrUnavailableError {\n const recovery =\n reason === 'lane-unsupported' || reason === 'projection-unsupported'\n ? 'select a perspective clustered or deferred Standard lane'\n : reason === 'reflection-fallback-unavailable'\n ? 'repair the submitted reflection fallback owner receipt'\n : reason === 'temporal-unavailable'\n ? 'submit the matching temporal-v1 producer receipt'\n : reason === 'recovery-unavailable'\n ? 'complete device and producer recovery before retrying'\n : 'restore the required scene, capability, or format input before retrying';\n return Object.freeze({\n code: 'ssr-unavailable',\n expected: 'SSR spatial admission has a complete Standard input and capability set',\n hint: recovery,\n detail: Object.freeze({\n lane,\n reason,\n required: Object.freeze([...required]),\n actual: Object.freeze({ ...actual }),\n recovery,\n }),\n });\n}\n\nfunction unavailableResult(\n lane: SsrSpatialLane,\n viewRange: number,\n failure: SsrUnavailableError,\n): SsrSpatialAdmission {\n return Object.freeze({\n status: 'fallback-only',\n lane,\n config: undefined,\n viewRange,\n work: ZERO_SPATIAL_WORK,\n failure,\n });\n}\n\n/**\n * Admit the active camera's schema-derived component into the M1 spatial\n * path. No graph/resource handle crosses this boundary.\n */\nexport function admitSsrSpatial(input: {\n readonly camera: SsrSpatialCamera;\n readonly environment: SsrSpatialEnvironment;\n}): SsrSpatialAdmission {\n const camera = input.camera;\n const environment = input.environment;\n const viewRange = camera.far - camera.near;\n const config = camera.screenSpaceReflection;\n if (config === undefined) {\n return Object.freeze({\n status: 'not-requested',\n lane: environment.lane,\n config: undefined,\n viewRange,\n work: ZERO_SPATIAL_WORK,\n });\n }\n\n const valid = validateScreenSpaceReflection(config, { viewRange });\n if (!valid.ok) {\n return Object.freeze({\n status: 'fallback-only',\n lane: environment.lane,\n config,\n viewRange,\n work: ZERO_SPATIAL_WORK,\n failure: valid.error,\n });\n }\n\n if (environment.m0.status !== 'admitted') {\n return unavailableResult(\n environment.lane,\n viewRange,\n unavailable(\n environment.lane,\n 'reflection-fallback-unavailable',\n ['admitted M0 dependency receipt'],\n { m0: false },\n ),\n );\n }\n if (environment.lane !== 'clustered' && environment.lane !== 'deferred') {\n return unavailableResult(\n environment.lane,\n viewRange,\n unavailable(environment.lane, 'lane-unsupported', ['clustered or deferred Standard lane'], {\n lane: environment.lane,\n }),\n );\n }\n if (camera.projection !== 'perspective') {\n return unavailableResult(\n environment.lane,\n viewRange,\n unavailable(environment.lane, 'projection-unsupported', ['perspective camera'], {\n projection: camera.projection,\n }),\n );\n }\n if (!environment.sceneInputs) {\n return unavailableResult(\n environment.lane,\n viewRange,\n unavailable(\n environment.lane,\n 'scene-input-unavailable',\n ['deferred Standard scene/material/fallback inputs'],\n { sceneInputs: false },\n ),\n );\n }\n if (!environment.temporal) {\n return unavailableResult(\n environment.lane,\n viewRange,\n unavailable(environment.lane, 'temporal-unavailable', ['temporal-v1'], { temporal: false }),\n );\n }\n if (!environment.reflectionFallback) {\n return unavailableResult(\n environment.lane,\n viewRange,\n unavailable(\n environment.lane,\n 'reflection-fallback-unavailable',\n ['submitted BRDF-projected fallback'],\n { reflectionFallback: false },\n ),\n );\n }\n if (environment.recovery === false) {\n return unavailableResult(\n environment.lane,\n viewRange,\n unavailable(environment.lane, 'recovery-unavailable', ['ready device and owners'], {\n recovery: false,\n }),\n );\n }\n const capabilities = environment.capabilities;\n if (\n !capabilities.compute ||\n !capabilities.storageTexture ||\n !capabilities.rgba16floatRenderable\n ) {\n return unavailableResult(\n environment.lane,\n viewRange,\n unavailable(\n environment.lane,\n 'capability-unavailable',\n ['compute', 'storageTexture', 'rgba16floatRenderable'],\n {\n compute: capabilities.compute,\n storageTexture: capabilities.storageTexture,\n rgba16floatRenderable: capabilities.rgba16floatRenderable,\n },\n ),\n );\n }\n if (!capabilities.r32floatSampledStorage) {\n return unavailableResult(\n environment.lane,\n viewRange,\n unavailable(\n environment.lane,\n 'format-unavailable',\n ['r32float sampled and storage mip chain'],\n { r32floatSampledStorage: false },\n ),\n );\n }\n return Object.freeze({\n status: 'admitted',\n lane: environment.lane,\n config: valid.value,\n viewRange,\n work: ADMITTED_SPATIAL_WORK,\n });\n}\n","import type { TextureFormat } from '@forgeax/engine-rhi';\nimport type { VolumeRecoveryState, VolumeSelectedLightFacts } from './recovery';\nimport type { VolumetricFogResourceFacts } from './resources';\n\nexport type VolumetricFogInspectionStatus = 'off' | 'available' | 'unavailable' | 'degraded';\n\nexport type VolumetricFogResourceStage = 'none' | 'candidate' | 'accepted' | 'lkg' | 'recovering';\n\nexport interface VolumetricFogInspection {\n /** Owners in the last successfully submitted volume collection. */\n readonly ownerCount: number;\n readonly status: VolumetricFogInspectionStatus;\n readonly resourceStage: VolumetricFogResourceStage;\n readonly guid: string | undefined;\n readonly generation: number | undefined;\n readonly digest: string | undefined;\n readonly candidateGeneration: number | undefined;\n readonly candidateDigest: string | undefined;\n readonly lkgGeneration: number | undefined;\n readonly candidateFailure: VolumeRecoveryState['candidateFailure'];\n readonly deviceEpoch: number;\n readonly format: TextureFormat | undefined;\n readonly passCount: number;\n readonly sampleCount: number;\n readonly memoryBytes: number;\n readonly resourceFacts: VolumetricFogResourceFacts | undefined;\n readonly selectedLight: VolumeSelectedLightFacts | undefined;\n readonly candidateSelectedLight: VolumeSelectedLightFacts | undefined;\n}\n\nexport interface VolumetricFogInspectionInput {\n readonly authored: boolean;\n readonly capability: 'available' | 'unavailable';\n readonly degraded?: boolean;\n readonly recovery?: VolumeRecoveryState;\n readonly acceptedDigest?: string;\n readonly format?: TextureFormat;\n readonly passCount?: number;\n readonly sampleCount?: number;\n readonly memoryBytes?: number;\n readonly resourceFacts?: VolumetricFogResourceFacts;\n}\n\nfunction resourceStage(input: VolumetricFogInspectionInput): VolumetricFogResourceStage {\n if (!input.authored || input.recovery === undefined) return 'none';\n if (input.recovery.status === 'candidate') return 'candidate';\n if (input.recovery.status === 'recovering') return 'recovering';\n if (input.recovery.status === 'degraded') return 'lkg';\n return 'accepted';\n}\n\nexport function inspectVolumetricFog(input: VolumetricFogInspectionInput): VolumetricFogInspection {\n const recovery = input.recovery;\n const status: VolumetricFogInspectionStatus = !input.authored\n ? 'off'\n : input.capability === 'unavailable'\n ? 'unavailable'\n : input.degraded === true || recovery?.status === 'degraded'\n ? 'degraded'\n : 'available';\n return Object.freeze({\n ownerCount: 0,\n status,\n resourceStage: resourceStage(input),\n guid: recovery?.guid,\n generation: recovery?.generation,\n digest: input.acceptedDigest,\n candidateGeneration: recovery?.candidateGeneration,\n candidateDigest: recovery?.candidateDigest,\n lkgGeneration: recovery?.lkgGeneration,\n candidateFailure: recovery?.candidateFailure,\n deviceEpoch: recovery?.deviceEpoch ?? 0,\n format: input.format,\n passCount: input.passCount ?? 0,\n sampleCount: input.sampleCount ?? 0,\n memoryBytes: input.memoryBytes ?? 0,\n resourceFacts: input.resourceFacts,\n selectedLight: recovery?.selectedLight,\n candidateSelectedLight: recovery?.candidateSelectedLight,\n });\n}\n","import type {\n MaterialDynamicFieldType,\n MaterialDynamicInputLayout,\n MaterialDynamicInputSchema,\n} from '@forgeax/engine-types';\nimport { deriveMaterialDynamicInputLayout, err, ok, type Result } from '@forgeax/engine-types';\n\nexport type DynamicInputValue = number | readonly number[];\n\n/** Stable public address of one admitted Surface draw member. */\nexport interface SurfaceDynamicInputMemberIdentity {\n /** `World.identity`; stable across renderer-local World reordering. */\n readonly worldIdentity: string;\n readonly entityKey: number;\n readonly drawItemIndex: number;\n readonly instanceOrdinal: number;\n}\n\nexport interface DynamicInputRange {\n readonly pageId: number;\n readonly sourceId: string;\n /** Producer-owned domain identity retained across device regeneration. */\n readonly domain: string;\n readonly byteOffset: number;\n readonly recordStart: number;\n readonly recordCount: number;\n readonly instanceIndex: number;\n readonly member: SurfaceDynamicInputMemberIdentity;\n readonly contentRevision: number;\n readonly bufferGeneration: number;\n readonly deviceGeneration: number;\n}\n\nexport interface DynamicInputDirtyRange {\n readonly byteStart: number;\n readonly byteEnd: number;\n}\n\nexport interface DynamicInputUploadReceipt {\n readonly sourceId: string;\n readonly pageId: number;\n readonly contentRevision: number;\n readonly bufferGeneration: number;\n readonly deviceGeneration: number;\n readonly ranges: readonly DynamicInputDirtyRange[];\n readonly bytes: number;\n}\n\nexport interface DynamicInputConsumptionReceipt extends DynamicInputRange {\n readonly frameNumber: number;\n readonly uploadedRevision: number;\n}\n\n/**\n * Renderer input for one frame of a published Surface dynamic page.\n *\n * `ranges` join by their stable World/entity/draw/instance member identity.\n * Producer order is irrelevant and cannot redirect one member's dynamic\n * records to another member after culling or World reordering.\n */\nexport interface SurfaceDynamicInputFrame {\n readonly page: ReadonlyDynamicInputPage;\n readonly ranges?: readonly DynamicInputRange[];\n /** Producer-owned membership/address revision; time and record values do not advance it. */\n readonly projectionRevision: number;\n readonly frameTime: number;\n}\n\nexport type DynamicInputErrorCode =\n | 'invalid-schema'\n | 'invalid-record'\n | 'range-overflow'\n | 'domain-overflow'\n | 'not-uploaded'\n | 'stale-generation'\n | 'released';\n\nexport interface DynamicInputErrorDetail {\n readonly operation:\n | 'create'\n | 'write'\n | 'reserve'\n | 'upload'\n | 'consume'\n | 'reconfigure'\n | 'release';\n readonly field?: string;\n readonly expected: string;\n readonly actual?: unknown;\n readonly sourceId?: string;\n readonly pageId?: number;\n}\n\nconst ERROR_POLICY: Readonly<\n Record<DynamicInputErrorCode, { readonly expected: string; readonly hint: string }>\n> = {\n 'invalid-schema': {\n expected: 'the dynamic input schema has one derived bounded record layout',\n hint: 'repair the root MaterialSurface dynamicInput declaration and recook it',\n },\n 'invalid-record': {\n expected: 'each dynamic record matches the derived scalar/vector fields',\n hint: 'write finite values using the field names and types declared by the material',\n },\n 'range-overflow': {\n expected: 'the instance range stays within the declared read-only page',\n hint: 'reduce the range or increase the producer page budget before publication',\n },\n 'domain-overflow': {\n expected: 'the page stays within its declared number of producer domains',\n hint: 'reuse an existing domain or publish a larger bounded declaration',\n },\n 'not-uploaded': {\n expected: 'the current page revision was uploaded before frame consumption',\n hint: 'submit the page upload receipt and retry the same frame',\n },\n 'stale-generation': {\n expected: 'the range, upload, and device use one current page generation',\n hint: 'discard stale addresses and rebuild the producer projection for the current device',\n },\n released: {\n expected: 'the read-only page is still attached to its owning Render lifecycle',\n hint: 'create a new page after releasing the old owner',\n },\n};\n\nexport class DynamicInputError extends Error {\n readonly code: DynamicInputErrorCode;\n readonly expected: string;\n readonly hint: string;\n readonly detail: DynamicInputErrorDetail;\n\n constructor(code: DynamicInputErrorCode, detail: DynamicInputErrorDetail) {\n super(`${code}: ${ERROR_POLICY[code].expected}`);\n this.name = 'DynamicInputError';\n this.code = code;\n this.expected = ERROR_POLICY[code].expected;\n this.hint = ERROR_POLICY[code].hint;\n this.detail = Object.freeze({ ...detail });\n }\n}\n\nexport type DynamicInputResult<T> = Result<T, DynamicInputError>;\n\ninterface DomainRecord {\n readonly name: string;\n readonly start: number;\n readonly end: number;\n}\n\nfunction alignRange(ranges: DynamicInputDirtyRange[], start: number, end: number): void {\n if (start >= end) return;\n let index = 0;\n while (index < ranges.length && (ranges[index]?.byteEnd ?? 0) < start) index += 1;\n while (index < ranges.length) {\n const existing = ranges[index];\n if (existing === undefined || existing.byteStart > end) break;\n start = Math.min(start, existing.byteStart);\n end = Math.max(end, existing.byteEnd);\n ranges.splice(index, 1);\n }\n ranges.splice(index, 0, { byteStart: start, byteEnd: end });\n}\n\nfunction fieldWidth(type: MaterialDynamicFieldType): number {\n switch (type) {\n case 'f32':\n case 'u32':\n return 1;\n case 'vec2<f32>':\n return 2;\n case 'vec3<f32>':\n return 3;\n case 'vec4<f32>':\n return 4;\n }\n}\n\nfunction finiteNumber(value: unknown): value is number {\n return typeof value === 'number' && Number.isFinite(value);\n}\n\nfunction invalid(\n code: DynamicInputErrorCode,\n operation: DynamicInputErrorDetail['operation'],\n expected: string,\n actual?: unknown,\n field?: string,\n page?: Readonly<{ sourceId: string; pageId: number }>,\n): DynamicInputError {\n return new DynamicInputError(code, {\n operation,\n expected,\n ...(actual === undefined ? {} : { actual }),\n ...(field === undefined ? {} : { field }),\n ...(page === undefined ? {} : page),\n });\n}\n\n/**\n * Generic Render-owned CPU side of a read-only dynamic input page. The page\n * has no GPU handle: the renderer's existing resource owner can upload the\n * detached bytes and attach the receipt to a prepared pass.\n */\nexport class ReadonlyDynamicInputPage {\n readonly sourceId: string;\n readonly pageId: number;\n readonly schema: MaterialDynamicInputSchema;\n readonly layout: MaterialDynamicInputLayout;\n readonly bytes: Uint8Array;\n private contentRevisionValue = 1;\n private bufferGenerationValue = 1;\n private deviceGenerationValue = 1;\n private uploadedRevisionValue = 0;\n private lastUploadedBytesValue = 0;\n private released = false;\n private readonly ownedRanges = new WeakSet<object>();\n private readonly ownedUploads = new WeakSet<object>();\n private readonly dirty = [\n {\n byteStart: 0,\n byteEnd: 0,\n } as DynamicInputDirtyRange,\n ];\n private readonly domains = new Map<string, DomainRecord>();\n\n private constructor(\n sourceId: string,\n pageId: number,\n schema: MaterialDynamicInputSchema,\n layout: MaterialDynamicInputLayout,\n ) {\n this.sourceId = sourceId;\n this.pageId = pageId;\n this.schema = schema;\n this.layout = layout;\n this.bytes = new Uint8Array(schema.maxPageBytes);\n this.dirty.length = 0;\n }\n\n static create(input: {\n readonly sourceId: string;\n readonly pageId: number;\n readonly schema: MaterialDynamicInputSchema;\n }): DynamicInputResult<ReadonlyDynamicInputPage> {\n if (input.sourceId.length === 0 || !Number.isSafeInteger(input.pageId) || input.pageId < 0) {\n return err(\n invalid(\n 'invalid-schema',\n 'create',\n 'sourceId is non-empty and pageId is non-negative',\n input.pageId,\n ),\n );\n }\n const layout = deriveMaterialDynamicInputLayout(input.schema);\n if (!layout.ok) {\n return err(\n invalid(\n 'invalid-schema',\n 'create',\n layout.error.expected,\n layout.error.actual,\n layout.error.field,\n ),\n );\n }\n return ok(\n new ReadonlyDynamicInputPage(input.sourceId, input.pageId, input.schema, layout.value),\n );\n }\n\n get contentRevision(): number {\n return this.contentRevisionValue;\n }\n\n get bufferGeneration(): number {\n return this.bufferGenerationValue;\n }\n\n get deviceGeneration(): number {\n return this.deviceGenerationValue;\n }\n\n get uploadedRevision(): number {\n return this.uploadedRevisionValue;\n }\n\n get lastUploadedBytes(): number {\n return this.lastUploadedBytesValue;\n }\n\n /** Write one complete record and mark only its byte interval dirty. */\n writeRecord(\n index: number,\n values: Readonly<Record<string, DynamicInputValue>>,\n ): DynamicInputResult<number> {\n const live = this.assertLive('write');\n if (!live.ok) return live;\n if (!Number.isSafeInteger(index) || index < 0 || index >= this.schema.maxRecords) {\n return err(\n invalid(\n 'range-overflow',\n 'write',\n `record index is within [0, ${this.schema.maxRecords})`,\n index,\n 'index',\n this,\n ),\n );\n }\n const recordOffset = index * this.layout.stride;\n // Encode into detached bytes first. A malformed later field must leave the\n // previously published record and its dirty/revision state untouched.\n const encoded = new Uint8Array(this.layout.stride);\n const view = new DataView(encoded.buffer, encoded.byteOffset, encoded.byteLength);\n for (const field of this.layout.fields) {\n const value = values[field.name];\n if (value === undefined) {\n return err(\n invalid(\n 'invalid-record',\n 'write',\n `record contains field ${field.name}`,\n value,\n field.name,\n this,\n ),\n );\n }\n const width = fieldWidth(field.type);\n const numbers = typeof value === 'number' ? [value] : value;\n if (numbers.length !== width || numbers.some((candidate) => !finiteNumber(candidate))) {\n return err(\n invalid(\n 'invalid-record',\n 'write',\n `${field.name} is a finite ${field.type}`,\n value,\n field.name,\n this,\n ),\n );\n }\n if (\n field.type === 'u32' &&\n (!Number.isInteger(numbers[0]) ||\n (numbers[0] as number) < 0 ||\n (numbers[0] as number) > 0xffffffff)\n ) {\n return err(\n invalid(\n 'invalid-record',\n 'write',\n `${field.name} is an unsigned 32-bit integer`,\n value,\n field.name,\n this,\n ),\n );\n }\n for (const [component, number] of numbers.entries()) {\n const offset = field.offset + component * 4;\n if (field.type === 'u32') view.setUint32(offset, number as number, true);\n else view.setFloat32(offset, number as number, true);\n }\n }\n this.bytes.set(encoded, recordOffset);\n this.contentRevisionValue += 1;\n alignRange(this.dirty, recordOffset, recordOffset + this.layout.stride);\n return ok(this.contentRevisionValue);\n }\n\n /** Reserve one explicit instance range; no skin address field is involved. */\n reserveRange(input: {\n readonly domain: string;\n readonly recordStart: number;\n readonly recordCount: number;\n readonly instanceIndex: number;\n readonly member: SurfaceDynamicInputMemberIdentity;\n }): DynamicInputResult<DynamicInputRange> {\n const live = this.assertLive('reserve');\n if (!live.ok) return live;\n if (input.domain.length === 0) {\n return err(\n invalid(\n 'domain-overflow',\n 'reserve',\n 'domain is a non-empty identity',\n input.domain,\n 'domain',\n this,\n ),\n );\n }\n if (!this.domains.has(input.domain) && this.domains.size >= this.schema.maxDomains) {\n return err(\n invalid(\n 'domain-overflow',\n 'reserve',\n `at most ${this.schema.maxDomains} domains are active`,\n this.domains.size + 1,\n 'domain',\n this,\n ),\n );\n }\n if (\n !Number.isSafeInteger(input.instanceIndex) ||\n input.instanceIndex < 0 ||\n input.instanceIndex > 0xffffffff\n ) {\n return err(\n invalid(\n 'range-overflow',\n 'reserve',\n 'instance index is an exact unsigned 32-bit integer',\n input.instanceIndex,\n 'instanceIndex',\n this,\n ),\n );\n }\n if (\n input.member.worldIdentity.length === 0 ||\n !Number.isSafeInteger(input.member.entityKey) ||\n input.member.entityKey < 0 ||\n input.member.entityKey > 0xffffffff ||\n !Number.isSafeInteger(input.member.drawItemIndex) ||\n input.member.drawItemIndex < 0 ||\n input.member.drawItemIndex > 0xffffffff ||\n !Number.isSafeInteger(input.member.instanceOrdinal) ||\n input.member.instanceOrdinal < 0 ||\n input.member.instanceOrdinal > 0xffffffff\n ) {\n return err(\n invalid(\n 'range-overflow',\n 'reserve',\n 'member is a stable World identity plus exact unsigned 32-bit entity, draw-item, and instance identities',\n input.member,\n 'member',\n this,\n ),\n );\n }\n if (\n !Number.isSafeInteger(input.recordStart) ||\n !Number.isSafeInteger(input.recordCount) ||\n input.recordStart < 0 ||\n input.recordCount <= 0 ||\n input.recordStart + input.recordCount > this.schema.maxRecords\n ) {\n return err(\n invalid(\n 'range-overflow',\n 'reserve',\n 'record range and instance index fit the declared page',\n input,\n 'recordStart',\n this,\n ),\n );\n }\n const range: DynamicInputRange = {\n pageId: this.pageId,\n sourceId: this.sourceId,\n domain: input.domain,\n byteOffset: input.recordStart * this.layout.stride,\n recordStart: input.recordStart,\n recordCount: input.recordCount,\n instanceIndex: input.instanceIndex,\n member: Object.freeze({ ...input.member }),\n contentRevision: this.contentRevisionValue,\n bufferGeneration: this.bufferGenerationValue,\n deviceGeneration: this.deviceGenerationValue,\n };\n this.ownedRanges.add(range);\n this.domains.set(input.domain, {\n name: input.domain,\n start: input.recordStart,\n end: input.recordStart + input.recordCount,\n });\n return ok(range);\n }\n\n /** Return detached dirty bytes for the existing resource owner to upload. */\n beginUpload(): DynamicInputResult<DynamicInputUploadReceipt> {\n const live = this.assertLive('upload');\n if (!live.ok) return live;\n const ranges = this.dirty.map((range) => ({ ...range }));\n const bytes = ranges.reduce((sum, range) => sum + range.byteEnd - range.byteStart, 0);\n const receipt: DynamicInputUploadReceipt = {\n sourceId: this.sourceId,\n pageId: this.pageId,\n contentRevision: this.contentRevisionValue,\n bufferGeneration: this.bufferGenerationValue,\n deviceGeneration: this.deviceGenerationValue,\n ranges,\n bytes,\n };\n this.ownedUploads.add(receipt);\n return ok(receipt);\n }\n\n /**\n * Commit an upload only after the owning queue write has succeeded. A\n * producer that changed the page while a write was in flight leaves the\n * dirty bytes pending and must retry the new revision.\n */\n commitUpload(receipt: DynamicInputUploadReceipt): DynamicInputResult<true> {\n const live = this.assertLive('upload');\n if (!live.ok) return live;\n if (\n !this.ownedUploads.has(receipt) ||\n receipt.sourceId !== this.sourceId ||\n receipt.pageId !== this.pageId ||\n receipt.bufferGeneration !== this.bufferGenerationValue ||\n receipt.deviceGeneration !== this.deviceGenerationValue ||\n receipt.contentRevision !== this.contentRevisionValue\n ) {\n return err(\n invalid(\n 'stale-generation',\n 'upload',\n 'the upload receipt still describes the current page revision and generation',\n receipt,\n 'receipt',\n this,\n ),\n );\n }\n this.uploadedRevisionValue = receipt.contentRevision;\n this.lastUploadedBytesValue = receipt.bytes;\n for (const range of receipt.ranges) {\n const index = this.dirty.findIndex(\n (candidate) =>\n candidate.byteStart === range.byteStart && candidate.byteEnd === range.byteEnd,\n );\n if (index >= 0) this.dirty.splice(index, 1);\n }\n return ok(true);\n }\n\n /** CPU-only convenience: begin and commit are still explicit in production. */\n upload(): DynamicInputResult<DynamicInputUploadReceipt> {\n const receipt = this.beginUpload();\n if (!receipt.ok) return receipt;\n const committed = this.commitUpload(receipt.value);\n if (!committed.ok) return committed;\n return receipt;\n }\n\n /** Consume an uploaded range after graph submission has completed. */\n consume(\n range: DynamicInputRange,\n frameNumber: number,\n ): DynamicInputResult<DynamicInputConsumptionReceipt> {\n const live = this.assertLive('consume');\n if (!live.ok) return live;\n if (\n !this.ownedRanges.has(range) ||\n range.sourceId !== this.sourceId ||\n range.pageId !== this.pageId ||\n range.bufferGeneration !== this.bufferGenerationValue ||\n range.deviceGeneration !== this.deviceGenerationValue ||\n range.recordStart < 0 ||\n range.recordCount <= 0 ||\n range.recordStart + range.recordCount > this.schema.maxRecords\n ) {\n return err(\n invalid(\n 'stale-generation',\n 'consume',\n 'range belongs to this current page generation',\n range,\n 'generation',\n this,\n ),\n );\n }\n if (this.uploadedRevisionValue < range.contentRevision) {\n return err(\n invalid(\n 'not-uploaded',\n 'consume',\n 'range content revision was uploaded before consumption',\n this.uploadedRevisionValue,\n 'contentRevision',\n this,\n ),\n );\n }\n return ok({ ...range, frameNumber, uploadedRevision: this.uploadedRevisionValue });\n }\n\n /** Device loss/rebuild changes physical generations while source identity stays stable. */\n reconfigureDevice(deviceGeneration: number): DynamicInputResult<number> {\n const live = this.assertLive('reconfigure');\n if (!live.ok) return live;\n if (!Number.isSafeInteger(deviceGeneration) || deviceGeneration < 0) {\n return err(\n invalid(\n 'stale-generation',\n 'reconfigure',\n 'deviceGeneration is a non-negative safe integer',\n deviceGeneration,\n 'deviceGeneration',\n this,\n ),\n );\n }\n const rendererInitialGeneration =\n this.bufferGenerationValue === 1 &&\n this.deviceGenerationValue === 1 &&\n deviceGeneration === 0;\n if (deviceGeneration < this.deviceGenerationValue && !rendererInitialGeneration) {\n return err(\n invalid(\n 'stale-generation',\n 'reconfigure',\n 'deviceGeneration does not precede the current device generation',\n deviceGeneration,\n 'deviceGeneration',\n this,\n ),\n );\n }\n this.deviceGenerationValue = deviceGeneration;\n this.bufferGenerationValue += 1;\n this.uploadedRevisionValue = 0;\n alignRange(this.dirty, 0, this.schema.maxRecords * this.layout.stride);\n return ok(this.bufferGenerationValue);\n }\n\n release(): DynamicInputResult<true> {\n if (this.released) return ok(true);\n this.released = true;\n this.domains.clear();\n this.dirty.length = 0;\n return ok(true);\n }\n\n private assertLive(operation: DynamicInputErrorDetail['operation']): DynamicInputResult<true> {\n return this.released\n ? err(\n invalid(\n 'released',\n operation,\n ERROR_POLICY.released.expected,\n undefined,\n undefined,\n this,\n ),\n )\n : ok(true);\n }\n}\n","export interface ProbeFilterState {\n readonly probeIndex: number;\n readonly faceCount: number;\n readonly mipCount: number;\n readonly cursor: number;\n readonly activeGeneration: number;\n}\n\nexport function createProbeFilterState(input: {\n readonly probeIndex: number;\n readonly faceCount?: number;\n readonly mipCount: number;\n readonly activeGeneration?: number;\n}): ProbeFilterState {\n return {\n probeIndex: input.probeIndex,\n faceCount: input.faceCount ?? 6,\n mipCount: input.mipCount,\n cursor: 0,\n activeGeneration: input.activeGeneration ?? 0,\n };\n}\n\nexport function advanceProbeFilter(\n state: ProbeFilterState,\n):\n | { readonly probeIndex: number; readonly faceIndex: number; readonly mipLevel: number }\n | undefined {\n const total = state.faceCount * state.mipCount;\n if (state.cursor >= total) return undefined;\n return {\n probeIndex: state.probeIndex,\n faceIndex: state.cursor % state.faceCount,\n mipLevel: Math.floor(state.cursor / state.faceCount),\n };\n}\n\nexport function commitProbeFilterStep(state: ProbeFilterState, success: boolean): ProbeFilterState {\n if (!success) return state;\n const nextCursor = state.cursor + 1;\n const complete = nextCursor >= state.faceCount * state.mipCount;\n return {\n ...state,\n cursor: nextCursor,\n activeGeneration: complete ? state.activeGeneration + 1 : state.activeGeneration,\n };\n}\n\nexport function probeFilterIsSteady(state: ProbeFilterState): boolean {\n return state.cursor >= state.faceCount * state.mipCount;\n}\n\nfunction normalize(vector: readonly [number, number, number]): [number, number, number] {\n const length = Math.hypot(vector[0], vector[1], vector[2]);\n if (length === 0) return [0, 0, 1];\n return [vector[0] / length, vector[1] / length, vector[2] / length];\n}\n\nexport function boxProjectReflectionDirection(\n direction: readonly [number, number, number],\n boxCenter: readonly [number, number, number],\n halfExtents: readonly [number, number, number],\n point: readonly [number, number, number],\n): [number, number, number] {\n const ray = normalize(direction);\n for (const axis of [0, 1, 2] as const) {\n if (Math.abs(point[axis] - boxCenter[axis]) >= halfExtents[axis]) return ray;\n }\n let distance = Number.POSITIVE_INFINITY;\n for (let axis = 0; axis < 3; axis += 1) {\n const component = ray[axis] ?? 0;\n if (component === 0) continue;\n const extent = halfExtents[axis] ?? 0;\n const edge = component > 0 ? (boxCenter[axis] ?? 0) + extent : (boxCenter[axis] ?? 0) - extent;\n const candidate = (edge - (point[axis] ?? 0)) / component;\n if (candidate > 0) distance = Math.min(distance, candidate);\n }\n if (!Number.isFinite(distance)) return ray;\n return normalize([\n (point[0] ?? 0) + ray[0] * distance - (boxCenter[0] ?? 0),\n (point[1] ?? 0) + ray[1] * distance - (boxCenter[1] ?? 0),\n (point[2] ?? 0) + ray[2] * distance - (boxCenter[2] ?? 0),\n ]);\n}\n","import type { Buffer, Sampler, TextureView } from '@forgeax/engine-rhi';\n\nexport interface ReflectionProbeTableRow {\n readonly primitiveKey?: string;\n readonly index: number;\n readonly worldId: number;\n readonly entityKey: number;\n readonly center: readonly [number, number, number];\n readonly halfExtents: readonly [number, number, number];\n readonly intensity: number;\n readonly generation: number;\n /** Renderer-owned filtered cube used by the Standard material lane. */\n readonly filteredView?: TextureView;\n /** Renderer-owned sampler paired with filteredView. */\n readonly sampler?: Sampler;\n /** Per-probe uniform payload; keeps MaterialAsset ABI unchanged. */\n readonly uniformBuffer?: Buffer;\n}\n\nexport interface ReflectionProbeTable {\n readonly rows: readonly ReflectionProbeTableRow[];\n readonly cpuIndexByPrimitive: (primitiveKey: string) => number | undefined;\n readonly gpuIndexByPrimitive: (primitiveKey: string) => number | undefined;\n}\n\nexport function buildReflectionProbeTable(\n rows: readonly ReflectionProbeTableRow[],\n): ReflectionProbeTable {\n const ordered = rows.slice().sort((a, b) => a.index - b.index);\n const indices = new Map<string, number>();\n for (const row of ordered) {\n if (row.primitiveKey !== undefined) indices.set(row.primitiveKey, row.index);\n }\n const indexFor = (primitiveKey: string): number | undefined => indices.get(primitiveKey);\n return {\n rows: Object.freeze(ordered),\n cpuIndexByPrimitive: indexFor,\n gpuIndexByPrimitive: indexFor,\n };\n}\n\nexport function reflectionProbeTableBytes(table: ReflectionProbeTable): number {\n return table.rows.length * 48;\n}\n","import type {\n ReflectionFallbackFailureStage,\n ReflectionFallbackInspection,\n ReflectionFallbackReceipt,\n ReflectionFallbackRecoveryAction,\n} from '../inspection-types';\n\nexport interface ReflectionFallbackFailureInput {\n readonly stage: ReflectionFallbackFailureStage;\n readonly code: string;\n readonly expected: string;\n readonly detail?: Readonly<Record<string, unknown>>;\n}\n\nfunction recoveryFor(\n receipt: ReflectionFallbackReceipt,\n failure?: ReflectionFallbackFailureInput,\n): ReflectionFallbackRecoveryAction {\n if (failure !== undefined) {\n const code = failure.code.toLowerCase();\n if (code.includes('device') || code.includes('format') || code.includes('capability')) {\n return 'rebuild';\n }\n if (failure.stage === 'prepare' || failure.stage === 'filter') return 'recapture';\n if (failure.stage === 'build' || failure.stage === 'encode') return 'rebuild';\n if (failure.stage === 'finish' || failure.stage === 'submit') return 'retry';\n // Completion failures may still retain a source-identical committed row;\n // use it as LKG, otherwise retry the producer completion.\n if (failure.stage === 'completion') {\n if (receipt.source === 'probe' && (receipt.state === 'active' || receipt.state === 'lkg')) {\n return 'use-LKG';\n }\n if (\n receipt.source === 'skylight' &&\n (receipt.state === 'active' || receipt.state === 'lkg')\n ) {\n return 'use-Skylight';\n }\n if (receipt.source === 'neutral' && receipt.state === 'neutral') return 'use-neutral';\n return 'retry';\n }\n }\n if (receipt.source === 'probe' && (receipt.state === 'active' || receipt.state === 'lkg')) {\n return 'use-LKG';\n }\n if (receipt.source === 'skylight' || receipt.state === 'lkg') return 'use-Skylight';\n return 'use-neutral';\n}\n\n/** Projects producer state and the latest closed failure into detached facts. */\nexport function inspectReflectionFallback(\n receipt: ReflectionFallbackReceipt,\n failure?: ReflectionFallbackFailureInput,\n): ReflectionFallbackInspection {\n return {\n receipt,\n recoveryAction: recoveryFor(receipt, failure),\n ...(failure === undefined\n ? {}\n : {\n failureStage: failure.stage,\n failureCode: failure.code,\n expected: failure.expected,\n ...(failure.detail === undefined ? {} : { detail: failure.detail }),\n }),\n };\n}\n","import type { ReflectionProbeUpdateIntent } from '../components/reflection-probe';\n\nexport const REFLECTION_PROBE_BYTES_PER_TEXEL = 8;\nexport const DEFAULT_REFLECTION_PROBE_LIMITS = Object.freeze({\n maxProbes: 16,\n maxResolution: 256,\n maxBytes: 64 * 1024 * 1024,\n});\n\nexport interface ReflectionProbeInput {\n readonly halfExtents: readonly [number, number, number];\n readonly priority: number;\n readonly intensity: number;\n readonly resolution: number;\n readonly boxProjection?: boolean;\n}\n\nexport interface ReflectionProbeFact extends ReflectionProbeInput {\n readonly worldId: number;\n readonly entityKey: number;\n readonly center: readonly [number, number, number];\n readonly revision: number;\n readonly updateIntent?: ReflectionProbeUpdateIntent;\n readonly invalidationVersion?: number;\n}\n\nexport interface ReflectionProbeAdmissionLimits {\n readonly maxProbes?: number;\n readonly maxResolution?: number;\n readonly maxBytes?: number;\n}\n\nexport interface ReflectionProbeInvalidInput {\n readonly code: 'reflection-probe-input-invalid';\n readonly field: string;\n readonly value: unknown;\n readonly expected: string;\n}\n\nexport interface ReflectionProbeBudgetFailure {\n readonly code: 'reflection-probe-budget-exceeded';\n readonly requested: number;\n readonly activeCount: number;\n readonly activeBytes: number;\n readonly maxProbes: number;\n readonly maxBytes: number;\n}\n\nexport type ReflectionProbeAdmission =\n | { readonly ok: true; readonly acceptedBytes: number }\n | { readonly ok: false; readonly error: ReflectionProbeBudgetFailure };\n\nexport function validateReflectionProbeInput(\n input: ReflectionProbeInput,\n): { readonly ok: true } | { readonly ok: false; readonly error: ReflectionProbeInvalidInput } {\n for (let index = 0; index < input.halfExtents.length; index += 1) {\n const value = input.halfExtents[index];\n if (value === undefined || !Number.isFinite(value) || value <= 0) {\n return {\n ok: false,\n error: {\n code: 'reflection-probe-input-invalid',\n field: `halfExtents[${index}]`,\n value,\n expected: 'a finite number greater than zero',\n },\n };\n }\n }\n if (!Number.isFinite(input.priority)) {\n return {\n ok: false,\n error: {\n code: 'reflection-probe-input-invalid',\n field: 'priority',\n value: input.priority,\n expected: 'a finite number',\n },\n };\n }\n if (!Number.isFinite(input.intensity) || input.intensity < 0) {\n return {\n ok: false,\n error: {\n code: 'reflection-probe-input-invalid',\n field: 'intensity',\n value: input.intensity,\n expected: 'a finite number greater than or equal to zero',\n },\n };\n }\n if (\n !Number.isInteger(input.resolution) ||\n input.resolution < 16 ||\n (input.resolution & (input.resolution - 1)) !== 0\n ) {\n return {\n ok: false,\n error: {\n code: 'reflection-probe-input-invalid',\n field: 'resolution',\n value: input.resolution,\n expected: 'a power of two of at least 16 pixels',\n },\n };\n }\n return { ok: true };\n}\n\nexport function estimateReflectionProbeBytes(\n resolution: number,\n limits: ReflectionProbeAdmissionLimits = DEFAULT_REFLECTION_PROBE_LIMITS,\n): number {\n const maxResolution = limits.maxResolution ?? DEFAULT_REFLECTION_PROBE_LIMITS.maxResolution;\n const clamped = Math.min(resolution, maxResolution);\n let filteredTexels = 0;\n for (let mip = 0; mip < 5; mip++) {\n const size = Math.max(1, Math.floor(clamped / 2 ** mip));\n filteredTexels += size * size;\n }\n // Raw cube + two alternating filtered cubes + their depth attachments.\n return (\n (clamped * clamped + 2 * filteredTexels) * 6 * REFLECTION_PROBE_BYTES_PER_TEXEL +\n 3 * clamped * clamped * 4\n );\n}\n\nexport function admitReflectionProbe(\n input: ReflectionProbeInput,\n current: { readonly acceptedCount: number; readonly acceptedBytes: number },\n limits: ReflectionProbeAdmissionLimits = DEFAULT_REFLECTION_PROBE_LIMITS,\n): ReflectionProbeAdmission {\n const maxProbes = limits.maxProbes ?? DEFAULT_REFLECTION_PROBE_LIMITS.maxProbes;\n const maxBytes = limits.maxBytes ?? DEFAULT_REFLECTION_PROBE_LIMITS.maxBytes;\n const maxResolution = limits.maxResolution ?? DEFAULT_REFLECTION_PROBE_LIMITS.maxResolution;\n const requested = estimateReflectionProbeBytes(input.resolution, { maxResolution });\n if (\n input.resolution > maxResolution ||\n current.acceptedCount >= maxProbes ||\n current.acceptedBytes + requested > maxBytes\n ) {\n return {\n ok: false,\n error: {\n code: 'reflection-probe-budget-exceeded',\n requested,\n activeCount: current.acceptedCount,\n activeBytes: current.acceptedBytes,\n maxProbes,\n maxBytes,\n },\n };\n }\n return { ok: true, acceptedBytes: current.acceptedBytes + requested };\n}\n\nexport interface ReflectionProbeSelection {\n readonly kind: 'probe';\n readonly worldId: number;\n readonly entityKey: number;\n readonly normalizedDistance: number;\n}\n\nexport interface SkylightSelection {\n readonly kind: 'skylight';\n}\n\nexport type ReflectionProbeSelectionResult = ReflectionProbeSelection | SkylightSelection;\n\nexport type ReflectionFallbackSource = 'probe' | 'skylight' | 'neutral';\n\nexport interface ReflectionFallbackProjectionInput {\n /** Stable renderable identity used to join the main-pass projection. */\n readonly renderableKey?: string;\n /** Stable producer source identity; never a live GPU handle. */\n readonly sourceKey?: string;\n readonly source: ReflectionFallbackSource;\n readonly coverage: number;\n readonly extent?: readonly [number, number, number];\n readonly linearHdr: readonly [number, number, number, number];\n readonly brdfSignature: string;\n}\n\nexport interface ReflectionFallbackProjection extends ReflectionFallbackProjectionInput {\n readonly source: ReflectionFallbackSource;\n}\n\nexport type ReflectionFallbackMismatchKind = 'source' | 'coverage' | 'extent' | 'brdf';\n\nexport interface ReflectionFallbackMismatch {\n readonly code:\n | 'reflection-fallback-source-mismatch'\n | 'reflection-fallback-coverage-mismatch'\n | 'reflection-fallback-extent-mismatch'\n | 'reflection-fallback-brdf-mismatch';\n readonly expected: string;\n readonly actual: string;\n}\n\nexport interface ReflectionFallbackInputInvalid {\n readonly code: 'reflection-fallback-input-invalid';\n readonly field: string;\n readonly expected: string;\n}\n\nexport type ReflectionFallbackProjectionResult =\n | { readonly ok: true; readonly value: ReflectionFallbackProjection }\n | { readonly ok: false; readonly error: ReflectionFallbackInputInvalid };\n\nexport function resolveReflectionFallbackSource(\n selection: ReflectionProbeSelectionResult,\n probeReady: boolean,\n skylightAvailable = true,\n): ReflectionFallbackSource {\n if (selection.kind === 'probe' && probeReady) return 'probe';\n // An unavailable probe follows the producer recovery order: use the active\n // Skylight when one exists, then the producer-owned neutral zero. Returning\n // neutral directly here would make the main Standard lighting lane and the\n // detached fallback projection disagree.\n if (skylightAvailable) return 'skylight';\n return 'neutral';\n}\n\nexport function reflectionFallbackCoverage(\n source: ReflectionFallbackSource,\n fact: ReflectionProbeFact | undefined,\n selection: ReflectionProbeSelectionResult,\n): number {\n if (source === 'neutral') return 0;\n if (source === 'skylight') return 1;\n if (fact === undefined || selection.kind !== 'probe') return 0;\n const normalized = Math.sqrt(Math.max(0, selection.normalizedDistance));\n return Math.max(0, Math.min(1, 1 - normalized / Math.sqrt(3)));\n}\n\nexport function reflectionFallbackSourceKey(\n source: ReflectionFallbackSource,\n selection: ReflectionProbeSelectionResult,\n skylight?: { readonly entityHandle: number; readonly equirectHandle: number },\n): string {\n if (source === 'probe' && selection.kind === 'probe') {\n return `probe:${selection.worldId}:${selection.entityKey}`;\n }\n if (source === 'skylight' && skylight !== undefined) {\n return `skylight:${skylight.entityHandle}:${skylight.equirectHandle}`;\n }\n return source;\n}\n\nexport function reflectionFallbackProjectionSignature(\n input: ReflectionFallbackProjectionInput,\n): string {\n return JSON.stringify({\n renderableKey: input.renderableKey,\n sourceKey: input.sourceKey,\n source: input.source,\n coverage: input.coverage,\n extent: input.extent,\n brdfSignature: input.brdfSignature,\n });\n}\n\nexport function deriveReflectionFallbackProjection(\n input: ReflectionFallbackProjectionInput,\n): ReflectionFallbackProjectionResult {\n if (!Number.isFinite(input.coverage) || input.coverage < 0 || input.coverage > 1) {\n return {\n ok: false,\n error: {\n code: 'reflection-fallback-input-invalid',\n field: 'coverage',\n expected: 'a finite number between zero and one',\n },\n };\n }\n if (input.extent?.some((value) => !Number.isFinite(value) || value <= 0)) {\n return {\n ok: false,\n error: {\n code: 'reflection-fallback-input-invalid',\n field: 'extent',\n expected: 'three finite numbers greater than zero',\n },\n };\n }\n if (input.linearHdr.some((value) => !Number.isFinite(value))) {\n return {\n ok: false,\n error: {\n code: 'reflection-fallback-input-invalid',\n field: 'linearHdr',\n expected: 'four finite linear HDR values',\n },\n };\n }\n if (input.brdfSignature.length === 0) {\n return {\n ok: false,\n error: {\n code: 'reflection-fallback-input-invalid',\n field: 'brdfSignature',\n expected: 'a non-empty BRDF signature',\n },\n };\n }\n const linearHdr = input.source === 'neutral' ? ([0, 0, 0, 0] as const) : [...input.linearHdr];\n return {\n ok: true,\n value: Object.freeze({\n ...(input.renderableKey === undefined ? {} : { renderableKey: input.renderableKey }),\n ...(input.sourceKey === undefined ? {} : { sourceKey: input.sourceKey }),\n source: input.source,\n coverage: input.coverage,\n ...(input.extent === undefined\n ? {}\n : {\n extent: Object.freeze([...input.extent]) as readonly [number, number, number],\n }),\n linearHdr: Object.freeze(linearHdr) as ReflectionFallbackProjection['linearHdr'],\n brdfSignature: input.brdfSignature,\n }),\n };\n}\n\nexport function validateReflectionFallbackCompatibility(\n expected: ReflectionFallbackProjectionInput,\n actual: ReflectionFallbackProjectionInput,\n): { readonly ok: true } | { readonly ok: false; readonly error: ReflectionFallbackMismatch } {\n const mismatch = (\n kind: ReflectionFallbackMismatchKind,\n expectedValue: string,\n actualValue: string,\n ): { readonly ok: false; readonly error: ReflectionFallbackMismatch } => ({\n ok: false,\n error: {\n code: `reflection-fallback-${kind}-mismatch` as ReflectionFallbackMismatch['code'],\n expected: expectedValue,\n actual: actualValue,\n },\n });\n if (expected.source !== actual.source) {\n return mismatch('source', expected.source, actual.source);\n }\n if (expected.coverage !== actual.coverage) {\n return mismatch('coverage', String(expected.coverage), String(actual.coverage));\n }\n const expectedExtent = expected.extent;\n const actualExtent = actual.extent;\n if (\n (expectedExtent === undefined && actualExtent !== undefined) ||\n (expectedExtent !== undefined &&\n (actualExtent === undefined ||\n expectedExtent.some((value, index) => value !== actualExtent[index])))\n ) {\n return mismatch('extent', JSON.stringify(expectedExtent), JSON.stringify(actualExtent));\n }\n if (expected.brdfSignature !== actual.brdfSignature) {\n return mismatch('brdf', expected.brdfSignature, actual.brdfSignature);\n }\n return { ok: true };\n}\n\nfunction contains(fact: ReflectionProbeFact, point: readonly [number, number, number]): boolean {\n return fact.halfExtents.every((extent, axis) => {\n const center = fact.center[axis] ?? 0;\n const coordinate = point[axis] ?? 0;\n return Math.abs(coordinate - center) <= extent;\n });\n}\n\nfunction normalizedDistance(\n fact: ReflectionProbeFact,\n point: readonly [number, number, number],\n): number {\n let squared = 0;\n for (let axis = 0; axis < 3; axis += 1) {\n const delta = (point[axis] ?? 0) - (fact.center[axis] ?? 0);\n const extent = fact.halfExtents[axis] ?? 1;\n squared += (delta / extent) ** 2;\n }\n return squared;\n}\n\nfunction isBetter(\n candidate: ReflectionProbeSelection,\n current: ReflectionProbeSelection,\n facts: readonly ReflectionProbeFact[],\n): boolean {\n const candidateFact = facts.find(\n (fact) => fact.worldId === candidate.worldId && fact.entityKey === candidate.entityKey,\n );\n const currentFact = facts.find(\n (fact) => fact.worldId === current.worldId && fact.entityKey === current.entityKey,\n );\n if (candidateFact === undefined || currentFact === undefined) return false;\n if (candidateFact.priority !== currentFact.priority)\n return candidateFact.priority > currentFact.priority;\n if (candidate.normalizedDistance !== current.normalizedDistance) {\n return candidate.normalizedDistance < current.normalizedDistance;\n }\n return (\n candidate.worldId < current.worldId ||\n (candidate.worldId === current.worldId && candidate.entityKey < current.entityKey)\n );\n}\n\nexport function selectReflectionProbe(\n facts: readonly ReflectionProbeFact[],\n primitiveCenter: readonly [number, number, number],\n): ReflectionProbeSelectionResult {\n let selected: ReflectionProbeSelection | undefined;\n for (const fact of facts) {\n if (!contains(fact, primitiveCenter)) continue;\n const candidate: ReflectionProbeSelection = {\n kind: 'probe',\n worldId: fact.worldId,\n entityKey: fact.entityKey,\n normalizedDistance: normalizedDistance(fact, primitiveCenter),\n };\n if (selected === undefined || isBetter(candidate, selected, facts)) selected = candidate;\n }\n return selected ?? { kind: 'skylight' };\n}\n\nexport interface ReflectionProbePrimitive {\n readonly worldId: number;\n readonly entityKey: number;\n /** Main-pass renderable key; world/entity is retained as the compatibility fallback. */\n readonly renderableKey?: string;\n readonly center: readonly [number, number, number];\n}\n\nexport interface ReflectionProbeProjectionSnapshot {\n readonly revision: number;\n readonly facts: readonly ReflectionProbeFact[];\n readonly selected: ReadonlyMap<string, ReflectionProbeSelectionResult>;\n readonly scannedPrimitives: number;\n}\n\nfunction primitiveKey(worldId: number, entityKey: number): string {\n return `${worldId}:${entityKey}`;\n}\n\nexport class ReflectionProbeProjection {\n private revision = 0;\n private facts: readonly ReflectionProbeFact[] = [];\n private selected = new Map<string, ReflectionProbeSelectionResult>();\n private signature = '';\n private scannedPrimitives = 0;\n\n update(\n facts: readonly ReflectionProbeFact[],\n primitives: readonly ReflectionProbePrimitive[],\n ): ReflectionProbeProjectionSnapshot {\n const nextFacts = facts\n .slice()\n .sort((a, b) => a.worldId - b.worldId || a.entityKey - b.entityKey);\n const signature = JSON.stringify({ facts: nextFacts, primitives });\n if (signature === this.signature) return this.snapshot();\n this.signature = signature;\n this.facts = nextFacts;\n this.selected = new Map();\n for (const primitive of primitives) {\n this.selected.set(\n primitive.renderableKey ?? primitiveKey(primitive.worldId, primitive.entityKey),\n selectReflectionProbe(nextFacts, primitive.center),\n );\n }\n this.scannedPrimitives = primitives.length;\n this.revision += 1;\n return this.snapshot();\n }\n\n snapshot(): ReflectionProbeProjectionSnapshot {\n return {\n revision: this.revision,\n facts: this.facts,\n selected: this.selected,\n scannedPrimitives: this.scannedPrimitives,\n };\n }\n\n selection(worldId: number, entityKey: number): ReflectionProbeSelectionResult {\n return this.selected.get(primitiveKey(worldId, entityKey)) ?? { kind: 'skylight' };\n }\n}\n","import { createVisibilityBudget } from './budget';\n\n/** Detached, bounded LOD/occlusion facts for renderer inspection consumers. */\n\nexport const LOD_OCCLUSION_INSPECTION_SCHEMA = 'forgeax::lod-occlusion-inspection::v2' as const;\nexport const LOD_OCCLUSION_INSPECTION_MAX_BYTES = 16 * 1024;\nconst MAX_INSPECTION_SAMPLES = 64;\n\nexport type LodOcclusionInspectionError = {\n readonly code: string;\n readonly expected: string;\n readonly hint: string;\n readonly detail?: Readonly<Record<string, string | number | boolean>>;\n};\n\nexport type LodOcclusionFallback =\n | { readonly active: false }\n | {\n readonly active: true;\n readonly reason: 'producer-failed' | 'page-exhausted' | 'query-failed' | 'device-loss';\n readonly error: LodOcclusionInspectionError;\n };\n\nexport type LodOcclusionDegradation =\n | { readonly active: false }\n | { readonly active: true; readonly reason: 'all-visible' | 'query-unavailable' };\n\nexport interface LodOcclusionInspectionSample {\n readonly primitiveSlot: number;\n readonly level: number;\n readonly visible: boolean;\n}\n\nexport interface LodOcclusionInspectionRow {\n readonly root: { readonly guid: string; readonly sourceKey: string };\n readonly view: {\n readonly attachmentId: string;\n readonly cameraEntity: number;\n readonly viewRole: 'main' | 'shadow' | 'reflection' | 'probe';\n readonly viewGeneration: number;\n };\n readonly slot: { readonly primitiveSlot: number; readonly slotGeneration: number };\n readonly generation: number;\n readonly count: {\n readonly candidates: number;\n readonly visible: number;\n readonly occluded: number;\n };\n readonly lodHistogram: readonly { readonly level: number; readonly count: number }[];\n /** Map latency for the most recently completed query page (bounded POD). */\n readonly queryLatencyUs: {\n readonly median: number;\n readonly p95: number;\n readonly last: number;\n };\n readonly pagePressure: { readonly used: number; readonly capacity: number };\n readonly fallback: LodOcclusionFallback;\n readonly degradation: LodOcclusionDegradation;\n readonly samples: readonly LodOcclusionInspectionSample[];\n}\n\nexport interface LodOcclusionInspectionSubmit {\n readonly frameId: number;\n readonly build: string;\n readonly deviceGeneration: number;\n}\n\n/**\n * Per-World attribution is only authoritative when the renderer publishes\n * the GPU facts from the same submit that owns the parent inspection. The\n * normal projection path remains useful diagnostics, but it must not be used\n * as evidence for a World-reorder or per-World LOD claim.\n */\nexport type LodOcclusionWorldAttribution =\n | { readonly status: 'unavailable'; readonly reason: 'projection-only' }\n | { readonly status: 'same-submit'; readonly submit: LodOcclusionInspectionSubmit };\n\nexport interface LodOcclusionWorldInspection {\n readonly attachmentId: string;\n readonly rows: readonly LodOcclusionInspectionRow[];\n readonly attribution: LodOcclusionWorldAttribution;\n}\n\nexport interface LodOcclusionInspectionBudget {\n readonly configuredQueryBudget: number;\n readonly effectiveQueryBudget: number;\n readonly settleSubmits: number;\n readonly retestSubmits: number;\n readonly expirySubmits: number;\n}\n\nexport interface LodOcclusionInspection extends LodOcclusionInspectionRow {\n readonly schema: typeof LOD_OCCLUSION_INSPECTION_SCHEMA;\n /** Atomic identity for the submit that produced every row below. */\n readonly submit: LodOcclusionInspectionSubmit;\n /** Immutable budget values used by the query and confidence owners. */\n readonly budget: LodOcclusionInspectionBudget;\n /** Stable attachment identity; array order is never an attribution key. */\n readonly worlds: readonly LodOcclusionWorldInspection[];\n}\n\nexport type LodOcclusionInspectionInput = Omit<\n LodOcclusionInspection,\n 'schema' | 'submit' | 'budget' | 'worlds'\n> & {\n readonly submit?: LodOcclusionInspectionSubmit;\n readonly budget?: LodOcclusionInspectionBudget;\n readonly worlds?: readonly LodOcclusionWorldInspectionInput[];\n};\n\nexport type LodOcclusionWorldInspectionInput = Omit<LodOcclusionWorldInspection, 'attribution'> & {\n readonly attribution?: LodOcclusionWorldAttribution;\n};\n\nexport type LodOcclusionInspectionAction =\n | { readonly action: 'none' }\n | { readonly action: 'rebuild'; readonly sourceKey: string; readonly reason: string }\n | { readonly action: 'cold-cook'; readonly sourceKey: string; readonly reason: string }\n | { readonly action: 'retry'; readonly sourceKey: string; readonly reason: string };\n\nfunction nonNegativeInteger(name: string, value: number): number {\n if (!Number.isInteger(value) || value < 0)\n throw new Error(`${name} must be a non-negative integer`);\n return value;\n}\n\nfunction copyError(error: LodOcclusionInspectionError): LodOcclusionInspectionError {\n return Object.freeze({\n code: error.code,\n expected: error.expected,\n hint: error.hint,\n ...(error.detail === undefined ? {} : { detail: Object.freeze({ ...error.detail }) }),\n });\n}\n\nfunction copyFallback(fallback: LodOcclusionFallback): LodOcclusionFallback {\n return fallback.active\n ? Object.freeze({ ...fallback, error: copyError(fallback.error) })\n : Object.freeze({ active: false });\n}\n\nfunction copySamples(\n samples: readonly LodOcclusionInspectionSample[],\n): readonly LodOcclusionInspectionSample[] {\n return Object.freeze(\n [...samples]\n .sort((left, right) => left.primitiveSlot - right.primitiveSlot)\n .slice(0, MAX_INSPECTION_SAMPLES)\n .map((sample) =>\n Object.freeze({\n primitiveSlot: nonNegativeInteger('sample.primitiveSlot', sample.primitiveSlot),\n level: nonNegativeInteger('sample.level', sample.level),\n visible: sample.visible,\n }),\n ),\n );\n}\n\nfunction copyWorldAttribution(\n attribution: LodOcclusionWorldAttribution | undefined,\n): LodOcclusionWorldAttribution {\n if (attribution === undefined) {\n return Object.freeze({ status: 'unavailable', reason: 'projection-only' });\n }\n if (attribution.status === 'same-submit') {\n if (typeof attribution.submit.build !== 'string' || attribution.submit.build.length === 0) {\n throw new Error('world.attribution.submit.build must be a non-empty string');\n }\n nonNegativeInteger('world.attribution.submit.frameId', attribution.submit.frameId);\n nonNegativeInteger(\n 'world.attribution.submit.deviceGeneration',\n attribution.submit.deviceGeneration,\n );\n return Object.freeze({\n status: 'same-submit',\n submit: Object.freeze({ ...attribution.submit }),\n });\n }\n if (attribution.status !== 'unavailable' || attribution.reason !== 'projection-only') {\n throw new Error('world.attribution must declare same-submit or projection-only');\n }\n return Object.freeze({ status: 'unavailable', reason: 'projection-only' });\n}\n\nfunction copyRow(row: LodOcclusionInspectionRow): LodOcclusionInspectionRow {\n for (const [name, value] of Object.entries({\n generation: row.generation,\n candidates: row.count.candidates,\n visible: row.count.visible,\n occluded: row.count.occluded,\n median: row.queryLatencyUs.median,\n p95: row.queryLatencyUs.p95,\n last: row.queryLatencyUs.last,\n pageUsed: row.pagePressure.used,\n pageCapacity: row.pagePressure.capacity,\n }))\n nonNegativeInteger(`inspection.${name}`, value);\n if (\n row.view.cameraEntity < 0 ||\n row.view.viewGeneration < 0 ||\n row.slot.primitiveSlot < 0 ||\n row.slot.slotGeneration < 0\n ) {\n throw new Error('inspection identity values must be non-negative');\n }\n if (row.pagePressure.used > row.pagePressure.capacity) {\n throw new Error('inspection page pressure exceeds capacity');\n }\n return Object.freeze({\n root: Object.freeze({ ...row.root }),\n view: Object.freeze({ ...row.view }),\n slot: Object.freeze({ ...row.slot }),\n generation: row.generation,\n count: Object.freeze({ ...row.count }),\n lodHistogram: Object.freeze(\n row.lodHistogram.map((histogram) =>\n Object.freeze({\n level: nonNegativeInteger('histogram.level', histogram.level),\n count: nonNegativeInteger('histogram.count', histogram.count),\n }),\n ),\n ),\n queryLatencyUs: Object.freeze({ ...row.queryLatencyUs }),\n pagePressure: Object.freeze({ ...row.pagePressure }),\n fallback: copyFallback(row.fallback),\n degradation: Object.freeze({ ...row.degradation }),\n samples: copySamples(row.samples),\n });\n}\n\nfunction copyWorlds(\n worlds: readonly LodOcclusionWorldInspectionInput[] | undefined,\n fallback: LodOcclusionInspectionRow,\n): readonly LodOcclusionWorldInspection[] {\n const source = worlds ?? [{ attachmentId: fallback.view.attachmentId, rows: [fallback] }];\n return Object.freeze(\n source.map((world) =>\n Object.freeze({\n attachmentId: world.attachmentId,\n rows: Object.freeze(world.rows.map((row) => copyRow(row))),\n attribution: copyWorldAttribution(world.attribution),\n }),\n ),\n );\n}\n\nexport function inspectLodOcclusion(input: LodOcclusionInspectionInput): LodOcclusionInspection {\n const row = copyRow(input);\n const defaultBudget = createVisibilityBudget();\n const budget = input.budget ?? {\n configuredQueryBudget: defaultBudget.configuredQueryBudget,\n effectiveQueryBudget: defaultBudget.effectiveQueryBudget,\n settleSubmits: defaultBudget.settleSubmits,\n retestSubmits: defaultBudget.retestSubmits,\n expirySubmits: defaultBudget.expirySubmits,\n };\n for (const [name, value] of Object.entries(budget))\n nonNegativeInteger(`inspection.budget.${name}`, value);\n const submit = input.submit ?? {\n frameId: input.generation,\n build: 'unknown',\n deviceGeneration: 0,\n };\n nonNegativeInteger('inspection.submit.frameId', submit.frameId);\n nonNegativeInteger('inspection.submit.deviceGeneration', submit.deviceGeneration);\n if (typeof submit.build !== 'string' || submit.build.length === 0) {\n throw new Error('inspection.submit.build must be a non-empty string');\n }\n const worlds = copyWorlds(input.worlds, row);\n for (const world of worlds) {\n if (\n world.attribution.status === 'same-submit' &&\n (world.attribution.submit.frameId !== submit.frameId ||\n world.attribution.submit.build !== submit.build ||\n world.attribution.submit.deviceGeneration !== submit.deviceGeneration)\n ) {\n throw new Error('world attribution must reference the parent inspection submit');\n }\n }\n const inspection: LodOcclusionInspection = Object.freeze({\n schema: LOD_OCCLUSION_INSPECTION_SCHEMA,\n ...row,\n submit: Object.freeze({ ...submit }),\n budget: Object.freeze({ ...budget }),\n worlds,\n });\n if (JSON.stringify(inspection).length > LOD_OCCLUSION_INSPECTION_MAX_BYTES) {\n throw new Error(`LOD occlusion inspection exceeds ${LOD_OCCLUSION_INSPECTION_MAX_BYTES} bytes`);\n }\n return inspection;\n}\n\nexport function serializeLodOcclusionInspection(inspection: LodOcclusionInspection): string {\n const serialized = JSON.stringify(inspection);\n if (serialized.length > LOD_OCCLUSION_INSPECTION_MAX_BYTES) {\n throw new Error(`LOD occlusion inspection exceeds ${LOD_OCCLUSION_INSPECTION_MAX_BYTES} bytes`);\n }\n return serialized;\n}\n\nexport function consumeLodOcclusionInspection(\n inspection: LodOcclusionInspection,\n): LodOcclusionInspectionAction {\n if (!inspection.fallback.active) return { action: 'none' };\n const { reason, error } = inspection.fallback;\n const action =\n error.code.startsWith('asset-') || reason === 'producer-failed'\n ? 'rebuild'\n : reason === 'query-failed' || reason === 'page-exhausted' || reason === 'device-loss'\n ? 'retry'\n : 'cold-cook';\n return { action, sourceKey: inspection.root.sourceKey, reason };\n}\n","// @forgeax/engine-render - bounded SSR spatial inspection projection.\n\nimport type { ScreenSpaceReflectionData } from '../components/screen-space-reflection';\nimport type { ReflectionFallbackSource } from '../inspection-types';\nimport type { SsrSpatialAdmission, SsrSpatialLane, SsrSpatialWork } from './admission';\nimport type { SsrConfigInvalidError, SsrUnavailableError } from './errors';\nimport type { SsrHistoryState } from './history';\n\nexport type SsrSpatialInspectionFailure = SsrConfigInvalidError | SsrUnavailableError;\n\nexport interface SsrSpatialHistoryInspection {\n readonly state: 'not-owned' | SsrHistoryState;\n readonly bytes: number;\n readonly resetCount: number;\n}\n\nexport interface SsrSpatialInspectionProjection {\n readonly status?: SsrSpatialInspection['status'];\n readonly coverage?: Partial<SsrSpatialInspection['coverage']>;\n readonly history?: SsrSpatialHistoryInspection;\n readonly passRoster?: readonly string[];\n readonly fallbackSource?: ReflectionFallbackSource;\n readonly failure?: SsrSpatialInspectionFailure;\n}\n\n/** Keep the public projection bounded even if a graph owner supplies a bad list. */\nexport const SSR_INSPECTION_MAX_PASSES = 64 as const;\n\nfunction nonNegativeSafeInteger(name: string, value: number): number {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw new Error(`${name} must be a non-negative safe integer`);\n }\n return value;\n}\n\nfunction copyHistory(history: SsrSpatialHistoryInspection): SsrSpatialHistoryInspection {\n nonNegativeSafeInteger('SSR inspection history.bytes', history.bytes);\n nonNegativeSafeInteger('SSR inspection history.resetCount', history.resetCount);\n return Object.freeze({\n state: history.state,\n bytes: history.bytes,\n resetCount: history.resetCount,\n });\n}\n\nfunction copyCoverage(\n coverage: Partial<SsrSpatialInspection['coverage']> | undefined,\n): SsrSpatialInspection['coverage'] {\n const result = {\n hitCount: coverage?.hitCount ?? null,\n fallbackCount: coverage?.fallbackCount ?? null,\n excludedCount: coverage?.excludedCount ?? null,\n };\n for (const [key, value] of Object.entries(result)) {\n if (value !== null) nonNegativeSafeInteger(`SSR inspection coverage.${key}`, value);\n }\n return Object.freeze(result);\n}\n\nfunction copyPassRoster(passRoster: readonly string[] | undefined): readonly string[] {\n return Object.freeze(\n [...(passRoster ?? [])].slice(0, SSR_INSPECTION_MAX_PASSES).map((name, index) => {\n if (typeof name !== 'string' || name.length === 0) {\n throw new Error(`SSR inspection passRoster[${index}] must be a non-empty string`);\n }\n return name;\n }),\n );\n}\n\nexport interface SsrSpatialInspection {\n readonly status: 'not-requested' | 'requested' | 'admitted' | 'fallback-only' | 'structural-only';\n readonly lane: SsrSpatialLane;\n readonly config: ScreenSpaceReflectionData | undefined;\n readonly viewRange: number;\n readonly coverage: {\n /** Null means no GPU coverage measurement is available for this frame. */\n readonly hitCount: number | null;\n readonly fallbackCount: number | null;\n readonly excludedCount: number | null;\n };\n readonly history: SsrSpatialHistoryInspection;\n readonly work: SsrSpatialWork;\n readonly passRoster: readonly string[];\n readonly fallbackSource: ReflectionFallbackSource | undefined;\n readonly failure: SsrSpatialInspectionFailure | undefined;\n}\n\n/** Project only detached, bounded facts from the spatial admission result. */\nexport function projectSsrSpatialInspection(\n admission: SsrSpatialAdmission,\n projection: SsrSpatialInspectionProjection = {},\n): SsrSpatialInspection {\n const config = admission.config;\n return Object.freeze({\n status: projection.status ?? admission.status,\n lane: admission.lane,\n config:\n config === undefined\n ? undefined\n : Object.freeze({\n maxDistance: config.maxDistance,\n thickness: config.thickness,\n maxRoughness: config.maxRoughness,\n }),\n viewRange: admission.viewRange,\n coverage: copyCoverage(projection.coverage),\n history: copyHistory(\n projection.history ?? {\n state: 'not-owned' as const,\n bytes: 0,\n resetCount: 0,\n },\n ),\n work: Object.freeze({ ...admission.work }),\n passRoster: copyPassRoster(projection.passRoster),\n fallbackSource: projection.fallbackSource,\n failure: projection.failure ?? admission.failure,\n });\n}\n\nexport function serializeSsrSpatialInspection(inspection: SsrSpatialInspection): string {\n return JSON.stringify(inspection);\n}\n","import type { Handle, MeshAsset } from '@forgeax/engine-types';\nimport { err, ok, type Result } from '@forgeax/engine-types';\n\n/** A standard MeshAsset candidate prepared for one attached World generation. */\nexport interface DynamicGeometryPrepareInput {\n readonly world: object;\n /** Live ECS entity carrying MeshFilter + MeshRenderer on the attached World. */\n readonly entity?: number;\n /** Optional derived-physics entity whose fixed-step publication gates draw. */\n readonly physicsEntity?: number;\n readonly mesh: MeshAsset;\n /** Existing World.sharedRefs handle whose standard GPU residency is prepared. */\n readonly meshHandle?: Handle<'MeshAsset', 'shared'>;\n readonly revision: number;\n /** Material identity is a consumer fact; MaterialAsset stays in the World. */\n readonly materialIdentity?: string;\n /** Topology changes invalidate motion/history consumers. */\n readonly topologyRevision?: number;\n /** Captured by the Renderer host from the World FixedTime resource. */\n readonly fixedStep?: number;\n}\n\n/** Explicit ECS/fixed-step ordering proof used by Renderer admission. */\nexport interface DynamicGeometryOrdering {\n readonly world: object;\n readonly fixedStep: number;\n}\n\nexport type DynamicGeometryCandidateState =\n | 'prepared'\n | 'accepted'\n | 'published'\n | 'cancelled'\n | 'retired';\n\nexport interface DynamicGeometryCandidate {\n readonly candidateId: string;\n readonly generation: number;\n readonly owner: object;\n readonly world: object;\n readonly entity?: number;\n readonly physicsEntity?: number;\n /** False when the pure lifecycle was used without a shared MeshAsset handle. */\n readonly gpuReady: boolean;\n /** CPU/GPU geometry bytes reserved by this candidate budget. */\n readonly meshBytes: number;\n readonly revision: number;\n readonly topologyRevision: number;\n readonly materialIdentity?: string;\n readonly meshHandle?: Handle<'MeshAsset', 'shared'>;\n readonly fixedStep?: number;\n readonly mesh: MeshAsset;\n readonly state: DynamicGeometryCandidateState;\n}\n\n/** Record-stage lane that consumed a published dynamic-geometry candidate. */\nexport type DynamicGeometryRecordStageLane = 'cpu' | 'gpu' | 'mixed';\n\n/** Receipt that ties candidate publication to the sole Renderer FrameReceipt. */\nexport interface DynamicGeometryReceipt {\n readonly candidateId: string;\n readonly generation: number;\n readonly revision: number;\n readonly topologyRevision: number;\n readonly fixedStep?: number;\n readonly frameId: number;\n readonly deviceGeneration: number;\n readonly frame: {\n readonly frameId: number;\n readonly deviceGeneration: number;\n readonly completed?: Promise<unknown>;\n };\n /** Whether the Renderer record stage consumed this candidate for this frame. */\n readonly recordStageConsumed: boolean;\n /** Lane evidence from the exact submitted record stage, when attached. */\n readonly recordStageLane?: DynamicGeometryRecordStageLane;\n /** Actual frame fixed step; may be newer than the preparation step. */\n readonly publicationFixedStep?: number;\n}\n\nexport interface DynamicGeometryInspection {\n readonly generation: number;\n readonly prepared: number;\n readonly accepted: number;\n readonly published: number;\n readonly retired: number;\n readonly latestRevision?: number;\n readonly latestFrameId?: number;\n readonly historyInvalidations: number;\n readonly invalidated: number;\n readonly meshBytes: number;\n readonly maxMeshBytes: number;\n}\n\nexport type DynamicGeometryErrorCode =\n | 'dynamic-geometry-disposed'\n | 'dynamic-geometry-world-not-attached'\n | 'dynamic-geometry-invalid'\n | 'dynamic-geometry-gpu-failed'\n | 'dynamic-geometry-gpu-not-ready'\n | 'dynamic-geometry-budget-exceeded'\n | 'dynamic-geometry-stale'\n | 'dynamic-geometry-generation-mismatch'\n | 'dynamic-geometry-candidate-not-found'\n | 'dynamic-geometry-candidate-state'\n | 'dynamic-geometry-receipt-mismatch'\n | 'dynamic-geometry-ordering-required';\n\nexport interface DynamicGeometryErrorDetail {\n readonly code: DynamicGeometryErrorCode;\n readonly candidateId?: string;\n readonly revision?: number;\n readonly generation?: number;\n readonly actual?: unknown;\n}\n\nexport class DynamicGeometryError extends Error {\n readonly code: DynamicGeometryErrorCode;\n readonly expected: string;\n readonly hint: string;\n readonly detail: DynamicGeometryErrorDetail;\n\n constructor(\n code: DynamicGeometryErrorCode,\n expected: string,\n hint: string,\n detail: Omit<DynamicGeometryErrorDetail, 'code'> = {},\n ) {\n super(`${code}: ${expected}`);\n this.name = 'DynamicGeometryError';\n this.code = code;\n this.expected = expected;\n this.hint = hint;\n this.detail = Object.freeze({ code, ...detail });\n }\n}\n\ninterface CandidateRecord {\n readonly world: object;\n candidate: DynamicGeometryCandidate;\n /** Published history remains queryable for its completion fence, but a\n * newer topology must prevent that history from being consumed again. */\n historyInvalidated: boolean;\n acceptedFrame?: { readonly frameId: number; readonly deviceGeneration: number };\n}\n\n/**\n * A public candidate is a credential, not a mutable state object. Keep the\n * owner/world check in `current` cheap, then compare every scalar admission\n * fact before a caller can cancel, retire, or inspect another record by\n * copying its candidate id. The renderer-owned MeshAsset copy remains the\n * content source for the actual draw.\n */\nexport function sameCandidateCredential(\n candidate: DynamicGeometryCandidate,\n committed: DynamicGeometryCandidate,\n): boolean {\n return (\n candidate.candidateId === committed.candidateId &&\n candidate.owner === committed.owner &&\n candidate.world === committed.world &&\n candidate.generation === committed.generation &&\n candidate.entity === committed.entity &&\n candidate.physicsEntity === committed.physicsEntity &&\n candidate.gpuReady === committed.gpuReady &&\n candidate.meshBytes === committed.meshBytes &&\n candidate.revision === committed.revision &&\n candidate.topologyRevision === committed.topologyRevision &&\n candidate.materialIdentity === committed.materialIdentity &&\n candidate.meshHandle === committed.meshHandle &&\n candidate.fixedStep === committed.fixedStep\n );\n}\n\nfunction cloneTypedArray<T extends Float32Array | Uint16Array | Uint32Array>(value: T): T {\n return new (value.constructor as new (source: T) => T)(value);\n}\n\nfunction cloneMesh(mesh: MeshAsset): MeshAsset {\n const attributes = Object.fromEntries(\n Object.entries(mesh.attributes).map(([key, value]) => [\n key,\n value instanceof ArrayBuffer\n ? value.slice(0)\n : value === undefined\n ? undefined\n : cloneTypedArray(value as never),\n ]),\n ) as MeshAsset['attributes'];\n return Object.freeze({\n ...mesh,\n vertices: new Float32Array(mesh.vertices),\n ...(mesh.indices === undefined ? {} : { indices: cloneTypedArray(mesh.indices) }),\n attributes,\n ...(mesh.aabb === undefined ? {} : { aabb: new Float32Array(mesh.aabb) }),\n submeshes: Object.freeze(mesh.submeshes.map((submesh) => Object.freeze({ ...submesh }))),\n materialSlots: Object.freeze(mesh.materialSlots.map((slot) => Object.freeze({ ...slot }))),\n });\n}\n\nfunction cloneCandidate(candidate: DynamicGeometryCandidate): DynamicGeometryCandidate {\n return Object.freeze({ ...candidate, mesh: cloneMesh(candidate.mesh) });\n}\n\nfunction validateMesh(mesh: MeshAsset): string | undefined {\n if (mesh.kind !== 'mesh') return 'MeshAsset.kind must be mesh';\n if (!(mesh.vertices instanceof Float32Array) || mesh.vertices.length === 0) {\n return 'MeshAsset.vertices must be a non-empty Float32Array';\n }\n // vertices may be interleaved. Attribute layout validation belongs to the\n // mesh producer/residency path; this gate must not assume an xyz-only stride.\n if (\n mesh.indices !== undefined &&\n !(mesh.indices instanceof Uint16Array || mesh.indices instanceof Uint32Array)\n ) {\n return 'MeshAsset.indices must be Uint16Array or Uint32Array';\n }\n if (mesh.submeshes.length === 0)\n return 'MeshAsset.submeshes must contain at least one topology range';\n if (\n mesh.submeshes.some(\n (submesh) =>\n !Number.isSafeInteger(submesh.materialSlot) ||\n submesh.materialSlot < 0 ||\n submesh.materialSlot >= mesh.materialSlots.length,\n )\n ) {\n return 'MeshAsset.materialSlots must cover every referenced materialSlot';\n }\n if (mesh.vertices.some((value) => !Number.isFinite(value)))\n return 'MeshAsset.vertices must be finite';\n return undefined;\n}\n\nfunction meshByteSize(mesh: MeshAsset): number {\n let bytes = mesh.vertices.byteLength + (mesh.indices?.byteLength ?? 0);\n for (const value of Object.values(mesh.attributes)) {\n if (value instanceof ArrayBuffer) bytes += value.byteLength;\n else if (value !== undefined && ArrayBuffer.isView(value)) bytes += value.byteLength;\n }\n if (mesh.aabb !== undefined) bytes += mesh.aabb.byteLength;\n // Submesh/material metadata is intentionally bounded by the candidate\n // count. The reserved byte budget is for typed geometry and GPU upload\n // inputs, which are the resources that can exhaust the renderer.\n return bytes;\n}\n\n/**\n * Renderer-owned lifecycle for standard MeshAsset candidates. It deliberately\n * has no device, buffer, queue, or frame clock; the host supplies generation\n * and FrameReceipt facts at the boundaries below.\n */\nexport interface DynamicGeometryLifecycle {\n prepare(\n input: DynamicGeometryPrepareInput,\n generation: number,\n ): Result<DynamicGeometryCandidate, DynamicGeometryError>;\n accept(\n candidate: DynamicGeometryCandidate,\n ordering?: DynamicGeometryOrdering,\n ): Result<DynamicGeometryCandidate, DynamicGeometryError>;\n cancel(\n candidate: DynamicGeometryCandidate,\n completion?: Promise<unknown>,\n ): Result<void, DynamicGeometryError>;\n retire(candidate: DynamicGeometryCandidate): Result<void, DynamicGeometryError>;\n /** Release the count/byte budget after receipt-bound GPU cleanup completes. */\n finalizeRetirement(candidate: DynamicGeometryCandidate): Result<void, DynamicGeometryError>;\n receipt(candidate: DynamicGeometryCandidate): DynamicGeometryReceipt | undefined;\n publishFrame(\n frame: {\n readonly frameId: number;\n readonly deviceGeneration: number;\n readonly completed?: Promise<unknown>;\n },\n worlds?: readonly object[],\n fixedStep?: number,\n canPublish?: (candidate: DynamicGeometryCandidate) => boolean,\n recordStageLane?: (\n candidate: DynamicGeometryCandidate,\n ) => DynamicGeometryRecordStageLane | undefined,\n ): readonly DynamicGeometryReceipt[];\n invalidateWorld(world: object, completion?: Promise<unknown>): void;\n invalidateGeneration(generation: number): void;\n inspect(): DynamicGeometryInspection;\n dispose(): void;\n}\n\nexport function createDynamicGeometryLifecycle(\n maxCandidates = 32,\n maxMeshBytes = 64 * 1024 * 1024,\n): DynamicGeometryLifecycle {\n const records = new Map<string, CandidateRecord>();\n const owner = {};\n let sequence = 0;\n let currentGeneration = 0;\n let disposed = false;\n let historyInvalidations = 0;\n let latestRevision: number | undefined;\n let latestFrameId: number | undefined;\n let retired = 0;\n let invalidated = 0;\n let meshBytes = 0;\n const latestRevisionByWorld = new WeakMap<object, Map<number | undefined, number>>();\n const latestTopologyRevisionByWorld = new WeakMap<object, Map<number | undefined, number>>();\n const publishedReceipts = new Map<string, DynamicGeometryReceipt>();\n\n const failure = (\n code: DynamicGeometryErrorCode,\n expected: string,\n hint: string,\n detail: Omit<DynamicGeometryErrorDetail, 'code'> = {},\n ): Result<never, DynamicGeometryError> =>\n err(new DynamicGeometryError(code, expected, hint, detail));\n\n const current = (candidate: DynamicGeometryCandidate): CandidateRecord | undefined => {\n const record = records.get(candidate.candidateId);\n if (\n record === undefined ||\n candidate.owner !== owner ||\n record.candidate.owner !== candidate.owner ||\n record.candidate.world !== candidate.world ||\n record.candidate.generation !== candidate.generation\n )\n return undefined;\n return record;\n };\n\n return {\n prepare(input, generation) {\n if (disposed)\n return failure('dynamic-geometry-disposed', 'renderer is alive', 'rebuild the Renderer');\n if (input.world === null || typeof input.world !== 'object') {\n return failure(\n 'dynamic-geometry-world-not-attached',\n 'candidate belongs to an attached World',\n 'attach the World before preparing geometry',\n );\n }\n if (!Number.isInteger(input.revision) || input.revision < 0) {\n return failure(\n 'dynamic-geometry-invalid',\n 'geometry revision is a non-negative integer',\n 'advance the consumer revision monotonically',\n { revision: input.revision },\n );\n }\n if (generation !== currentGeneration && currentGeneration !== 0) {\n return failure(\n 'dynamic-geometry-generation-mismatch',\n 'candidate uses the active renderer generation',\n 'discard stale generation work and prepare again',\n { generation, actual: currentGeneration },\n );\n }\n if (records.size >= maxCandidates) {\n return failure(\n 'dynamic-geometry-budget-exceeded',\n 'candidate count remains within the bounded renderer budget',\n 'cancel or retire an earlier candidate before retrying',\n { actual: records.size },\n );\n }\n const invalid = validateMesh(input.mesh);\n if (invalid !== undefined)\n return failure(\n 'dynamic-geometry-invalid',\n 'MeshAsset satisfies the standard geometry contract',\n invalid,\n );\n const candidateBytes = meshByteSize(input.mesh);\n if (\n !Number.isSafeInteger(candidateBytes) ||\n candidateBytes < 0 ||\n meshBytes > maxMeshBytes - candidateBytes\n ) {\n return failure(\n 'dynamic-geometry-budget-exceeded',\n 'candidate mesh bytes remain within the bounded renderer resource budget',\n 'cancel or retire an earlier candidate before retrying',\n { actual: { meshBytes, candidateBytes, maxMeshBytes } },\n );\n }\n const candidateId = `mesh:${generation}:${++sequence}:${input.revision}`;\n const candidate: DynamicGeometryCandidate = Object.freeze({\n candidateId,\n generation,\n owner,\n world: input.world,\n ...(input.entity === undefined ? {} : { entity: input.entity }),\n ...(input.physicsEntity === undefined ? {} : { physicsEntity: input.physicsEntity }),\n gpuReady: input.meshHandle !== undefined,\n meshBytes: candidateBytes,\n revision: input.revision,\n topologyRevision: input.topologyRevision ?? input.revision,\n ...(input.materialIdentity === undefined\n ? {}\n : { materialIdentity: input.materialIdentity }),\n ...(input.meshHandle === undefined ? {} : { meshHandle: input.meshHandle }),\n ...(input.fixedStep === undefined ? {} : { fixedStep: input.fixedStep }),\n mesh: cloneMesh(input.mesh),\n state: 'prepared',\n });\n records.set(candidateId, {\n world: input.world,\n candidate,\n historyInvalidated: false,\n });\n meshBytes += candidateBytes;\n currentGeneration = generation;\n // Keep the credential handed to the consumer separate from the\n // renderer-owned copy. Mesh typed arrays remain mutable at runtime even\n // when exposed through a readonly TypeScript field.\n return ok(cloneCandidate(candidate));\n },\n accept(candidate, ordering) {\n if (disposed)\n return failure('dynamic-geometry-disposed', 'renderer is alive', 'rebuild the Renderer');\n const record = current(candidate);\n if (record === undefined)\n return failure(\n 'dynamic-geometry-candidate-not-found',\n 'candidate is owned by this renderer',\n 'discard the stale credential',\n );\n if (candidate.generation !== currentGeneration) {\n return failure(\n 'dynamic-geometry-generation-mismatch',\n 'candidate generation matches the active renderer generation',\n 'prepare against the current renderer generation',\n { candidateId: candidate.candidateId },\n );\n }\n if (record.candidate.state !== 'prepared') {\n return failure(\n 'dynamic-geometry-candidate-state',\n 'candidate is prepared exactly once before acceptance',\n 'retain the accepted or published receipt',\n { candidateId: candidate.candidateId },\n );\n }\n if (!sameCandidateCredential(candidate, record.candidate)) {\n return failure(\n 'dynamic-geometry-receipt-mismatch',\n 'acceptance uses the exact prepared candidate credential',\n 'discard the altered credential and use the value returned by prepare',\n { candidateId: candidate.candidateId },\n );\n }\n if (ordering !== undefined) {\n if (\n ordering.world !== record.world ||\n !Number.isInteger(ordering.fixedStep) ||\n ordering.fixedStep < 0\n ) {\n return failure(\n 'dynamic-geometry-ordering-required',\n 'acceptance ordering names the candidate World and a non-negative fixed step',\n 'submit the PhysicsWorld publication ordering for the same attached World',\n { candidateId: candidate.candidateId, actual: ordering },\n );\n }\n }\n const newest = [...records.values()]\n .filter(\n (entry) =>\n entry.candidate.candidateId !== candidate.candidateId &&\n entry.world === record.world &&\n entry.candidate.entity === record.candidate.entity &&\n (entry.candidate.state === 'prepared' || entry.candidate.state === 'accepted'),\n )\n .map((entry) => entry.candidate.revision)\n .concat(latestRevisionByWorld.get(record.world)?.get(record.candidate.entity) ?? -1)\n .sort((a, b) => b - a)[0];\n if (newest !== undefined && record.candidate.revision <= newest) {\n return failure(\n 'dynamic-geometry-stale',\n 'accepted geometry revision is newer than the active candidate',\n 'advance topology revision before accepting',\n { candidateId: candidate.candidateId },\n );\n }\n const accepted = Object.freeze({\n ...record.candidate,\n ...(ordering === undefined ? {} : { fixedStep: ordering.fixedStep }),\n state: 'accepted' as const,\n });\n const previousTopologies = [...records.values()]\n .filter(\n (entry) =>\n entry.candidate.candidateId !== candidate.candidateId &&\n entry.world === record.world &&\n entry.candidate.entity === record.candidate.entity,\n )\n .map((entry) => entry.candidate.topologyRevision);\n const previousLatestTopology = latestTopologyRevisionByWorld\n .get(record.world)\n ?.get(record.candidate.entity);\n const newestTopology = previousTopologies\n .concat(previousLatestTopology === undefined ? [] : [previousLatestTopology])\n .sort((a, b) => b - a)[0];\n if (newestTopology !== undefined && accepted.topologyRevision < newestTopology) {\n return failure(\n 'dynamic-geometry-stale',\n 'accepted topology revision is not older than the active geometry history',\n 'advance topology revision before accepting a replacement candidate',\n { candidateId: candidate.candidateId },\n );\n }\n if (newestTopology !== undefined && accepted.topologyRevision > newestTopology) {\n historyInvalidations += 1;\n // Invalidate publication eligibility, not resource ownership. The host\n // cancels superseded candidates with their allocation completion fence.\n for (const previous of records.values()) {\n if (\n previous.world !== record.world ||\n previous.candidate.entity !== record.candidate.entity ||\n previous.candidate.candidateId === candidate.candidateId ||\n previous.candidate.topologyRevision >= accepted.topologyRevision\n )\n continue;\n if (!previous.historyInvalidated) {\n previous.historyInvalidated = true;\n invalidated += 1;\n }\n }\n }\n record.candidate = accepted;\n return ok(cloneCandidate(accepted));\n },\n cancel(candidate, completion) {\n const record = current(candidate);\n if (record === undefined)\n return failure(\n 'dynamic-geometry-candidate-not-found',\n 'candidate is owned by this renderer',\n 'discard the stale credential',\n );\n if (!sameCandidateCredential(candidate, record.candidate))\n return failure(\n 'dynamic-geometry-receipt-mismatch',\n 'cancellation uses the exact prepared candidate credential',\n 'discard the altered credential and use the value returned by prepare',\n { candidateId: candidate.candidateId },\n );\n if (record.candidate.state !== 'prepared' && record.candidate.state !== 'accepted') {\n return failure(\n 'dynamic-geometry-candidate-state',\n 'only prepared or accepted geometry can be cancelled once',\n 'retire published geometry or await the existing terminal cleanup',\n );\n }\n record.candidate = Object.freeze({ ...record.candidate, state: 'cancelled' as const });\n const release = (): void => {\n if (records.get(candidate.candidateId) !== record) return;\n records.delete(candidate.candidateId);\n meshBytes = Math.max(0, meshBytes - record.candidate.meshBytes);\n };\n if (completion === undefined) release();\n else void completion.then(release, release);\n return ok(undefined);\n },\n retire(candidate) {\n const record = current(candidate);\n if (record === undefined)\n return failure(\n 'dynamic-geometry-candidate-not-found',\n 'retirement uses a published candidate owned by this renderer',\n 'discard the stale credential and do not evict any unrelated mesh',\n { candidateId: candidate.candidateId },\n );\n if (!sameCandidateCredential(candidate, record.candidate))\n return failure(\n 'dynamic-geometry-receipt-mismatch',\n 'retirement uses the exact published candidate credential',\n 'discard the altered credential and use the value returned by publish',\n { candidateId: candidate.candidateId },\n );\n if (record.candidate.state !== 'published') {\n return failure(\n 'dynamic-geometry-candidate-state',\n 'only published geometry can enter receipt-bound retirement',\n 'publish the candidate from a submitted frame first',\n );\n }\n record.candidate = Object.freeze({ ...record.candidate, state: 'retired' as const });\n publishedReceipts.delete(candidate.candidateId);\n retired += 1;\n // Retiring is the logical state transition. Keep the candidate record\n // and its typed bytes until the owner calls `finalizeRetirement` after\n // every record-stage completion fence and GPU lease are gone. This is\n // what makes the declared count/byte budget include in-flight work.\n return ok(undefined);\n },\n finalizeRetirement(candidate) {\n const record = current(candidate);\n if (record === undefined)\n return failure(\n 'dynamic-geometry-candidate-not-found',\n 'retirement finalization uses a candidate retained by this lifecycle',\n 'discard the stale credential or finish the current receipt-bound retirement',\n );\n if (!sameCandidateCredential(candidate, record.candidate))\n return failure(\n 'dynamic-geometry-receipt-mismatch',\n 'retirement finalization uses the exact published candidate credential',\n 'discard the altered credential and use the value returned by publication',\n { candidateId: candidate.candidateId },\n );\n if (record.candidate.state !== 'retired')\n return failure(\n 'dynamic-geometry-candidate-state',\n 'only a retired candidate can release its deferred budget',\n 'retire the published candidate before finalizing its receipt-bound cleanup',\n { candidateId: candidate.candidateId },\n );\n records.delete(candidate.candidateId);\n meshBytes = Math.max(0, meshBytes - record.candidate.meshBytes);\n return ok(undefined);\n },\n publishFrame(frame, worlds, fixedStep, canPublish, recordStageLane) {\n if (disposed || frame.deviceGeneration !== currentGeneration) return [];\n const receipts: DynamicGeometryReceipt[] = [];\n for (const record of records.values()) {\n const canRepeatPublished =\n record.candidate.state === 'published' &&\n // Attached Renderer publication revalidates the entity binding in\n // `canPublish`, so a history-invalidated candidate can still record\n // a real draw for its live entity. Detached lifecycle publication\n // remains one-shot once that history is invalidated.\n (canPublish !== undefined || !record.historyInvalidated);\n if (record.candidate.state !== 'accepted' && !canRepeatPublished) continue;\n if (worlds !== undefined && !worlds.includes(record.world)) continue;\n if (\n record.candidate.fixedStep !== undefined &&\n (fixedStep === undefined || record.candidate.fixedStep > fixedStep)\n ) {\n continue;\n }\n if (canPublish !== undefined && !canPublish(record.candidate)) continue;\n const consumedLane =\n canPublish === undefined ? undefined : recordStageLane?.(record.candidate);\n record.candidate = Object.freeze({ ...record.candidate, state: 'published' as const });\n const receipt = Object.freeze({\n candidateId: record.candidate.candidateId,\n generation: record.candidate.generation,\n revision: record.candidate.revision,\n topologyRevision: record.candidate.topologyRevision,\n ...(record.candidate.fixedStep === undefined\n ? {}\n : { fixedStep: record.candidate.fixedStep }),\n frameId: frame.frameId,\n deviceGeneration: frame.deviceGeneration,\n recordStageConsumed: canPublish !== undefined,\n ...(consumedLane === undefined ? {} : { recordStageLane: consumedLane }),\n ...(fixedStep === undefined ? {} : { publicationFixedStep: fixedStep }),\n frame: Object.freeze({ ...frame }),\n });\n receipts.push(receipt);\n publishedReceipts.set(record.candidate.candidateId, receipt);\n latestRevision = record.candidate.revision;\n latestFrameId = frame.frameId;\n if (!latestRevisionByWorld.has(record.world))\n latestRevisionByWorld.set(record.world, new Map());\n latestRevisionByWorld\n .get(record.world)\n ?.set(record.candidate.entity, record.candidate.revision);\n if (!latestTopologyRevisionByWorld.has(record.world))\n latestTopologyRevisionByWorld.set(record.world, new Map());\n latestTopologyRevisionByWorld\n .get(record.world)\n ?.set(record.candidate.entity, record.candidate.topologyRevision);\n }\n return receipts;\n },\n invalidateWorld(world, completion) {\n for (const [id, record] of records) {\n if (record.world !== world) continue;\n // An earlier terminal operation already owns this reservation's fence.\n if (record.candidate.state === 'cancelled' || record.candidate.state === 'retired')\n continue;\n publishedReceipts.delete(id);\n record.candidate = Object.freeze({ ...record.candidate, state: 'cancelled' as const });\n const release = (): void => {\n if (records.get(id) !== record) return;\n records.delete(id);\n meshBytes = Math.max(0, meshBytes - record.candidate.meshBytes);\n };\n if (completion === undefined) release();\n else void completion.then(release, release);\n invalidated += 1;\n }\n latestRevisionByWorld.delete(world);\n latestTopologyRevisionByWorld.delete(world);\n },\n invalidateGeneration(generation) {\n if (generation === currentGeneration) return;\n currentGeneration = generation;\n const invalidatedWorlds = new Set<object>();\n for (const [id, record] of records) {\n if (record.candidate.generation !== generation) {\n records.delete(id);\n publishedReceipts.delete(id);\n meshBytes = Math.max(0, meshBytes - record.candidate.meshBytes);\n invalidatedWorlds.add(record.world);\n invalidated += 1;\n }\n }\n for (const world of invalidatedWorlds) {\n latestRevisionByWorld.delete(world);\n latestTopologyRevisionByWorld.delete(world);\n }\n },\n receipt(candidate) {\n const receipt = publishedReceipts.get(candidate.candidateId);\n const record = records.get(candidate.candidateId);\n if (record === undefined || !sameCandidateCredential(candidate, record.candidate)) {\n return undefined;\n }\n return receipt?.generation === candidate.generation ? receipt : undefined;\n },\n inspect() {\n let prepared = 0;\n let accepted = 0;\n let published = 0;\n for (const record of records.values()) {\n if (record.candidate.state === 'prepared') prepared += 1;\n else if (record.candidate.state === 'accepted') accepted += 1;\n else if (record.candidate.state === 'published') published += 1;\n }\n return Object.freeze({\n generation: currentGeneration,\n prepared,\n accepted,\n published,\n retired,\n ...(latestRevision === undefined ? {} : { latestRevision }),\n ...(latestFrameId === undefined ? {} : { latestFrameId }),\n historyInvalidations,\n invalidated,\n meshBytes,\n maxMeshBytes,\n });\n },\n dispose() {\n disposed = true;\n records.clear();\n publishedReceipts.clear();\n meshBytes = 0;\n },\n };\n}\n","import type { Handle } from '@forgeax/engine-types';\nimport type { ExtractedFrame, RenderableSnapshot } from '../render-system-extract';\n\n/** One asset closure for source publication and receiver admission. */\nexport function publicationDependencies(\n row: Pick<RenderableSnapshot, 'assetHandle' | 'materials'>,\n): Handle<string, 'shared'>[] {\n const handles = new Set<Handle<string, 'shared'>>([row.assetHandle as Handle<string, 'shared'>]);\n for (const material of row.materials) {\n for (const handle of [\n material.materialHandle,\n material.baseColorTexture,\n material.metallicRoughnessTexture,\n material.normalTexture,\n material.emissiveTexture,\n material.occlusionTexture,\n ]) {\n if (handle) handles.add(handle as Handle<string, 'shared'>);\n }\n for (const handle of material.textureHandles?.values() ?? []) handles.add(handle);\n for (const handle of material.samplerHandles?.values() ?? []) handles.add(handle);\n }\n return [...handles];\n}\n\n/** Resources selected once for the frame rather than attached to geometry. */\nexport function publicationFrameDependencies(\n frame: Pick<\n ExtractedFrame,\n 'cameras' | 'auxiliaryCameras' | 'skylight' | 'skybox' | 'lights' | 'volumetricFog'\n >,\n): Handle<string, 'shared'>[] {\n const handles = new Set<Handle<string, 'shared'>>();\n const add = (handle: number | undefined) => {\n if (handle) handles.add(handle as Handle<string, 'shared'>);\n };\n add(frame.skylight?.equirectHandle);\n add(frame.skybox?.equirectHandle);\n for (const camera of [...frame.cameras, ...frame.auxiliaryCameras]) add(camera.output?.colorLut);\n for (const light of frame.lights.spot) {\n add(light.iesProfileHandle);\n add(light.cookieHandle);\n add(light.projectorHandle);\n }\n const fogs =\n frame.volumetricFog === undefined\n ? []\n : [frame.volumetricFog, ...(frame.volumetricFog.additional ?? [])];\n for (const fog of fogs) {\n add(fog.densityHandle);\n add(fog.projectorHandle);\n }\n return [...handles];\n}\n","// @forgeax/engine-runtime - tilemap-chunk-extract-system.\n//\n// Walks every TileLayer attached to a Tilemap via ChildOf; when a layer is\n// dirty (or has never been extracted), purges its previously-spawned derived\n// per-cell entities and re-spawns one ECS entity per non-zero cell. Each\n// derived entity carries Transform + MeshFilter (HANDLE_QUAD) + MeshRenderer\n// + Layer + ChildOf { parent: layerEntity }. The ChildOf edge lets\n// `world.despawn(tilemapEntity)` cascade-despawn the entire subtree\n// (Tilemap -> TileLayer -> derived render entities) via the engine's\n// default `linkedSpawn: true` (tweak-20260714 M2, requirements AC-02/03/04).\n//\n// M0 baseline: unit-cell 1x1 form, single-atlas, no UV inset.\n// M2 extension (plan-strategy §D-2 + §D-7 step 3):\n// M3 extension (plan-strategy §D-7 step 2 + §D-12):\n// - resolveTilesetMaterial walks the 3-hop chain\n// `tile.regionIndex -> regions[i].atlasIndex ?? 0 -> atlases[idx]`\n// so multi-atlas tilesets route each region to the correct GPU\n// texture handle (requirements AC-04 / AC-11). Cache key stays\n// binary `(atlasHandle, regionIndex)` -- atlasHandle already\n// encodes the atlas pick.\n// - spawnDerivedRenderEntities scales the quad by widthCells x\n// heightCells (defaults 1 x 1) and offsets the centre so the pivot\n// lands at the (pivotX, pivotY) location inside the anchor cell.\n// - basePivotForX = D ? pivotY : pivotX (and dually for Y), so the\n// 90deg CW z-rotation correctly swaps which atlas-axis pivot maps\n// to which world axis.\n// - effectivePivotX = H ? (1 - basePivotForX) : basePivotForX (and\n// dually for Y). The anchor pivot under H flip lands at the\n// mirrored cell position (charter P4 - same semantics as Tiled's\n// \"pivot stays in atlas-local coords, flips with the texel grid\").\n// - posX = (cellX + effectivePivotX + (0.5 - effectivePivotX) * widthCells)\n// * tileSizeX\n// posY analogous with effectivePivotY + heightCells.\n// - scaleX/scaleY: signed by H/V flip; magnitude is widthCells *\n// tileSizeX / heightCells * tileSizeY (multi-cell scale).\n// - resolveTilesetMaterial inset-shrinks the region UV rectangle by\n// half a texel on every edge so GPU bilinear filtering at the\n// atlas-tile boundary never bleeds into the adjacent tile\n// (charter P3 - default behaviour avoids visual defects).\n//\n// M3 boundary: per-entity sort key with effectivePivotY is wired in\n// render-system-extract (m3-t5), not here.\n//\n// Cache key for resolveTilesetMaterial is BINARY: (atlasHandle, regionIndex).\n// AI users widthCells / pivot variations share the same material handle\n// (charter P4 consistent abstraction; plan-strategy §D-9 / §D-12).\n//\n// Anchors: plan-tasks m0-t10 / m2-t2 / m2-t4; plan-strategy §D-1 +\n// §D-2 (multi-cell + flip x pivot) + §D-5 (M0 baseline file-by-file\n// ECS API adaptation) + §D-7 step 3 (half-texel UV inset).\n\nimport {\n HANDLE_QUAD,\n resolveTilesetRuntime,\n type TilesetAtlasLookup,\n} from '@forgeax/engine-assets-runtime';\nimport type { EntityHandle, World } from '@forgeax/engine-ecs';\nimport { decodeTileBits } from '@forgeax/engine-graphics-extras';\nimport { type box3, frustum, mat4 } from '@forgeax/engine-math';\nimport { ChildOf, Children, GlobalTransform, Transform } from '@forgeax/engine-scene';\nimport {\n type Handle,\n type MaterialAsset,\n type TilesetAsset,\n type TilesetRegion,\n type TilesetTileEntry,\n toShared,\n unwrapHandle,\n} from '@forgeax/engine-types';\nimport {\n CAMERA_PROJECTION_ORTHOGRAPHIC,\n Camera,\n decodeSortScope,\n Layer,\n MeshFilter,\n MeshRenderer,\n type SortScope,\n SpriteInstances,\n TileLayer,\n Tilemap,\n} from './components';\nimport { SPRITE_PREMULTIPLIED_ALPHA_BLEND } from './materials';\n\n// Module-scoped caches (charter P5 — engine-side memoisation; AI users\n// never reach in). Test harness can flush them via the reset helpers.\n//\n// Two material caches coexist because the extract system produces two\n// kinds of derived entities, each with a different material-key granularity:\n//\n// 1. `atlasMaterialCache` — key `${atlasId}|${regionIndex}` → per-region\n// material with the UV rectangle baked into `values.region`.\n// Used by the per-cell entity path (sortScope='per-cell' object\n// layers). Each tile graphic gets a distinct MaterialAsset.\n//\n// 2. `atlasOnlyMaterialCache` — key `${atlasId}` → per-atlas material\n// with `values.region: [0,0,1,1]` placeholder. Used by the\n// SpriteInstances batched path (sortScope='layer' terrain layers).\n// The shader's PER_INSTANCE_REGION=true variant reads per-instance\n// UV from the instance buffer, not from the material UBO, so the\n// placeholder is ignored at draw time.\nlet atlasMaterialCache = new WeakMap<World, Map<string, Handle<'MaterialAsset', 'shared'>>>();\nlet atlasOnlyMaterialCache = new WeakMap<World, Map<string, Handle<'MaterialAsset', 'shared'>>>();\n// tweak-20260714 M3 (plan-strategy §2 D-3): the terrain (sortScope='layer')\n// derived-entity tracker Map + first-frame-heuristic Set that used to live\n// alongside these material caches were retired once every derived entity\n// was attached as `ChildOf` child of its TileLayer (M2). The reverse\n// mirror `Children.entities` on the TileLayer is now the SSOT for\n// \"which derived entities belong to this layer\" — engine-maintained on\n// `world.addComponent(ChildOf) / world.despawn`, deriving-not-duplicating\n// (architecture-principles §2). `purgeDerivedEntities` reads that mirror\n// directly; the \"already built\" gate uses `Children.entities.length > 0`,\n// which naturally handles both first frames (empty ⇒ rebuild) and steady\n// state (populated ⇒ skip) without a second parallel ledger.\n\n// ─── Chunk-streaming state for sortScope='per-cell' (object) layers ───────\n//\n// Object layers stream per-chunk: only chunks whose world AABB intersects the\n// camera frustum have per-cell entities alive in the ECS world. This keeps\n// extractFrame's entity count proportional to visible tile count rather than\n// total map tile count (charter P5: engine-side memoisation / streaming).\n//\n// Design: one WeakMap entry per World owns three bounded maps:\n// layers : layerKey → pre-bucketed specs by chunkIndex (built once\n// from bucketTileLayer, rebuilt on dirty). Avoids re-reading\n// the full tileset and re-materialising every frame.\n// chunkEntities : \"${layerKey}:${chunkIdx}\" → spawned entity ids\n// for that chunk (purged when chunk leaves frustum).\n// activeChunks : layerKey → Set<chunkIdx> currently spawned.\n//\n// bug-20260703-tilemap-chunk-stale-frustum-and-cull-overhang (D2): each entry\n// stores the ACTUAL world-space bounding box (union of every tile's post-TRS\n// footprint from `computeTileTrs`) rather than a tile-aligned grid box.\n// Multi-cell tiles (`widthCells` / `heightCells > 1`) and non-central pivots\n// let a tile extend beyond its anchor chunk's grid; the grid box would\n// despawn the anchor chunk while overhanging tiles were still on screen,\n// causing edge-of-chunk flicker as the camera pans. Bounds are computed once\n// per (dirty | first-time) rebuild, so the per-frame visibility test stays a\n// single `frustum.intersectsBox` call (plan-strategy §2 D-3).\ninterface ChunkStreamEntry {\n readonly specs: readonly DerivedSpawnSpec[];\n readonly bounds: box3.Box3Like;\n}\ninterface StreamLayerCache {\n readonly byChunk: ReadonlyMap<number, ChunkStreamEntry>;\n readonly tilemap: {\n readonly cols: number;\n readonly rows: number;\n readonly tileSize: ArrayLike<number>;\n readonly chunkSize: number;\n };\n readonly layerOrder: number;\n readonly sortScope: SortScope;\n}\ninterface PerWorldStreamingCache {\n readonly layers: Map<string, StreamLayerCache>;\n readonly chunkEntities: Map<string, EntityHandle[]>;\n readonly activeChunks: Map<string, Set<number>>;\n}\n\nlet streamingCacheByWorld = new WeakMap<World, PerWorldStreamingCache>();\n\nfunction streamingCache(world: World): PerWorldStreamingCache {\n let cache = streamingCacheByWorld.get(world);\n if (cache === undefined) {\n cache = {\n layers: new Map(),\n chunkEntities: new Map(),\n activeChunks: new Map(),\n };\n streamingCacheByWorld.set(world, cache);\n }\n return cache;\n}\n\n/**\n * Flush both material caches. Useful in test harnesses + after a\n * TilesetAsset reload.\n */\nexport function resetTilemapChunkExtractCache(): void {\n atlasMaterialCache = new WeakMap<World, Map<string, Handle<'MaterialAsset', 'shared'>>>();\n atlasOnlyMaterialCache = new WeakMap<World, Map<string, Handle<'MaterialAsset', 'shared'>>>();\n}\n\n/**\n * Flush the per-cell streaming caches. Useful in test harnesses + when\n * the World is re-created.\n *\n * Signature preserved (AC-08 hard constraint) after tweak-20260714 M3\n * retired the terrain-side tracker Map + first-frame heuristic Set:\n * terrain layers now derive their \"already-built\" state from\n * `Children.entities` on the TileLayer (mirror of ChildOf, engine-\n * maintained), so the tracker only needs to clear the 3 streaming\n * caches (plan-strategy §2 D-3 + §2 D-5).\n */\nexport function resetTilemapDerivedEntityTracker(): void {\n streamingCacheByWorld = new WeakMap<World, PerWorldStreamingCache>();\n}\n\n/**\n * @internal Test-only helper for AC-11 (tweak-20260714 M4). Returns the\n * union of `layerKey`s currently referenced by the three per-cell\n * streaming caches. Post-diff-cleanup, an evicted layerKey MUST NOT\n * appear here; a slot subsequently reused for a fresh TileLayer sees\n * empty caches and rebuilds from zero (plan-strategy §2 D-4).\n *\n * Parsing the per-World `chunkEntities` key format `${entity}:${chunkIdx}`\n * is intentional so callers observe cleanup on all three maps without\n * depending on the invariant `activeSet ↔ chunkEntities\n * keys are paired` — the test then also cross-checks that invariant.\n */\nexport function _peekPerCellStreamingLayerKeys(world: World): readonly number[] {\n const cache = streamingCacheByWorld.get(world);\n if (cache === undefined) return [];\n const out = new Set<number>();\n for (const layerKey of cache.layers.keys()) {\n if (Number.isFinite(Number(layerKey))) out.add(Number(layerKey));\n }\n for (const layerKey of cache.activeChunks.keys()) {\n if (Number.isFinite(Number(layerKey))) out.add(Number(layerKey));\n }\n for (const key of cache.chunkEntities.keys()) {\n const parts = key.split(':');\n const entity = parts[0];\n if (entity !== undefined && Number.isFinite(Number(entity))) out.add(Number(entity));\n }\n return Array.from(out);\n}\n\n/**\n * Compute the per-layer / per-chunk packed value carried in `Layer.value`\n * on derived entities. `sortScope` is the closed string union from\n * `TileLayer.sortScope`:\n * - `'layer'` (default): `(layerOrder << 20) | (chunkIndex & 0xFFFFF)` —\n * terrain semantics, layerOrder dominates with chunkIndex\n * tiebreak within the layer.\n * - `'per-cell'`: returns `(layerOrder << 20)` (chunkIndex folded to 0)\n * so every derived entity in the layer shares one\n * Layer.value and can Y-interleave with sprite entities\n * carrying the same value (e.g. a player sprite riding\n * `SPRITE_LAYER_VALUE = layerOrder << 20`).\n *\n * Round-2 rename (D-V-3): the third arg was `ySort: boolean` before the\n * sortScope union landed; it is now the closed `SortScope` union with\n * default `'layer'`. The 0x200000 / chunked-bits semantics for the two\n * arms are preserved exactly so existing pixel-parity baselines stay\n * stable (only the AI-user surface widens to a self-documenting literal).\n */\nexport function encodeTilemapLayerValue(\n layerOrder: number,\n chunkIndex: number,\n sortScope: SortScope = 'layer',\n): number {\n if (sortScope === 'per-cell') return (layerOrder << 20) | 0;\n return (layerOrder << 20) | (chunkIndex & 0xfffff) | 0;\n}\n\n/**\n * Resolve (regionIndex) into a per-tile sprite material handle by walking\n * the 3-hop chain:\n *\n * tile.regionIndex -> regions[regionIndex] -> region.atlasIndex ?? 0\n * -> atlases[atlasIndex]\n *\n * (plan-strategy §D-7 step 2 + requirements §AC-04 / §AC-11). Caches the\n * resulting MaterialAsset handle so repeated lookups hit a single\n * registered material per atlas-region pair; the cache key stays the\n * binary tuple `(atlasHandle, regionIndex)` -- atlasHandle already\n * encodes the atlasIndex pick so widening to a 3-tuple key would only\n * inflate the SSOT without adding signal (charter P4 + plan-strategy\n * §D-12). atlasIndex out-of-range is caught at register time by\n * `validateTilesetPayload` (m1-t6); the runtime resolver falls through\n * to handle 0 when an atlas slot is unexpectedly empty so the renderer\n * skips the draw rather than silently sampling the wrong texture\n * (charter P3 fail-safe).\n *\n * The shader is `forgeax::sprite`; values are filled with the atlas\n * texture handle + a UV region rectangle covering the supplied\n * TilesetRegion (half-texel inset added in m2-t4).\n */\nfunction resolveTilesetMaterial(\n world: World,\n tileset: TilesetAsset,\n regionIndex: number,\n lookup: (guid: string) => TilesetAtlasLookup,\n): Handle<'MaterialAsset', 'shared'> {\n const region = tileset.regions[regionIndex];\n if (region === undefined) return toShared<'MaterialAsset'>(0);\n // 3-hop walk: regions[i].atlasIndex (default 0) -> atlases[atlasIndex].\n // atlasIndex out-of-range is register-time fail-fast via\n // `validateTilesetPayload` (m1-t6); the runtime resolver still bails\n // when the slot is unexpectedly empty (charter P3 fail-safe).\n const atlasIndex = region.atlasIndex ?? 0;\n const atlasGuid = tileset.atlases[atlasIndex];\n if (atlasGuid === undefined) return toShared<'MaterialAsset'>(0);\n const atlas = resolveTilesetRuntime(world, atlasGuid, lookup);\n if (!atlas.ok) return toShared<'MaterialAsset'>(0);\n const atlasHandle = atlas.value.handle;\n const atlasId = unwrapHandle(atlasHandle);\n const cacheKey = `${atlasId}|${regionIndex}`;\n const cache =\n atlasMaterialCache.get(world) ?? new Map<string, Handle<'MaterialAsset', 'shared'>>();\n atlasMaterialCache.set(world, cache);\n const cached = cache.get(cacheKey);\n if (cached !== undefined) return cached;\n\n // Atlas-space rectangle -> normalised UV. M2 adds a half-texel inset\n // on every edge (plan-strategy §D-7 step 3) so GPU bilinear filtering\n // at the region boundary never samples the adjacent atlas tile. Atlas\n // pixel extent comes from atlasSizes[atlasIndex] when present (exact\n // per-atlas pixel dimensions); falls back to columns * tileWidth for\n // single-atlas or legacy callers.\n const atlasSize = tileset.atlasSizes?.[atlasIndex];\n const atlasWidth = Math.max(\n 1,\n atlasSize !== undefined ? atlasSize.pixelWidth : tileset.columns * tileset.tileWidth,\n );\n const atlasHeight = Math.max(\n 1,\n atlasSize !== undefined ? atlasSize.pixelHeight : tileset.rows * tileset.tileHeight,\n );\n const halfTexelU = 0.5 / atlasWidth;\n const halfTexelV = 0.5 / atlasHeight;\n const u = region.x / atlasWidth + halfTexelU;\n const v = region.y / atlasHeight + halfTexelV;\n const w = region.width / atlasWidth - 2 * halfTexelU;\n const h = region.height / atlasHeight - 2 * halfTexelV;\n\n const matPayload: MaterialAsset = {\n kind: 'material',\n passes: [\n {\n name: 'Forward',\n program: { module: 'forgeax::sprite' },\n renderState: {\n ...{ blend: SPRITE_PREMULTIPLIED_ALPHA_BLEND },\n tags: { LightMode: 'Forward' },\n queue: 3000,\n },\n },\n ],\n values: {\n colorTint: [1.0, 1.0, 1.0, 1.0],\n baseColorTexture: atlasHandle,\n region: [u, v, w, h],\n pivotAndSize: [0.5, 0.5, 1.0, 1.0],\n flipY: 1.0,\n },\n };\n const matHandle = world.allocSharedRef<'MaterialAsset', MaterialAsset>(\n 'MaterialAsset',\n matPayload,\n );\n cache.set(cacheKey, matHandle);\n return matHandle;\n}\n\n/**\n * Resolve an atlas-only sprite material (no baked-in UV region). One\n * material per atlas — used by the SpriteInstances batched draw path\n * (sortScope='layer'). The per-instance UV region rectangle lives in the\n * `SpriteInstances.regions` buffer instead of in the material UBO.\n *\n * `values.region` is a `[0, 0, 1, 1]` placeholder. The sprite shader's\n * `PER_INSTANCE_REGION=true` variant reads region from\n * `instances[idx].region` and ignores the material slot; selecting that\n * variant is the record stage's responsibility (see\n * `render-system-record.ts` sprite pass pipeline selection).\n *\n * Returns the registered MaterialAsset slot id (unwrapped Handle u32) or\n * 0 if the atlas slot is empty (charter P3 fail-safe; mirrors\n * `resolveTilesetMaterial`).\n */\nfunction resolveAtlasOnlyMaterial(\n world: World,\n tileset: TilesetAsset,\n atlasIndex: number,\n lookup: (guid: string) => TilesetAtlasLookup,\n): Handle<'MaterialAsset', 'shared'> {\n const atlasGuid = tileset.atlases[atlasIndex];\n if (atlasGuid === undefined) return toShared<'MaterialAsset'>(0);\n const atlas = resolveTilesetRuntime(world, atlasGuid, lookup);\n if (!atlas.ok) return toShared<'MaterialAsset'>(0);\n const atlasHandle = atlas.value.handle;\n const atlasId = unwrapHandle(atlasHandle);\n const cacheKey = String(atlasId);\n const cache =\n atlasOnlyMaterialCache.get(world) ?? new Map<string, Handle<'MaterialAsset', 'shared'>>();\n atlasOnlyMaterialCache.set(world, cache);\n const cached = cache.get(cacheKey);\n if (cached !== undefined) return cached;\n\n const matPayload: MaterialAsset = {\n kind: 'material',\n passes: [\n {\n name: 'Forward',\n program: { module: 'forgeax::sprite' },\n renderState: {\n ...{ blend: SPRITE_PREMULTIPLIED_ALPHA_BLEND },\n tags: { LightMode: 'Forward' },\n queue: 3000,\n },\n },\n ],\n values: {\n colorTint: [1.0, 1.0, 1.0, 1.0],\n baseColorTexture: atlasHandle,\n region: [0.0, 0.0, 1.0, 1.0],\n pivotAndSize: [0.5, 0.5, 1.0, 1.0],\n flipY: 1.0,\n },\n };\n const matHandle = world.allocSharedRef<'MaterialAsset', MaterialAsset>(\n 'MaterialAsset',\n matPayload,\n );\n cache.set(cacheKey, matHandle);\n return matHandle;\n}\n\n/**\n * Compute the half-texel-inset normalised UV rectangle for a TilesetRegion\n * (atlas-space pixels → atlas-normalised [u, v, w, h]). Mirrors the inset\n * computation inside `resolveTilesetMaterial` so the per-instance region\n * data fed into `SpriteInstances.regions` produces pixel-identical sampling\n * to the per-region material path (charter P4 consistent abstraction).\n */\nfunction computeRegionUv(\n tileset: TilesetAsset,\n region: TilesetRegion,\n atlasIndex: number,\n): [u: number, v: number, w: number, h: number] {\n const atlasSize = tileset.atlasSizes?.[atlasIndex];\n const atlasWidth = Math.max(\n 1,\n atlasSize !== undefined ? atlasSize.pixelWidth : tileset.columns * tileset.tileWidth,\n );\n const atlasHeight = Math.max(\n 1,\n atlasSize !== undefined ? atlasSize.pixelHeight : tileset.rows * tileset.tileHeight,\n );\n const halfTexelU = 0.5 / atlasWidth;\n const halfTexelV = 0.5 / atlasHeight;\n return [\n region.x / atlasWidth + halfTexelU,\n region.y / atlasHeight + halfTexelV,\n region.width / atlasWidth - 2 * halfTexelU,\n region.height / atlasHeight - 2 * halfTexelV,\n ];\n}\n\ninterface DerivedSpawnSpec {\n readonly cellX: number;\n readonly cellY: number;\n readonly tileId: number;\n readonly packedTile: number;\n readonly materialHandle: Handle<'MaterialAsset', 'shared'>;\n readonly chunkIndex: number;\n // M2: multi-cell footprint + custom pivot land per-tile via TilesetTileEntry.\n readonly widthCells: number;\n readonly heightCells: number;\n readonly pivotX: number;\n readonly pivotY: number;\n // Atlas + region indices retained so the SpriteInstances (sortScope=\n // 'layer') path can group cells by atlas and look up per-instance UV\n // without re-walking the 3-hop chain `tileId → regions → atlasIndex`.\n readonly atlasIndex: number;\n readonly regionIndex: number;\n}\n\nconst SQRT1_2 = Math.SQRT1_2;\n\n/**\n * Compute the post-flip \"effective pivot Y\" for a tilemap tile entry.\n *\n * Mirrors the D-2 first-line composition used by `spawnDerivedRenderEntities`:\n *\n * basePivotForY = flipDiagonal ? pivotX : pivotY\n * effectivePivotY = flipV ? (1 - basePivotForY) : basePivotForY\n *\n * Exported so the render-system-extract sprite-bucket sort key path can\n * reproduce the *same* per-entity pivot value that landed on\n * `Transform.posY` -- otherwise the foot-Y formula\n * `posY - effectivePivotY * |scaleY|` would drift on flipped tiles\n * (charter P4 single-source pivot SSOT; plan-strategy §D-1 + §D-2 +\n * requirements §AC-12 / §AC-13).\n */\nexport function effectivePivotYForTilemapFlip(\n pivotY: number,\n pivotX: number,\n flipV: boolean,\n flipDiagonal: boolean,\n): number {\n const base = flipDiagonal ? pivotX : pivotY;\n return flipV ? 1 - base : base;\n}\n\n/**\n * Compute the per-cell derived spawn spec for one non-zero cell. Carries\n * widthCells / heightCells / pivotX / pivotY from the TilesetTileEntry so\n * `spawnDerivedRenderEntities` can apply the D-2 geometric correction\n * without re-reading the asset registry.\n */\nfunction specFor(\n layerCols: number,\n chunkSize: number,\n cellIndex: number,\n packedTile: number,\n materialHandle: Handle<'MaterialAsset', 'shared'>,\n entry: TilesetTileEntry,\n atlasIndex: number,\n): DerivedSpawnSpec {\n const cellX = cellIndex % layerCols;\n const cellY = Math.floor(cellIndex / layerCols);\n const chunkX = Math.floor(cellX / chunkSize);\n const chunkY = Math.floor(cellY / chunkSize);\n const chunksPerRow = Math.max(1, Math.ceil(layerCols / chunkSize));\n const chunkIndex = chunkY * chunksPerRow + chunkX;\n const { tileId } = decodeTileBits(packedTile);\n return {\n cellX,\n cellY,\n tileId,\n packedTile,\n materialHandle,\n chunkIndex,\n widthCells: entry.widthCells ?? 1,\n heightCells: entry.heightCells ?? 1,\n pivotX: entry.pivotX ?? 0.5,\n pivotY: entry.pivotY ?? 0.5,\n atlasIndex,\n regionIndex: entry.regionIndex,\n };\n}\n\n/**\n * Compute the post-flip TRS components for one tile cell. The plan-strategy\n * §D-2 multi-cell + flip x pivot composite formula (first-line form):\n *\n * basePivotForX = D ? pivotY : pivotX\n * basePivotForY = D ? pivotX : pivotY\n * effectivePivotX = H ? (1 - basePivotForX) : basePivotForX\n * effectivePivotY = V ? (1 - basePivotForY) : basePivotForY\n * posX = (cellX + effectivePivotX + (0.5 - effectivePivotX) * widthCells)\n * * tileSizeX\n * posY = (cellY + effectivePivotY + (0.5 - effectivePivotY) * heightCells)\n * * tileSizeY\n * scaleX = (H ? -1 : 1) * widthCells * tileSizeX\n * scaleY = (V ? -1 : 1) * heightCells * tileSizeY\n * quatZ = D ? Math.SQRT1_2 : 0\n * quatW = D ? Math.SQRT1_2 : 1\n *\n * Single SSOT consumed by both the per-cell entity spawn path and the\n * SpriteInstances batched path so the two routes produce pixel-identical\n * world transforms (charter P4 consistent abstraction).\n */\nfunction computeTileTrs(\n tilemap: { tileSize: ArrayLike<number> },\n spec: DerivedSpawnSpec,\n packedTile: number,\n): {\n posX: number;\n posY: number;\n scaleX: number;\n scaleY: number;\n quatZ: number;\n quatW: number;\n} {\n const { flipH, flipV, flipDiagonal } = decodeTileBits(packedTile);\n const basePivotForX = flipDiagonal ? spec.pivotY : spec.pivotX;\n const effectivePivotX = flipH ? 1 - basePivotForX : basePivotForX;\n const effectivePivotY = effectivePivotYForTilemapFlip(\n spec.pivotY,\n spec.pivotX,\n flipV,\n flipDiagonal,\n );\n const tileSizeX = tilemap.tileSize[0] ?? 1;\n const tileSizeY = tilemap.tileSize[1] ?? 1;\n return {\n posX: (spec.cellX + effectivePivotX + (0.5 - effectivePivotX) * spec.widthCells) * tileSizeX,\n posY: (spec.cellY + effectivePivotY + (0.5 - effectivePivotY) * spec.heightCells) * tileSizeY,\n scaleX: (flipH ? -1 : 1) * spec.widthCells * tileSizeX,\n scaleY: (flipV ? -1 : 1) * spec.heightCells * tileSizeY,\n quatZ: flipDiagonal ? SQRT1_2 : 0,\n quatW: flipDiagonal ? SQRT1_2 : 1,\n };\n}\n\n/**\n * Spawn a single derived per-cell render entity. Used by the per-cell\n * sortScope path (`sortScope='per-cell'`, object layers) where each cell\n * needs an independent Y-sort position to interleave with sprite entities\n * (e.g. player) at arbitrary Y positions.\n *\n * `layerEntity` becomes the derived entity's `ChildOf.parent`, so\n * `world.despawn(layerEntity)` cascade-despawns every derived cell entity\n * via the engine's `linkedSpawn: true` default (feat-20260616). Combined\n * with the Tilemap -> TileLayer ChildOf edge, a single\n * `world.despawn(tilemapEntity)` unwinds the entire subtree without a\n * bespoke tilemap-scoped cleanup pass (requirements AC-02 / AC-03).\n */\nfunction spawnDerivedRenderEntities(\n world: World,\n tilemap: { tileSize: ArrayLike<number> },\n layerEntity: EntityHandle,\n layerOrder: number,\n spec: DerivedSpawnSpec,\n packedTile: number,\n sortScope: SortScope = 'layer',\n): EntityHandle {\n const { posX, posY, scaleX, scaleY, quatZ, quatW } = computeTileTrs(tilemap, spec, packedTile);\n const layerValue = encodeTilemapLayerValue(layerOrder, spec.chunkIndex, sortScope);\n return world\n .spawn(\n {\n component: Transform,\n data: {\n pos: [posX, posY, 0],\n quat: [0, 0, quatZ, quatW],\n scale: [scaleX, scaleY, 1],\n },\n },\n { component: MeshFilter, data: { assetHandle: HANDLE_QUAD } },\n {\n component: MeshRenderer,\n data: {\n materials: [spec.materialHandle],\n },\n },\n { component: Layer, data: { value: layerValue } },\n { component: ChildOf, data: { parent: layerEntity } },\n )\n .unwrap();\n}\n\n/**\n * Spawn one batched SpriteInstances entity per (TileLayer, chunk, atlas)\n * group. Used by the `sortScope='layer'` path (terrain layers): every\n * cell in the group becomes one instance in the same drawIndexed call.\n *\n * The chunk grid is the unit declared by `Tilemap.chunkSize` (default\n * 16x16). One SpriteInstances entity per (chunk, atlas) pair keeps each\n * GPU instance buffer small (256 cells x 80B = 20KB worst case) and lets\n * downstream frustum culling / incremental rebuild operate at chunk\n * granularity (industry standard: Godot quadrant_size, Bevy ChunkSize,\n * Tiled TMX chunks).\n *\n * Layout:\n * - Transform: identity (the per-instance mat4 carries world-space TRS).\n * - MeshFilter: HANDLE_QUAD.\n * - MeshRenderer: atlas-only sprite material (region placeholder; shader\n * reads per-instance UV from SpriteInstances.regions under the\n * PER_INSTANCE_REGION=true variant — selected at record stage).\n * - SpriteInstances: { transforms: Float32Array(N*16),\n * regions: Float32Array(N*4) }.\n * - Layer: encodeTilemapLayerValue(layerOrder, chunkIndex, 'layer').\n * chunkIndex distinguishes adjacent chunks of the same layer in the\n * transparent-sort key so the back-to-front ordering between chunks\n * remains stable (chunks within a layer don't visually overlap in\n * normal tilemap scenes; the chunkIndex tiebreaker is byte-exact\n * with the per-cell path's encoding).\n *\n * Returns the spawned EntityHandle. Empty groups (zero cells) short-circuit\n * and return `undefined`.\n */\nfunction spawnSpriteInstancesGroup(\n world: World,\n tilemap: { cols: number; tileSize: ArrayLike<number>; chunkSize: number },\n tileset: TilesetAsset,\n layerEntity: EntityHandle,\n layerOrder: number,\n chunkIndex: number,\n atlasIndex: number,\n materialHandle: Handle<'MaterialAsset', 'shared'>,\n cellSpecs: readonly DerivedSpawnSpec[],\n): EntityHandle | undefined {\n if (cellSpecs.length === 0) return undefined;\n const N = cellSpecs.length;\n const transforms = new Float32Array(N * 16);\n const regions = new Float32Array(N * 4);\n const tmpMat = mat4.create();\n const tmpT: [number, number, number] = [0, 0, 0];\n const tmpR: [number, number, number, number] = [0, 0, 0, 1];\n const tmpS: [number, number, number] = [1, 1, 1];\n\n // Per-chunk frustum cull: entity Transform = chunk world center + chunk\n // extents (scaleX/Y). The frustum culler reads the entity AABB (HANDLE_QUAD\n // local [-0.5, 0.5]² expanded by entity scale/pos) → world AABB exactly\n // covers the chunk footprint.\n //\n // Per-instance transforms become chunk-local: inv_chunk * world_tile.\n // inv_chunk is a pure TRS-inverse (no rotation), so for each column c of\n // the world mat W:\n // local[c*4+0] = (W[c*4+0] - chunkCenterX * W[c*4+3]) * invSX\n // local[c*4+1] = (W[c*4+1] - chunkCenterY * W[c*4+3]) * invSY\n // local[c*4+2] = W[c*4+2]\n // local[c*4+3] = W[c*4+3]\n // The sprite shader then produces:\n // world = chunk_TRS * local_tile * pos_local\n // = chunk_TRS * (inv_chunk * world_tile) * pos_local\n // = world_tile * pos_local ✓ (pixel-identical to identity path)\n //\n // Tiles whose widthCells/heightCells straddle a chunk boundary will have\n // instance transforms that exceed the chunk AABB; the entity is still drawn\n // (conservative cull only skips when the chunk AABB is fully outside).\n const chunksPerRow = Math.max(1, Math.ceil(tilemap.cols / tilemap.chunkSize));\n const chunkX = chunkIndex % chunksPerRow;\n const chunkY = Math.floor(chunkIndex / chunksPerRow);\n const chunkScaleX = tilemap.chunkSize * (tilemap.tileSize[0] ?? 1);\n const chunkScaleY = tilemap.chunkSize * (tilemap.tileSize[1] ?? 1);\n const chunkCenterX = (chunkX + 0.5) * chunkScaleX;\n const chunkCenterY = (chunkY + 0.5) * chunkScaleY;\n const invSX = chunkScaleX > 0 ? 1 / chunkScaleX : 1;\n const invSY = chunkScaleY > 0 ? 1 / chunkScaleY : 1;\n\n for (let i = 0; i < N; i++) {\n const spec = cellSpecs[i] as DerivedSpawnSpec;\n const { posX, posY, scaleX, scaleY, quatZ, quatW } = computeTileTrs(\n tilemap,\n spec,\n spec.packedTile,\n );\n tmpT[0] = posX;\n tmpT[1] = posY;\n tmpT[2] = 0;\n tmpR[0] = 0;\n tmpR[1] = 0;\n tmpR[2] = quatZ;\n tmpR[3] = quatW;\n tmpS[0] = scaleX;\n tmpS[1] = scaleY;\n tmpS[2] = 1;\n mat4.compose(tmpMat, tmpT, tmpR, tmpS);\n\n // Write chunk-local transform: inv_chunk * world_tile (see formula above).\n const dst = i * 16;\n for (let c = 0; c < 4; c++) {\n const base = c * 4;\n const w3 = tmpMat[base + 3] ?? 0;\n transforms[dst + base + 0] = ((tmpMat[base + 0] ?? 0) - chunkCenterX * w3) * invSX;\n transforms[dst + base + 1] = ((tmpMat[base + 1] ?? 0) - chunkCenterY * w3) * invSY;\n transforms[dst + base + 2] = tmpMat[base + 2] ?? 0;\n transforms[dst + base + 3] = w3;\n }\n\n const region = tileset.regions[spec.regionIndex];\n if (region !== undefined) {\n const [u, v, w, h] = computeRegionUv(tileset, region, atlasIndex);\n regions[i * 4 + 0] = u;\n regions[i * 4 + 1] = v;\n regions[i * 4 + 2] = w;\n regions[i * 4 + 3] = h;\n }\n }\n\n const layerValue = encodeTilemapLayerValue(layerOrder, chunkIndex, 'layer');\n // plan-strategy D-2: the SpriteInstances entity's Transform.posY is set\n // to `chunkCenterY` (becomes `world[13]` in the entity's local-to-world\n // matrix). This is the LAYER_Y fold sort key — terrain rows share a\n // chunk Y, so per-chunk Y resolution is exactly the granularity the\n // fold pass needs. Per-tile world[13] (instance-level) is intentionally\n // _not_ used; instances live in the chunk-local space anchored at\n // chunkCenterY (see line 601-647 above). This is intentional, not a bug.\n return world\n .spawn(\n {\n component: Transform,\n data: {\n pos: [chunkCenterX, chunkCenterY, 0],\n quat: [0, 0, 0, 1],\n scale: [chunkScaleX, chunkScaleY, 1],\n },\n },\n { component: MeshFilter, data: { assetHandle: HANDLE_QUAD } },\n {\n component: MeshRenderer,\n data: {\n materials: [materialHandle],\n },\n },\n { component: SpriteInstances, data: { transforms, regions } },\n { component: Layer, data: { value: layerValue } },\n { component: ChildOf, data: { parent: layerEntity } },\n )\n .unwrap();\n}\n\n/**\n * Bucket a single layer's tiles into per-non-zero-cell spawn specs.\n * Returns the parent Tilemap metadata + the resolved spawn specs.\n */\nfunction bucketTileLayer(\n world: World,\n layerEntity: EntityHandle,\n parentEntity: EntityHandle,\n lookup: (guid: string) => TilesetAtlasLookup,\n):\n | {\n readonly tilemap: {\n cols: number;\n rows: number;\n tileSize: ArrayLike<number>;\n chunkSize: number;\n };\n readonly layerOrder: number;\n readonly sortScope: SortScope;\n readonly tileset: TilesetAsset;\n readonly specs: readonly DerivedSpawnSpec[];\n }\n | undefined {\n const tilemapRes = world.get(parentEntity, Tilemap);\n if (!tilemapRes.ok) return undefined;\n const tilemap = tilemapRes.value;\n const tilesetPayload = lookup(tilemap.tileset);\n if (tilesetPayload === undefined || 'code' in tilesetPayload) return undefined;\n if (tilesetPayload.kind !== 'tileset') return undefined;\n const tileset = tilesetPayload;\n\n const layerRes = world.get(layerEntity, TileLayer);\n if (!layerRes.ok) return undefined;\n const layer = layerRes.value;\n const tiles = layer.tiles as Uint32Array;\n const sortScope = decodeSortScope(layer.sortScope);\n\n // sortScope='layer' (terrain) uses the SpriteInstances batched path which\n // groups cells by atlas under an atlas-only material; sortScope='per-cell'\n // (object) keeps the per-cell entity path with per-region materials so\n // each cell can interleave with sprites by foot-Y. The material resolver\n // selection here keeps the spec's `materialHandle` in the correct\n // granularity for whichever spawn path consumes it downstream.\n const useSpriteInstances = sortScope === 'layer';\n\n const specs: DerivedSpawnSpec[] = [];\n for (let i = 0; i < tiles.length; i++) {\n const packed = tiles[i] ?? 0;\n if (packed === 0) continue;\n const { tileId } = decodeTileBits(packed);\n if (tileId === 0) continue;\n const entry = tileset.tiles[tileId - 1];\n if (entry === undefined) continue;\n const region = tileset.regions[entry.regionIndex];\n if (region === undefined) continue;\n const atlasIndex = region.atlasIndex ?? 0;\n const materialHandle = useSpriteInstances\n ? resolveAtlasOnlyMaterial(world, tileset, atlasIndex, lookup)\n : resolveTilesetMaterial(world, tileset, entry.regionIndex, lookup);\n const spec = specFor(\n tilemap.cols,\n tilemap.chunkSize,\n i,\n packed,\n materialHandle,\n entry,\n atlasIndex,\n );\n specs.push(spec);\n }\n return {\n tilemap,\n layerOrder: layer.layerOrder,\n sortScope,\n tileset,\n specs,\n };\n}\n\n/**\n * Compute the camera frustum planes for the first Camera + Transform entity\n * found in the world. Returns null when no camera exists or the projection\n * parameters are degenerate (callers treat null as always-visible).\n *\n * Mirrors the frustum-plane computation in render-system-extract so both\n * cull paths use byte-identical planes (charter P4 consistent abstraction).\n */\nfunction buildCameraFrustumPlanes(world: World): frustum.Frustum | null {\n const query = world.query({ with: [Camera, Transform, GlobalTransform] }).unwrap();\n let result: frustum.Frustum | null = null;\n for (const row of query) {\n const camEntity = row.entity;\n\n const camRes = world.get(camEntity, Camera);\n const trRes = world.get(camEntity, GlobalTransform);\n if (!camRes.ok || !trRes.ok) continue;\n\n const cam = camRes.value;\n const tr = trRes.value;\n\n const { near, far } = cam;\n if (near >= far) continue;\n\n const proj = mat4.create();\n if (cam.projection === CAMERA_PROJECTION_ORTHOGRAPHIC) {\n mat4.orthographic(\n proj as Parameters<typeof mat4.orthographic>[0],\n cam.left,\n cam.right,\n cam.top,\n cam.bottom,\n near,\n far,\n );\n } else {\n mat4.perspective(\n proj as Parameters<typeof mat4.perspective>[0],\n cam.fov,\n cam.aspect,\n near,\n far,\n );\n }\n const view = mat4.create();\n mat4.invert(\n view as Parameters<typeof mat4.invert>[0],\n tr.world as Parameters<typeof mat4.invert>[1],\n );\n const vp = mat4.create();\n mat4.multiply(\n vp as Parameters<typeof mat4.multiply>[0],\n proj as Parameters<typeof mat4.multiply>[1],\n view as Parameters<typeof mat4.multiply>[2],\n );\n const f = frustum.create();\n frustum.fromViewProjection(f, vp as Parameters<typeof frustum.fromViewProjection>[1]);\n result = f;\n break;\n }\n return result;\n}\n\n/**\n * bug-20260703-tilemap-chunk-stale-frustum-and-cull-overhang (D2): compute\n * the world-space AABB that tightly encloses every tile inside a chunk\n * after post-TRS placement (`computeTileTrs` applied per spec, SSOT shared\n * with the per-cell spawn path and SpriteInstances batched path). This is\n * the SSOT the streaming visibility test uses to decide whether a chunk's\n * tiles could still be visible; using it instead of the tile-aligned grid\n * box makes multi-cell / non-central-pivot overhang round-trip correctly,\n * so an overhanging tile no longer disappears when its anchor chunk goes\n * off-screen (plan-strategy §2 D-2).\n *\n * Empty spec list -> inverted `Number.MAX_VALUE` sentinel (plan-strategy\n * §2 D-4). `bucketTileLayer` filters empty cells before the byChunk map\n * is built, so this branch should never trigger in production; the\n * sentinel is an explicit \"no visible pixels\" value that\n * `frustum.intersectsBox` rejects immediately, avoiding a silent NaN\n * propagation path (charter P3 explicit failure).\n *\n * Note: `frustum.intersectsBox` picks a p-vertex per plane and computes\n * `dot(normal, p) + d`. When normal has a zero component, multiplying by\n * `Infinity` yields `NaN` (`NaN < 0 === false` -> false positive\n * intersection). The sentinel uses finite `Number.MAX_VALUE` on the axes\n * we want inverted so `0 * MAX_VALUE === 0` and the non-zero-normal axis\n * dominates, driving `dot` to `-Infinity` and correctly rejecting.\n *\n * Z is expanded to +/- 1 so flat sprite geometry (`pos_local.z === 0`) is\n * never degenerate against the frustum's near/far planes.\n *\n * @internal exported for M2 overhang / empty-chunk sentinel unit tests\n * (plan-strategy §5.3); not part of the AI user surface.\n */\nexport function computeChunkStreamBounds(\n tilemap: { tileSize: ArrayLike<number> },\n specs: readonly DerivedSpawnSpec[],\n): box3.Box3Like {\n let minX = Number.MAX_VALUE;\n let minY = Number.MAX_VALUE;\n let maxX = -Number.MAX_VALUE;\n let maxY = -Number.MAX_VALUE;\n for (const spec of specs) {\n const { posX, posY, scaleX, scaleY } = computeTileTrs(tilemap, spec, spec.packedTile);\n const halfW = Math.abs(scaleX) * 0.5;\n const halfH = Math.abs(scaleY) * 0.5;\n const x0 = posX - halfW;\n const x1 = posX + halfW;\n const y0 = posY - halfH;\n const y1 = posY + halfH;\n if (x0 < minX) minX = x0;\n if (y0 < minY) minY = y0;\n if (x1 > maxX) maxX = x1;\n if (y1 > maxY) maxY = y1;\n }\n return [minX, minY, -1, maxX, maxY, 1];\n}\n\n/**\n * Despawn every derived render entity currently attached to `layerEntity`.\n *\n * After tweak-20260714 M3 the terrain path locates its previously-spawned\n * children via `Children.entities` on the TileLayer (mirror of ChildOf,\n * engine-maintained via the relationship hook) rather than a module-level\n * tracker Map — SSOT collapse per architecture-principles §2 (Derive,\n * Don't Duplicate). The snapshot returned by\n * `world.get(layerEntity, Children).entities` is a fresh read-only\n * Uint32Array that is stable across the iteration even though each\n * despawn prunes the mirror in place.\n *\n * Empty children (never-built layer, or already-purged) trivially\n * short-circuits — this is the \"empty array no-op\" equivalence to the\n * old first-frame-heuristic guard (plan-strategy §2 D-3 edge case 3).\n */\nfunction purgeDerivedEntities(world: World, layerEntity: EntityHandle): void {\n const r = world.get(layerEntity, Children);\n if (!r.ok) return;\n const snap = r.value.entities;\n for (let i = 0; i < snap.length; i++) {\n const e = snap[i];\n if (e !== undefined) world.despawn(e as EntityHandle);\n }\n}\n\n/**\n * Snapshot of a single TileLayer's per-frame work item — populated by the\n * main-loop query and consumed both by the per-cell diff-cleanup preamble\n * (`evictDeadPerCellStreamingCaches`) and the per-layer processing branches.\n */\ninterface LayerWork {\n readonly layerEntity: EntityHandle;\n readonly parentEntity: EntityHandle;\n readonly dirty: number;\n readonly sortScopeRaw: number;\n}\n\n/**\n * tweak-20260714 M4 diff-cleanup preamble (plan-strategy §2 D-4 +\n * requirements §5 AC-11 + §8 edge case #4).\n *\n * The per-cell streaming maps are owned by one weak World entry and outlive\n * individual TileLayer entities while that World is alive. When a TileLayer\n * is despawned (or cascade-collected via `world.despawn(tilemapEntity)`) the\n * ECS mirrors clean up entities and `Children.entities`, but these maps retain\n * the dead layer's entries until this diff. On slot reuse, the stale entries\n * would corrupt rebuild: `activeSet` still lists old\n * chunkIndexes, and the rebuild branch would attempt to despawn stale\n * entity IDs before repopulating.\n *\n * Fix: at the top of each frame, diff this World's cached layer keys against\n * the fresh query. The set\n * difference names layers that vanished since the previous call; evict\n * their entries from all three Maps. `activeSet` is the SSOT for \"which\n * chunkIndexes have entries under this layer\" (each insertion / removal\n * pairs a `chunkEntities` set/delete with an `activeSet` add/delete), so\n * cleanup iterates `activeSet` rather than scanning `chunkEntities.keys()` —\n * O(chunks-per-dead-layer) instead\n * of O(total-cache-keys).\n *\n * Cross-world isolation is structural: the WeakMap key is the World object.\n * No duplicated World id is retained in every layer/chunk key.\n *\n * Per-frame cost (OOS-3 invariant): the two `keys()` iterations scan\n * O(cache_size) ≤ O(all-ever-seen-layers-for-this-worldId). Typical\n * scenes have ≤ 10 layers so this is a handful of Map lookups; no\n * matrix arithmetic. Actual eviction work only runs on frames where a\n * layer vanished — steady-state frames pay only the diff scan.\n */\nfunction evictDeadPerCellStreamingCaches(work: readonly LayerWork[], world: World): void {\n const cache = streamingCache(world);\n const aliveLayerKeys = new Set<string>();\n for (const w of work) {\n aliveLayerKeys.add(String(w.layerEntity));\n }\n const deadLayerKeys = new Set<string>();\n for (const layerKey of cache.activeChunks.keys()) {\n if (!aliveLayerKeys.has(layerKey)) deadLayerKeys.add(layerKey);\n }\n for (const layerKey of cache.layers.keys()) {\n if (!aliveLayerKeys.has(layerKey)) deadLayerKeys.add(layerKey);\n }\n for (const deadKey of deadLayerKeys) {\n const activeSet = cache.activeChunks.get(deadKey);\n if (activeSet !== undefined) {\n for (const chunkIdx of activeSet) {\n cache.chunkEntities.delete(`${deadKey}:${chunkIdx}`);\n }\n cache.activeChunks.delete(deadKey);\n }\n cache.layers.delete(deadKey);\n }\n}\n\n/**\n * Walk every TileLayer ChildOf-ing a Tilemap, extract its non-zero cells\n * into derived render entities. A Renderer attaches this system to FrameEnd;\n * World's final publication then resolves newly-created GlobalTransform.world values before the\n * read-only render walk begins.\n *\n * Two paths based on `TileLayer.sortScope`:\n *\n * `'layer'` (terrain, default):\n * Batched SpriteInstances path — spawned once, reused until dirty. Each\n * (chunk, atlas) pair becomes one SpriteInstances entity whose Transform\n * covers the chunk footprint, so the frustum culler rejects off-screen\n * chunks at entity granularity.\n *\n * `'per-cell'` (object layers):\n * Chunk-streaming path — specs are bucketed by chunkIndex once (rebuilt\n * on dirty) and the live entity set is updated every frame to match the\n * camera frustum. Only chunks whose world AABB intersects the frustum\n * have ECS entities alive, keeping `extractFrame` iteration proportional\n * to visible tile count rather than total map tile count.\n */\nexport function tilemapChunkExtractSystem(\n world: World,\n lookup: (guid: string) => TilesetAtlasLookup = () => undefined,\n): void {\n const streaming = streamingCache(world);\n const work: LayerWork[] = [];\n const tileLayerQuery = world.query({ read: [TileLayer, ChildOf] }).unwrap();\n for (const row of tileLayerQuery) {\n const layer = row.get(TileLayer);\n const parent = row.get(ChildOf).parent;\n if (parent === null) continue;\n work.push({\n layerEntity: row.entity,\n parentEntity: parent,\n dirty: layer.dirty,\n sortScopeRaw: layer.sortScope,\n });\n }\n\n evictDeadPerCellStreamingCaches(work, world);\n\n // Compute the camera frustum once per frame — only needed when at least\n // one streaming (per-cell) layer exists. Null = always-visible fallback.\n let frustumPlanes: frustum.Frustum | null | undefined;\n\n for (const w of work) {\n // The outer WeakMap owns World identity; this generation-bearing packed\n // entity handle prevents aliasing when an ECS slot is reused.\n const layerKey = String(w.layerEntity);\n // AC-04: decode via the canonical SortScope union; avoid relying on the\n // raw encoding (0='layer', 1='per-cell') leaking through this call site.\n // `decodeSortScope` is the SSOT used throughout `bucketTileLayer` (see\n // line 730); this main-loop branch is the last remaining numeric check.\n const isStreaming = decodeSortScope(w.sortScopeRaw) === 'per-cell';\n\n if (!isStreaming) {\n // ── Terrain batched path (sortScope='layer') ──────────────────────\n // Spawn once per dirty; entity AABB covers the chunk footprint for\n // entity-level frustum culling in render-system-extract.\n //\n // \"already built\" is derived from Children.entities (mirror of\n // ChildOf, engine-maintained). Empty children ⇒ never built (or\n // just purged) ⇒ don't skip. Populated children + dirty=0 ⇒\n // steady state ⇒ skip. Populated + dirty=1 ⇒ purge + rebuild.\n // architecture-principles §2 (Derive, Don't Duplicate): the\n // former module-level \"ever-built\" Set was a second copy of\n // information that Children.entities already carries.\n const childrenRes = world.get(w.layerEntity, Children);\n const childCount = childrenRes.ok ? childrenRes.value.entities.length : 0;\n if (childCount > 0 && w.dirty === 0) continue;\n\n purgeDerivedEntities(world, w.layerEntity);\n\n const bucket = bucketTileLayer(world, w.layerEntity, w.parentEntity, lookup);\n if (bucket === undefined) continue;\n\n const byChunkAtlas = new Map<number, DerivedSpawnSpec[]>();\n for (const spec of bucket.specs) {\n const key = ((spec.chunkIndex & 0xfffff) << 16) | (spec.atlasIndex & 0xffff);\n const list = byChunkAtlas.get(key);\n if (list === undefined) {\n byChunkAtlas.set(key, [spec]);\n } else {\n list.push(spec);\n }\n }\n for (const groupSpecs of byChunkAtlas.values()) {\n const first = groupSpecs[0];\n if (first === undefined) continue;\n spawnSpriteInstancesGroup(\n world,\n bucket.tilemap,\n bucket.tileset,\n w.layerEntity,\n bucket.layerOrder,\n first.chunkIndex,\n first.atlasIndex,\n first.materialHandle,\n groupSpecs,\n );\n }\n if (w.dirty !== 0) {\n world.set(w.layerEntity, TileLayer, { dirty: 0 }).unwrap();\n }\n continue;\n }\n\n // ── Object streaming path (sortScope='per-cell') ───────────────────\n // Step 1: rebuild specs cache when dirty or first time.\n if (w.dirty !== 0 || !streaming.layers.has(layerKey)) {\n // Despawn all currently-active chunks for this layer.\n const activeSet = streaming.activeChunks.get(layerKey);\n if (activeSet !== undefined) {\n for (const chunkIdx of activeSet) {\n const key = `${layerKey}:${chunkIdx}`;\n const entities = streaming.chunkEntities.get(key);\n if (entities !== undefined) {\n for (const e of entities) world.despawn(e as EntityHandle);\n streaming.chunkEntities.delete(key);\n }\n }\n activeSet.clear();\n }\n streaming.layers.delete(layerKey);\n\n const bucket = bucketTileLayer(world, w.layerEntity, w.parentEntity, lookup);\n if (bucket !== undefined) {\n const byChunkSpecs = new Map<number, DerivedSpawnSpec[]>();\n for (const spec of bucket.specs) {\n const list = byChunkSpecs.get(spec.chunkIndex);\n if (list === undefined) {\n byChunkSpecs.set(spec.chunkIndex, [spec]);\n } else {\n list.push(spec);\n }\n }\n // bug-20260703 D2: promote each chunk's bucket to a ChunkStreamEntry\n // carrying the world-space bounds that enclose every tile's actual\n // footprint (not the tile-aligned grid box). The visibility test\n // then rejects the chunk only when its TRUE pixels are all\n // off-screen, so multi-cell / off-pivot tiles no longer flicker at\n // chunk-boundary crossings (plan-strategy §2 D-2 / D-3).\n const byChunk = new Map<number, ChunkStreamEntry>();\n for (const [chunkIdx, specs] of byChunkSpecs) {\n byChunk.set(chunkIdx, {\n specs,\n bounds: computeChunkStreamBounds(bucket.tilemap, specs),\n });\n }\n streaming.layers.set(layerKey, {\n byChunk,\n tilemap: bucket.tilemap,\n layerOrder: bucket.layerOrder,\n sortScope: bucket.sortScope,\n });\n }\n if (w.dirty !== 0) {\n world.set(w.layerEntity, TileLayer, { dirty: 0 }).unwrap();\n }\n }\n\n const cache = streaming.layers.get(layerKey);\n if (cache === undefined) continue;\n\n // Step 2: lazy-compute camera frustum on first streaming layer.\n if (frustumPlanes === undefined) {\n frustumPlanes = buildCameraFrustumPlanes(world);\n }\n\n // Step 3: diff visible chunks against active set.\n const activeSet = streaming.activeChunks.get(layerKey) ?? new Set<number>();\n streaming.activeChunks.set(layerKey, activeSet);\n const { tilemap } = cache;\n\n for (const [chunkIdx, entry] of cache.byChunk) {\n const { specs, bounds } = entry;\n const visible = frustumPlanes === null || frustum.intersectsBox(frustumPlanes, bounds);\n const wasActive = activeSet.has(chunkIdx);\n\n if (visible && !wasActive) {\n // Spawn per-cell entities for this newly-visible chunk.\n const spawned: EntityHandle[] = [];\n for (const spec of specs) {\n const e = spawnDerivedRenderEntities(\n world,\n tilemap,\n w.layerEntity,\n cache.layerOrder,\n spec,\n spec.packedTile,\n cache.sortScope,\n );\n spawned.push(e);\n }\n streaming.chunkEntities.set(`${layerKey}:${chunkIdx}`, spawned);\n activeSet.add(chunkIdx);\n } else if (!visible && wasActive) {\n // Despawn per-cell entities for this newly-invisible chunk.\n const key = `${layerKey}:${chunkIdx}`;\n const entities = streaming.chunkEntities.get(key);\n if (entities !== undefined) {\n for (const e of entities) world.despawn(e);\n streaming.chunkEntities.delete(key);\n }\n activeSet.delete(chunkIdx);\n }\n }\n }\n}\n","import type { AssetRegistry } from '@forgeax/engine-assets-runtime';\nimport { Update, type World } from '@forgeax/engine-ecs';\nimport { registerPropagateTransforms } from '@forgeax/engine-scene';\nimport type { GpuResidencyCache } from '../device/gpu-residency';\nimport { glyphTextLayoutSystem } from '../glyph-text-layout-system';\nimport { tilemapChunkExtractSystem } from '../tilemap-chunk-extract-system';\n\nlet nextId = 0;\n/** Derived authoring stays beside World; only completed mesh data reaches the Renderer. */\nexport function registerRenderSourceSystems(\n world: World,\n assets: AssetRegistry,\n meshes: Pick<GpuResidencyCache, 'updateMesh'>,\n): () => void {\n const releaseTransforms = registerPropagateTransforms(world);\n const name = `renderDerived:${++nextId}`;\n const result = world.addSystem(Update, {\n name,\n queries: [],\n fn: (world) => {\n tilemapChunkExtractSystem(world, (guid) => assets.lookup(guid));\n glyphTextLayoutSystem(world, meshes).unwrap();\n },\n });\n if (!result.ok) {\n releaseTransforms();\n throw result.error;\n }\n return () => {\n world.removeSystem(Update, name).unwrap();\n releaseTransforms();\n };\n}\n","import type { MaterialCookProgramContext } from '@forgeax/engine-pack/material-cook';\nimport type { RhiCaps } from '@forgeax/engine-rhi';\n\n/** The receiving device selects the immutable material program domain. */\nexport function renderMaterialContext(caps: Pick<RhiCaps, 'backendKind' | 'storageBuffer'>): {\n readonly materialContext?: MaterialCookProgramContext;\n} {\n if (caps.backendKind === 'null') return {};\n return {\n materialContext: {\n backend: caps.backendKind === 'wgpu-webgl2' ? 'webgl2' : caps.backendKind,\n capability: caps.storageBuffer ? 'storage-buffer' : 'uniform-fallback',\n pipeline: 'forward',\n geometry: 'mesh',\n pass: 'forward',\n profile: 'forgeax-material-wgsl-v1',\n toolchain: 'naga-oil',\n instrumentation: 'none',\n },\n };\n}\n","import { RuntimeMaterialValue, RuntimeMeshVertices } from '@forgeax/engine-assets-runtime';\nimport type { Component, EntityHandle, Query, World } from '@forgeax/engine-ecs';\nimport { createStateProjection } from '@forgeax/engine-ecs/projection';\nimport { ChildOf, GlobalTransform, MorphWeights, Transform } from '@forgeax/engine-scene';\nimport { Skin } from '@forgeax/engine-skinning';\nimport {\n Instances,\n Layer,\n Lines,\n MeshFilter,\n MeshRenderer,\n Points,\n SortKey,\n SpriteInstances,\n SpriteRegionOverride,\n Visibility,\n} from '../components';\nexport type GlobalTransformChangeQuery = Query<readonly [typeof GlobalTransform]>;\n\n// Retained geometry consumes these component changes. Camera, lighting and\n// environment facts are freshly extracted by deriveFramePlan on every draw;\n// their edits must not recreate unrelated geometry or its submission history.\nexport const RENDERABLE_SOURCE_COMPONENTS = [\n ChildOf,\n MeshFilter,\n MeshRenderer,\n Instances,\n SpriteInstances,\n SpriteRegionOverride,\n Skin,\n Layer,\n Visibility,\n MorphWeights,\n Points,\n Lines,\n SortKey,\n] as const;\nexport function createGlobalTransformChangeQuery(world: World): GlobalTransformChangeQuery {\n const result = world.query({ read: [GlobalTransform], changed: [GlobalTransform] });\n if (!result.ok) throw result.error;\n const query = result.value as GlobalTransformChangeQuery;\n for (const _span of query.spans().unwrap()) {\n // The full rebuild consumed these values; establish the observation baseline.\n }\n return query;\n}\n\nexport function createRenderSourceState(world: World, additional: readonly Component[] = []) {\n // Numerical poses already have one span reader. Keep their table membership\n // in this projection, without scanning their changed rows a second time.\n const components = [\n ...RENDERABLE_SOURCE_COMPONENTS,\n RuntimeMaterialValue,\n RuntimeMeshVertices,\n ...additional,\n ];\n const projection = createStateProjection(world, components, [\n ...components,\n Transform,\n GlobalTransform,\n ]);\n const entities = new Map<number, EntityHandle>();\n const contentHandles = new Map<number, readonly number[]>();\n const batch = projection.read();\n for (const index of batch.indices) {\n const entity = projection.entity(index);\n if (entity !== undefined) {\n entities.set(index, entity);\n const handles: number[] = [];\n const material = world.hasComponent(entity, RuntimeMaterialValue)\n ? world.get(entity, RuntimeMaterialValue)\n : undefined;\n const mesh = world.hasComponent(entity, RuntimeMeshVertices)\n ? world.get(entity, RuntimeMeshVertices)\n : undefined;\n if (material?.ok) handles.push(Number(material.value.asset));\n if (mesh?.ok) handles.push(Number(mesh.value.asset));\n if (handles.length > 0) contentHandles.set(index, handles);\n }\n }\n return { projection, entities, contentHandles, batch };\n}\n\nexport function isRenderableMember(world: World, entity: number): boolean {\n return (\n world.hasComponent(entity as EntityHandle, MeshRenderer) &&\n world.hasComponent(entity as EntityHandle, Transform) &&\n world.hasComponent(entity as EntityHandle, MeshFilter)\n );\n}\n"]}
|