@photivra/engine 2.12.0 → 2.14.0
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/CHANGELOG.md +144 -1
- package/CITATION.cff +1 -1
- package/README.md +7 -7
- package/SECURITY.md +1 -1
- package/THIRD_PARTY.md +3 -0
- package/dist/camera/lens-projection.js +2 -1
- package/dist/camera/lens-projection.js.map +1 -1
- package/dist/capture/dng-import.js +1 -1
- package/dist/capture/dng-import.js.map +1 -1
- package/dist/capture/export-jpeg.d.ts +1 -1
- package/dist/capture/export-jpeg.js +6 -4
- package/dist/capture/export-jpeg.js.map +1 -1
- package/dist/capture/host-yield-cadence.js +1 -1
- package/dist/capture/host-yield-cadence.js.map +1 -1
- package/dist/capture/native-environment-optical-stage.js +1 -1
- package/dist/capture/native-environment-optical-stage.js.map +1 -1
- package/dist/capture/native-raw.js +1 -1
- package/dist/capture/native-raw.js.map +1 -1
- package/dist/capture/packed-sensor-raw.js +3 -3
- package/dist/capture/packed-sensor-raw.js.map +1 -1
- package/dist/capture/sensor-raw-producer.js +1 -1
- package/dist/capture/sensor-raw-producer.js.map +1 -1
- package/dist/color/capture-color.js +3 -3
- package/dist/color/capture-color.js.map +1 -1
- package/dist/color/chromatic-adaptation.js +2 -2
- package/dist/color/chromatic-adaptation.js.map +1 -1
- package/dist/color/color-matching-functions.js +1 -1
- package/dist/color/color-matching-functions.js.map +1 -1
- package/dist/color/colorimetry-math.js +2 -2
- package/dist/color/colorimetry-math.js.map +1 -1
- package/dist/color/illuminants.js +3 -3
- package/dist/color/illuminants.js.map +1 -1
- package/dist/color/rgb-color-spaces.js +1 -1
- package/dist/color/rgb-color-spaces.js.map +1 -1
- package/dist/color/sensor-color-development.js +1 -1
- package/dist/color/sensor-color-development.js.map +1 -1
- package/dist/core/record-validation.js +3 -3
- package/dist/core/record-validation.js.map +1 -1
- package/dist/core/version.d.ts +1 -1
- package/dist/core/version.js +1 -1
- package/dist/core/version.js.map +1 -1
- package/dist/equipment/generic-prime-lenses.js +3 -3
- package/dist/equipment/generic-prime-lenses.js.map +1 -1
- package/dist/equipment/generic-tier-assets.d.ts +23 -1
- package/dist/equipment/generic-tier-assets.js +58 -30
- package/dist/equipment/generic-tier-assets.js.map +1 -1
- package/dist/equipment/generic-tier-presets.d.ts +6 -3
- package/dist/equipment/generic-tier-presets.js +26 -13
- package/dist/equipment/generic-tier-presets.js.map +1 -1
- package/dist/exposure/auto-iso-slowest-shutter.d.ts +120 -0
- package/dist/exposure/auto-iso-slowest-shutter.js +217 -0
- package/dist/exposure/auto-iso-slowest-shutter.js.map +1 -0
- package/dist/exposure/exposure-mode-resolver.d.ts +57 -1
- package/dist/exposure/exposure-mode-resolver.js +238 -33
- package/dist/exposure/exposure-mode-resolver.js.map +1 -1
- package/dist/exposure/flash-ttl.js +1 -1
- package/dist/exposure/flash-ttl.js.map +1 -1
- package/dist/exposure/flash.js +1 -1
- package/dist/exposure/flash.js.map +1 -1
- package/dist/facade/chart-material-layers.js +2 -2
- package/dist/facade/chart-material-layers.js.map +1 -1
- package/dist/facade/chart-radiance-batch.js +1 -1
- package/dist/facade/chart-radiance-batch.js.map +1 -1
- package/dist/facade/chart-scenes.d.ts +45 -8
- package/dist/facade/chart-scenes.js +101 -44
- package/dist/facade/chart-scenes.js.map +1 -1
- package/dist/facade/color-patches.d.ts +129 -0
- package/dist/facade/color-patches.js +209 -0
- package/dist/facade/color-patches.js.map +1 -0
- package/dist/facade/diffraction-provider.js +12 -13
- package/dist/facade/diffraction-provider.js.map +1 -1
- package/dist/facade/display-view-gpu.js +1 -1
- package/dist/facade/display-view-gpu.js.map +1 -1
- package/dist/facade/display-view.d.ts +27 -0
- package/dist/facade/display-view.js +234 -65
- package/dist/facade/display-view.js.map +1 -1
- package/dist/facade/scene-radiance.js +2 -2
- package/dist/facade/scene-radiance.js.map +1 -1
- package/dist/facade/simulate-capture.d.ts +139 -12
- package/dist/facade/simulate-capture.js +209 -36
- package/dist/facade/simulate-capture.js.map +1 -1
- package/dist/facade/simulate-display-view.js +2 -2
- package/dist/facade/simulate-display-view.js.map +1 -1
- package/dist/gpu/chart-composite-gpu.js +2 -2
- package/dist/gpu/chart-composite-gpu.js.map +1 -1
- package/dist/gpu/display-view-composite-material-module.js +1 -1
- package/dist/gpu/display-view-composite-material-module.js.map +1 -1
- package/dist/gpu/display-view-quality-gpu.d.ts +2 -1
- package/dist/gpu/display-view-quality-gpu.js +24 -14
- package/dist/gpu/display-view-quality-gpu.js.map +1 -1
- package/dist/gpu/image-kernel-execution.js +2 -2
- package/dist/gpu/image-kernel-execution.js.map +1 -1
- package/dist/gpu/temporal-sum-gpu.js +23 -23
- package/dist/gpu/webgpu-runtime.js +1 -1
- package/dist/gpu/webgpu-runtime.js.map +1 -1
- package/dist/gpu/wgsl-chart-composite-kernel.js +318 -318
- package/dist/gpu/wgsl-chart-composite-kernel.js.map +1 -1
- package/dist/gpu/wgsl-chart-kernel.js +117 -117
- package/dist/gpu/wgsl-chart-kernel.js.map +1 -1
- package/dist/gpu/wgsl-display-view-quality-kernel.d.ts +13 -1
- package/dist/gpu/wgsl-display-view-quality-kernel.js +522 -488
- package/dist/gpu/wgsl-display-view-quality-kernel.js.map +1 -1
- package/dist/gpu/wgsl-display-view-speed-kernel.js +248 -248
- package/dist/gpu/wgsl-display-view-speed-kernel.js.map +1 -1
- package/dist/gpu/wgsl-kernels.js +203 -203
- package/dist/gpu/wgsl-kernels.js.map +1 -1
- package/dist/gpu/wgsl-sensor-kernel.js +302 -302
- package/dist/gpu/wgsl-sensor-kernel.js.map +1 -1
- package/dist/index.d.ts +8 -5
- package/dist/index.js +6 -3
- package/dist/index.js.map +1 -1
- package/dist/motion/temporal-exposure-sum.js +1 -1
- package/dist/motion/temporal-exposure-sum.js.map +1 -1
- package/dist/optics/diffraction-psf-profile.js +4 -4
- package/dist/optics/diffraction-psf-profile.js.map +1 -1
- package/dist/optics/front-of-lens-filter.js +1 -1
- package/dist/optics/front-of-lens-filter.js.map +1 -1
- package/dist/optics/irradiance-convolution.d.ts +10 -0
- package/dist/optics/irradiance-convolution.js +49 -14
- package/dist/optics/irradiance-convolution.js.map +1 -1
- package/dist/output/native-capture-sdr.js +1 -1
- package/dist/output/native-capture-sdr.js.map +1 -1
- package/dist/output/png-encoder.js +2 -2
- package/dist/output/png-encoder.js.map +1 -1
- package/dist/output/print-jpeg.js +13 -10
- package/dist/output/print-jpeg.js.map +1 -1
- package/dist/output/text-metadata.d.ts +22 -2
- package/dist/output/text-metadata.js +58 -9
- package/dist/output/text-metadata.js.map +1 -1
- package/dist/sensor/fixed-pattern-noise.js +1 -1
- package/dist/sensor/fixed-pattern-noise.js.map +1 -1
- package/dist/sensor/readout-exposure-linkage.js +1 -1
- package/dist/sensor/readout-exposure-linkage.js.map +1 -1
- package/docs/API_REFERENCE.md +49 -1
- package/docs/QUICK_START.md +104 -9
- package/docs/USAGE.md +241 -2
- package/docs/api/core-version.md +1 -1
- package/docs/api/equipment-generic-tier-assets.md +41 -1
- package/docs/api/equipment-generic-tier-presets.md +11 -3
- package/docs/api/exports.json +172 -2
- package/docs/api/exposure-auto-iso-slowest-shutter.md +139 -0
- package/docs/api/exposure-exposure-mode-resolver.md +68 -0
- package/docs/api/facade-chart-scenes.md +36 -5
- package/docs/api/facade-color-patches.md +150 -0
- package/docs/api/facade-simulate-capture.md +140 -9
- package/docs/api/output-text-metadata.md +34 -0
- package/llms.txt +1 -0
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"native-environment-optical-stage.js","sourceRoot":"","sources":["../../src/capture/native-environment-optical-stage.ts"],"names":[],"mappings":"AAAA,sCAAsC;AAEtC;;;;;;;;;;;;GAYG;AAEH,OAAO,EAAE,mBAAmB,EAAsE,MAAM,iBAAiB,CAAC;AAG1H,OAAO,EAAE,iCAAiC,EAAqC,MAAM,oCAAoC,CAAC;AAC1H,OAAO,EAAE,gCAAgC,EAAE,MAAM,2BAA2B,CAAC;AAC7E,OAA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BAAyB,CAAC,6BAA6B,CAAC,CAAC;QACzF,CAAC;KACF,CAAC,CAAC;IACH,6GAA6G;IAC7G,IAAI,CAAC,aAAa,CAAC,cAAc,CAAC,IAAI,CAAC,IAAI,EAAE,YAAY,CAAC,EAAE,KAAK,CAAC,OAAO,EAAE,IAAI,OAAO,EAAE,CAAC,EAAE,CAAC;QAC1F,IAAI,CAAC,OAAO,EAAE,CAAC;QACf,MAAM,IAAI,yBAAyB,CAAC,0FAA0F,CAAC,CAAC;IAClI,CAAC;IACD,OAAO,EAAE,IAAI,EAAE,YAAY,EAAE,CAAC;AAChC,CAAC","sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Keeps (retains) the result of the optical stage of a native environment capture, so the sensor stage\n * can be re-run with new post-optics settings without calling the radiance callbacks again.\n *\n * Optical stage: scene radiance → optics, PSF (point-spread function) and pupil → expected photo signal\n * via EQE (external quantum efficiency). Sensor stage: dark charge → charge realization → readout.\n *\n * Reuse is exact, not approximate: the sensor stage receives a photo signal whose every number is the\n * float64 value the optical stage produced, and the same charge/noise/ADC code runs on it. Reuse is\n * refused unless the capture's optical binding and every site's environment input are strictly equal\n * to those the stage was produced from.\n * @see docs/NATIVE_RAW_AND_PRINT.md for the invariance analysis, memory bound and limits.\n */\n\nimport { createNativeRawTask, type NativeRawInput, type NativeRawPlan, type NativeRawTileRequest } from \"./native-raw.js\";\nimport type { SimulateEnvironmentSensorRawFrameInput } from \"./environment-raw-producer.js\";\nimport type { SensorRawProducerSiteInput } from \"./sensor-raw-producer.js\";\nimport { parseSensorEqeTemporalPhotoSignal, type SensorEqeTemporalPhotoSignal } from \"../sensor/temporal-photo-signal.js\";\nimport { calculateSensorDarkCurrentCharge } from \"../sensor/dark-current.js\";\nimport { requireAllowlistedRecord } from \"../core/record-validation.js\";\nimport { stringifyCanonicalJson } from \"../core/canonical-json.js\";\nimport { freezeOwnedData } from \"../core/owned-data.js\";\nimport { InvalidConfigurationError } from \"../core/configuration-error.js\";\n\ntype EnvironmentSite = SimulateEnvironmentSensorRawFrameInput[\"sites\"][number];\ntype SiteEnvironment = EnvironmentSite[\"environment\"];\n\n/**\n * Fixed retention limits. The per-site footprint of a retained optical stage is\n * `fixedBytesPerSite + bytesPerTemporalSamplePerSite × temporalSampleCount` bytes of typed-array storage;\n * distinct environment and photo templates (each about one site's input size) are capped separately.\n */\nexport const NATIVE_ENVIRONMENT_OPTICAL_STAGE_LIMITS = Object.freeze({\n /** Two one-byte template indices plus seven float64 values (site x/y, window start/end/duration, photon/electron counts). */\n fixedBytesPerSite: 58,\n /** Three float64 values per temporal midpoint: time, incident-photon rate, generated-electron rate. */\n bytesPerTemporalSamplePerSite: 24,\n /** Distinct per-site environment inputs once the site index and integration ID are removed. */\n maximumEnvironmentTemplates: 256,\n /** Distinct photo-signal identity/evidence records once per-site numbers are removed. */\n maximumPhotoTemplates: 256\n});\n\n/** Optional request on NativeEnvironmentRawInput to keep the optical stage. The byte budget covers the typed-array storage described by the limits. */\nexport interface NativeEnvironmentOpticalStageRetention {\n maximumRetainedBytes: number;\n}\n\n/**\n * Opaque, engine-owned optical-stage result. It is valid only for captures whose optical binding and every\n * site's environment input are strictly equal to those that produced it. dispose() zeroes and releases the\n * storage; a disposed stage refuses every later use.\n */\nexport interface NativeEnvironmentOpticalStage {\n readonly kind: \"native-environment-optical-stage\";\n readonly pixelCount: number;\n readonly temporalSampleCount: number;\n /** Typed-array bytes held: pixelCount × (fixedBytesPerSite + bytesPerTemporalSamplePerSite × temporalSampleCount). */\n readonly retainedBytes: number;\n /** Radiance callbacks the producing task executed; reuse executes none. */\n readonly providerEvaluationCount: number;\n readonly disposed: boolean;\n dispose(): void;\n}\n\n/** Input for a post-optics re-run. `raw` may differ from the original capture only in post-optics fields. */\nexport interface NativeEnvironmentSensorStageInput {\n raw: NativeRawInput;\n sceneBinding: SimulateEnvironmentSensorRawFrameInput[\"sceneBinding\"];\n}\n/** Supplies the same physical site inputs as the original capture. Environments must equal the retained ones exactly. */\nexport interface NativeEnvironmentSensorStageProvider {\n readTile(request: Readonly<NativeRawTileRequest>, signal: AbortSignal): Promise<{ captureId: string; frameId: string; x: number; y: number;\n width: number; height: number; sites: SimulateEnvironmentSensorRawFrameInput[\"sites\"] }>;\n yieldControl(signal: AbortSignal): Promise<void>;\n}\n\nconst FIXED_VALUES = 7;\nconst ENVIRONMENT_SHARED_KEYS = [\"sceneBindings\", \"optics\", \"motion\", \"psf\", \"pupil\", \"fieldThroughput\"] as const;\n\nfunction canonical(value: unknown): string {\n return stringifyCanonicalJson(value, { undefinedObjectProperties: \"omit\", nonFiniteNumberMessage: \"Invalid native scene binding.\",\n unsupportedValueMessage: \"Invalid native scene binding.\" });\n}\n\nfunction isPlainRecord(value: object): boolean {\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\n/**\n * Strict structural equality of plain data: Object.is for primitives (so 0 and -0 differ), identical own\n * key sets, arrays element by element. Anything that is not a plain record or array is unequal unless it is\n * the same reference, so an unexpected value refuses reuse instead of being treated as equal.\n */\nfunction strictlyEqual(a: unknown, b: unknown, verified: WeakMap<object, WeakSet<object>>, skip?: ReadonlySet<string>): boolean {\n if (Object.is(a, b)) return true;\n if (typeof a !== \"object\" || typeof b !== \"object\" || a === null || b === null) return false;\n if (!skip && verified.get(a)?.has(b)) return true;\n if (Array.isArray(a)) {\n if (!Array.isArray(b) || a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (!(i in a) || !(i in b) || !strictlyEqual(a[i], b[i], verified)) return false;\n }\n } else {\n if (Array.isArray(b) || !isPlainRecord(a) || !isPlainRecord(b)) return false;\n const ak = Object.keys(a), bk = Object.keys(b);\n if (ak.length !== bk.length || Object.getOwnPropertySymbols(a).length !== 0 || Object.getOwnPropertySymbols(b).length !== 0) return false;\n for (const key of ak) {\n if (!Object.prototype.hasOwnProperty.call(b, key)) return false;\n if (skip?.has(key)) continue;\n if (!strictlyEqual((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key], verified)) return false;\n }\n }\n if (!skip) {\n let set = verified.get(a);\n if (!set) verified.set(a, set = new WeakSet());\n set.add(b);\n }\n return true;\n}\n\n/**\n * Environment equality except the two per-site fields that are bound to the absolute native index and\n * checked separately: temporalIntegrationId and sensor.spatialSampling.site.\n */\nfunction environmentMatches(e: SiteEnvironment, t: SiteEnvironment, verified: WeakMap<object, WeakSet<object>>): boolean {\n if (typeof e !== \"object\" || e === null || typeof e.sensor !== \"object\" || e.sensor === null ||\n typeof e.sensor.spatialSampling !== \"object\" || e.sensor.spatialSampling === null) return false;\n return strictlyEqual(e, t, verified, new Set([\"temporalIntegrationId\", \"sensor\"])) &&\n strictlyEqual(e.sensor, t.sensor, verified, new Set([\"spatialSampling\"])) &&\n strictlyEqual(e.sensor.spatialSampling, t.sensor.spatialSampling, verified, new Set([\"site\"]));\n}\n\n/**\n * Post-optics capture fields: noise seed/realization/model, ISO metadata, white-balance intent, adopted white,\n * capture identity, source artifact metadata and declared models. The optical stage never reads them.\n * Everything else in the normalized plan (scene state/time, geometry including orientation, focal length,\n * aperture, shutter, focus, frame/mode/CFA/binding profiles and the exposure window) is part of the binding.\n */\nfunction opticalBinding(plan: NativeRawPlan, sceneBinding: unknown): unknown {\n const { captureId, noise, source, whiteBalanceIntent, adoptedWhiteXyz, models, exposure, ...capture } = plan.exposure;\n void captureId; void noise; void source; void whiteBalanceIntent; void adoptedWhiteXyz; void models;\n const { iso, ...opticalExposure } = exposure; void iso;\n const { capture: frameCapture, ...frame } = plan.frame; void frameCapture;\n return { capture: { ...capture, exposure: opticalExposure }, frame, exposureWindow: plan.exposureWindow ?? null, sceneBinding };\n}\n\ninterface OpticalStageState {\n pixelCount: number;\n nativeWidth: number;\n frameId: string;\n stride: number;\n temporalSampleCount: number;\n binding: unknown;\n values: Float64Array;\n environmentIndex: Uint8Array;\n photoIndex: Uint8Array;\n environments: SiteEnvironment[];\n photoTemplates: Record<string, unknown>[];\n providerEvaluationCount: number;\n disposed: boolean;\n}\nconst STAGES = new WeakMap<object, OpticalStageState>();\n\nfunction release(state: OpticalStageState): void {\n state.values.fill(0); state.environmentIndex.fill(0); state.photoIndex.fill(0);\n state.values = new Float64Array(0); state.environmentIndex = new Uint8Array(0); state.photoIndex = new Uint8Array(0);\n state.environments = []; state.photoTemplates = []; state.disposed = true;\n}\n\nfunction photoTemplate(p: SensorEqeTemporalPhotoSignal): Record<string, unknown> {\n const { temporalIntegrationId, site, startOffsetSecondsFromOpeningReference, endOffsetSecondsFromOpeningReference,\n localExposureDurationSeconds, expectedIncidentPhotonCount, expectedGeneratedElectronCount, temporalSamples, ...rest } = p;\n void temporalIntegrationId; void site; void startOffsetSecondsFromOpeningReference; void endOffsetSecondsFromOpeningReference;\n void localExposureDurationSeconds; void expectedIncidentPhotonCount; void expectedGeneratedElectronCount; void temporalSamples;\n return rest;\n}\n\n/** Shared by full acquisition and reuse so the sensor stage receives an identical site record either way. */\nexport function composeNativeEnvironmentSensorSite(site: Omit<EnvironmentSite, \"environment\">, photoSignal: SensorEqeTemporalPhotoSignal): SensorRawProducerSiteInput {\n const darkCharge = calculateSensorDarkCurrentCharge({ exposure: photoSignal, darkCurrentProfile: site.darkCurrentProfile,\n operatingTemperatureC: site.operatingTemperatureC }).value;\n return { ...site.readout, charge: { ...site.charge, photoSignal, darkCharge } } as SensorRawProducerSiteInput;\n}\n\n/** Validates the optional retention request before any provider work. */\nexport function parseNativeEnvironmentOpticalStageRetention(value: unknown): NativeEnvironmentOpticalStageRetention {\n const r = requireAllowlistedRecord(value, [\"maximumRetainedBytes\"], \"Invalid optical-stage retention request.\");\n if (typeof r.maximumRetainedBytes !== \"number\" || !Number.isSafeInteger(r.maximumRetainedBytes) || r.maximumRetainedBytes < 1) {\n throw new InvalidConfigurationError(\"Optical-stage retention requires a positive safe-integer byte budget.\");\n }\n return { maximumRetainedBytes: r.maximumRetainedBytes };\n}\n\n/** Internal recorder used by createNativeEnvironmentRawTask when retention is requested. */\nexport interface NativeEnvironmentOpticalStageRecorder {\n /** Interns one planned site before any radiance callback; throws if a limit or the byte budget would be exceeded. */\n admit(index: number, environment: SiteEnvironment, sharedCanonical: string): void;\n record(index: number, photoSignal: SensorEqeTemporalPhotoSignal): void;\n finish(providerEvaluationCount: number): NativeEnvironmentOpticalStage;\n discard(): void;\n}\n\nexport function createNativeEnvironmentOpticalStageRecorder(plan: NativeRawPlan, sceneBinding: unknown,\n retention: NativeEnvironmentOpticalStageRetention): NativeEnvironmentOpticalStageRecorder {\n const L = NATIVE_ENVIRONMENT_OPTICAL_STAGE_LIMITS;\n const state: OpticalStageState = { pixelCount: plan.pixelCount, nativeWidth: plan.exposure.geometry.nativeRaster.pixelWidth,\n frameId: plan.frame.frameId, stride: 0, temporalSampleCount: 0, binding: freezeOwnedData(structuredClone(opticalBinding(plan, sceneBinding))),\n values: new Float64Array(0), environmentIndex: new Uint8Array(0), photoIndex: new Uint8Array(0), environments: [], photoTemplates: [],\n providerEvaluationCount: 0, disposed: false };\n const environmentKeys = new Map<string, number[]>(), photoKeys = new Map<string, number[]>(), verified = new WeakMap<object, WeakSet<object>>();\n const admitted = new Uint8Array(plan.pixelCount);\n let recorded = 0;\n function residualKey(e: SiteEnvironment, sharedCanonical: string): string {\n const rest: Record<string, unknown> = { ...e, temporalIntegrationId: undefined,\n sensor: { ...e.sensor, spatialSampling: { ...e.sensor.spatialSampling, site: undefined } } };\n for (const key of ENVIRONMENT_SHARED_KEYS) rest[key] = undefined;\n return sharedCanonical+\"\\u0000\"+canonical(rest);\n }\n return {\n admit(index, environment, sharedCanonical): void {\n if (state.disposed) throw new InvalidConfigurationError(\"Optical-stage retention was released.\");\n const n = environment.temporalSampleCount;\n if (state.stride === 0) {\n const bytes = plan.pixelCount*(L.fixedBytesPerSite+L.bytesPerTemporalSamplePerSite*n);\n if (!Number.isSafeInteger(bytes) || bytes > retention.maximumRetainedBytes) throw new InvalidConfigurationError(\"Optical-stage retention exceeds its byte budget.\");\n state.temporalSampleCount = n; state.stride = FIXED_VALUES+3*n;\n state.values = new Float64Array(plan.pixelCount*state.stride);\n state.environmentIndex = new Uint8Array(plan.pixelCount); state.photoIndex = new Uint8Array(plan.pixelCount);\n } else if (n !== state.temporalSampleCount) throw new InvalidConfigurationError(\"Optical-stage retention requires one temporal sample count per event.\");\n const key = residualKey(environment, sharedCanonical), candidates = environmentKeys.get(key) ?? [];\n let found = candidates.find(i => environmentMatches(environment, state.environments[i]!, verified));\n if (found === undefined) {\n if (state.environments.length >= L.maximumEnvironmentTemplates) throw new InvalidConfigurationError(\"Optical-stage retention exceeds its distinct site-environment limit.\");\n found = state.environments.length;\n state.environments.push(environment);\n candidates.push(found); environmentKeys.set(key, candidates);\n }\n state.environmentIndex[index] = found; admitted[index] = 1;\n },\n record(index, p): void {\n if (state.disposed || admitted[index] !== 1) throw new InvalidConfigurationError(\"Optical-stage retention was released or not admitted.\");\n const samples = p.temporalSamples;\n if (samples.length !== state.temporalSampleCount) throw new InvalidConfigurationError(\"Optical-stage temporal sample count changed.\");\n const template = photoTemplate(p), key = canonical(template), candidates = photoKeys.get(key) ?? [];\n let found = candidates.find(i => strictlyEqual(template, state.photoTemplates[i]!, verified));\n if (found === undefined) {\n if (state.photoTemplates.length >= L.maximumPhotoTemplates) throw new InvalidConfigurationError(\"Optical-stage retention exceeds its distinct photo-identity limit.\");\n found = state.photoTemplates.length;\n state.photoTemplates.push(freezeOwnedData(structuredClone(template)));\n candidates.push(found); photoKeys.set(key, candidates);\n }\n state.photoIndex[index] = found;\n const v = state.values, o = index*state.stride;\n v[o] = p.site.x; v[o+1] = p.site.y; v[o+2] = p.startOffsetSecondsFromOpeningReference; v[o+3] = p.endOffsetSecondsFromOpeningReference;\n v[o+4] = p.localExposureDurationSeconds; v[o+5] = p.expectedIncidentPhotonCount; v[o+6] = p.expectedGeneratedElectronCount;\n for (let t = 0; t < samples.length; t++) {\n const s = samples[t]!, q = o+FIXED_VALUES+3*t;\n v[q] = s.timeSecondsFromOpeningReference; v[q+1] = s.incidentPhotonRatePerSecond; v[q+2] = s.expectedGeneratedElectronRatePerSecond;\n }\n admitted[index] = 2; recorded++;\n },\n finish(providerEvaluationCount): NativeEnvironmentOpticalStage {\n if (state.disposed || recorded !== plan.pixelCount) throw new InvalidConfigurationError(\"Optical-stage retention is incomplete.\");\n for (const environment of state.environments) freezeOwnedData(environment);\n state.providerEvaluationCount = providerEvaluationCount;\n const handle: NativeEnvironmentOpticalStage = Object.freeze({ kind: \"native-environment-optical-stage\" as const,\n pixelCount: state.pixelCount, temporalSampleCount: state.temporalSampleCount,\n retainedBytes: state.pixelCount*(L.fixedBytesPerSite+L.bytesPerTemporalSamplePerSite*state.temporalSampleCount),\n providerEvaluationCount, get disposed(): boolean { return state.disposed; },\n dispose(): void { if (!state.disposed) release(state); } });\n STAGES.set(handle, state);\n return handle;\n },\n discard(): void { if (!state.disposed) release(state); }\n };\n}\n\n/**\n * Internal: re-runs only the sensor stage (dark charge, charge realization, capacity, seeded noise and ADC) from a retained\n * optical stage. The capture may change post-optics settings only: noise seed/realization, ISO metadata, readout\n * regime/gain, charge sampling/capacity/completeness, dark-current profile and temperature, white-balance intent,\n * capture identity and tile width. Every optical input must be strictly equal, otherwise this refuses before\n * output: the capture binding is checked here, each site's environment as its tile is read.\n */\nexport function createSensorStageRawTask<B>(input: NativeEnvironmentSensorStageInput, opticalStage: NativeEnvironmentOpticalStage,\n provider: NativeEnvironmentSensorStageProvider, parseSceneBinding: (value: unknown) => B):\n { task: ReturnType<typeof createNativeRawTask>; sceneBinding: B } {\n const state = typeof opticalStage === \"object\" && opticalStage !== null ? STAGES.get(opticalStage) : undefined;\n if (!state) throw new InvalidConfigurationError(\"Optical-stage reuse requires an engine-produced optical stage.\");\n if (state.disposed) throw new InvalidConfigurationError(\"Optical stage was disposed.\");\n const r = requireAllowlistedRecord(input, [\"raw\", \"sceneBinding\"], \"Invalid native sensor-stage input.\");\n const sceneBinding = parseSceneBinding(r.sceneBinding);\n if (!provider || typeof provider.readTile !== \"function\" || typeof provider.yieldControl !== \"function\") {\n throw new InvalidConfigurationError(\"Sensor-stage reuse requires physical site input and host yields.\");\n }\n const read = provider.readTile.bind(provider), yieldControl = provider.yieldControl.bind(provider);\n const width = state.nativeWidth, frameId = state.frameId;\n const task = createNativeRawTask(input.raw, {\n async readTile(request, signal) {\n const supplied = await read(request, signal);\n if (signal.aborted) throw new InvalidConfigurationError(\"Native sensor-stage acquisition aborted.\");\n if (state.disposed) throw new InvalidConfigurationError(\"Optical stage was disposed.\");\n const tile = requireAllowlistedRecord(supplied, [\"captureId\", \"frameId\", \"x\", \"y\", \"width\", \"height\", \"sites\"], \"Invalid physical source tile.\");\n for (const key of Object.keys(request) as (keyof NativeRawTileRequest)[]) if (tile[key] !== request[key]) throw new InvalidConfigurationError(\"Physical source tile identity mismatch.\");\n if (!Array.isArray(tile.sites) || tile.sites.length !== request.width || Array.from({ length: request.width }, (_, i) => i in (tile.sites as unknown[])).includes(false)) {\n throw new InvalidConfigurationError(\"Physical source tile needs exact native coverage.\");\n }\n // The supplied environment is only compared, in one synchronous pass, and never used: execution uses the\n // retained stage. Only the post-optics parts the sensor stage uses are cloned. The equality cache is per\n // tile, so a caller object changed between tiles is compared again.\n const tileVerified = new WeakMap<object, WeakSet<object>>();\n const suppliedSites = tile.sites as unknown[];\n const sites = structuredClone(suppliedSites.map((value, j) => {\n const site = requireAllowlistedRecord(value, [\"environment\", \"darkCurrentProfile\", \"operatingTemperatureC\", \"charge\", \"readout\"], \"Invalid physical site input.\");\n const index = request.y*width+request.x+j, e = site.environment as SiteEnvironment;\n if (typeof e !== \"object\" || e === null || !environmentMatches(e, state.environments[state.environmentIndex[index]!]!, tileVerified) ||\n e.temporalIntegrationId !== frameId+\":native:\"+index || typeof e.sensor.spatialSampling.site !== \"object\" || e.sensor.spatialSampling.site === null ||\n !strictlyEqual(e.sensor.spatialSampling.site, { x: index%width, y: Math.floor(index/width) }, tileVerified)) {\n throw new InvalidConfigurationError(\"Site environment differs from the retained optical stage; recompute the optical stage.\");\n }\n return { temporalIntegrationId: e.temporalIntegrationId, darkCurrentProfile: site.darkCurrentProfile, operatingTemperatureC: site.operatingTemperatureC,\n charge: site.charge, readout: site.readout };\n })) as (Omit<EnvironmentSite, \"environment\"> & { temporalIntegrationId: string })[];\n const photos = sites.map((site, j) => {\n const index = request.y*width+request.x+j;\n if (site.temporalIntegrationId !== frameId+\":native:\"+index) {\n throw new InvalidConfigurationError(\"Site environment differs from the retained optical stage; recompute the optical stage.\");\n }\n const v = state.values, o = index*state.stride, template = state.photoTemplates[state.photoIndex[index]!]!;\n const temporalSamples = Array.from({ length: state.temporalSampleCount }, (_, t) => {\n const q = o+FIXED_VALUES+3*t;\n return { timeSecondsFromOpeningReference: v[q]!, incidentPhotonRatePerSecond: v[q+1]!, expectedGeneratedElectronRatePerSecond: v[q+2]! };\n });\n return freezeOwnedData(parseSensorEqeTemporalPhotoSignal({ ...template, temporalIntegrationId: site.temporalIntegrationId, site: { x: v[o]!, y: v[o+1]! },\n startOffsetSecondsFromOpeningReference: v[o+2]!, endOffsetSecondsFromOpeningReference: v[o+3]!, localExposureDurationSeconds: v[o+4]!,\n expectedIncidentPhotonCount: v[o+5]!, expectedGeneratedElectronCount: v[o+6]!, temporalSamples }));\n });\n return { ...request, sites: sites.map((site, j) => composeNativeEnvironmentSensorSite(site, photos[j]!)) };\n },\n // Host yields are time-budgeted and always follow the final tile, so a stage disposed\n // while the host runs is caught here even when no further tile would be read.\n async yieldControl(signal) {\n await yieldControl(signal);\n if (state.disposed) throw new InvalidConfigurationError(\"Optical stage was disposed.\");\n }\n });\n // The task's own accepted plan is the one compared, so nothing is planned twice and no callback has run yet.\n if (!strictlyEqual(opticalBinding(task.plan, sceneBinding), state.binding, new WeakMap())) {\n task.dispose();\n throw new InvalidConfigurationError(\"Optical stage does not match this capture's optical inputs; recompute the optical stage.\");\n }\n return { task, sceneBinding };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"native-environment-optical-stage.js","sourceRoot":"","sources":["../../src/capture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EAAE,CAAC,kCAAkC,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC,CAAE,CAAC,CAAC,EAAE,CAAC;QAC7G,CAAC;QACD,sFAAsF;QACtF,8EAA8E;QAC9E,KAAK,CAAC,YAAY,CAAC,MAAM;YACvB,MAAM,YAAY,CAAC,MAAM,CAAC,CAAC;YAC3B,IAAI,KAAK,CAAC,QAAQ;gBAAE,MAAM,IAAI,yBAAyB,CAAC,6BAA6B,CAAC,CAAC;QACzF,CAAC;KACF,CAAC,CAAC;IACH,6GAA6G;IAC7G,IAAI,CAAC,aAAa,CAAC,cAAc,CAAC,IAAI,CAAC,IAAI,EAAE,YAAY,CAAC,EAAE,KAAK,CAAC,OAAO,EAAE,IAAI,OAAO,EAAE,CAAC,EAAE,CAAC;QAC1F,IAAI,CAAC,OAAO,EAAE,CAAC;QACf,MAAM,IAAI,yBAAyB,CAAC,0FAA0F,CAAC,CAAC;IAClI,CAAC;IACD,OAAO,EAAE,IAAI,EAAE,YAAY,EAAE,CAAC;AAChC,CAAC","sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Keeps (retains) the result of the optical stage of a native environment capture, so the sensor stage\n * can be re-run with new post-optics settings without calling the radiance callbacks again.\n *\n * Optical stage: scene radiance → optics, PSF (point-spread function) and pupil → expected photo signal\n * via EQE (external quantum efficiency). Sensor stage: dark charge → charge realization → readout.\n *\n * Reuse is exact, not approximate: the sensor stage receives a photo signal whose every number is the\n * float64 value the optical stage produced, and the same charge/noise/ADC code runs on it. Reuse is\n * refused unless the capture's optical binding and every site's environment input are strictly equal\n * to those the stage was produced from.\n * @see docs/NATIVE_RAW_AND_PRINT.md for the invariance analysis, memory bound and limits.\n */\n\nimport { createNativeRawTask, type NativeRawInput, type NativeRawPlan, type NativeRawTileRequest } from \"./native-raw.js\";\nimport type { SimulateEnvironmentSensorRawFrameInput } from \"./environment-raw-producer.js\";\nimport type { SensorRawProducerSiteInput } from \"./sensor-raw-producer.js\";\nimport { parseSensorEqeTemporalPhotoSignal, type SensorEqeTemporalPhotoSignal } from \"../sensor/temporal-photo-signal.js\";\nimport { calculateSensorDarkCurrentCharge } from \"../sensor/dark-current.js\";\nimport { requireAllowlistedRecord } from \"../core/record-validation.js\";\nimport { stringifyCanonicalJson } from \"../core/canonical-json.js\";\nimport { freezeOwnedData } from \"../core/owned-data.js\";\nimport { InvalidConfigurationError } from \"../core/configuration-error.js\";\n\ntype EnvironmentSite = SimulateEnvironmentSensorRawFrameInput[\"sites\"][number];\ntype SiteEnvironment = EnvironmentSite[\"environment\"];\n\n/**\n * Fixed retention limits. The per-site footprint of a retained optical stage is\n * `fixedBytesPerSite + bytesPerTemporalSamplePerSite × temporalSampleCount` bytes of typed-array storage;\n * distinct environment and photo templates (each about one site's input size) are capped separately.\n */\nexport const NATIVE_ENVIRONMENT_OPTICAL_STAGE_LIMITS = /* @__PURE__ */ Object.freeze({\n /** Two one-byte template indices plus seven float64 values (site x/y, window start/end/duration, photon/electron counts). */\n fixedBytesPerSite: 58,\n /** Three float64 values per temporal midpoint: time, incident-photon rate, generated-electron rate. */\n bytesPerTemporalSamplePerSite: 24,\n /** Distinct per-site environment inputs once the site index and integration ID are removed. */\n maximumEnvironmentTemplates: 256,\n /** Distinct photo-signal identity/evidence records once per-site numbers are removed. */\n maximumPhotoTemplates: 256\n});\n\n/** Optional request on NativeEnvironmentRawInput to keep the optical stage. The byte budget covers the typed-array storage described by the limits. */\nexport interface NativeEnvironmentOpticalStageRetention {\n maximumRetainedBytes: number;\n}\n\n/**\n * Opaque, engine-owned optical-stage result. It is valid only for captures whose optical binding and every\n * site's environment input are strictly equal to those that produced it. dispose() zeroes and releases the\n * storage; a disposed stage refuses every later use.\n */\nexport interface NativeEnvironmentOpticalStage {\n readonly kind: \"native-environment-optical-stage\";\n readonly pixelCount: number;\n readonly temporalSampleCount: number;\n /** Typed-array bytes held: pixelCount × (fixedBytesPerSite + bytesPerTemporalSamplePerSite × temporalSampleCount). */\n readonly retainedBytes: number;\n /** Radiance callbacks the producing task executed; reuse executes none. */\n readonly providerEvaluationCount: number;\n readonly disposed: boolean;\n dispose(): void;\n}\n\n/** Input for a post-optics re-run. `raw` may differ from the original capture only in post-optics fields. */\nexport interface NativeEnvironmentSensorStageInput {\n raw: NativeRawInput;\n sceneBinding: SimulateEnvironmentSensorRawFrameInput[\"sceneBinding\"];\n}\n/** Supplies the same physical site inputs as the original capture. Environments must equal the retained ones exactly. */\nexport interface NativeEnvironmentSensorStageProvider {\n readTile(request: Readonly<NativeRawTileRequest>, signal: AbortSignal): Promise<{ captureId: string; frameId: string; x: number; y: number;\n width: number; height: number; sites: SimulateEnvironmentSensorRawFrameInput[\"sites\"] }>;\n yieldControl(signal: AbortSignal): Promise<void>;\n}\n\nconst FIXED_VALUES = 7;\nconst ENVIRONMENT_SHARED_KEYS = [\"sceneBindings\", \"optics\", \"motion\", \"psf\", \"pupil\", \"fieldThroughput\"] as const;\n\nfunction canonical(value: unknown): string {\n return stringifyCanonicalJson(value, { undefinedObjectProperties: \"omit\", nonFiniteNumberMessage: \"Invalid native scene binding.\",\n unsupportedValueMessage: \"Invalid native scene binding.\" });\n}\n\nfunction isPlainRecord(value: object): boolean {\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\n/**\n * Strict structural equality of plain data: Object.is for primitives (so 0 and -0 differ), identical own\n * key sets, arrays element by element. Anything that is not a plain record or array is unequal unless it is\n * the same reference, so an unexpected value refuses reuse instead of being treated as equal.\n */\nfunction strictlyEqual(a: unknown, b: unknown, verified: WeakMap<object, WeakSet<object>>, skip?: ReadonlySet<string>): boolean {\n if (Object.is(a, b)) return true;\n if (typeof a !== \"object\" || typeof b !== \"object\" || a === null || b === null) return false;\n if (!skip && verified.get(a)?.has(b)) return true;\n if (Array.isArray(a)) {\n if (!Array.isArray(b) || a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (!(i in a) || !(i in b) || !strictlyEqual(a[i], b[i], verified)) return false;\n }\n } else {\n if (Array.isArray(b) || !isPlainRecord(a) || !isPlainRecord(b)) return false;\n const ak = Object.keys(a), bk = Object.keys(b);\n if (ak.length !== bk.length || Object.getOwnPropertySymbols(a).length !== 0 || Object.getOwnPropertySymbols(b).length !== 0) return false;\n for (const key of ak) {\n if (!Object.prototype.hasOwnProperty.call(b, key)) return false;\n if (skip?.has(key)) continue;\n if (!strictlyEqual((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key], verified)) return false;\n }\n }\n if (!skip) {\n let set = verified.get(a);\n if (!set) verified.set(a, set = new WeakSet());\n set.add(b);\n }\n return true;\n}\n\n/**\n * Environment equality except the two per-site fields that are bound to the absolute native index and\n * checked separately: temporalIntegrationId and sensor.spatialSampling.site.\n */\nfunction environmentMatches(e: SiteEnvironment, t: SiteEnvironment, verified: WeakMap<object, WeakSet<object>>): boolean {\n if (typeof e !== \"object\" || e === null || typeof e.sensor !== \"object\" || e.sensor === null ||\n typeof e.sensor.spatialSampling !== \"object\" || e.sensor.spatialSampling === null) return false;\n return strictlyEqual(e, t, verified, new Set([\"temporalIntegrationId\", \"sensor\"])) &&\n strictlyEqual(e.sensor, t.sensor, verified, new Set([\"spatialSampling\"])) &&\n strictlyEqual(e.sensor.spatialSampling, t.sensor.spatialSampling, verified, new Set([\"site\"]));\n}\n\n/**\n * Post-optics capture fields: noise seed/realization/model, ISO metadata, white-balance intent, adopted white,\n * capture identity, source artifact metadata and declared models. The optical stage never reads them.\n * Everything else in the normalized plan (scene state/time, geometry including orientation, focal length,\n * aperture, shutter, focus, frame/mode/CFA/binding profiles and the exposure window) is part of the binding.\n */\nfunction opticalBinding(plan: NativeRawPlan, sceneBinding: unknown): unknown {\n const { captureId, noise, source, whiteBalanceIntent, adoptedWhiteXyz, models, exposure, ...capture } = plan.exposure;\n void captureId; void noise; void source; void whiteBalanceIntent; void adoptedWhiteXyz; void models;\n const { iso, ...opticalExposure } = exposure; void iso;\n const { capture: frameCapture, ...frame } = plan.frame; void frameCapture;\n return { capture: { ...capture, exposure: opticalExposure }, frame, exposureWindow: plan.exposureWindow ?? null, sceneBinding };\n}\n\ninterface OpticalStageState {\n pixelCount: number;\n nativeWidth: number;\n frameId: string;\n stride: number;\n temporalSampleCount: number;\n binding: unknown;\n values: Float64Array;\n environmentIndex: Uint8Array;\n photoIndex: Uint8Array;\n environments: SiteEnvironment[];\n photoTemplates: Record<string, unknown>[];\n providerEvaluationCount: number;\n disposed: boolean;\n}\nconst STAGES = new WeakMap<object, OpticalStageState>();\n\nfunction release(state: OpticalStageState): void {\n state.values.fill(0); state.environmentIndex.fill(0); state.photoIndex.fill(0);\n state.values = new Float64Array(0); state.environmentIndex = new Uint8Array(0); state.photoIndex = new Uint8Array(0);\n state.environments = []; state.photoTemplates = []; state.disposed = true;\n}\n\nfunction photoTemplate(p: SensorEqeTemporalPhotoSignal): Record<string, unknown> {\n const { temporalIntegrationId, site, startOffsetSecondsFromOpeningReference, endOffsetSecondsFromOpeningReference,\n localExposureDurationSeconds, expectedIncidentPhotonCount, expectedGeneratedElectronCount, temporalSamples, ...rest } = p;\n void temporalIntegrationId; void site; void startOffsetSecondsFromOpeningReference; void endOffsetSecondsFromOpeningReference;\n void localExposureDurationSeconds; void expectedIncidentPhotonCount; void expectedGeneratedElectronCount; void temporalSamples;\n return rest;\n}\n\n/** Shared by full acquisition and reuse so the sensor stage receives an identical site record either way. */\nexport function composeNativeEnvironmentSensorSite(site: Omit<EnvironmentSite, \"environment\">, photoSignal: SensorEqeTemporalPhotoSignal): SensorRawProducerSiteInput {\n const darkCharge = calculateSensorDarkCurrentCharge({ exposure: photoSignal, darkCurrentProfile: site.darkCurrentProfile,\n operatingTemperatureC: site.operatingTemperatureC }).value;\n return { ...site.readout, charge: { ...site.charge, photoSignal, darkCharge } } as SensorRawProducerSiteInput;\n}\n\n/** Validates the optional retention request before any provider work. */\nexport function parseNativeEnvironmentOpticalStageRetention(value: unknown): NativeEnvironmentOpticalStageRetention {\n const r = requireAllowlistedRecord(value, [\"maximumRetainedBytes\"], \"Invalid optical-stage retention request.\");\n if (typeof r.maximumRetainedBytes !== \"number\" || !Number.isSafeInteger(r.maximumRetainedBytes) || r.maximumRetainedBytes < 1) {\n throw new InvalidConfigurationError(\"Optical-stage retention requires a positive safe-integer byte budget.\");\n }\n return { maximumRetainedBytes: r.maximumRetainedBytes };\n}\n\n/** Internal recorder used by createNativeEnvironmentRawTask when retention is requested. */\nexport interface NativeEnvironmentOpticalStageRecorder {\n /** Interns one planned site before any radiance callback; throws if a limit or the byte budget would be exceeded. */\n admit(index: number, environment: SiteEnvironment, sharedCanonical: string): void;\n record(index: number, photoSignal: SensorEqeTemporalPhotoSignal): void;\n finish(providerEvaluationCount: number): NativeEnvironmentOpticalStage;\n discard(): void;\n}\n\nexport function createNativeEnvironmentOpticalStageRecorder(plan: NativeRawPlan, sceneBinding: unknown,\n retention: NativeEnvironmentOpticalStageRetention): NativeEnvironmentOpticalStageRecorder {\n const L = NATIVE_ENVIRONMENT_OPTICAL_STAGE_LIMITS;\n const state: OpticalStageState = { pixelCount: plan.pixelCount, nativeWidth: plan.exposure.geometry.nativeRaster.pixelWidth,\n frameId: plan.frame.frameId, stride: 0, temporalSampleCount: 0, binding: freezeOwnedData(structuredClone(opticalBinding(plan, sceneBinding))),\n values: new Float64Array(0), environmentIndex: new Uint8Array(0), photoIndex: new Uint8Array(0), environments: [], photoTemplates: [],\n providerEvaluationCount: 0, disposed: false };\n const environmentKeys = new Map<string, number[]>(), photoKeys = new Map<string, number[]>(), verified = new WeakMap<object, WeakSet<object>>();\n const admitted = new Uint8Array(plan.pixelCount);\n let recorded = 0;\n function residualKey(e: SiteEnvironment, sharedCanonical: string): string {\n const rest: Record<string, unknown> = { ...e, temporalIntegrationId: undefined,\n sensor: { ...e.sensor, spatialSampling: { ...e.sensor.spatialSampling, site: undefined } } };\n for (const key of ENVIRONMENT_SHARED_KEYS) rest[key] = undefined;\n return sharedCanonical+\"\\u0000\"+canonical(rest);\n }\n return {\n admit(index, environment, sharedCanonical): void {\n if (state.disposed) throw new InvalidConfigurationError(\"Optical-stage retention was released.\");\n const n = environment.temporalSampleCount;\n if (state.stride === 0) {\n const bytes = plan.pixelCount*(L.fixedBytesPerSite+L.bytesPerTemporalSamplePerSite*n);\n if (!Number.isSafeInteger(bytes) || bytes > retention.maximumRetainedBytes) throw new InvalidConfigurationError(\"Optical-stage retention exceeds its byte budget.\");\n state.temporalSampleCount = n; state.stride = FIXED_VALUES+3*n;\n state.values = new Float64Array(plan.pixelCount*state.stride);\n state.environmentIndex = new Uint8Array(plan.pixelCount); state.photoIndex = new Uint8Array(plan.pixelCount);\n } else if (n !== state.temporalSampleCount) throw new InvalidConfigurationError(\"Optical-stage retention requires one temporal sample count per event.\");\n const key = residualKey(environment, sharedCanonical), candidates = environmentKeys.get(key) ?? [];\n let found = candidates.find(i => environmentMatches(environment, state.environments[i]!, verified));\n if (found === undefined) {\n if (state.environments.length >= L.maximumEnvironmentTemplates) throw new InvalidConfigurationError(\"Optical-stage retention exceeds its distinct site-environment limit.\");\n found = state.environments.length;\n state.environments.push(environment);\n candidates.push(found); environmentKeys.set(key, candidates);\n }\n state.environmentIndex[index] = found; admitted[index] = 1;\n },\n record(index, p): void {\n if (state.disposed || admitted[index] !== 1) throw new InvalidConfigurationError(\"Optical-stage retention was released or not admitted.\");\n const samples = p.temporalSamples;\n if (samples.length !== state.temporalSampleCount) throw new InvalidConfigurationError(\"Optical-stage temporal sample count changed.\");\n const template = photoTemplate(p), key = canonical(template), candidates = photoKeys.get(key) ?? [];\n let found = candidates.find(i => strictlyEqual(template, state.photoTemplates[i]!, verified));\n if (found === undefined) {\n if (state.photoTemplates.length >= L.maximumPhotoTemplates) throw new InvalidConfigurationError(\"Optical-stage retention exceeds its distinct photo-identity limit.\");\n found = state.photoTemplates.length;\n state.photoTemplates.push(freezeOwnedData(structuredClone(template)));\n candidates.push(found); photoKeys.set(key, candidates);\n }\n state.photoIndex[index] = found;\n const v = state.values, o = index*state.stride;\n v[o] = p.site.x; v[o+1] = p.site.y; v[o+2] = p.startOffsetSecondsFromOpeningReference; v[o+3] = p.endOffsetSecondsFromOpeningReference;\n v[o+4] = p.localExposureDurationSeconds; v[o+5] = p.expectedIncidentPhotonCount; v[o+6] = p.expectedGeneratedElectronCount;\n for (let t = 0; t < samples.length; t++) {\n const s = samples[t]!, q = o+FIXED_VALUES+3*t;\n v[q] = s.timeSecondsFromOpeningReference; v[q+1] = s.incidentPhotonRatePerSecond; v[q+2] = s.expectedGeneratedElectronRatePerSecond;\n }\n admitted[index] = 2; recorded++;\n },\n finish(providerEvaluationCount): NativeEnvironmentOpticalStage {\n if (state.disposed || recorded !== plan.pixelCount) throw new InvalidConfigurationError(\"Optical-stage retention is incomplete.\");\n for (const environment of state.environments) freezeOwnedData(environment);\n state.providerEvaluationCount = providerEvaluationCount;\n const handle: NativeEnvironmentOpticalStage = Object.freeze({ kind: \"native-environment-optical-stage\" as const,\n pixelCount: state.pixelCount, temporalSampleCount: state.temporalSampleCount,\n retainedBytes: state.pixelCount*(L.fixedBytesPerSite+L.bytesPerTemporalSamplePerSite*state.temporalSampleCount),\n providerEvaluationCount, get disposed(): boolean { return state.disposed; },\n dispose(): void { if (!state.disposed) release(state); } });\n STAGES.set(handle, state);\n return handle;\n },\n discard(): void { if (!state.disposed) release(state); }\n };\n}\n\n/**\n * Internal: re-runs only the sensor stage (dark charge, charge realization, capacity, seeded noise and ADC) from a retained\n * optical stage. The capture may change post-optics settings only: noise seed/realization, ISO metadata, readout\n * regime/gain, charge sampling/capacity/completeness, dark-current profile and temperature, white-balance intent,\n * capture identity and tile width. Every optical input must be strictly equal, otherwise this refuses before\n * output: the capture binding is checked here, each site's environment as its tile is read.\n */\nexport function createSensorStageRawTask<B>(input: NativeEnvironmentSensorStageInput, opticalStage: NativeEnvironmentOpticalStage,\n provider: NativeEnvironmentSensorStageProvider, parseSceneBinding: (value: unknown) => B):\n { task: ReturnType<typeof createNativeRawTask>; sceneBinding: B } {\n const state = typeof opticalStage === \"object\" && opticalStage !== null ? STAGES.get(opticalStage) : undefined;\n if (!state) throw new InvalidConfigurationError(\"Optical-stage reuse requires an engine-produced optical stage.\");\n if (state.disposed) throw new InvalidConfigurationError(\"Optical stage was disposed.\");\n const r = requireAllowlistedRecord(input, [\"raw\", \"sceneBinding\"], \"Invalid native sensor-stage input.\");\n const sceneBinding = parseSceneBinding(r.sceneBinding);\n if (!provider || typeof provider.readTile !== \"function\" || typeof provider.yieldControl !== \"function\") {\n throw new InvalidConfigurationError(\"Sensor-stage reuse requires physical site input and host yields.\");\n }\n const read = provider.readTile.bind(provider), yieldControl = provider.yieldControl.bind(provider);\n const width = state.nativeWidth, frameId = state.frameId;\n const task = createNativeRawTask(input.raw, {\n async readTile(request, signal) {\n const supplied = await read(request, signal);\n if (signal.aborted) throw new InvalidConfigurationError(\"Native sensor-stage acquisition aborted.\");\n if (state.disposed) throw new InvalidConfigurationError(\"Optical stage was disposed.\");\n const tile = requireAllowlistedRecord(supplied, [\"captureId\", \"frameId\", \"x\", \"y\", \"width\", \"height\", \"sites\"], \"Invalid physical source tile.\");\n for (const key of Object.keys(request) as (keyof NativeRawTileRequest)[]) if (tile[key] !== request[key]) throw new InvalidConfigurationError(\"Physical source tile identity mismatch.\");\n if (!Array.isArray(tile.sites) || tile.sites.length !== request.width || Array.from({ length: request.width }, (_, i) => i in (tile.sites as unknown[])).includes(false)) {\n throw new InvalidConfigurationError(\"Physical source tile needs exact native coverage.\");\n }\n // The supplied environment is only compared, in one synchronous pass, and never used: execution uses the\n // retained stage. Only the post-optics parts the sensor stage uses are cloned. The equality cache is per\n // tile, so a caller object changed between tiles is compared again.\n const tileVerified = new WeakMap<object, WeakSet<object>>();\n const suppliedSites = tile.sites as unknown[];\n const sites = structuredClone(suppliedSites.map((value, j) => {\n const site = requireAllowlistedRecord(value, [\"environment\", \"darkCurrentProfile\", \"operatingTemperatureC\", \"charge\", \"readout\"], \"Invalid physical site input.\");\n const index = request.y*width+request.x+j, e = site.environment as SiteEnvironment;\n if (typeof e !== \"object\" || e === null || !environmentMatches(e, state.environments[state.environmentIndex[index]!]!, tileVerified) ||\n e.temporalIntegrationId !== frameId+\":native:\"+index || typeof e.sensor.spatialSampling.site !== \"object\" || e.sensor.spatialSampling.site === null ||\n !strictlyEqual(e.sensor.spatialSampling.site, { x: index%width, y: Math.floor(index/width) }, tileVerified)) {\n throw new InvalidConfigurationError(\"Site environment differs from the retained optical stage; recompute the optical stage.\");\n }\n return { temporalIntegrationId: e.temporalIntegrationId, darkCurrentProfile: site.darkCurrentProfile, operatingTemperatureC: site.operatingTemperatureC,\n charge: site.charge, readout: site.readout };\n })) as (Omit<EnvironmentSite, \"environment\"> & { temporalIntegrationId: string })[];\n const photos = sites.map((site, j) => {\n const index = request.y*width+request.x+j;\n if (site.temporalIntegrationId !== frameId+\":native:\"+index) {\n throw new InvalidConfigurationError(\"Site environment differs from the retained optical stage; recompute the optical stage.\");\n }\n const v = state.values, o = index*state.stride, template = state.photoTemplates[state.photoIndex[index]!]!;\n const temporalSamples = Array.from({ length: state.temporalSampleCount }, (_, t) => {\n const q = o+FIXED_VALUES+3*t;\n return { timeSecondsFromOpeningReference: v[q]!, incidentPhotonRatePerSecond: v[q+1]!, expectedGeneratedElectronRatePerSecond: v[q+2]! };\n });\n return freezeOwnedData(parseSensorEqeTemporalPhotoSignal({ ...template, temporalIntegrationId: site.temporalIntegrationId, site: { x: v[o]!, y: v[o+1]! },\n startOffsetSecondsFromOpeningReference: v[o+2]!, endOffsetSecondsFromOpeningReference: v[o+3]!, localExposureDurationSeconds: v[o+4]!,\n expectedIncidentPhotonCount: v[o+5]!, expectedGeneratedElectronCount: v[o+6]!, temporalSamples }));\n });\n return { ...request, sites: sites.map((site, j) => composeNativeEnvironmentSensorSite(site, photos[j]!)) };\n },\n // Host yields are time-budgeted and always follow the final tile, so a stage disposed\n // while the host runs is caught here even when no further tile would be read.\n async yieldControl(signal) {\n await yieldControl(signal);\n if (state.disposed) throw new InvalidConfigurationError(\"Optical stage was disposed.\");\n }\n });\n // The task's own accepted plan is the one compared, so nothing is planned twice and no callback has run yet.\n if (!strictlyEqual(opticalBinding(task.plan, sceneBinding), state.binding, new WeakMap())) {\n task.dispose();\n throw new InvalidConfigurationError(\"Optical stage does not match this capture's optical inputs; recompute the optical stage.\");\n }\n return { task, sceneBinding };\n}\n"]}
|
|
@@ -18,7 +18,7 @@ import { calculateCaptureExposureWindows } from "../sensor/exposure-window.js";
|
|
|
18
18
|
import { SENSOR_RAW_PRODUCER_NOISE_MODEL, calculateNativeRawSite, parseNativeRawProducerSite, validateNativeRawReadoutIdentity } from "./sensor-raw-producer.js";
|
|
19
19
|
export const NATIVE_RAW_SCHEMA_VERSION = "0.1.0";
|
|
20
20
|
/** `maximumPixels` is the default pixel limit; a request may raise it with its own `maximumPixels`, up to `ceilingPixels`. */
|
|
21
|
-
export const NATIVE_RAW_LIMITS = Object.freeze({ maximumPixels: 24_000_000, ceilingPixels: FULL_RESOLUTION_CEILING_PIXELS, maximumDimension: 16_384,
|
|
21
|
+
export const NATIVE_RAW_LIMITS = /* @__PURE__ */ Object.freeze({ maximumPixels: 24_000_000, ceilingPixels: FULL_RESOLUTION_CEILING_PIXELS, maximumDimension: 16_384,
|
|
22
22
|
tileWidth: 256, tileHeight: 1, outputBytesPerPixel: 7 });
|
|
23
23
|
/** Default whole-event radiance query budget ceiling of the native environment tasks; it scales with a raised `maximumPixels`. */
|
|
24
24
|
const DEFAULT_MAXIMUM_PROVIDER_EVALUATIONS = 2_000_000_000;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"native-raw.js","sourceRoot":"","sources":["../../src/capture/native-raw.ts"],"names":[],"mappings":"AAAA,sCAAsC;AAEtC;;;GAGG;AACH,OAAO,EAAE,gCAAgC,EAAiF,MAAM,wBAAwB,CAAC;AACzJ,OAAO,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AACxD,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAC3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,OAAO,EAAE,CAAA,CAAC,CAAA,KAAK,CAAC,MAAM,EAAE,CAAC,CAAC;gBAAA,KAAK,GAAC,SAAS,CAAC;gBAAA,KAAK,GAAC,WAAW,CAAC;YAC7G,CAAC;YAAA,OAAM,KAAK,EAAC,CAAC;gBAAA,OAAO,EAAE,CAAC;gBAAA,IAAG,CAAC,KAAK,CAAC,MAAM,CAAC,OAAO,EAAC,CAAC;oBAAA,KAAK,GAAC,QAAQ,CAAC;oBAAA,KAAK,CAAC,KAAK,EAAE,CAAC;gBAAA,CAAC;gBAAA,MAAM,KAAK,CAAC;YAAA,CAAC;QAC/F,CAAC;QACD,MAAM,KAAU,IAAG,KAAK,KAAG,OAAO,IAAE,KAAK,KAAG,SAAS,IAAE,KAAK,KAAG,WAAW,EAAC,CAAC;YAAA,KAAK,GAAC,WAAW,CAAC;YAAA,KAAK,CAAC,KAAK,EAAE,CAAC;YAAA,OAAO,EAAE,CAAC;QAAA,CAAC,CAAA,CAAC;QACxH,OAAO,KAAU,IAAG,KAAK,KAAG,aAAa,EAAC,CAAC;YAAA,KAAK,GAAC,UAAU,CAAC;YAAA,KAAK,CAAC,KAAK,EAAE,CAAC;YAAA,OAAO,EAAE,CAAC;QAAA,CAAC,CAAA,CAAC;QACtF,UAAU,KAAqB,IAAG,KAAK,KAAG,WAAW,IAAE,CAAC,MAAM;YAAC,MAAM,IAAI,yBAAyB,CAAC,gCAAgC,CAAC,CAAC,CAAA,MAAM,MAAM,GAAC,MAAM,CAAC,CAAA,MAAM,GAAC,IAAI,CAAC,CAAA,KAAK,GAAC,SAAS,CAAC,CAAA,KAAK,GAAC,aAAa,CAAC,CAAA,OAAO,MAAM,CAAC,CAAA,CAAC;KACzN,CAAC;AACJ,CAAC","sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Native RAW capture with the existing per-site (scalar) RAW model: an up-front plan and limit check from\n * metadata only, then bounded tile-by-tile execution.\n */\nimport { normalizeCaptureExposureMetadata, type SimulatedCaptureInput, type SimulatedCapture, type CaptureExposureSource } from \"./simulated-capture.js\";\nimport { ENGINE_API_VERSION } from \"../core/version.js\";\nimport { InvalidConfigurationError } from \"../core/configuration-error.js\";\nimport { requireAllowlistedRecord, requirePublicOpaqueId } from \"../core/record-validation.js\";\nimport { freezeOwnedData } from \"../core/owned-data.js\";\nimport { FULL_RESOLUTION_CEILING_PIXELS, resolveRaisedLimit, scaleBudgetCeiling } from \"../core/pixel-limits.js\";\nimport { calculateSiteEffectiveSaturationCode, createPhaseWhiteLevelAccumulator } from \"./raw-white-level.js\";\nimport { DEFAULT_HOST_YIELD_CADENCE, createHostYieldGate, type HostYieldCadence, type HostYieldGate } from \"./host-yield-cadence.js\";\nimport { parseCaptureModeProfile } from \"../sensor/capture-mode.js\";\nimport { parseSensorColorSamplingProfile } from \"../sensor/color-sampling.js\";\nimport { parseNativeEffectiveRasterColorSamplingBindingProfile, resolveCaptureModeColorSamplingContributors } from \"../sensor/capture-color-sampling-binding.js\";\nimport { calculateCaptureExposureWindows } from \"../sensor/exposure-window.js\";\nimport { SENSOR_RAW_PRODUCER_NOISE_MODEL, calculateNativeRawSite, parseNativeRawProducerSite,\n validateNativeRawReadoutIdentity, type NativeRawProducerFrameContext, type SensorRawProducerSiteInput,\n type SensorRawProducerExposureWindowInput } from \"./sensor-raw-producer.js\";\n\nexport const NATIVE_RAW_SCHEMA_VERSION = \"0.1.0\" as const;\n/** `maximumPixels` is the default pixel limit; a request may raise it with its own `maximumPixels`, up to `ceilingPixels`. */\nexport const NATIVE_RAW_LIMITS = Object.freeze({ maximumPixels: 24_000_000, ceilingPixels: FULL_RESOLUTION_CEILING_PIXELS, maximumDimension: 16_384,\n tileWidth: 256, tileHeight: 1, outputBytesPerPixel: 7 });\n/** Default whole-event radiance query budget ceiling of the native environment tasks; it scales with a raised `maximumPixels`. */\nconst DEFAULT_MAXIMUM_PROVIDER_EVALUATIONS = 2_000_000_000;\n/** A shooting event and where its source came from. Not a finished float master or committed RAW frame. */\nexport type NativeRawExposureInput = Omit<SimulatedCaptureInput, \"planes\" | \"source\"> & {source:CaptureExposureSource};\nexport type NativeRawExposure = Omit<SimulatedCapture, \"schemaVersion\" | \"planes\" | \"source\"> & {source:CaptureExposureSource};\nexport interface NativeRawInput {\n exposure: NativeRawExposureInput;\n frameId: string;\n modeId: string;\n captureModeProfile: NativeRawProducerFrameContext[\"captureModeProfile\"];\n colorSamplingProfile: NativeRawProducerFrameContext[\"colorSamplingProfile\"];\n bindingProfile: NativeRawProducerFrameContext[\"bindingProfile\"];\n exposureWindow?: SensorRawProducerExposureWindowInput;\n maximumOutputBytes: number;\n /** Optional tile width for execution, in native sites, 1–256. Default 256. It does not affect sampling. */\n tileWidth?: number;\n /**\n * Optional opt-in pixel limit for large sensors: an integer from 1 to `NATIVE_RAW_LIMITS.ceilingPixels`.\n * Default `NATIVE_RAW_LIMITS.maximumPixels` (24 000 000). `maximumOutputBytes` still applies. A raised limit\n * also raises the native environment tasks' whole-event query budget ceiling in proportion\n * (2 000 000 000 per 24 000 000 pixels). It does not affect sampling.\n */\n maximumPixels?: number;\n}\nexport interface NativeRawPlan {\n schemaVersion: typeof NATIVE_RAW_SCHEMA_VERSION;\n exposure: NativeRawExposure;\n frame: NativeRawProducerFrameContext;\n exposureWindow?: SensorRawProducerExposureWindowInput;\n pixelCount: number;\n outputBytes: number;\n tileCount: number;\n /** Present only when an execution tile width was given. Otherwise the plan keeps its earlier shape. */\n tileWidth?: number;\n /** Present only when a pixel limit was given. Otherwise the plan keeps its earlier shape. */\n maximumPixels?: number;\n upstreamRadiometryVerified: false;\n seedSchedule: \"murmur3-capture-seed-native-index-stream-v2\";\n}\n/** Tile rectangle, in absolute full-sensor CFA coordinates, before orientation, active-area crop or output scaling. */\nexport interface NativeRawTileRequest { captureId: string; frameId: string; x: number; y: number; width: number; height: number }\nexport interface NativeRawTile extends NativeRawTileRequest { sites: readonly SensorRawProducerSiteInput[] }\nexport interface NativeRawProvider {\n readTile(request: Readonly<NativeRawTileRequest>, signal: AbortSignal): Promise<NativeRawTile>;\n yieldControl(signal: AbortSignal): Promise<void>;\n}\n/** Row-major arrays owned only by the output. They cannot be attached to the bounded SensorRawFrame type. */\nexport interface NativeRawOutput {\n plan: NativeRawPlan;\n codes: Uint16Array;\n blackLevels: Uint16Array;\n digitalSaturationCodes: Uint16Array;\n /** Saturation flags. Bit 0: physical charge clamp; bit 1: pre-ADC clamp; bit 2: digital saturation. */\n saturationFlags: Uint8Array;\n /**\n * Effective white (full-saturation) code for each absolute CFA repeat phase, indexed\n * `phaseY*repeatWidthSites+phaseX`: min(digital saturation, round(black + min(capacity, pre-ADC\n * saturation)/gain)). See `calculateEffectiveSaturationCode`. A few bytes, not one value per pixel.\n */\n effectiveSaturationCodes: Uint16Array;\n}\n/** Internal: lean per-site outputs of an engine-built site (see native-environment-lean.ts). */\nexport interface NativeRawLeanOutput { rawCode: number; blackLevelCode: number; digitalSaturationCode: number; flags: number; whiteCode: number }\n/**\n * Internal hook for tiles the engine builds itself (native environment RAW).\n *\n * claim() recognizes only entries the hook itself created, for sites whose parsing and identity checks are\n * provably redundant. compute() returns the outputs calculateNativeRawSite would produce, falling back to it\n * internally. observe() sees every fully computed site.\n */\nexport interface NativeRawLeanSensorHook {\n claim(site: unknown): object | undefined;\n compute(handle: object, index: number, seed: number, timing: ReturnType<typeof calculateCaptureExposureWindows>[\"value\"][\"samples\"][number] | undefined): NativeRawLeanOutput;\n observe(index: number, parsed: SensorRawProducerSiteInput, result: ReturnType<typeof calculateNativeRawSite>, whiteCode: number, seed: number): void;\n}\nexport type NativeRawTaskState = \"ready\" | \"running\" | \"completed\" | \"cancelled\" | \"failed\" | \"disposed\" | \"transferred\";\nexport interface NativeRawTask {\n readonly plan: NativeRawPlan;\n readonly state: NativeRawTaskState;\n readonly completedTileCount: number;\n run(): Promise<void>;\n cancel(): void;\n dispose(): void;\n takeOutput(): NativeRawOutput;\n}\nfunction windows(exposure: NativeRawExposure, schedule: SensorRawProducerExposureWindowInput,\n points: readonly {x:number;y:number}[]): ReturnType<typeof calculateCaptureExposureWindows>[\"value\"] {\n const r=requireAllowlistedRecord(schedule,[\"shutterMechanism\",\"nominalExposureDurationSeconds\",\"opening\",\"closing\"],\"Invalid RAW exposure schedule.\");\n requireAllowlistedRecord(r.nominalExposureDurationSeconds,[\"value\",\"unit\",\"evidence\"],\"Invalid RAW nominal exposure.\");\n for(const boundary of [r.opening,r.closing]){\n const b=requireAllowlistedRecord(boundary,[\"kind\",\"directionNative\",\"traversalDurationSeconds\"],\"Invalid RAW exposure boundary.\");\n if(b.directionNative!==undefined)requireAllowlistedRecord(b.directionNative,[\"value\",\"evidence\"],\"Invalid RAW scan direction.\");\n if(b.traversalDurationSeconds!==undefined)requireAllowlistedRecord(b.traversalDurationSeconds,[\"value\",\"unit\",\"evidence\"],\"Invalid RAW scan duration.\");\n }\n const result=calculateCaptureExposureWindows({...schedule,nativeRaster:exposure.geometry.nativeRaster,samplePointsNative:points});\n if(result.value.nominalExposureDurationSeconds.value!==exposure.exposure.shutterSeconds)throw new InvalidConfigurationError(\"RAW schedule differs from exposure duration.\");\n return result.value;\n}\n/** Plans the task and checks the image size, resources and profiles before any callback or output allocation. No placeholder plane is made. */\nexport function calculateNativeRawPlan(input: NativeRawInput): NativeRawPlan {\n const r=requireAllowlistedRecord(input,[\"exposure\",\"frameId\",\"modeId\",\"captureModeProfile\",\"colorSamplingProfile\",\"bindingProfile\",\"exposureWindow\",\"maximumOutputBytes\",\"tileWidth\",\"maximumPixels\"],\"Invalid native RAW input.\");\n if(r.tileWidth!==undefined&&(typeof r.tileWidth!==\"number\"||!Number.isSafeInteger(r.tileWidth)||r.tileWidth<1||r.tileWidth>NATIVE_RAW_LIMITS.tileWidth))\n throw new InvalidConfigurationError(\"Native RAW tile width must be an integer from 1 to 256.\");\n const tileWidth=(r.tileWidth as number|undefined)??NATIVE_RAW_LIMITS.tileWidth;\n const maximumPixels=resolveRaisedLimit(r.maximumPixels,NATIVE_RAW_LIMITS.maximumPixels,NATIVE_RAW_LIMITS.ceilingPixels,\n \"Native RAW maximumPixels must be an integer from 1 to \"+NATIVE_RAW_LIMITS.ceilingPixels+\".\");\n const exposure=normalizeCaptureExposureMetadata(r.exposure,ENGINE_API_VERSION,true),native=exposure.geometry.nativeRaster;\n const pixelCount=native.pixelWidth*native.pixelHeight,outputBytes=pixelCount*NATIVE_RAW_LIMITS.outputBytesPerPixel;\n if(pixelCount>maximumPixels||native.pixelWidth>NATIVE_RAW_LIMITS.maximumDimension||native.pixelHeight>NATIVE_RAW_LIMITS.maximumDimension||\n !Number.isSafeInteger(r.maximumOutputBytes)||typeof r.maximumOutputBytes!==\"number\"||r.maximumOutputBytes<outputBytes)throw new InvalidConfigurationError(\"Native RAW raster exceeds output admission budget.\");\n const frame={frameId:requirePublicOpaqueId(r.frameId,\"Invalid RAW frame ID.\"),capture:exposure,\n modeId:requirePublicOpaqueId(r.modeId,\"Invalid RAW mode ID.\"),containerBitDepth:16 as const,\n captureModeProfile:parseCaptureModeProfile(r.captureModeProfile),colorSamplingProfile:parseSensorColorSamplingProfile(r.colorSamplingProfile),\n bindingProfile:parseNativeEffectiveRasterColorSamplingBindingProfile(r.bindingProfile)};\n const mode=frame.captureModeProfile.modes.find(m=>m.modeId===frame.modeId);\n if(exposure.noise.model.id!==SENSOR_RAW_PRODUCER_NOISE_MODEL.id||exposure.noise.model.version!==SENSOR_RAW_PRODUCER_NOISE_MODEL.version||\n frame.colorSamplingProfile.layout.kind!==\"periodic-mosaic\"||mode?.acquisition.kind!==\"single-frame\"||mode.perFrameSampling.kind!==\"native-effective-raster\"||(mode.reconstructionStages?.length??0)!==0)\n throw new InvalidConfigurationError(\"Native RAW requires exact noise identity and single-frame native periodic CFA.\");\n // The binding is one affine mapping for the whole frame, so checking both corners covers it. Do this before any provider work.\n for(const p of [{x:0,y:0},{x:native.pixelWidth-1,y:native.pixelHeight-1}]){\n const c=resolveCaptureModeColorSamplingContributors({nativeRaster:native,captureModeProfile:frame.captureModeProfile,modeId:frame.modeId,colorSamplingProfile:frame.colorSamplingProfile,bindingProfile:frame.bindingProfile,modeSampleIndexFullFrame:p});\n if(c.totalContributorSites!==1||c.channelComposition.kind!==\"single-channel\")throw new InvalidConfigurationError(\"Native RAW must preserve one native CFA site per sample.\");\n }\n const schedule=r.exposureWindow===undefined?undefined:structuredClone(r.exposureWindow) as SensorRawProducerExposureWindowInput;\n // For the supported linear scans, the extreme values occur at the image corners. Check them before capture.\n if(schedule)windows(exposure,schedule,[{x:.5,y:.5},{x:native.pixelWidth-.5,y:.5},{x:.5,y:native.pixelHeight-.5},{x:native.pixelWidth-.5,y:native.pixelHeight-.5}]);\n return freezeOwnedData({schemaVersion:NATIVE_RAW_SCHEMA_VERSION,exposure,frame,pixelCount,outputBytes,\n tileCount:Math.ceil(native.pixelWidth/tileWidth)*native.pixelHeight,\n ...(r.tileWidth===undefined?{}:{tileWidth}),\n ...(r.maximumPixels===undefined?{}:{maximumPixels}),\n ...(schedule?{exposureWindow:schedule}:{}),upstreamRadiometryVerified:false as const,\n seedSchedule:\"murmur3-capture-seed-native-index-stream-v2\" as const});\n}\n/**\n * Internal: the largest whole-event radiance query budget a native environment task admits for this plan:\n * 2 000 000 000, scaled in proportion when the plan raised its pixel limit above 24 000 000. Not exported from the package.\n */\nexport function nativeRawMaximumProviderEvaluations(plan: Pick<NativeRawPlan,\"maximumPixels\">): number {\n return plan.maximumPixels===undefined?DEFAULT_MAXIMUM_PROVIDER_EVALUATIONS:scaleBudgetCeiling(DEFAULT_MAXIMUM_PROVIDER_EVALUATIONS,plan.maximumPixels);\n}\n/**\n * Runs validated per-site events (EQE photo signal, dark signal, charge completeness) through the shared\n * reference per-site physics.\n *\n * Tiles are read and committed one at a time. The task yields to the host at tile boundaries once about\n * 8 ms of work has passed since the last yield, and after the final tile. It checks for cancellation\n * before every tile, after every read and after every yield.\n */\nexport function createNativeRawTask(input: NativeRawInput,provider: NativeRawProvider): NativeRawTask {\n return createNativeRawTaskWithCadence(input,provider,DEFAULT_HOST_YIELD_CADENCE);\n}\n/** Internal: the same task with an explicit host-yield timing. Timing never changes tiles, seeds or output. Not exported from the package. */\nexport function createNativeRawTaskWithCadence(input: NativeRawInput,provider: NativeRawProvider,cadence: HostYieldCadence,\n /** Internal: a yield timer shared with a provider that also yields inside readTile, so both use one time budget. */\n sharedGate?: HostYieldGate,\n /** Internal: faster (\"lean\") per-site sensor execution for engine-built tiles. It never changes output or errors. */\n leanSensor?: NativeRawLeanSensorHook,\n /**\n * Internal: run only native rows [y, y + height) (a partition). The output arrays then hold just those rows, and\n * effectiveSaturationCodes holds 0 for CFA phases the rows do not contain; the merge step completes them.\n * Seeds, tiles and per-site values are those of the whole-frame task.\n */\n rows?: { readonly y: number; readonly height: number; readonly firstSite?: (site: SensorRawProducerSiteInput) => void;\n /** Internal (2.3 region rendering): also restrict to native columns [x, x + width). The output arrays are then that rectangle, row-major. */\n readonly x?: number; readonly width?: number }): NativeRawTask {\n const plan=calculateNativeRawPlan(input);\n if(!provider||typeof provider.readTile!==\"function\"||typeof provider.yieldControl!==\"function\")throw new InvalidConfigurationError(\"Native RAW requires reader and host event-loop yield.\");\n const read=provider.readTile.bind(provider),yieldControl=provider.yieldControl.bind(provider),abort=new AbortController();\n const native=plan.exposure.geometry.nativeRaster,tileWidth=plan.tileWidth??NATIVE_RAW_LIMITS.tileWidth;\n const rowStart=rows?.y??0,rowEnd=rowStart+(rows?.height??native.pixelHeight),colStart=rows?.x??0,colEnd=colStart+(rows?.width??native.pixelWidth);\n if(colStart<0||colEnd>native.pixelWidth||colEnd<=colStart)throw new InvalidConfigurationError(\"Native RAW column band must lie inside the native raster.\");\n const bandWidth=colEnd-colStart,length=(rowEnd-rowStart)*bandWidth;\n let state:NativeRawTaskState=\"ready\",count=0,output:NativeRawOutput|null=null,first:SensorRawProducerSiteInput|undefined;\n function release(): void {if(output){output.codes.fill(0);output.blackLevels.fill(0);output.digitalSaturationCodes.fill(0);output.saturationFlags.fill(0);output.effectiveSaturationCodes.fill(0);}output=null;first=undefined;}\n function active(): void {if(abort.signal.aborted)throw new InvalidConfigurationError(\"Native RAW execution aborted.\");}\n return {plan,get state(): NativeRawTaskState {return state;},get completedTileCount(): number {return count;},\n async run(): Promise<void> {\n if(state!==\"ready\")throw new InvalidConfigurationError(\"Native RAW task is single-use.\");state=\"running\";\n try{\n const gate=sharedGate??createHostYieldGate(cadence);sharedGate?.restart();\n const layout=plan.frame.colorSamplingProfile.layout;if(layout.kind!==\"periodic-mosaic\")throw new InvalidConfigurationError(\"Native RAW requires periodic CFA.\");\n const white=createPhaseWhiteLevelAccumulator(native.pixelWidth,layout.repeatWidthSites,layout.repeatHeightSites);\n output={plan,codes:new Uint16Array(length),blackLevels:new Uint16Array(length),digitalSaturationCodes:new Uint16Array(length),saturationFlags:new Uint8Array(length),effectiveSaturationCodes:new Uint16Array(layout.repeatWidthSites*layout.repeatHeightSites)};\n for(let y=rowStart;y<rowEnd;y++)for(let x=colStart;x<colEnd;x+=tileWidth){\n active();const request=Object.freeze({captureId:plan.exposure.captureId,frameId:plan.frame.frameId,x,y,width:Math.min(tileWidth,colEnd-x),height:1});\n {\n const supplied=await read(request,abort.signal);active();\n const tile=requireAllowlistedRecord(supplied,[\"captureId\",\"frameId\",\"x\",\"y\",\"width\",\"height\",\"sites\"],\"Invalid native RAW tile.\");\n for(const key of Object.keys(request) as (keyof NativeRawTileRequest)[])if(tile[key]!==request[key])throw new InvalidConfigurationError(\"Native RAW tile identity mismatch.\");\n if(!Array.isArray(tile.sites)||tile.sites.length!==request.width||Array.from({length:request.width},(_,i)=>i in (tile.sites as unknown[])).includes(false))throw new InvalidConfigurationError(\"Native RAW tile needs exact dense coverage.\");\n const timing=plan.exposureWindow?windows(plan.exposure,plan.exposureWindow,Array.from({length:request.width},(_,i)=>({x:x+i+.5,y:y+.5}))):undefined;\n // Lean entries (built by the engine, provably valid against an earlier verified template) skip parsing and\n // identity checks. They are only claimed once the frame's first site is fixed.\n const lean=leanSensor&&first!==undefined?(tile.sites as unknown[]).map(site=>leanSensor.claim(site)):undefined;\n const sites=tile.sites.map((site,j)=>lean?.[j]?undefined:parseNativeRawProducerSite(site,y*native.pixelWidth+x+j,plan.frame,timing?.samples[j]));\n if(first===undefined){first=sites[0];if(first)rows?.firstSite?.(first);}for(const s of sites)if(s)validateNativeRawReadoutIdentity(s,first!);\n // Every site in this tile is validated before any output is written. A failure never returns partial output.\n const seed=plan.exposure.noise.seedUint32;\n for(let j=0;j<sites.length;j++){\n // index: absolute native index (seeds, CFA phase); at: position in this task's output arrays.\n const index=y*native.pixelWidth+x+j,at=(y-rowStart)*bandWidth+x+j-colStart,handle=lean?.[j];\n if(handle){\n const o=leanSensor!.compute(handle,index,seed,timing?.samples[j]);\n output.codes[at]=o.rawCode;output.blackLevels[at]=o.blackLevelCode;output.digitalSaturationCodes[at]=o.digitalSaturationCode;\n output.saturationFlags[at]=o.flags;white.record(index,o.whiteCode);continue;\n }\n const result=calculateNativeRawSite(sites[j]!,seed,index),r=result.readout.value;\n output.codes[at]=r.rawCode;output.blackLevels[at]=r.blackLevelCode;output.digitalSaturationCodes[at]=r.digitalSaturationCode;\n output.saturationFlags[at]=Number(r.physicalScalarSaturationApplied)|Number(r.preAdcSaturationApplied)<<1|Number(r.digitalSaturationApplied)<<2;\n const whiteCode=calculateSiteEffectiveSaturationCode(r,sites[j]!.readoutProfile,sites[j]!.regimeId);\n white.record(index,whiteCode);\n leanSensor?.observe(index,sites[j]!,result,whiteCode,seed);\n }\n count++;\n }\n // Yield when the time budget is spent, and always after the final tile. Yield timing never changes output.\n if(gate.due()||(y===rowEnd-1&&x+tileWidth>=colEnd)){await yieldControl(abort.signal);active();gate.restart();}\n }\n output.effectiveSaturationCodes.set(rows?white.partial():white.finish());first=undefined;state=\"completed\";\n }catch(error){release();if(!abort.signal.aborted){state=\"failed\";abort.abort();}throw error;}\n },\n cancel(): void {if(state===\"ready\"||state===\"running\"||state===\"completed\"){state=\"cancelled\";abort.abort();release();}},\n dispose(): void {if(state!==\"transferred\"){state=\"disposed\";abort.abort();release();}},\n takeOutput(): NativeRawOutput {if(state!==\"completed\"||!output)throw new InvalidConfigurationError(\"Native RAW output unavailable.\");const result=output;output=null;first=undefined;state=\"transferred\";return result;}\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"native-raw.js","sourceRoot":"","sources":["../../src/capture/native-raw.ts"],"names":[],"mappings":"AAAA,sCAAsC;AAEtC;;;GAGG;AACH,OAAO,EAAE,gCAAgC,EAAiF,MAAM,wBAAwB,CAAC;AACzJ,OAAO,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AACxD,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAC3E,OAAO,EAAE,wBAAwB,EAAE,qBAAqB,EAAE,MAAM,8BAA8B,CAAC;AAC/F,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,8BAA8B,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AACjH,OAAO,EAAE,oCAAoC,EAAE,gCAAgC,EAAE,MAAM,sBAAsB,CAAC;AAC9G,OAAO,EAAE,0BAA0B,EAAE,mBAAmB,EAA6C,MAAM,yBAAyB,CAAC;AACrI,OAAO,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AACpE,OAAO,EAAE,+BAA+B,EAAE,MAAM,6BAA6B,CAAC;AAC9E,OAAO,EAAE,qDAAqD,EAAE,2CAA2C,EAAE,MAAM,6CAA6C,CAAC;AACjK,OAAO,EAAE,+BAA+B,EAAE,MAAM,8BAA8B,CAAC;AAC/E,OAAO,EAAE,+BAA+B,EAAE,sBAAsB,EAAE,0BAA0B,EAC1F,gCAAgC,EACW,MAAM,0BAA0B,CAAC;AAE9E,MAAM,CAAC,MAAM,yBAAyB,GAAG,OAAgB,CAAC;AAC1D,8HAA8H;AAC9H,MAAM,CAAC,MAAM,iBAAiB,GAAG,eAAe,CAAC,MAAM,CAAC,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F,UAAU,KAAqB,IAAG,KAAK,KAAG,WAAW,IAAE,CAAC,MAAM;YAAC,MAAM,IAAI,yBAAyB,CAAC,gCAAgC,CAAC,CAAC,CAAA,MAAM,MAAM,GAAC,MAAM,CAAC,CAAA,MAAM,GAAC,IAAI,CAAC,CAAA,KAAK,GAAC,SAAS,CAAC,CAAA,KAAK,GAAC,aAAa,CAAC,CAAA,OAAO,MAAM,CAAC,CAAA,CAAC;KACzN,CAAC;AACJ,CAAC","sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Native RAW capture with the existing per-site (scalar) RAW model: an up-front plan and limit check from\n * metadata only, then bounded tile-by-tile execution.\n */\nimport { normalizeCaptureExposureMetadata, type SimulatedCaptureInput, type SimulatedCapture, type CaptureExposureSource } from \"./simulated-capture.js\";\nimport { ENGINE_API_VERSION } from \"../core/version.js\";\nimport { InvalidConfigurationError } from \"../core/configuration-error.js\";\nimport { requireAllowlistedRecord, requirePublicOpaqueId } from \"../core/record-validation.js\";\nimport { freezeOwnedData } from \"../core/owned-data.js\";\nimport { FULL_RESOLUTION_CEILING_PIXELS, resolveRaisedLimit, scaleBudgetCeiling } from \"../core/pixel-limits.js\";\nimport { calculateSiteEffectiveSaturationCode, createPhaseWhiteLevelAccumulator } from \"./raw-white-level.js\";\nimport { DEFAULT_HOST_YIELD_CADENCE, createHostYieldGate, type HostYieldCadence, type HostYieldGate } from \"./host-yield-cadence.js\";\nimport { parseCaptureModeProfile } from \"../sensor/capture-mode.js\";\nimport { parseSensorColorSamplingProfile } from \"../sensor/color-sampling.js\";\nimport { parseNativeEffectiveRasterColorSamplingBindingProfile, resolveCaptureModeColorSamplingContributors } from \"../sensor/capture-color-sampling-binding.js\";\nimport { calculateCaptureExposureWindows } from \"../sensor/exposure-window.js\";\nimport { SENSOR_RAW_PRODUCER_NOISE_MODEL, calculateNativeRawSite, parseNativeRawProducerSite,\n validateNativeRawReadoutIdentity, type NativeRawProducerFrameContext, type SensorRawProducerSiteInput,\n type SensorRawProducerExposureWindowInput } from \"./sensor-raw-producer.js\";\n\nexport const NATIVE_RAW_SCHEMA_VERSION = \"0.1.0\" as const;\n/** `maximumPixels` is the default pixel limit; a request may raise it with its own `maximumPixels`, up to `ceilingPixels`. */\nexport const NATIVE_RAW_LIMITS = /* @__PURE__ */ Object.freeze({ maximumPixels: 24_000_000, ceilingPixels: FULL_RESOLUTION_CEILING_PIXELS, maximumDimension: 16_384,\n tileWidth: 256, tileHeight: 1, outputBytesPerPixel: 7 });\n/** Default whole-event radiance query budget ceiling of the native environment tasks; it scales with a raised `maximumPixels`. */\nconst DEFAULT_MAXIMUM_PROVIDER_EVALUATIONS = 2_000_000_000;\n/** A shooting event and where its source came from. Not a finished float master or committed RAW frame. */\nexport type NativeRawExposureInput = Omit<SimulatedCaptureInput, \"planes\" | \"source\"> & {source:CaptureExposureSource};\nexport type NativeRawExposure = Omit<SimulatedCapture, \"schemaVersion\" | \"planes\" | \"source\"> & {source:CaptureExposureSource};\nexport interface NativeRawInput {\n exposure: NativeRawExposureInput;\n frameId: string;\n modeId: string;\n captureModeProfile: NativeRawProducerFrameContext[\"captureModeProfile\"];\n colorSamplingProfile: NativeRawProducerFrameContext[\"colorSamplingProfile\"];\n bindingProfile: NativeRawProducerFrameContext[\"bindingProfile\"];\n exposureWindow?: SensorRawProducerExposureWindowInput;\n maximumOutputBytes: number;\n /** Optional tile width for execution, in native sites, 1–256. Default 256. It does not affect sampling. */\n tileWidth?: number;\n /**\n * Optional opt-in pixel limit for large sensors: an integer from 1 to `NATIVE_RAW_LIMITS.ceilingPixels`.\n * Default `NATIVE_RAW_LIMITS.maximumPixels` (24 000 000). `maximumOutputBytes` still applies. A raised limit\n * also raises the native environment tasks' whole-event query budget ceiling in proportion\n * (2 000 000 000 per 24 000 000 pixels). It does not affect sampling.\n */\n maximumPixels?: number;\n}\nexport interface NativeRawPlan {\n schemaVersion: typeof NATIVE_RAW_SCHEMA_VERSION;\n exposure: NativeRawExposure;\n frame: NativeRawProducerFrameContext;\n exposureWindow?: SensorRawProducerExposureWindowInput;\n pixelCount: number;\n outputBytes: number;\n tileCount: number;\n /** Present only when an execution tile width was given. Otherwise the plan keeps its earlier shape. */\n tileWidth?: number;\n /** Present only when a pixel limit was given. Otherwise the plan keeps its earlier shape. */\n maximumPixels?: number;\n upstreamRadiometryVerified: false;\n seedSchedule: \"murmur3-capture-seed-native-index-stream-v2\";\n}\n/** Tile rectangle, in absolute full-sensor CFA coordinates, before orientation, active-area crop or output scaling. */\nexport interface NativeRawTileRequest { captureId: string; frameId: string; x: number; y: number; width: number; height: number }\nexport interface NativeRawTile extends NativeRawTileRequest { sites: readonly SensorRawProducerSiteInput[] }\nexport interface NativeRawProvider {\n readTile(request: Readonly<NativeRawTileRequest>, signal: AbortSignal): Promise<NativeRawTile>;\n yieldControl(signal: AbortSignal): Promise<void>;\n}\n/** Row-major arrays owned only by the output. They cannot be attached to the bounded SensorRawFrame type. */\nexport interface NativeRawOutput {\n plan: NativeRawPlan;\n codes: Uint16Array;\n blackLevels: Uint16Array;\n digitalSaturationCodes: Uint16Array;\n /** Saturation flags. Bit 0: physical charge clamp; bit 1: pre-ADC clamp; bit 2: digital saturation. */\n saturationFlags: Uint8Array;\n /**\n * Effective white (full-saturation) code for each absolute CFA repeat phase, indexed\n * `phaseY*repeatWidthSites+phaseX`: min(digital saturation, round(black + min(capacity, pre-ADC\n * saturation)/gain)). See `calculateEffectiveSaturationCode`. A few bytes, not one value per pixel.\n */\n effectiveSaturationCodes: Uint16Array;\n}\n/** Internal: lean per-site outputs of an engine-built site (see native-environment-lean.ts). */\nexport interface NativeRawLeanOutput { rawCode: number; blackLevelCode: number; digitalSaturationCode: number; flags: number; whiteCode: number }\n/**\n * Internal hook for tiles the engine builds itself (native environment RAW).\n *\n * claim() recognizes only entries the hook itself created, for sites whose parsing and identity checks are\n * provably redundant. compute() returns the outputs calculateNativeRawSite would produce, falling back to it\n * internally. observe() sees every fully computed site.\n */\nexport interface NativeRawLeanSensorHook {\n claim(site: unknown): object | undefined;\n compute(handle: object, index: number, seed: number, timing: ReturnType<typeof calculateCaptureExposureWindows>[\"value\"][\"samples\"][number] | undefined): NativeRawLeanOutput;\n observe(index: number, parsed: SensorRawProducerSiteInput, result: ReturnType<typeof calculateNativeRawSite>, whiteCode: number, seed: number): void;\n}\nexport type NativeRawTaskState = \"ready\" | \"running\" | \"completed\" | \"cancelled\" | \"failed\" | \"disposed\" | \"transferred\";\nexport interface NativeRawTask {\n readonly plan: NativeRawPlan;\n readonly state: NativeRawTaskState;\n readonly completedTileCount: number;\n run(): Promise<void>;\n cancel(): void;\n dispose(): void;\n takeOutput(): NativeRawOutput;\n}\nfunction windows(exposure: NativeRawExposure, schedule: SensorRawProducerExposureWindowInput,\n points: readonly {x:number;y:number}[]): ReturnType<typeof calculateCaptureExposureWindows>[\"value\"] {\n const r=requireAllowlistedRecord(schedule,[\"shutterMechanism\",\"nominalExposureDurationSeconds\",\"opening\",\"closing\"],\"Invalid RAW exposure schedule.\");\n requireAllowlistedRecord(r.nominalExposureDurationSeconds,[\"value\",\"unit\",\"evidence\"],\"Invalid RAW nominal exposure.\");\n for(const boundary of [r.opening,r.closing]){\n const b=requireAllowlistedRecord(boundary,[\"kind\",\"directionNative\",\"traversalDurationSeconds\"],\"Invalid RAW exposure boundary.\");\n if(b.directionNative!==undefined)requireAllowlistedRecord(b.directionNative,[\"value\",\"evidence\"],\"Invalid RAW scan direction.\");\n if(b.traversalDurationSeconds!==undefined)requireAllowlistedRecord(b.traversalDurationSeconds,[\"value\",\"unit\",\"evidence\"],\"Invalid RAW scan duration.\");\n }\n const result=calculateCaptureExposureWindows({...schedule,nativeRaster:exposure.geometry.nativeRaster,samplePointsNative:points});\n if(result.value.nominalExposureDurationSeconds.value!==exposure.exposure.shutterSeconds)throw new InvalidConfigurationError(\"RAW schedule differs from exposure duration.\");\n return result.value;\n}\n/** Plans the task and checks the image size, resources and profiles before any callback or output allocation. No placeholder plane is made. */\nexport function calculateNativeRawPlan(input: NativeRawInput): NativeRawPlan {\n const r=requireAllowlistedRecord(input,[\"exposure\",\"frameId\",\"modeId\",\"captureModeProfile\",\"colorSamplingProfile\",\"bindingProfile\",\"exposureWindow\",\"maximumOutputBytes\",\"tileWidth\",\"maximumPixels\"],\"Invalid native RAW input.\");\n if(r.tileWidth!==undefined&&(typeof r.tileWidth!==\"number\"||!Number.isSafeInteger(r.tileWidth)||r.tileWidth<1||r.tileWidth>NATIVE_RAW_LIMITS.tileWidth))\n throw new InvalidConfigurationError(\"Native RAW tile width must be an integer from 1 to 256.\");\n const tileWidth=(r.tileWidth as number|undefined)??NATIVE_RAW_LIMITS.tileWidth;\n const maximumPixels=resolveRaisedLimit(r.maximumPixels,NATIVE_RAW_LIMITS.maximumPixels,NATIVE_RAW_LIMITS.ceilingPixels,\n \"Native RAW maximumPixels must be an integer from 1 to \"+NATIVE_RAW_LIMITS.ceilingPixels+\".\");\n const exposure=normalizeCaptureExposureMetadata(r.exposure,ENGINE_API_VERSION,true),native=exposure.geometry.nativeRaster;\n const pixelCount=native.pixelWidth*native.pixelHeight,outputBytes=pixelCount*NATIVE_RAW_LIMITS.outputBytesPerPixel;\n if(pixelCount>maximumPixels||native.pixelWidth>NATIVE_RAW_LIMITS.maximumDimension||native.pixelHeight>NATIVE_RAW_LIMITS.maximumDimension||\n !Number.isSafeInteger(r.maximumOutputBytes)||typeof r.maximumOutputBytes!==\"number\"||r.maximumOutputBytes<outputBytes)throw new InvalidConfigurationError(\"Native RAW raster exceeds output admission budget.\");\n const frame={frameId:requirePublicOpaqueId(r.frameId,\"Invalid RAW frame ID.\"),capture:exposure,\n modeId:requirePublicOpaqueId(r.modeId,\"Invalid RAW mode ID.\"),containerBitDepth:16 as const,\n captureModeProfile:parseCaptureModeProfile(r.captureModeProfile),colorSamplingProfile:parseSensorColorSamplingProfile(r.colorSamplingProfile),\n bindingProfile:parseNativeEffectiveRasterColorSamplingBindingProfile(r.bindingProfile)};\n const mode=frame.captureModeProfile.modes.find(m=>m.modeId===frame.modeId);\n if(exposure.noise.model.id!==SENSOR_RAW_PRODUCER_NOISE_MODEL.id||exposure.noise.model.version!==SENSOR_RAW_PRODUCER_NOISE_MODEL.version||\n frame.colorSamplingProfile.layout.kind!==\"periodic-mosaic\"||mode?.acquisition.kind!==\"single-frame\"||mode.perFrameSampling.kind!==\"native-effective-raster\"||(mode.reconstructionStages?.length??0)!==0)\n throw new InvalidConfigurationError(\"Native RAW requires exact noise identity and single-frame native periodic CFA.\");\n // The binding is one affine mapping for the whole frame, so checking both corners covers it. Do this before any provider work.\n for(const p of [{x:0,y:0},{x:native.pixelWidth-1,y:native.pixelHeight-1}]){\n const c=resolveCaptureModeColorSamplingContributors({nativeRaster:native,captureModeProfile:frame.captureModeProfile,modeId:frame.modeId,colorSamplingProfile:frame.colorSamplingProfile,bindingProfile:frame.bindingProfile,modeSampleIndexFullFrame:p});\n if(c.totalContributorSites!==1||c.channelComposition.kind!==\"single-channel\")throw new InvalidConfigurationError(\"Native RAW must preserve one native CFA site per sample.\");\n }\n const schedule=r.exposureWindow===undefined?undefined:structuredClone(r.exposureWindow) as SensorRawProducerExposureWindowInput;\n // For the supported linear scans, the extreme values occur at the image corners. Check them before capture.\n if(schedule)windows(exposure,schedule,[{x:.5,y:.5},{x:native.pixelWidth-.5,y:.5},{x:.5,y:native.pixelHeight-.5},{x:native.pixelWidth-.5,y:native.pixelHeight-.5}]);\n return freezeOwnedData({schemaVersion:NATIVE_RAW_SCHEMA_VERSION,exposure,frame,pixelCount,outputBytes,\n tileCount:Math.ceil(native.pixelWidth/tileWidth)*native.pixelHeight,\n ...(r.tileWidth===undefined?{}:{tileWidth}),\n ...(r.maximumPixels===undefined?{}:{maximumPixels}),\n ...(schedule?{exposureWindow:schedule}:{}),upstreamRadiometryVerified:false as const,\n seedSchedule:\"murmur3-capture-seed-native-index-stream-v2\" as const});\n}\n/**\n * Internal: the largest whole-event radiance query budget a native environment task admits for this plan:\n * 2 000 000 000, scaled in proportion when the plan raised its pixel limit above 24 000 000. Not exported from the package.\n */\nexport function nativeRawMaximumProviderEvaluations(plan: Pick<NativeRawPlan,\"maximumPixels\">): number {\n return plan.maximumPixels===undefined?DEFAULT_MAXIMUM_PROVIDER_EVALUATIONS:scaleBudgetCeiling(DEFAULT_MAXIMUM_PROVIDER_EVALUATIONS,plan.maximumPixels);\n}\n/**\n * Runs validated per-site events (EQE photo signal, dark signal, charge completeness) through the shared\n * reference per-site physics.\n *\n * Tiles are read and committed one at a time. The task yields to the host at tile boundaries once about\n * 8 ms of work has passed since the last yield, and after the final tile. It checks for cancellation\n * before every tile, after every read and after every yield.\n */\nexport function createNativeRawTask(input: NativeRawInput,provider: NativeRawProvider): NativeRawTask {\n return createNativeRawTaskWithCadence(input,provider,DEFAULT_HOST_YIELD_CADENCE);\n}\n/** Internal: the same task with an explicit host-yield timing. Timing never changes tiles, seeds or output. Not exported from the package. */\nexport function createNativeRawTaskWithCadence(input: NativeRawInput,provider: NativeRawProvider,cadence: HostYieldCadence,\n /** Internal: a yield timer shared with a provider that also yields inside readTile, so both use one time budget. */\n sharedGate?: HostYieldGate,\n /** Internal: faster (\"lean\") per-site sensor execution for engine-built tiles. It never changes output or errors. */\n leanSensor?: NativeRawLeanSensorHook,\n /**\n * Internal: run only native rows [y, y + height) (a partition). The output arrays then hold just those rows, and\n * effectiveSaturationCodes holds 0 for CFA phases the rows do not contain; the merge step completes them.\n * Seeds, tiles and per-site values are those of the whole-frame task.\n */\n rows?: { readonly y: number; readonly height: number; readonly firstSite?: (site: SensorRawProducerSiteInput) => void;\n /** Internal (2.3 region rendering): also restrict to native columns [x, x + width). The output arrays are then that rectangle, row-major. */\n readonly x?: number; readonly width?: number }): NativeRawTask {\n const plan=calculateNativeRawPlan(input);\n if(!provider||typeof provider.readTile!==\"function\"||typeof provider.yieldControl!==\"function\")throw new InvalidConfigurationError(\"Native RAW requires reader and host event-loop yield.\");\n const read=provider.readTile.bind(provider),yieldControl=provider.yieldControl.bind(provider),abort=new AbortController();\n const native=plan.exposure.geometry.nativeRaster,tileWidth=plan.tileWidth??NATIVE_RAW_LIMITS.tileWidth;\n const rowStart=rows?.y??0,rowEnd=rowStart+(rows?.height??native.pixelHeight),colStart=rows?.x??0,colEnd=colStart+(rows?.width??native.pixelWidth);\n if(colStart<0||colEnd>native.pixelWidth||colEnd<=colStart)throw new InvalidConfigurationError(\"Native RAW column band must lie inside the native raster.\");\n const bandWidth=colEnd-colStart,length=(rowEnd-rowStart)*bandWidth;\n let state:NativeRawTaskState=\"ready\",count=0,output:NativeRawOutput|null=null,first:SensorRawProducerSiteInput|undefined;\n function release(): void {if(output){output.codes.fill(0);output.blackLevels.fill(0);output.digitalSaturationCodes.fill(0);output.saturationFlags.fill(0);output.effectiveSaturationCodes.fill(0);}output=null;first=undefined;}\n function active(): void {if(abort.signal.aborted)throw new InvalidConfigurationError(\"Native RAW execution aborted.\");}\n return {plan,get state(): NativeRawTaskState {return state;},get completedTileCount(): number {return count;},\n async run(): Promise<void> {\n if(state!==\"ready\")throw new InvalidConfigurationError(\"Native RAW task is single-use.\");state=\"running\";\n try{\n const gate=sharedGate??createHostYieldGate(cadence);sharedGate?.restart();\n const layout=plan.frame.colorSamplingProfile.layout;if(layout.kind!==\"periodic-mosaic\")throw new InvalidConfigurationError(\"Native RAW requires periodic CFA.\");\n const white=createPhaseWhiteLevelAccumulator(native.pixelWidth,layout.repeatWidthSites,layout.repeatHeightSites);\n output={plan,codes:new Uint16Array(length),blackLevels:new Uint16Array(length),digitalSaturationCodes:new Uint16Array(length),saturationFlags:new Uint8Array(length),effectiveSaturationCodes:new Uint16Array(layout.repeatWidthSites*layout.repeatHeightSites)};\n for(let y=rowStart;y<rowEnd;y++)for(let x=colStart;x<colEnd;x+=tileWidth){\n active();const request=Object.freeze({captureId:plan.exposure.captureId,frameId:plan.frame.frameId,x,y,width:Math.min(tileWidth,colEnd-x),height:1});\n {\n const supplied=await read(request,abort.signal);active();\n const tile=requireAllowlistedRecord(supplied,[\"captureId\",\"frameId\",\"x\",\"y\",\"width\",\"height\",\"sites\"],\"Invalid native RAW tile.\");\n for(const key of Object.keys(request) as (keyof NativeRawTileRequest)[])if(tile[key]!==request[key])throw new InvalidConfigurationError(\"Native RAW tile identity mismatch.\");\n if(!Array.isArray(tile.sites)||tile.sites.length!==request.width||Array.from({length:request.width},(_,i)=>i in (tile.sites as unknown[])).includes(false))throw new InvalidConfigurationError(\"Native RAW tile needs exact dense coverage.\");\n const timing=plan.exposureWindow?windows(plan.exposure,plan.exposureWindow,Array.from({length:request.width},(_,i)=>({x:x+i+.5,y:y+.5}))):undefined;\n // Lean entries (built by the engine, provably valid against an earlier verified template) skip parsing and\n // identity checks. They are only claimed once the frame's first site is fixed.\n const lean=leanSensor&&first!==undefined?(tile.sites as unknown[]).map(site=>leanSensor.claim(site)):undefined;\n const sites=tile.sites.map((site,j)=>lean?.[j]?undefined:parseNativeRawProducerSite(site,y*native.pixelWidth+x+j,plan.frame,timing?.samples[j]));\n if(first===undefined){first=sites[0];if(first)rows?.firstSite?.(first);}for(const s of sites)if(s)validateNativeRawReadoutIdentity(s,first!);\n // Every site in this tile is validated before any output is written. A failure never returns partial output.\n const seed=plan.exposure.noise.seedUint32;\n for(let j=0;j<sites.length;j++){\n // index: absolute native index (seeds, CFA phase); at: position in this task's output arrays.\n const index=y*native.pixelWidth+x+j,at=(y-rowStart)*bandWidth+x+j-colStart,handle=lean?.[j];\n if(handle){\n const o=leanSensor!.compute(handle,index,seed,timing?.samples[j]);\n output.codes[at]=o.rawCode;output.blackLevels[at]=o.blackLevelCode;output.digitalSaturationCodes[at]=o.digitalSaturationCode;\n output.saturationFlags[at]=o.flags;white.record(index,o.whiteCode);continue;\n }\n const result=calculateNativeRawSite(sites[j]!,seed,index),r=result.readout.value;\n output.codes[at]=r.rawCode;output.blackLevels[at]=r.blackLevelCode;output.digitalSaturationCodes[at]=r.digitalSaturationCode;\n output.saturationFlags[at]=Number(r.physicalScalarSaturationApplied)|Number(r.preAdcSaturationApplied)<<1|Number(r.digitalSaturationApplied)<<2;\n const whiteCode=calculateSiteEffectiveSaturationCode(r,sites[j]!.readoutProfile,sites[j]!.regimeId);\n white.record(index,whiteCode);\n leanSensor?.observe(index,sites[j]!,result,whiteCode,seed);\n }\n count++;\n }\n // Yield when the time budget is spent, and always after the final tile. Yield timing never changes output.\n if(gate.due()||(y===rowEnd-1&&x+tileWidth>=colEnd)){await yieldControl(abort.signal);active();gate.restart();}\n }\n output.effectiveSaturationCodes.set(rows?white.partial():white.finish());first=undefined;state=\"completed\";\n }catch(error){release();if(!abort.signal.aborted){state=\"failed\";abort.abort();}throw error;}\n },\n cancel(): void {if(state===\"ready\"||state===\"running\"||state===\"completed\"){state=\"cancelled\";abort.abort();release();}},\n dispose(): void {if(state!==\"transferred\"){state=\"disposed\";abort.abort();release();}},\n takeOutput(): NativeRawOutput {if(state!==\"completed\"||!output)throw new InvalidConfigurationError(\"Native RAW output unavailable.\");const result=output;output=null;first=undefined;state=\"transferred\";return result;}\n };\n}\n"]}
|
|
@@ -27,7 +27,7 @@ import { evaluateFixedPatternColumnOffset, evaluateFixedPatternRowOffset, evalua
|
|
|
27
27
|
import { SENSOR_RAW_PRODUCER_NOISE_MODEL } from "./sensor-raw-producer.js";
|
|
28
28
|
export const PACKED_SENSOR_RAW_SCHEMA_VERSION = "0.1.0";
|
|
29
29
|
/** `maximumRegionSites` is the default region limit; a request may raise it with its own `maximumRegionSites`, up to `ceilingRegionSites`. */
|
|
30
|
-
export const PACKED_SENSOR_RAW_LIMITS = Object.freeze({
|
|
30
|
+
export const PACKED_SENSOR_RAW_LIMITS = /* @__PURE__ */ Object.freeze({
|
|
31
31
|
maximumRegionSites: 24_000_000,
|
|
32
32
|
ceilingRegionSites: FULL_RESOLUTION_CEILING_PIXELS,
|
|
33
33
|
maximumNativeSites: 0xffffffff,
|
|
@@ -138,7 +138,7 @@ export function createPackedFixedPattern(plan) {
|
|
|
138
138
|
};
|
|
139
139
|
}
|
|
140
140
|
/** Saturation and clamp flags of one site: bit 0 physical, 1 pre-ADC, 2 digital, 3 lower clamp. */
|
|
141
|
-
export const PACKED_SENSOR_RAW_FLAG = Object.freeze({ physical: 1, preAdc: 2, digital: 4, lower: 8 });
|
|
141
|
+
export const PACKED_SENSOR_RAW_FLAG = /* @__PURE__ */ Object.freeze({ physical: 1, preAdc: 2, digital: 4, lower: 8 });
|
|
142
142
|
/**
|
|
143
143
|
* One site of the reference, in the operation order of `calculateNativeRawSite`. Returns the code and
|
|
144
144
|
* its flags. `index` is the absolute native row-major index; `pattern` is the site's fixed-pattern
|
|
@@ -202,7 +202,7 @@ export function simulatePackedSensorRows(plan, photo, dark, row0, row1, codes, c
|
|
|
202
202
|
}
|
|
203
203
|
}
|
|
204
204
|
}
|
|
205
|
-
const NO_EXTRAS = Object.freeze({ pattern: null, additional: Object.freeze([]) });
|
|
205
|
+
const NO_EXTRAS = /* @__PURE__ */ Object.freeze({ pattern: null, additional: /* @__PURE__ */ Object.freeze([]) });
|
|
206
206
|
/** The extras of a validated input; `snapshot` copies the arrays. @internal */
|
|
207
207
|
export function packedSensorExtras(plan, input, snapshot) {
|
|
208
208
|
return { pattern: createPackedFixedPattern(plan),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"packed-sensor-raw.js","sourceRoot":"","sources":["../../src/capture/packed-sensor-raw.ts"],"names":[],"mappings":"AAAA,sCAAsC;AAEtC;;;;;;;;;;;;;;;;;;GAkBG;AACH,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAC3E,OAAO,EAAE,wBAAwB,EAAE,MAAM,8BAA8B,CAAC;AACxE,OAAO,EAAE,8BAA8B,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAC7F,OAAO,EAAE,WAAW,EAAE,0BAA0B,EAAE,aAAa,EACxB,MAAM,0BAA0B,CAAC;AACxE,OAAO,EAAE,gCAAgC,EAAE,gCAAgC,EAAE,iCAAiC,EAC5G,4BAA4B,EAAE,gCAAgC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,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IACrE,wBAAwB,CAAC,IAAI,EAAE,KAAK,CAAC,cAAc,EAAE,KAAK,CAAC,aAAa,EAAE,CAAC,EAAE,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,KAAK,EAAE,MAAM,EAC5G,kBAAkB,CAAC,IAAI,EAAE,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC;IAC1C,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,WAAW,EAAE,uBAAuB,CAAC,MAAM,CAAC,EAAE,CAAC;AACvE,CAAC","sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Packed sensor stage (#277): expected electrons per native site → seeded Poisson photo and dark charge →\n * physical capacity → Gaussian read noise → pre-ADC limit → ADC (INL, round half up, optional digital\n * gain) → RAW code, on typed arrays for one rectangular region of the native raster.\n *\n * This is the float64 CPU reference for the `webgpu-f32` sensor stage. It runs the same equations, the\n * same seeded noise model (`photivra-native-raw-noise` 0.4.0) and the same floating-point operation\n * order as `calculateNativeRawSite` in the per-site producer, so for the same expected electrons and\n * readout regime its codes are bit-identical to the per-site engine (tested). The per-site stream\n * seeds are MurmurHash3_x86_32 of (capture seed, absolute native row-major index, stream ID), so the\n * region and any banding cannot change a code.\n *\n * Optional (2.0): a fixed-pattern noise profile (`SENSOR_FIXED_PATTERN_NOISE_MODEL`; PRNU and DSNU or\n * hot-pixel factors on the Poisson means, row and column offsets added with read noise) and up to 8\n * additional stored-charge components (Poisson or deterministic), in the producer's exact order.\n *\n * Supported domain (frame-wide, fails closed otherwise): one readout regime, one physical charge\n * capacity, one fixed-pattern profile. See docs/WEBGPU.md.\n */\nimport { InvalidConfigurationError } from \"../core/configuration-error.js\";\nimport { requireAllowlistedRecord } from \"../core/record-validation.js\";\nimport { FULL_RESOLUTION_CEILING_PIXELS, resolveRaisedLimit } from \"../core/pixel-limits.js\";\nimport { adcTransfer, resolveSensorReadoutRegime, samplePoisson, type ResolvedSensorReadoutRegime,\n type SensorReadoutConversionProfile } from \"../sensor/raw-readout.js\";\nimport { createDeterministicUniformStream, deriveNativeSiteStreamSeedUint32, sampleDeterministicStandardNormal,\n NATIVE_SITE_CHARGE_STREAM_ID, NATIVE_SITE_READ_NOISE_STREAM_ID } from \"../sensor/stochastic-seed.js\";\nimport { evaluateFixedPatternColumnOffset, evaluateFixedPatternRowOffset, evaluateFixedPatternSiteFactors, parseSensorFixedPatternNoiseProfile,\n type SensorFixedPatternNoiseProfile } from \"../sensor/fixed-pattern-noise.js\";\nimport type { SensorAdditionalChargeSamplingModel } from \"../sensor/raw-readout.js\";\nimport { SENSOR_RAW_PRODUCER_NOISE_MODEL } from \"./sensor-raw-producer.js\";\n\nexport const PACKED_SENSOR_RAW_SCHEMA_VERSION = \"0.1.0\" as const;\n/** `maximumRegionSites` is the default region limit; a request may raise it with its own `maximumRegionSites`, up to `ceilingRegionSites`. */\nexport const PACKED_SENSOR_RAW_LIMITS = Object.freeze({\n maximumRegionSites: 24_000_000,\n ceilingRegionSites: FULL_RESOLUTION_CEILING_PIXELS,\n maximumNativeSites: 0xffffffff,\n maximumDimension: 65_535,\n maximumAdcBitDepth: 16,\n maximumReadNoiseComponents: 16,\n maximumAdditionalChargeComponents: 8\n});\n\n/**\n * Optional fixed-pattern noise for a packed region. The colour-sampling site of native site (X, Y) is\n * (X + siteOrigin.x, Y + siteOrigin.y); the pattern is seeded from those coordinates, as in\n * `calculateSensorFixedPatternSite`.\n */\nexport interface PackedSensorFixedPatternNoise {\n profile: SensorFixedPatternNoiseProfile;\n /** Must equal `profile.colorSamplingProfileId`. */\n colorSamplingProfileId: string;\n siteOrigin: { x: number; y: number };\n}\n/** One additional stored-charge component, realized after photo and dark charge in declaration order. */\nexport interface PackedSensorAdditionalChargeComponent {\n componentId: string;\n /** `poisson` draws from the charge stream; `deterministic-expected-electron-equivalent` adds the expectation. */\n model: SensorAdditionalChargeSamplingModel;\n /** Expected electrons per region site, row-major. Finite, ≥ 0. */\n expectedElectrons: Float32Array | Float64Array;\n}\n\nexport interface PackedSensorRawInput {\n schemaVersion: typeof PACKED_SENSOR_RAW_SCHEMA_VERSION;\n /** Full native raster. Site seeds use the absolute index `(region.y + row) * nativeWidth + region.x + column`. */\n nativeWidth: number;\n nativeHeight: number;\n /** Region of the native raster to simulate, in native sites. */\n region: { x: number; y: number; width: number; height: number };\n /** The committed capture's noise seed (`capture.noise.seedUint32`). */\n captureSeedUint32: number;\n /** Expected photo-generated electrons per region site (EQE and local exposure applied), row-major. Finite, ≥ 0. */\n photoElectrons: Float32Array | Float64Array;\n /** Expected dark electrons per region site, row-major. Finite, ≥ 0. */\n darkElectrons: Float32Array | Float64Array;\n /** Physical charge storage capacity in electrons, the same at every site. */\n physicalChargeCapacityElectrons: number;\n readoutProfile: SensorReadoutConversionProfile;\n regimeId: string;\n /** Optional (2.0). */\n fixedPatternNoise?: PackedSensorFixedPatternNoise;\n /** Optional (2.0), at most 8. */\n additionalChargeComponents?: readonly PackedSensorAdditionalChargeComponent[];\n /**\n * Optional opt-in region limit for large sensors: an integer from 1 to `PACKED_SENSOR_RAW_LIMITS.ceilingRegionSites`.\n * Default `PACKED_SENSOR_RAW_LIMITS.maximumRegionSites` (24 000 000). It does not change the result.\n */\n maximumRegionSites?: number;\n}\n\n/** Validated plan. Arrays are borrowed, not copied. */\nexport interface PackedSensorRawPlan {\n nativeWidth: number;\n nativeHeight: number;\n region: Readonly<{ x: number; y: number; width: number; height: number }>;\n siteCount: number;\n captureSeedUint32: number;\n physicalChargeCapacityElectrons: number;\n readout: ResolvedSensorReadoutRegime;\n noiseModel: typeof SENSOR_RAW_PRODUCER_NOISE_MODEL;\n seedSchedule: \"murmur3-capture-seed-native-index-stream-v2\";\n /** Largest expected photo and dark electron counts in the region (before fixed-pattern factors). */\n maximumPhotoElectrons: number;\n maximumDarkElectrons: number;\n /** Parsed fixed-pattern profile and colour-site origin, or null. */\n fixedPatternNoise: Readonly<{ profile: SensorFixedPatternNoiseProfile; siteOrigin: Readonly<{ x: number; y: number }> }> | null;\n /** Additional components (identity, model and largest expectation); their arrays stay on the input. */\n additionalChargeComponents: readonly Readonly<{ componentId: string; model: SensorAdditionalChargeSamplingModel; maximumExpectedElectrons: number }>[];\n}\n\n/** Per-region saturation and clamp counts, as in the per-site readout diagnostics. */\nexport interface PackedSensorRawDiagnostics {\n physicalSaturationSiteCount: number;\n preAdcSaturationSiteCount: number;\n digitalSaturationSiteCount: number;\n lowerClampSiteCount: number;\n}\n\nexport interface PackedSensorRawResult {\n plan: PackedSensorRawPlan;\n /** RAW codes, row-major over the region. */\n codes: Uint16Array;\n diagnostics: PackedSensorRawDiagnostics;\n}\n\nfunction integer(value: unknown, minimum: number, maximum: number): number {\n if (typeof value !== \"number\" || !Number.isSafeInteger(value) || value < minimum || value > maximum) {\n throw new InvalidConfigurationError(\"Invalid packed sensor RAW geometry or seed.\");\n }\n return value;\n}\n\nfunction maximumOf(values: Float32Array | Float64Array, count: number): number {\n if (!(values instanceof Float32Array || values instanceof Float64Array) || values.length !== count) {\n throw new InvalidConfigurationError(\"Packed sensor RAW electron arrays must match the region size.\");\n }\n let maximum = 0;\n for (let i = 0; i < count; i++) {\n const v = values[i]!;\n // The negated comparison also rejects NaN.\n if (!(v >= 0 && v <= Number.MAX_VALUE)) throw new InvalidConfigurationError(\"Expected electrons must be finite and non-negative.\");\n if (v > maximum) maximum = v;\n }\n return maximum;\n}\n\n/** Validates the request (every array value once) and returns its plan. */\nexport function calculatePackedSensorRawPlan(input: PackedSensorRawInput): PackedSensorRawPlan {\n const r = requireAllowlistedRecord(input, [\"schemaVersion\", \"nativeWidth\", \"nativeHeight\", \"region\", \"captureSeedUint32\", \"photoElectrons\",\n \"darkElectrons\", \"physicalChargeCapacityElectrons\", \"readoutProfile\", \"regimeId\", \"fixedPatternNoise\", \"additionalChargeComponents\", \"maximumRegionSites\"],\n \"Invalid packed sensor RAW input.\");\n const L = PACKED_SENSOR_RAW_LIMITS;\n if (r.schemaVersion !== PACKED_SENSOR_RAW_SCHEMA_VERSION) throw new InvalidConfigurationError(\"Unsupported packed sensor RAW schema.\");\n const nativeWidth = integer(r.nativeWidth, 1, L.maximumDimension), nativeHeight = integer(r.nativeHeight, 1, L.maximumDimension);\n if (nativeWidth * nativeHeight > L.maximumNativeSites) throw new InvalidConfigurationError(\"Native raster exceeds the uint32 site index.\");\n const g = requireAllowlistedRecord(r.region, [\"x\", \"y\", \"width\", \"height\"], \"Invalid packed sensor RAW region.\");\n const x = integer(g.x, 0, nativeWidth - 1), y = integer(g.y, 0, nativeHeight - 1);\n const width = integer(g.width, 1, nativeWidth - x), height = integer(g.height, 1, nativeHeight - y);\n const maximumRegionSites = resolveRaisedLimit(r.maximumRegionSites, L.maximumRegionSites, L.ceilingRegionSites,\n \"Packed sensor RAW maximumRegionSites must be an integer from 1 to \" + L.ceilingRegionSites + \".\");\n if (width * height > maximumRegionSites) throw new InvalidConfigurationError(\"Packed sensor RAW region exceeds the site limit.\");\n const captureSeedUint32 = integer(r.captureSeedUint32, 0, 0xffffffff);\n const capacity = r.physicalChargeCapacityElectrons;\n if (typeof capacity !== \"number\" || !(capacity > 0 && capacity <= Number.MAX_VALUE)) {\n throw new InvalidConfigurationError(\"Physical charge capacity must be finite and positive.\");\n }\n const readout = resolveSensorReadoutRegime({ profile: r.readoutProfile as SensorReadoutConversionProfile, regimeId: r.regimeId as string });\n if (readout.regime.adc.bitDepth > L.maximumAdcBitDepth || readout.regime.readNoiseComponents.length > L.maximumReadNoiseComponents) {\n throw new InvalidConfigurationError(\"Packed sensor RAW requires a uint16 ADC and at most 16 read-noise components.\");\n }\n const siteCount = width * height;\n const maximumPhotoElectrons = maximumOf(r.photoElectrons as Float64Array, siteCount);\n const maximumDarkElectrons = maximumOf(r.darkElectrons as Float64Array, siteCount);\n let fixedPatternNoise: PackedSensorRawPlan[\"fixedPatternNoise\"] = null;\n if (r.fixedPatternNoise !== undefined) {\n const f = requireAllowlistedRecord(r.fixedPatternNoise, [\"profile\", \"colorSamplingProfileId\", \"siteOrigin\"], \"Invalid packed fixed-pattern noise.\");\n const profile = parseSensorFixedPatternNoiseProfile(f.profile);\n if (f.colorSamplingProfileId !== profile.colorSamplingProfileId) {\n throw new InvalidConfigurationError(\"Fixed-pattern noise profile colour-sampling identity must match the packed region.\");\n }\n const o = requireAllowlistedRecord(f.siteOrigin, [\"x\", \"y\"], \"Invalid packed fixed-pattern site origin.\");\n const ox = integer(o.x, 0, 0xffffffff - (x + width - 1)), oy = integer(o.y, 0, 0xffffffff - (y + height - 1));\n fixedPatternNoise = Object.freeze({ profile, siteOrigin: Object.freeze({ x: ox, y: oy }) });\n }\n const components = r.additionalChargeComponents === undefined ? [] : r.additionalChargeComponents;\n if (!Array.isArray(components) || components.length > L.maximumAdditionalChargeComponents) {\n throw new InvalidConfigurationError(\"Packed sensor RAW takes at most 8 additional stored-charge components.\");\n }\n const ids = new Set<string>();\n const additionalChargeComponents = components.map((value: unknown) => {\n const c = requireAllowlistedRecord(value, [\"componentId\", \"model\", \"expectedElectrons\"], \"Invalid packed additional charge component.\");\n if (typeof c.componentId !== \"string\" || c.componentId.length === 0 || ids.has(c.componentId) ||\n (c.model !== \"poisson\" && c.model !== \"deterministic-expected-electron-equivalent\")) {\n throw new InvalidConfigurationError(\"Additional charge components need unique IDs and a Poisson or deterministic model.\");\n }\n ids.add(c.componentId);\n return Object.freeze({ componentId: c.componentId, model: c.model as SensorAdditionalChargeSamplingModel,\n maximumExpectedElectrons: maximumOf(c.expectedElectrons as Float64Array, siteCount) });\n });\n return Object.freeze({ nativeWidth, nativeHeight, region: Object.freeze({ x, y, width, height }), siteCount, captureSeedUint32,\n physicalChargeCapacityElectrons: capacity, readout, noiseModel: SENSOR_RAW_PRODUCER_NOISE_MODEL,\n seedSchedule: \"murmur3-capture-seed-native-index-stream-v2\" as const, maximumPhotoElectrons, maximumDarkElectrons,\n fixedPatternNoise, additionalChargeComponents: Object.freeze(additionalChargeComponents) });\n}\n\n/** Fixed-pattern values that one site needs. @internal */\nexport interface PackedSensorSitePattern { photoResponseGainFactor: number; darkCurrentFactor: number; readoutOffsetElectrons: number }\n\n/**\n * Evaluates the fixed-pattern values of region sites with the model's own functions. Row and column\n * offsets are computed once per row and column; `readoutOffsetElectrons` is row + column, as in\n * `calculateSensorFixedPatternSite`. @internal\n */\nexport function createPackedFixedPattern(plan: PackedSensorRawPlan): ((column: number, row: number) => PackedSensorSitePattern) | null {\n const f = plan.fixedPatternNoise;\n if (f === null) return null;\n const { region } = plan, x0 = region.x + f.siteOrigin.x, y0 = region.y + f.siteOrigin.y;\n const rows = new Float64Array(region.height), columns = new Float64Array(region.width);\n for (let row = 0; row < region.height; row++) rows[row] = evaluateFixedPatternRowOffset(f.profile, y0 + row);\n for (let column = 0; column < region.width; column++) columns[column] = evaluateFixedPatternColumnOffset(f.profile, x0 + column);\n return (column, row) => {\n const factors = evaluateFixedPatternSiteFactors(f.profile, x0 + column, y0 + row);\n return { photoResponseGainFactor: factors.photoResponseGainFactor, darkCurrentFactor: factors.darkCurrentFactor,\n readoutOffsetElectrons: rows[row]! + columns[column]! };\n };\n}\n\n/** Saturation and clamp flags of one site: bit 0 physical, 1 pre-ADC, 2 digital, 3 lower clamp. */\nexport const PACKED_SENSOR_RAW_FLAG = Object.freeze({ physical: 1, preAdc: 2, digital: 4, lower: 8 });\n\n/**\n * One site of the reference, in the operation order of `calculateNativeRawSite`. Returns the code and\n * its flags. `index` is the absolute native row-major index; `pattern` is the site's fixed-pattern\n * values (required when the plan has a profile) and `additional` its additional-component expectations,\n * in the plan's order.\n * @internal\n */\nexport function simulatePackedSensorSite(plan: PackedSensorRawPlan, photoE: number, darkE: number, index: number,\n pattern: PackedSensorSitePattern | null = null, additional: readonly number[] = []): { code: number; flags: number } {\n const seed = plan.captureSeedUint32, regime = plan.readout.regime, capacity = plan.physicalChargeCapacityElectrons;\n if ((plan.fixedPatternNoise === null) !== (pattern === null) || additional.length !== plan.additionalChargeComponents.length) {\n throw new InvalidConfigurationError(\"Packed sensor site extras must match the plan.\");\n }\n const random = createDeterministicUniformStream(deriveNativeSiteStreamSeedUint32(seed, index, NATIVE_SITE_CHARGE_STREAM_ID));\n // As in simulateSensorChargeRealization: the fixed-pattern factors multiply the Poisson means.\n const photoMean = pattern === null ? photoE : photoE * pattern.photoResponseGainFactor;\n const darkMean = pattern === null ? darkE : darkE * pattern.darkCurrentFactor;\n const photoRealized = samplePoisson(photoMean, random), darkRealized = samplePoisson(darkMean, random);\n let additionalRealized = 0;\n for (let k = 0; k < additional.length; k++) {\n const expected = additional[k]!;\n additionalRealized = additionalRealized + (plan.additionalChargeComponents[k]!.model === \"poisson\" ? samplePoisson(expected, random) : expected);\n }\n const realized = photoRealized + darkRealized + additionalRealized;\n const readRandom = createDeterministicUniformStream(deriveNativeSiteStreamSeedUint32(seed, index, NATIVE_SITE_READ_NOISE_STREAM_ID));\n const afterPhysical = Math.min(realized, capacity);\n let totalReadNoise = 0;\n for (const component of regime.readNoiseComponents) {\n totalReadNoise = totalReadNoise + (component.rmsElectrons.value === 0 ? 0 : sampleDeterministicStandardNormal(readRandom) * component.rmsElectrons.value);\n }\n const afterReadNoise = afterPhysical + totalReadNoise + (pattern === null ? 0 : pattern.readoutOffsetElectrons);\n const threshold = regime.preAdcSaturationElectronEquivalent.value;\n const afterPreAdc = Math.min(afterReadNoise, threshold);\n const quantized = adcTransfer(regime, plan.readout.adcMaximumCode, afterPreAdc).quantized;\n const saturation = regime.adc.digitalSaturationCode;\n const flags = (afterPhysical < realized ? PACKED_SENSOR_RAW_FLAG.physical : 0) | (afterReadNoise > threshold ? PACKED_SENSOR_RAW_FLAG.preAdc : 0) |\n (quantized >= saturation ? PACKED_SENSOR_RAW_FLAG.digital : 0) | (quantized < 0 ? PACKED_SENSOR_RAW_FLAG.lower : 0);\n return { code: Math.max(0, Math.min(quantized, saturation)), flags };\n}\n\n/**\n * Reference rows `[row0, row1)` of the region into `codes` (indexed from the region start), adding flags\n * into `counts` (physical, pre-ADC, digital, lower).\n * @internal\n */\nexport function simulatePackedSensorRows(plan: PackedSensorRawPlan, photo: Float32Array | Float64Array, dark: Float32Array | Float64Array,\n row0: number, row1: number, codes: Uint16Array, counts: number[], extras: PackedSensorExtras = NO_EXTRAS): void {\n const { region, nativeWidth } = plan;\n const additional = new Array<number>(extras.additional.length).fill(0);\n for (let row = row0; row < row1; row++) {\n for (let column = 0, i = row * region.width; column < region.width; column++, i++) {\n for (let k = 0; k < additional.length; k++) additional[k] = extras.additional[k]![i]!;\n const site = simulatePackedSensorSite(plan, photo[i]!, dark[i]!, (region.y + row) * nativeWidth + region.x + column,\n extras.pattern === null ? null : extras.pattern(column, row), additional);\n codes[i] = site.code;\n if (site.flags & 1) counts[0]!++;\n if (site.flags & 2) counts[1]!++;\n if (site.flags & 4) counts[2]!++;\n if (site.flags & 8) counts[3]!++;\n }\n }\n}\n\n/** Per-site extras of a region: the fixed-pattern evaluator and the additional-component arrays. @internal */\nexport interface PackedSensorExtras {\n pattern: ((column: number, row: number) => PackedSensorSitePattern) | null;\n additional: readonly (Float32Array | Float64Array)[];\n}\nconst NO_EXTRAS: PackedSensorExtras = Object.freeze({ pattern: null, additional: Object.freeze([]) });\n\n/** The extras of a validated input; `snapshot` copies the arrays. @internal */\nexport function packedSensorExtras(plan: PackedSensorRawPlan, input: PackedSensorRawInput, snapshot: boolean): PackedSensorExtras {\n return { pattern: createPackedFixedPattern(plan),\n additional: (input.additionalChargeComponents ?? []).map(c => (snapshot ? c.expectedElectrons.slice() : c.expectedElectrons)) };\n}\n\nexport function packedSensorDiagnostics(counts: readonly number[]): PackedSensorRawDiagnostics {\n return { physicalSaturationSiteCount: counts[0]!, preAdcSaturationSiteCount: counts[1]!, digitalSaturationSiteCount: counts[2]!,\n lowerClampSiteCount: counts[3]! };\n}\n\n/**\n * Synchronous float64 reference for a bounded region. Use the image-kernel accelerator for large\n * regions, host yields or the `webgpu-f32` backend.\n */\nexport function simulatePackedSensorRaw(input: PackedSensorRawInput): PackedSensorRawResult {\n const plan = calculatePackedSensorRawPlan(input);\n const codes = new Uint16Array(plan.siteCount), counts = [0, 0, 0, 0];\n simulatePackedSensorRows(plan, input.photoElectrons, input.darkElectrons, 0, plan.region.height, codes, counts,\n packedSensorExtras(plan, input, false));\n return { plan, codes, diagnostics: packedSensorDiagnostics(counts) };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"packed-sensor-raw.js","sourceRoot":"","sources":["../../src/capture/packed-sensor-raw.ts"],"names":[],"mappings":"AAAA,sCAAsC;AAEtC;;;;;;;;;;;;;;;;;;GAkBG;AACH,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAC3E,OAAO,EAAE,wBAAwB,EAAE,MAAM,8BAA8B,CAAC;AACxE,OAAO,EAAE,8BAA8B,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAC7F,OAAO,EAAE,WAAW,EAAE,0BAA0B,EAAE,aAAa,EACxB,MAAM,0BAA0B,CAAC;AACxE,OAAO,EAAE,gCAAgC,EAAE,gCAAgC,EAAE,iCAAiC,EAC5G,4BAA4B,EAAE,gCAAgC,EAAE,MAAM,8BAA8B,CAAC;AACvG,OAAO,EAAE,gCAAgC,EAAE,6BAA6B,EAAE,+BAA+B,EAAE,mCAAmC,EACvG,MAAM,kCAAkC,CAAC;AAEhF,OAAO,EAAE,+BAA+B,EAAE,MAAM,0BAA0B,CAAC;AAE3E,MAAM,CAAC,MAAM,gCAAgC,GAAG,OAAgB,CAAC;AACjE,8IAA8I;AAC9I,MAAM,CAAC,MAAM,wBAAwB,GAAG,eAAe,CAAC,MAAM,CAAC,MAAM,CAAC;IACpE,kBAAkB,EAAE,UAAU;IAC9B,kBAAkB,EAAE,8BAA8B;IAClD,kBAAkB,EAAE,UAAU;IAC9B,gBAAgB,EAAE,MAAM;IACxB,kBAAkB,EAAE,EAAE;IACtB,0BAA0B,EAAE,EAAE;IAC9B,iCAAiC,EAAE,CAAC;CACrC,CAAC,CAAC;AAqFH,SAAS,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,wBAAwB,CAAC,IAAI,CAAC;QAC9C,UAAU,EAAE,CAAC,KAAK,CAAC,0BAA0B,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,iBAAiB,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,iBAAiB,CAAC,CAAC,EAAE,CAAC;AACpI,CAAC;AAED,MAAM,UAAU,uBAAuB,CAAC,MAAyB;IAC/D,OAAO,EAAE,2BAA2B,EAAE,MAAM,CAAC,CAAC,CAAE,EAAE,yBAAyB,EAAE,MAAM,CAAC,CAAC,CAAE,EAAE,0BAA0B,EAAE,MAAM,CAAC,CAAC,CAAE;QAC7H,mBAAmB,EAAE,MAAM,CAAC,CAAC,CAAE,EAAE,CAAC;AACtC,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,uBAAuB,CAAC,KAA2B;IACjE,MAAM,IAAI,GAAG,4BAA4B,CAAC,KAAK,CAAC,CAAC;IACjD,MAAM,KAAK,GAAG,IAAI,WAAW,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,MAAM,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IACrE,wBAAwB,CAAC,IAAI,EAAE,KAAK,CAAC,cAAc,EAAE,KAAK,CAAC,aAAa,EAAE,CAAC,EAAE,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,KAAK,EAAE,MAAM,EAC5G,kBAAkB,CAAC,IAAI,EAAE,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC;IAC1C,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,WAAW,EAAE,uBAAuB,CAAC,MAAM,CAAC,EAAE,CAAC;AACvE,CAAC","sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Packed sensor stage (#277): expected electrons per native site → seeded Poisson photo and dark charge →\n * physical capacity → Gaussian read noise → pre-ADC limit → ADC (INL, round half up, optional digital\n * gain) → RAW code, on typed arrays for one rectangular region of the native raster.\n *\n * This is the float64 CPU reference for the `webgpu-f32` sensor stage. It runs the same equations, the\n * same seeded noise model (`photivra-native-raw-noise` 0.4.0) and the same floating-point operation\n * order as `calculateNativeRawSite` in the per-site producer, so for the same expected electrons and\n * readout regime its codes are bit-identical to the per-site engine (tested). The per-site stream\n * seeds are MurmurHash3_x86_32 of (capture seed, absolute native row-major index, stream ID), so the\n * region and any banding cannot change a code.\n *\n * Optional (2.0): a fixed-pattern noise profile (`SENSOR_FIXED_PATTERN_NOISE_MODEL`; PRNU and DSNU or\n * hot-pixel factors on the Poisson means, row and column offsets added with read noise) and up to 8\n * additional stored-charge components (Poisson or deterministic), in the producer's exact order.\n *\n * Supported domain (frame-wide, fails closed otherwise): one readout regime, one physical charge\n * capacity, one fixed-pattern profile. See docs/WEBGPU.md.\n */\nimport { InvalidConfigurationError } from \"../core/configuration-error.js\";\nimport { requireAllowlistedRecord } from \"../core/record-validation.js\";\nimport { FULL_RESOLUTION_CEILING_PIXELS, resolveRaisedLimit } from \"../core/pixel-limits.js\";\nimport { adcTransfer, resolveSensorReadoutRegime, samplePoisson, type ResolvedSensorReadoutRegime,\n type SensorReadoutConversionProfile } from \"../sensor/raw-readout.js\";\nimport { createDeterministicUniformStream, deriveNativeSiteStreamSeedUint32, sampleDeterministicStandardNormal,\n NATIVE_SITE_CHARGE_STREAM_ID, NATIVE_SITE_READ_NOISE_STREAM_ID } from \"../sensor/stochastic-seed.js\";\nimport { evaluateFixedPatternColumnOffset, evaluateFixedPatternRowOffset, evaluateFixedPatternSiteFactors, parseSensorFixedPatternNoiseProfile,\n type SensorFixedPatternNoiseProfile } from \"../sensor/fixed-pattern-noise.js\";\nimport type { SensorAdditionalChargeSamplingModel } from \"../sensor/raw-readout.js\";\nimport { SENSOR_RAW_PRODUCER_NOISE_MODEL } from \"./sensor-raw-producer.js\";\n\nexport const PACKED_SENSOR_RAW_SCHEMA_VERSION = \"0.1.0\" as const;\n/** `maximumRegionSites` is the default region limit; a request may raise it with its own `maximumRegionSites`, up to `ceilingRegionSites`. */\nexport const PACKED_SENSOR_RAW_LIMITS = /* @__PURE__ */ Object.freeze({\n maximumRegionSites: 24_000_000,\n ceilingRegionSites: FULL_RESOLUTION_CEILING_PIXELS,\n maximumNativeSites: 0xffffffff,\n maximumDimension: 65_535,\n maximumAdcBitDepth: 16,\n maximumReadNoiseComponents: 16,\n maximumAdditionalChargeComponents: 8\n});\n\n/**\n * Optional fixed-pattern noise for a packed region. The colour-sampling site of native site (X, Y) is\n * (X + siteOrigin.x, Y + siteOrigin.y); the pattern is seeded from those coordinates, as in\n * `calculateSensorFixedPatternSite`.\n */\nexport interface PackedSensorFixedPatternNoise {\n profile: SensorFixedPatternNoiseProfile;\n /** Must equal `profile.colorSamplingProfileId`. */\n colorSamplingProfileId: string;\n siteOrigin: { x: number; y: number };\n}\n/** One additional stored-charge component, realized after photo and dark charge in declaration order. */\nexport interface PackedSensorAdditionalChargeComponent {\n componentId: string;\n /** `poisson` draws from the charge stream; `deterministic-expected-electron-equivalent` adds the expectation. */\n model: SensorAdditionalChargeSamplingModel;\n /** Expected electrons per region site, row-major. Finite, ≥ 0. */\n expectedElectrons: Float32Array | Float64Array;\n}\n\nexport interface PackedSensorRawInput {\n schemaVersion: typeof PACKED_SENSOR_RAW_SCHEMA_VERSION;\n /** Full native raster. Site seeds use the absolute index `(region.y + row) * nativeWidth + region.x + column`. */\n nativeWidth: number;\n nativeHeight: number;\n /** Region of the native raster to simulate, in native sites. */\n region: { x: number; y: number; width: number; height: number };\n /** The committed capture's noise seed (`capture.noise.seedUint32`). */\n captureSeedUint32: number;\n /** Expected photo-generated electrons per region site (EQE and local exposure applied), row-major. Finite, ≥ 0. */\n photoElectrons: Float32Array | Float64Array;\n /** Expected dark electrons per region site, row-major. Finite, ≥ 0. */\n darkElectrons: Float32Array | Float64Array;\n /** Physical charge storage capacity in electrons, the same at every site. */\n physicalChargeCapacityElectrons: number;\n readoutProfile: SensorReadoutConversionProfile;\n regimeId: string;\n /** Optional (2.0). */\n fixedPatternNoise?: PackedSensorFixedPatternNoise;\n /** Optional (2.0), at most 8. */\n additionalChargeComponents?: readonly PackedSensorAdditionalChargeComponent[];\n /**\n * Optional opt-in region limit for large sensors: an integer from 1 to `PACKED_SENSOR_RAW_LIMITS.ceilingRegionSites`.\n * Default `PACKED_SENSOR_RAW_LIMITS.maximumRegionSites` (24 000 000). It does not change the result.\n */\n maximumRegionSites?: number;\n}\n\n/** Validated plan. Arrays are borrowed, not copied. */\nexport interface PackedSensorRawPlan {\n nativeWidth: number;\n nativeHeight: number;\n region: Readonly<{ x: number; y: number; width: number; height: number }>;\n siteCount: number;\n captureSeedUint32: number;\n physicalChargeCapacityElectrons: number;\n readout: ResolvedSensorReadoutRegime;\n noiseModel: typeof SENSOR_RAW_PRODUCER_NOISE_MODEL;\n seedSchedule: \"murmur3-capture-seed-native-index-stream-v2\";\n /** Largest expected photo and dark electron counts in the region (before fixed-pattern factors). */\n maximumPhotoElectrons: number;\n maximumDarkElectrons: number;\n /** Parsed fixed-pattern profile and colour-site origin, or null. */\n fixedPatternNoise: Readonly<{ profile: SensorFixedPatternNoiseProfile; siteOrigin: Readonly<{ x: number; y: number }> }> | null;\n /** Additional components (identity, model and largest expectation); their arrays stay on the input. */\n additionalChargeComponents: readonly Readonly<{ componentId: string; model: SensorAdditionalChargeSamplingModel; maximumExpectedElectrons: number }>[];\n}\n\n/** Per-region saturation and clamp counts, as in the per-site readout diagnostics. */\nexport interface PackedSensorRawDiagnostics {\n physicalSaturationSiteCount: number;\n preAdcSaturationSiteCount: number;\n digitalSaturationSiteCount: number;\n lowerClampSiteCount: number;\n}\n\nexport interface PackedSensorRawResult {\n plan: PackedSensorRawPlan;\n /** RAW codes, row-major over the region. */\n codes: Uint16Array;\n diagnostics: PackedSensorRawDiagnostics;\n}\n\nfunction integer(value: unknown, minimum: number, maximum: number): number {\n if (typeof value !== \"number\" || !Number.isSafeInteger(value) || value < minimum || value > maximum) {\n throw new InvalidConfigurationError(\"Invalid packed sensor RAW geometry or seed.\");\n }\n return value;\n}\n\nfunction maximumOf(values: Float32Array | Float64Array, count: number): number {\n if (!(values instanceof Float32Array || values instanceof Float64Array) || values.length !== count) {\n throw new InvalidConfigurationError(\"Packed sensor RAW electron arrays must match the region size.\");\n }\n let maximum = 0;\n for (let i = 0; i < count; i++) {\n const v = values[i]!;\n // The negated comparison also rejects NaN.\n if (!(v >= 0 && v <= Number.MAX_VALUE)) throw new InvalidConfigurationError(\"Expected electrons must be finite and non-negative.\");\n if (v > maximum) maximum = v;\n }\n return maximum;\n}\n\n/** Validates the request (every array value once) and returns its plan. */\nexport function calculatePackedSensorRawPlan(input: PackedSensorRawInput): PackedSensorRawPlan {\n const r = requireAllowlistedRecord(input, [\"schemaVersion\", \"nativeWidth\", \"nativeHeight\", \"region\", \"captureSeedUint32\", \"photoElectrons\",\n \"darkElectrons\", \"physicalChargeCapacityElectrons\", \"readoutProfile\", \"regimeId\", \"fixedPatternNoise\", \"additionalChargeComponents\", \"maximumRegionSites\"],\n \"Invalid packed sensor RAW input.\");\n const L = PACKED_SENSOR_RAW_LIMITS;\n if (r.schemaVersion !== PACKED_SENSOR_RAW_SCHEMA_VERSION) throw new InvalidConfigurationError(\"Unsupported packed sensor RAW schema.\");\n const nativeWidth = integer(r.nativeWidth, 1, L.maximumDimension), nativeHeight = integer(r.nativeHeight, 1, L.maximumDimension);\n if (nativeWidth * nativeHeight > L.maximumNativeSites) throw new InvalidConfigurationError(\"Native raster exceeds the uint32 site index.\");\n const g = requireAllowlistedRecord(r.region, [\"x\", \"y\", \"width\", \"height\"], \"Invalid packed sensor RAW region.\");\n const x = integer(g.x, 0, nativeWidth - 1), y = integer(g.y, 0, nativeHeight - 1);\n const width = integer(g.width, 1, nativeWidth - x), height = integer(g.height, 1, nativeHeight - y);\n const maximumRegionSites = resolveRaisedLimit(r.maximumRegionSites, L.maximumRegionSites, L.ceilingRegionSites,\n \"Packed sensor RAW maximumRegionSites must be an integer from 1 to \" + L.ceilingRegionSites + \".\");\n if (width * height > maximumRegionSites) throw new InvalidConfigurationError(\"Packed sensor RAW region exceeds the site limit.\");\n const captureSeedUint32 = integer(r.captureSeedUint32, 0, 0xffffffff);\n const capacity = r.physicalChargeCapacityElectrons;\n if (typeof capacity !== \"number\" || !(capacity > 0 && capacity <= Number.MAX_VALUE)) {\n throw new InvalidConfigurationError(\"Physical charge capacity must be finite and positive.\");\n }\n const readout = resolveSensorReadoutRegime({ profile: r.readoutProfile as SensorReadoutConversionProfile, regimeId: r.regimeId as string });\n if (readout.regime.adc.bitDepth > L.maximumAdcBitDepth || readout.regime.readNoiseComponents.length > L.maximumReadNoiseComponents) {\n throw new InvalidConfigurationError(\"Packed sensor RAW requires a uint16 ADC and at most 16 read-noise components.\");\n }\n const siteCount = width * height;\n const maximumPhotoElectrons = maximumOf(r.photoElectrons as Float64Array, siteCount);\n const maximumDarkElectrons = maximumOf(r.darkElectrons as Float64Array, siteCount);\n let fixedPatternNoise: PackedSensorRawPlan[\"fixedPatternNoise\"] = null;\n if (r.fixedPatternNoise !== undefined) {\n const f = requireAllowlistedRecord(r.fixedPatternNoise, [\"profile\", \"colorSamplingProfileId\", \"siteOrigin\"], \"Invalid packed fixed-pattern noise.\");\n const profile = parseSensorFixedPatternNoiseProfile(f.profile);\n if (f.colorSamplingProfileId !== profile.colorSamplingProfileId) {\n throw new InvalidConfigurationError(\"Fixed-pattern noise profile colour-sampling identity must match the packed region.\");\n }\n const o = requireAllowlistedRecord(f.siteOrigin, [\"x\", \"y\"], \"Invalid packed fixed-pattern site origin.\");\n const ox = integer(o.x, 0, 0xffffffff - (x + width - 1)), oy = integer(o.y, 0, 0xffffffff - (y + height - 1));\n fixedPatternNoise = Object.freeze({ profile, siteOrigin: Object.freeze({ x: ox, y: oy }) });\n }\n const components = r.additionalChargeComponents === undefined ? [] : r.additionalChargeComponents;\n if (!Array.isArray(components) || components.length > L.maximumAdditionalChargeComponents) {\n throw new InvalidConfigurationError(\"Packed sensor RAW takes at most 8 additional stored-charge components.\");\n }\n const ids = new Set<string>();\n const additionalChargeComponents = components.map((value: unknown) => {\n const c = requireAllowlistedRecord(value, [\"componentId\", \"model\", \"expectedElectrons\"], \"Invalid packed additional charge component.\");\n if (typeof c.componentId !== \"string\" || c.componentId.length === 0 || ids.has(c.componentId) ||\n (c.model !== \"poisson\" && c.model !== \"deterministic-expected-electron-equivalent\")) {\n throw new InvalidConfigurationError(\"Additional charge components need unique IDs and a Poisson or deterministic model.\");\n }\n ids.add(c.componentId);\n return Object.freeze({ componentId: c.componentId, model: c.model as SensorAdditionalChargeSamplingModel,\n maximumExpectedElectrons: maximumOf(c.expectedElectrons as Float64Array, siteCount) });\n });\n return Object.freeze({ nativeWidth, nativeHeight, region: Object.freeze({ x, y, width, height }), siteCount, captureSeedUint32,\n physicalChargeCapacityElectrons: capacity, readout, noiseModel: SENSOR_RAW_PRODUCER_NOISE_MODEL,\n seedSchedule: \"murmur3-capture-seed-native-index-stream-v2\" as const, maximumPhotoElectrons, maximumDarkElectrons,\n fixedPatternNoise, additionalChargeComponents: Object.freeze(additionalChargeComponents) });\n}\n\n/** Fixed-pattern values that one site needs. @internal */\nexport interface PackedSensorSitePattern { photoResponseGainFactor: number; darkCurrentFactor: number; readoutOffsetElectrons: number }\n\n/**\n * Evaluates the fixed-pattern values of region sites with the model's own functions. Row and column\n * offsets are computed once per row and column; `readoutOffsetElectrons` is row + column, as in\n * `calculateSensorFixedPatternSite`. @internal\n */\nexport function createPackedFixedPattern(plan: PackedSensorRawPlan): ((column: number, row: number) => PackedSensorSitePattern) | null {\n const f = plan.fixedPatternNoise;\n if (f === null) return null;\n const { region } = plan, x0 = region.x + f.siteOrigin.x, y0 = region.y + f.siteOrigin.y;\n const rows = new Float64Array(region.height), columns = new Float64Array(region.width);\n for (let row = 0; row < region.height; row++) rows[row] = evaluateFixedPatternRowOffset(f.profile, y0 + row);\n for (let column = 0; column < region.width; column++) columns[column] = evaluateFixedPatternColumnOffset(f.profile, x0 + column);\n return (column, row) => {\n const factors = evaluateFixedPatternSiteFactors(f.profile, x0 + column, y0 + row);\n return { photoResponseGainFactor: factors.photoResponseGainFactor, darkCurrentFactor: factors.darkCurrentFactor,\n readoutOffsetElectrons: rows[row]! + columns[column]! };\n };\n}\n\n/** Saturation and clamp flags of one site: bit 0 physical, 1 pre-ADC, 2 digital, 3 lower clamp. */\nexport const PACKED_SENSOR_RAW_FLAG = /* @__PURE__ */ Object.freeze({ physical: 1, preAdc: 2, digital: 4, lower: 8 });\n\n/**\n * One site of the reference, in the operation order of `calculateNativeRawSite`. Returns the code and\n * its flags. `index` is the absolute native row-major index; `pattern` is the site's fixed-pattern\n * values (required when the plan has a profile) and `additional` its additional-component expectations,\n * in the plan's order.\n * @internal\n */\nexport function simulatePackedSensorSite(plan: PackedSensorRawPlan, photoE: number, darkE: number, index: number,\n pattern: PackedSensorSitePattern | null = null, additional: readonly number[] = []): { code: number; flags: number } {\n const seed = plan.captureSeedUint32, regime = plan.readout.regime, capacity = plan.physicalChargeCapacityElectrons;\n if ((plan.fixedPatternNoise === null) !== (pattern === null) || additional.length !== plan.additionalChargeComponents.length) {\n throw new InvalidConfigurationError(\"Packed sensor site extras must match the plan.\");\n }\n const random = createDeterministicUniformStream(deriveNativeSiteStreamSeedUint32(seed, index, NATIVE_SITE_CHARGE_STREAM_ID));\n // As in simulateSensorChargeRealization: the fixed-pattern factors multiply the Poisson means.\n const photoMean = pattern === null ? photoE : photoE * pattern.photoResponseGainFactor;\n const darkMean = pattern === null ? darkE : darkE * pattern.darkCurrentFactor;\n const photoRealized = samplePoisson(photoMean, random), darkRealized = samplePoisson(darkMean, random);\n let additionalRealized = 0;\n for (let k = 0; k < additional.length; k++) {\n const expected = additional[k]!;\n additionalRealized = additionalRealized + (plan.additionalChargeComponents[k]!.model === \"poisson\" ? samplePoisson(expected, random) : expected);\n }\n const realized = photoRealized + darkRealized + additionalRealized;\n const readRandom = createDeterministicUniformStream(deriveNativeSiteStreamSeedUint32(seed, index, NATIVE_SITE_READ_NOISE_STREAM_ID));\n const afterPhysical = Math.min(realized, capacity);\n let totalReadNoise = 0;\n for (const component of regime.readNoiseComponents) {\n totalReadNoise = totalReadNoise + (component.rmsElectrons.value === 0 ? 0 : sampleDeterministicStandardNormal(readRandom) * component.rmsElectrons.value);\n }\n const afterReadNoise = afterPhysical + totalReadNoise + (pattern === null ? 0 : pattern.readoutOffsetElectrons);\n const threshold = regime.preAdcSaturationElectronEquivalent.value;\n const afterPreAdc = Math.min(afterReadNoise, threshold);\n const quantized = adcTransfer(regime, plan.readout.adcMaximumCode, afterPreAdc).quantized;\n const saturation = regime.adc.digitalSaturationCode;\n const flags = (afterPhysical < realized ? PACKED_SENSOR_RAW_FLAG.physical : 0) | (afterReadNoise > threshold ? PACKED_SENSOR_RAW_FLAG.preAdc : 0) |\n (quantized >= saturation ? PACKED_SENSOR_RAW_FLAG.digital : 0) | (quantized < 0 ? PACKED_SENSOR_RAW_FLAG.lower : 0);\n return { code: Math.max(0, Math.min(quantized, saturation)), flags };\n}\n\n/**\n * Reference rows `[row0, row1)` of the region into `codes` (indexed from the region start), adding flags\n * into `counts` (physical, pre-ADC, digital, lower).\n * @internal\n */\nexport function simulatePackedSensorRows(plan: PackedSensorRawPlan, photo: Float32Array | Float64Array, dark: Float32Array | Float64Array,\n row0: number, row1: number, codes: Uint16Array, counts: number[], extras: PackedSensorExtras = NO_EXTRAS): void {\n const { region, nativeWidth } = plan;\n const additional = new Array<number>(extras.additional.length).fill(0);\n for (let row = row0; row < row1; row++) {\n for (let column = 0, i = row * region.width; column < region.width; column++, i++) {\n for (let k = 0; k < additional.length; k++) additional[k] = extras.additional[k]![i]!;\n const site = simulatePackedSensorSite(plan, photo[i]!, dark[i]!, (region.y + row) * nativeWidth + region.x + column,\n extras.pattern === null ? null : extras.pattern(column, row), additional);\n codes[i] = site.code;\n if (site.flags & 1) counts[0]!++;\n if (site.flags & 2) counts[1]!++;\n if (site.flags & 4) counts[2]!++;\n if (site.flags & 8) counts[3]!++;\n }\n }\n}\n\n/** Per-site extras of a region: the fixed-pattern evaluator and the additional-component arrays. @internal */\nexport interface PackedSensorExtras {\n pattern: ((column: number, row: number) => PackedSensorSitePattern) | null;\n additional: readonly (Float32Array | Float64Array)[];\n}\nconst NO_EXTRAS: PackedSensorExtras = /* @__PURE__ */ Object.freeze({ pattern: null, additional: /* @__PURE__ */ Object.freeze([]) });\n\n/** The extras of a validated input; `snapshot` copies the arrays. @internal */\nexport function packedSensorExtras(plan: PackedSensorRawPlan, input: PackedSensorRawInput, snapshot: boolean): PackedSensorExtras {\n return { pattern: createPackedFixedPattern(plan),\n additional: (input.additionalChargeComponents ?? []).map(c => (snapshot ? c.expectedElectrons.slice() : c.expectedElectrons)) };\n}\n\nexport function packedSensorDiagnostics(counts: readonly number[]): PackedSensorRawDiagnostics {\n return { physicalSaturationSiteCount: counts[0]!, preAdcSaturationSiteCount: counts[1]!, digitalSaturationSiteCount: counts[2]!,\n lowerClampSiteCount: counts[3]! };\n}\n\n/**\n * Synchronous float64 reference for a bounded region. Use the image-kernel accelerator for large\n * regions, host yields or the `webgpu-f32` backend.\n */\nexport function simulatePackedSensorRaw(input: PackedSensorRawInput): PackedSensorRawResult {\n const plan = calculatePackedSensorRawPlan(input);\n const codes = new Uint16Array(plan.siteCount), counts = [0, 0, 0, 0];\n simulatePackedSensorRows(plan, input.photoElectrons, input.darkElectrons, 0, plan.region.height, codes, counts,\n packedSensorExtras(plan, input, false));\n return { plan, codes, diagnostics: packedSensorDiagnostics(counts) };\n}\n"]}
|
|
@@ -34,7 +34,7 @@ export const SENSOR_RAW_PRODUCER_SCHEMA_VERSION = "0.3.0";
|
|
|
34
34
|
* 0.4.0: exact ADC rounding with ties up, normal-approximation Poisson draws for means of 1e9 and above,
|
|
35
35
|
* optional post-ADC digital gain and INL (integral non-linearity), and optional per-sensor fixed-pattern noise.
|
|
36
36
|
*/
|
|
37
|
-
export const SENSOR_RAW_PRODUCER_NOISE_MODEL = Object.freeze({ id: "photivra-native-raw-noise", version: "0.4.0" });
|
|
37
|
+
export const SENSOR_RAW_PRODUCER_NOISE_MODEL = /* @__PURE__ */ Object.freeze({ id: "photivra-native-raw-noise", version: "0.4.0" });
|
|
38
38
|
function fields(value, allowed) {
|
|
39
39
|
return requireAllowlistedRecord(value, allowed, "Invalid sensor RAW producer fields.");
|
|
40
40
|
}
|