@photivra/engine 2.17.0 → 2.19.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 +116 -1
- package/CITATION.cff +1 -1
- package/README.md +6 -6
- package/SECURITY.md +1 -1
- package/dist/camera/sensor-equivalence.d.ts +156 -0
- package/dist/camera/sensor-equivalence.js +208 -0
- package/dist/camera/sensor-equivalence.js.map +1 -0
- package/dist/capture/focus-control.js +2 -75
- package/dist/capture/focus-control.js.map +1 -1
- package/dist/capture/native-environment-lean.d.ts +1 -0
- package/dist/capture/native-environment-lean.js +1 -1
- package/dist/capture/native-environment-lean.js.map +1 -1
- package/dist/capture/native-environment-optical-stage.d.ts +1 -0
- package/dist/capture/native-environment-optical-stage.js +2 -5
- package/dist/capture/native-environment-optical-stage.js.map +1 -1
- package/dist/capture/native-environment-raw.js +1 -5
- package/dist/capture/native-environment-raw.js.map +1 -1
- package/dist/capture/native-environment-tabulated.d.ts +5 -0
- package/dist/capture/native-environment-tabulated.js +1 -1
- package/dist/capture/native-environment-tabulated.js.map +1 -1
- package/dist/capture/release-sequence.js +2 -47
- package/dist/capture/release-sequence.js.map +1 -1
- package/dist/color/white-balance.d.ts +2 -0
- package/dist/color/white-balance.js +3 -56
- package/dist/color/white-balance.js.map +1 -1
- package/dist/composition/image-formation-plan.d.ts +1 -0
- package/dist/composition/image-formation-plan.js +3 -49
- package/dist/composition/image-formation-plan.js.map +1 -1
- package/dist/core/evidence-provenance.js +1 -16
- package/dist/core/evidence-provenance.js.map +1 -1
- package/dist/core/record-validation.d.ts +54 -0
- package/dist/core/record-validation.js +176 -0
- package/dist/core/record-validation.js.map +1 -1
- package/dist/core/scientific-assurance.js +1 -18
- package/dist/core/scientific-assurance.js.map +1 -1
- package/dist/core/shared-helpers.d.ts +33 -0
- package/dist/core/shared-helpers.js +34 -0
- package/dist/core/shared-helpers.js.map +1 -0
- package/dist/core/spectral-composition.js +1 -36
- package/dist/core/spectral-composition.js.map +1 -1
- package/dist/core/spectral.js +1 -19
- package/dist/core/spectral.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/exposure-capabilities.d.ts +1 -0
- package/dist/equipment/exposure-capabilities.js +2 -36
- package/dist/equipment/exposure-capabilities.js.map +1 -1
- package/dist/equipment/ideal-lens.d.ts +25 -0
- package/dist/equipment/ideal-lens.js +21 -0
- package/dist/equipment/ideal-lens.js.map +1 -0
- package/dist/equipment/iso-capabilities.js +2 -49
- package/dist/equipment/iso-capabilities.js.map +1 -1
- package/dist/equipment/metering-capabilities.js +1 -26
- package/dist/equipment/metering-capabilities.js.map +1 -1
- package/dist/equipment/release-capabilities.js +1 -53
- package/dist/equipment/release-capabilities.js.map +1 -1
- package/dist/exposure/auto-iso-slowest-shutter.js +1 -7
- package/dist/exposure/auto-iso-slowest-shutter.js.map +1 -1
- package/dist/exposure/exposure-duration-control.js +1 -16
- package/dist/exposure/exposure-duration-control.js.map +1 -1
- package/dist/exposure/exposure-mode-resolver.js +1 -17
- package/dist/exposure/exposure-mode-resolver.js.map +1 -1
- package/dist/exposure/filtered-exposure-time.d.ts +93 -0
- package/dist/exposure/filtered-exposure-time.js +129 -0
- package/dist/exposure/filtered-exposure-time.js.map +1 -0
- package/dist/exposure/flash-ttl.d.ts +1 -0
- package/dist/exposure/flash-ttl.js +1 -1
- package/dist/exposure/flash-ttl.js.map +1 -1
- package/dist/exposure/flash.js +1 -49
- package/dist/exposure/flash.js.map +1 -1
- package/dist/exposure/metering-scene-radiance.js +1 -25
- package/dist/exposure/metering-scene-radiance.js.map +1 -1
- package/dist/exposure/metering-target.js +1 -30
- package/dist/exposure/metering-target.js.map +1 -1
- package/dist/exposure/metering-temporal.js +1 -8
- package/dist/exposure/metering-temporal.js.map +1 -1
- package/dist/exposure/metering.js +1 -72
- package/dist/exposure/metering.js.map +1 -1
- package/dist/exposure/program-line.js +1 -45
- package/dist/exposure/program-line.js.map +1 -1
- package/dist/facade/catalogue-lens-signal.d.ts +94 -0
- package/dist/facade/catalogue-lens-signal.js +362 -0
- package/dist/facade/catalogue-lens-signal.js.map +1 -0
- package/dist/facade/defocus-image-space-provider.js +5 -2
- package/dist/facade/defocus-image-space-provider.js.map +1 -1
- package/dist/facade/develop-joined-parts.d.ts +29 -0
- package/dist/facade/develop-joined-parts.js +33 -0
- package/dist/facade/develop-joined-parts.js.map +1 -0
- package/dist/facade/display-view-lens-signal.d.ts +32 -1
- package/dist/facade/display-view-lens-signal.js +85 -10
- package/dist/facade/display-view-lens-signal.js.map +1 -1
- package/dist/facade/expected-signal-setup.d.ts +8 -0
- package/dist/facade/expected-signal-setup.js +7 -0
- package/dist/facade/expected-signal-setup.js.map +1 -1
- package/dist/facade/expected-signal.d.ts +5 -0
- package/dist/facade/expected-signal.js +5 -1
- package/dist/facade/expected-signal.js.map +1 -1
- package/dist/facade/generic-lens-capture.d.ts +5 -2
- package/dist/facade/generic-lens-capture.js +5 -2
- package/dist/facade/generic-lens-capture.js.map +1 -1
- package/dist/facade/simulate-capture.d.ts +67 -8
- package/dist/facade/simulate-capture.js +262 -126
- package/dist/facade/simulate-capture.js.map +1 -1
- package/dist/facade/simulate-display-view.js +1 -1
- package/dist/facade/simulate-display-view.js.map +1 -1
- package/dist/gpu/chart-composite-gpu.js +1 -3
- package/dist/gpu/chart-composite-gpu.js.map +1 -1
- package/dist/gpu/chart-radiance-gpu.js +1 -5
- package/dist/gpu/chart-radiance-gpu.js.map +1 -1
- package/dist/gpu/display-view-quality-gpu.d.ts +13 -1
- package/dist/gpu/display-view-quality-gpu.js +4 -8
- package/dist/gpu/display-view-quality-gpu.js.map +1 -1
- package/dist/gpu/display-view-speed-gpu.js +3 -25
- package/dist/gpu/display-view-speed-gpu.js.map +1 -1
- package/dist/gpu/sensor-stage-gpu.js +1 -5
- package/dist/gpu/sensor-stage-gpu.js.map +1 -1
- package/dist/gpu/webgpu-runtime.d.ts +2 -0
- package/dist/gpu/webgpu-runtime.js +3 -0
- package/dist/gpu/webgpu-runtime.js.map +1 -1
- package/dist/index.d.ts +6 -1
- package/dist/index.js +5 -0
- package/dist/index.js.map +1 -1
- package/dist/motion/camera-rotation.js +1 -6
- package/dist/motion/camera-rotation.js.map +1 -1
- package/dist/motion/capture-rotation-inverse-mapping.d.ts +12 -0
- package/dist/motion/capture-rotation-inverse-mapping.js +2 -2
- package/dist/motion/capture-rotation-inverse-mapping.js.map +1 -1
- package/dist/motion/capture-rotation-temporal-quadrature.d.ts +1 -0
- package/dist/motion/capture-rotation-temporal-quadrature.js +1 -1
- package/dist/motion/capture-rotation-temporal-quadrature.js.map +1 -1
- package/dist/motion/capture-rotation-trajectory.js +2 -17
- package/dist/motion/capture-rotation-trajectory.js.map +1 -1
- package/dist/motion/capture-translation-parallax-temporal-quadrature.d.ts +1 -0
- package/dist/motion/capture-translation-parallax-temporal-quadrature.js +3 -14
- package/dist/motion/capture-translation-parallax-temporal-quadrature.js.map +1 -1
- package/dist/motion/extended-object-projection.js +5 -40
- package/dist/motion/extended-object-projection.js.map +1 -1
- package/dist/optics/atmospheric-haze.js +1 -7
- package/dist/optics/atmospheric-haze.js.map +1 -1
- package/dist/optics/brown-conrady-distortion.js +1 -7
- package/dist/optics/brown-conrady-distortion.js.map +1 -1
- package/dist/optics/complex-pupil-psf.d.ts +1 -0
- package/dist/optics/complex-pupil-psf.js +2 -84
- package/dist/optics/complex-pupil-psf.js.map +1 -1
- package/dist/optics/focus-state.js +1 -11
- package/dist/optics/focus-state.js.map +1 -1
- package/dist/optics/front-of-lens-filter.d.ts +5 -0
- package/dist/optics/front-of-lens-filter.js +3 -65
- package/dist/optics/front-of-lens-filter.js.map +1 -1
- package/dist/optics/generic-nd-filter-presets.d.ts +12 -0
- package/dist/optics/generic-nd-filter-presets.js +48 -0
- package/dist/optics/generic-nd-filter-presets.js.map +1 -0
- package/dist/optics/illumination-vignetting.js +1 -6
- package/dist/optics/illumination-vignetting.js.map +1 -1
- package/dist/optics/lens-psf-profile.d.ts +4 -1
- package/dist/optics/lens-psf-profile.js +12 -111
- package/dist/optics/lens-psf-profile.js.map +1 -1
- package/dist/optics/longitudinal-chromatic-aberration.js +1 -7
- package/dist/optics/longitudinal-chromatic-aberration.js.map +1 -1
- package/dist/optics/pupil-vignetting.js +1 -7
- package/dist/optics/pupil-vignetting.js.map +1 -1
- package/dist/optics/radial-distortion.js +1 -6
- package/dist/optics/radial-distortion.js.map +1 -1
- package/dist/optics/scene-to-sensor-irradiance.js +4 -96
- package/dist/optics/scene-to-sensor-irradiance.js.map +1 -1
- package/dist/optics/stray-light.d.ts +1 -0
- package/dist/optics/stray-light.js +1 -1
- package/dist/optics/stray-light.js.map +1 -1
- package/dist/optics/zernike-wavefront.js +1 -7
- package/dist/optics/zernike-wavefront.js.map +1 -1
- package/dist/output/capture-geometry.js +1 -8
- package/dist/output/capture-geometry.js.map +1 -1
- package/dist/output/developed-lens-corrections.d.ts +62 -0
- package/dist/output/developed-lens-corrections.js +135 -0
- package/dist/output/developed-lens-corrections.js.map +1 -0
- package/dist/output/generic-lens-corrections.d.ts +2 -6
- package/dist/output/generic-lens-corrections.js +3 -6
- package/dist/output/generic-lens-corrections.js.map +1 -1
- package/dist/output/geometric-transforms.js +1 -4
- package/dist/output/geometric-transforms.js.map +1 -1
- package/dist/output/native-capture-sdr.d.ts +2 -2
- package/dist/output/native-capture-sdr.js +3 -2
- package/dist/output/native-capture-sdr.js.map +1 -1
- package/dist/processing/development-detail.d.ts +29 -0
- package/dist/processing/development-detail.js +128 -107
- package/dist/processing/development-detail.js.map +1 -1
- package/dist/schema/illumination-temporal.js +3 -72
- package/dist/schema/illumination-temporal.js.map +1 -1
- package/dist/schema/illumination.d.ts +1 -0
- package/dist/schema/illumination.js +2 -65
- package/dist/schema/illumination.js.map +1 -1
- package/dist/schema/scene-radiance-temporal.js +2 -14
- package/dist/schema/scene-radiance-temporal.js.map +1 -1
- package/dist/schema/scene-radiance.js +2 -60
- package/dist/schema/scene-radiance.js.map +1 -1
- package/dist/schema/validation.d.ts +2 -0
- package/dist/schema/validation.js +2 -17
- package/dist/schema/validation.js.map +1 -1
- package/dist/sensor/accumulated-charge.js +2 -59
- package/dist/sensor/accumulated-charge.js.map +1 -1
- package/dist/sensor/architecture.js +1 -16
- package/dist/sensor/architecture.js.map +1 -1
- package/dist/sensor/camera-saturation-capacity.d.ts +1 -0
- package/dist/sensor/camera-saturation-capacity.js +3 -55
- package/dist/sensor/camera-saturation-capacity.js.map +1 -1
- package/dist/sensor/capture-color-sampling-binding.js +1 -26
- package/dist/sensor/capture-color-sampling-binding.js.map +1 -1
- package/dist/sensor/capture-mode-timing.js +1 -39
- package/dist/sensor/capture-mode-timing.js.map +1 -1
- package/dist/sensor/capture-mode.js +1 -23
- package/dist/sensor/capture-mode.js.map +1 -1
- package/dist/sensor/color-sampling.js +1 -26
- package/dist/sensor/color-sampling.js.map +1 -1
- package/dist/sensor/constant-rate-temporal-integration.js +2 -46
- package/dist/sensor/constant-rate-temporal-integration.js.map +1 -1
- package/dist/sensor/dark-current.js +2 -45
- package/dist/sensor/dark-current.js.map +1 -1
- package/dist/sensor/eqe-electron-rate.js +2 -35
- package/dist/sensor/eqe-electron-rate.js.map +1 -1
- package/dist/sensor/exposure-window.d.ts +5 -0
- package/dist/sensor/exposure-window.js +7 -22
- package/dist/sensor/exposure-window.js.map +1 -1
- package/dist/sensor/iso-gain.js +1 -7
- package/dist/sensor/iso-gain.js.map +1 -1
- package/dist/sensor/iso-signal-chain.js +1 -43
- package/dist/sensor/iso-signal-chain.js.map +1 -1
- package/dist/sensor/optical-stack.js +1 -25
- package/dist/sensor/optical-stack.js.map +1 -1
- package/dist/sensor/photon-energy.js +1 -26
- package/dist/sensor/photon-energy.js.map +1 -1
- package/dist/sensor/physical-charge-capacity.js +3 -77
- package/dist/sensor/physical-charge-capacity.js.map +1 -1
- package/dist/sensor/radiometry-readiness.js +2 -23
- package/dist/sensor/radiometry-readiness.js.map +1 -1
- package/dist/sensor/raw-readout.d.ts +3 -0
- package/dist/sensor/raw-readout.js +4 -66
- package/dist/sensor/raw-readout.js.map +1 -1
- package/dist/sensor/raw-reconstruction.js +2 -64
- package/dist/sensor/raw-reconstruction.js.map +1 -1
- package/dist/sensor/readout-exposure-linkage.js +1 -9
- package/dist/sensor/readout-exposure-linkage.js.map +1 -1
- package/dist/sensor/readout-timing.js +3 -57
- package/dist/sensor/readout-timing.js.map +1 -1
- package/dist/sensor/response-application-compatibility.d.ts +2 -0
- package/dist/sensor/response-application-compatibility.js +3 -29
- package/dist/sensor/response-application-compatibility.js.map +1 -1
- package/dist/sensor/response-operating-range.d.ts +1 -0
- package/dist/sensor/response-operating-range.js +3 -79
- package/dist/sensor/response-operating-range.js.map +1 -1
- package/dist/sensor/responsivity-photocurrent.js +4 -108
- package/dist/sensor/responsivity-photocurrent.js.map +1 -1
- package/dist/sensor/sampling-aperture.js +1 -25
- package/dist/sensor/sampling-aperture.js.map +1 -1
- package/dist/sensor/spatial-sample-reduction.js +2 -19
- package/dist/sensor/spatial-sample-reduction.js.map +1 -1
- package/dist/sensor/spatial-sampling-quadrature.js +1 -3
- package/dist/sensor/spatial-sampling-quadrature.js.map +1 -1
- package/dist/sensor/spatio-spectral-reduction.js +1 -18
- package/dist/sensor/spatio-spectral-reduction.js.map +1 -1
- package/dist/sensor/spectral-coverage.d.ts +10 -1
- package/dist/sensor/spectral-coverage.js +1 -1
- package/dist/sensor/spectral-coverage.js.map +1 -1
- package/dist/sensor/spectral-quadrature.js +2 -35
- package/dist/sensor/spectral-quadrature.js.map +1 -1
- package/dist/sensor/spectral-response.js +1 -47
- package/dist/sensor/spectral-response.js.map +1 -1
- package/dist/stabilization/camera-shake.js +1 -6
- package/dist/stabilization/camera-shake.js.map +1 -1
- package/dist/stabilization/system.js +2 -80
- package/dist/stabilization/system.js.map +1 -1
- package/docs/AGENT_GUIDE.md +4 -0
- package/docs/API_REFERENCE.md +69 -2
- package/docs/QUICK_START.md +136 -6
- package/docs/USAGE.md +89 -3
- package/docs/api/camera-sensor-equivalence.md +209 -0
- package/docs/api/core-version.md +1 -1
- package/docs/api/equipment-ideal-lens.md +26 -0
- package/docs/api/exports.json +118 -3
- package/docs/api/exposure-filtered-exposure-time.md +105 -0
- package/docs/api/facade-develop-joined-parts.md +32 -0
- package/docs/api/facade-simulate-capture.md +62 -8
- package/docs/api/optics-generic-nd-filter-presets.md +34 -0
- package/docs/api/optics-lens-psf-profile.md +3 -1
- package/docs/api/output-developed-lens-corrections.md +12 -0
- package/docs/api/output-generic-lens-corrections.md +0 -9
- package/llms.txt +3 -0
- package/package.json +1 -1
|
@@ -70,6 +70,7 @@ export interface NativeEnvironmentSensorStageProvider {
|
|
|
70
70
|
}>;
|
|
71
71
|
yieldControl(signal: AbortSignal): Promise<void>;
|
|
72
72
|
}
|
|
73
|
+
export declare function canonical(value: unknown): string;
|
|
73
74
|
/** Shared by full acquisition and reuse so the sensor stage receives an identical site record either way. */
|
|
74
75
|
export declare function composeNativeEnvironmentSensorSite(site: Omit<EnvironmentSite, "environment">, photoSignal: SensorEqeTemporalPhotoSignal): SensorRawProducerSiteInput;
|
|
75
76
|
/** Validates the optional retention request before any provider work. */
|
|
@@ -19,6 +19,7 @@ import { requireAllowlistedRecord } from "../core/record-validation.js";
|
|
|
19
19
|
import { stringifyCanonicalJson } from "../core/canonical-json.js";
|
|
20
20
|
import { freezeOwnedData } from "../core/owned-data.js";
|
|
21
21
|
import { InvalidConfigurationError } from "../core/configuration-error.js";
|
|
22
|
+
import { isPlainRecord } from "./native-environment-lean.js";
|
|
22
23
|
/**
|
|
23
24
|
* Fixed retention limits. The per-site footprint of a retained optical stage is
|
|
24
25
|
* `fixedBytesPerSite + bytesPerTemporalSamplePerSite × temporalSampleCount` bytes of typed-array storage;
|
|
@@ -36,14 +37,10 @@ export const NATIVE_ENVIRONMENT_OPTICAL_STAGE_LIMITS = /* @__PURE__ */ Object.fr
|
|
|
36
37
|
});
|
|
37
38
|
const FIXED_VALUES = 7;
|
|
38
39
|
const ENVIRONMENT_SHARED_KEYS = ["sceneBindings", "optics", "motion", "psf", "pupil", "fieldThroughput"];
|
|
39
|
-
function canonical(value) {
|
|
40
|
+
export function canonical(value) {
|
|
40
41
|
return stringifyCanonicalJson(value, { undefinedObjectProperties: "omit", nonFiniteNumberMessage: "Invalid native scene binding.",
|
|
41
42
|
unsupportedValueMessage: "Invalid native scene binding." });
|
|
42
43
|
}
|
|
43
|
-
function isPlainRecord(value) {
|
|
44
|
-
const prototype = Object.getPrototypeOf(value);
|
|
45
|
-
return prototype === Object.prototype || prototype === null;
|
|
46
|
-
}
|
|
47
44
|
/**
|
|
48
45
|
* Strict structural equality of plain data: Object.is for primitives (so 0 and -0 differ), identical own
|
|
49
46
|
* key sets, arrays element by element. Anything that is not a plain record or array is unequal unless it is
|
|
@@ -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,OAAO,EAAE,wBAAwB,EAAE,MAAM,8BAA8B,CAAC;AACxE,OAAO,EAAE,sBAAsB,EAAE,MAAM,2BAA2B,CAAC;AACnE,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAK3E;;;;GAIG;AACH,MAAM,CAAC,MAAM,uCAAuC,GAAG,eAAe,CAAC,MAAM,CAAC,MAAM,CAAC;IACnF,6HAA6H;IAC7H,iBAAiB,EAAE,EAAE;IACrB,uGAAuG;IACvG,6BAA6B,EAAE,EAAE;IACjC,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C;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"]}
|
|
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,OAAO,EAAE,wBAAwB,EAAE,MAAM,8BAA8B,CAAC;AACxE,OAAO,EAAE,sBAAsB,EAAE,MAAM,2BAA2B,CAAC;AACnE,OAA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C;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\";\nimport { isPlainRecord } from \"./native-environment-lean.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\nexport function canonical(value: unknown): string {\n return stringifyCanonicalJson(value, { undefinedObjectProperties: \"omit\", nonFiniteNumberMessage: \"Invalid native scene binding.\",\n unsupportedValueMessage: \"Invalid native scene binding.\" });\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"]}
|
|
@@ -9,17 +9,13 @@ import { createPhaseWhiteLevelAccumulator } from "./raw-white-level.js";
|
|
|
9
9
|
import { createEnvironmentRawFrameCanonicalMemo, planEnvironmentRawSite } from "./environment-raw-producer.js";
|
|
10
10
|
import { DEFAULT_HOST_YIELD_CADENCE, createHostYieldGate } from "./host-yield-cadence.js";
|
|
11
11
|
import { executeEnvironmentSensorPhotoSignal, prebuildApertureRadianceQuery } from "../sensor/environment-photo-signal.js";
|
|
12
|
-
import { composeNativeEnvironmentSensorSite, createNativeEnvironmentOpticalStageRecorder, createSensorStageRawTask, parseNativeEnvironmentOpticalStageRetention } from "./native-environment-optical-stage.js";
|
|
12
|
+
import { composeNativeEnvironmentSensorSite, createNativeEnvironmentOpticalStageRecorder, createSensorStageRawTask, parseNativeEnvironmentOpticalStageRetention, canonical } from "./native-environment-optical-stage.js";
|
|
13
13
|
import { parseEvidenceList } from "../core/evidence-provenance.js";
|
|
14
14
|
import { rejectUnknownFields, requireAllowlistedRecord, requirePublicOpaqueId } from "../core/record-validation.js";
|
|
15
|
-
import { stringifyCanonicalJson } from "../core/canonical-json.js";
|
|
16
15
|
import { freezeOwnedData } from "../core/owned-data.js";
|
|
17
16
|
import { InvalidConfigurationError } from "../core/configuration-error.js";
|
|
18
17
|
import { createNativeEnvironmentLeanExecutor, createNativeEnvironmentSensorLean, isLeanEnvironmentPlan } from "./native-environment-lean.js";
|
|
19
18
|
import { prepareCaptureExposureWindowSampler } from "../sensor/exposure-window.js";
|
|
20
|
-
function canonical(value) {
|
|
21
|
-
return stringifyCanonicalJson(value, { undefinedObjectProperties: "omit", nonFiniteNumberMessage: "Invalid native scene binding.", unsupportedValueMessage: "Invalid native scene binding." });
|
|
22
|
-
}
|
|
23
19
|
/** Site-environment fields that one native event shares across every site (same set as the optical-stage binding). */
|
|
24
20
|
const SHARED_STATE_KEYS = ["sceneBindings", "optics", "motion", "psf", "pupil", "fieldThroughput"];
|
|
25
21
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"native-environment-raw.js","sourceRoot":"","sources":["../../src/capture/native-environment-raw.ts"],"names":[],"mappings":"AAAA,sCAAsC;AAEtC;;;GAGG;AACH,OAAO,EAAC,sBAAsB,EAAC,0BAA0B,EAAC,gCAAgC,EAAC,MAAM,wCAAwC,CAAC;AAC1I,OAAO,EAAE,sBAAsB,EAAE,8BAA8B,EAAE,mCAAmC,EACN,MAAM,iBAAiB,CAAC;AACtH,OAAO,EAAE,gCAAgC,EAAE,MAAM,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AAM,UAAU,sCAAsC,CAAC,KAAuC,EAAC,YAA0C,EACvI,QAA6C;IAC7C,MAAM,EAAC,IAAI,EAAC,YAAY,EAAC,GAAC,wBAAwB,CAAC,KAAK,EAAC,YAAY,EAAC,QAAQ,EAAC,iBAAiB,CAAC,CAAC;IAClG,OAAO,EAAC,IAAI,EAAC,IAAI,CAAC,IAAI,EAAC,IAAI,KAAK,KAAsB,OAAO,IAAI,CAAC,KAAK,CAAC,CAAA,CAAC,EAAC,IAAI,kBAAkB,KAAU,OAAO,IAAI,CAAC,kBAAkB,CAAC,CAAA,CAAC,EAAC,IAAI,uBAAuB,KAAU,OAAO,CAAC,CAAC,CAAA,CAAC;QACxL,GAAG,EAAC,GAAgB,EAAE,CAAA,IAAI,CAAC,GAAG,EAAE,EAAC,MAAM,EAAC,GAAO,EAAE,CAAA,IAAI,CAAC,MAAM,EAAE,EAAC,OAAO,EAAC,GAAO,EAAE,CAAA,IAAI,CAAC,OAAO,EAAE;QAC9F,UAAU,KAA8B,OAAO,EAAC,GAAG,EAAC,IAAI,CAAC,UAAU,EAAE,EAAC,YAAY,EAAC,uBAAuB,EAAC,CAAC,EAAC,cAAc,EAAC,oDAAoD,EAAC,yBAAyB,EAAC,KAAK,EAAC,uBAAuB,EAAC,KAAK,EAAC,CAAC,CAAA,CAAC;KAClP,CAAC;AACJ,CAAC","sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Native RAW capture from a scene-radiance provider: source radiance → optics → EQE (external quantum\n * efficiency) → packed RAW codes for the full native sensor, within fixed work limits.\n */\nimport {internalRadianceAccess,isInternalNativeTileReader,isInternalSceneRadianceEvaluator} from \"../core/internal-radiance-evaluator.js\";\nimport { calculateNativeRawPlan, createNativeRawTaskWithCadence, nativeRawMaximumProviderEvaluations, type NativeRawInput, type NativeRawOutput,\n type NativeRawPlan, type NativeRawTask, type NativeRawTileRequest, type NativeRawTaskState } from \"./native-raw.js\";\nimport { createPhaseWhiteLevelAccumulator } from \"./raw-white-level.js\";\nimport type { SensorRawProducerSiteInput } from \"./sensor-raw-producer.js\";\nimport { createEnvironmentRawFrameCanonicalMemo, planEnvironmentRawSite, type SimulateEnvironmentSensorRawFrameInput } from \"./environment-raw-producer.js\";\nimport { DEFAULT_HOST_YIELD_CADENCE, createHostYieldGate, type HostYieldCadence } from \"./host-yield-cadence.js\";\nimport { executeEnvironmentSensorPhotoSignal, prebuildApertureRadianceQuery } from \"../sensor/environment-photo-signal.js\";\nimport { composeNativeEnvironmentSensorSite, createNativeEnvironmentOpticalStageRecorder, createSensorStageRawTask,\n parseNativeEnvironmentOpticalStageRetention, type NativeEnvironmentOpticalStage, type NativeEnvironmentOpticalStageRetention,\n type NativeEnvironmentSensorStageInput, type NativeEnvironmentSensorStageProvider } from \"./native-environment-optical-stage.js\";\nimport { parseEvidenceList } from \"../core/evidence-provenance.js\";\nimport { rejectUnknownFields, requireAllowlistedRecord, requirePublicOpaqueId } 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\";\nimport { createNativeEnvironmentLeanExecutor, createNativeEnvironmentSensorLean, isLeanEnvironmentPlan,\n type LeanEnvironmentPlan } from \"./native-environment-lean.js\";\nimport { prepareCaptureExposureWindowSampler } from \"../sensor/exposure-window.js\";\nimport type { SensorEqeTemporalPhotoSignal } from \"../sensor/temporal-photo-signal.js\";\nimport type { SceneRadianceEvaluationRequest, SceneRadianceEvaluationResult } from \"../schema/scene-radiance.js\";\nimport type { SensorApertureRay } from \"../optics/sensor-aperture-rays.js\";\n\ntype SitePlan = ReturnType<typeof planEnvironmentRawSite> | LeanEnvironmentPlan;\ntype PhotoSignal = SensorEqeTemporalPhotoSignal;\n\nexport interface NativeEnvironmentRawInput {\n raw: NativeRawInput;\n sceneBinding: SimulateEnvironmentSensorRawFrameInput[\"sceneBinding\"];\n /** Budget of provider calls for the whole capture, checked before work starts; at most 2 billion. Staying within it does not imply convergence. */\n maximumProviderEvaluations: number;\n /**\n * Optional: keep the optical stage (per-site expected photo signal, tied to every optical input) on the\n * output, for createNativeEnvironmentSensorStageTask. If omitted, behaviour and output shape are unchanged.\n */\n opticalStage?: NativeEnvironmentOpticalStageRetention;\n}\nexport interface NativeEnvironmentRawTile extends NativeRawTileRequest {\n sites: SimulateEnvironmentSensorRawFrameInput[\"sites\"];\n}\n/** One radiance query of a batch: the frozen provider request and, for an ideal-pupil ray, its frozen aperture ray. */\nexport interface NativeEnvironmentRadianceQuery {\n request: Readonly<SceneRadianceEvaluationRequest>;\n apertureRay?: Readonly<SensorApertureRay>;\n}\nexport interface NativeEnvironmentRawProvider {\n /** Supplies physical site profiles, not photo counts or precomputed RAW codes. */\n readTile(request: Readonly<NativeRawTileRequest>,signal:AbortSignal):Promise<NativeEnvironmentRawTile>;\n evaluateRadiance: SimulateEnvironmentSensorRawFrameInput[\"evaluateRadiance\"];\n evaluateApertureRadiance?: SimulateEnvironmentSensorRawFrameInput[\"evaluateApertureRadiance\"];\n /**\n * Optional batched light sampling (2.0, additive). When present, the engine makes one call per tile instead of one\n * evaluateRadiance or evaluateApertureRadiance call per query. `queries` holds every query of the tile's sites, in\n * exactly the order the per-query callbacks would be made, each with the same frozen request (and aperture ray).\n * Return one result per query, in the same order; a promise is allowed (for example a GPU readback). Each result\n * is validated by the same parser and binding checks as a per-query result, so for the same results the output is\n * byte-identical. The per-query evaluators stay required as the reference contract, but are not called.\n */\n evaluateRadianceBatch?(queries:readonly NativeEnvironmentRadianceQuery[],signal:AbortSignal):\n readonly SceneRadianceEvaluationResult[]|Promise<readonly SceneRadianceEvaluationResult[]>;\n /** Optional, bounded diagnostic callback. Counts are expected values before any noise, clipping or ADC (analogue-to-digital conversion). */\n observePhotoTile?(tile:Readonly<NativeEnvironmentPhotoTile>,signal:AbortSignal):void|Promise<void>;\n yieldControl(signal:AbortSignal):Promise<void>;\n}\nexport interface NativeEnvironmentPhotoTile extends NativeRawTileRequest {\n sites:readonly {nativeIndex:number;expectedIncidentPhotonCount:number;expectedGeneratedElectronCount:number}[];\n}\nexport interface NativeEnvironmentRawOutput {\n raw: NativeRawOutput;\n sceneBinding: NativeEnvironmentRawInput[\"sceneBinding\"];\n providerEvaluationCount: number;\n upstreamOrigin: \"executed-environment-query-provider-optics-psf-eqe\";\n providerTransportVerified: false;\n productionPlanActivated: false;\n /** Present only when NativeEnvironmentRawInput.opticalStage was requested. The caller owns and disposes it. */\n opticalStage?: NativeEnvironmentOpticalStage;\n}\nexport interface NativeEnvironmentRawTask extends Omit<NativeRawTask,\"takeOutput\"> {\n readonly providerEvaluationCount: number;\n takeOutput(): NativeEnvironmentRawOutput;\n}\nfunction canonical(value:unknown):string {\n return stringifyCanonicalJson(value,{undefinedObjectProperties:\"omit\",nonFiniteNumberMessage:\"Invalid native scene binding.\",unsupportedValueMessage:\"Invalid native scene binding.\"});\n}\n/** Site-environment fields that one native event shares across every site (same set as the optical-stage binding). */\nconst SHARED_STATE_KEYS = [\"sceneBindings\",\"optics\",\"motion\",\"psf\",\"pupil\",\"fieldThroughput\"] as const;\ntype SiteEnvironment = SimulateEnvironmentSensorRawFrameInput[\"sites\"][number][\"environment\"];\n/** The frame's first accepted shared state: its canonical string and its engine-owned (cloned) values. */\ninterface SharedStateReference {\n readonly canonical: string;\n readonly values: readonly unknown[];\n /** Arrays of the reference already checked to carry no holes or extra properties. */\n readonly cleanArrays: WeakSet<object>;\n}\n/**\n * Strict structural equality of structured-clone output against the reference: Object.is for primitives (0 and\n * -0 differ), identical prototypes limited to plain records and arrays, identical own keys in identical order,\n * and arrays with no holes or non-index properties. Anything else is unequal unless it is the same reference.\n * Equal values therefore serialize to the same canonical string and are interchangeable for every reader, so a\n * site may adopt the reference values. Recursion is bounded by the reference, which serialized without error.\n */\nfunction samePlainData(value: unknown, reference: unknown, cleanArrays: WeakSet<object>): boolean {\n if (Object.is(value, reference)) return true;\n if (typeof value !== \"object\" || typeof reference !== \"object\" || value === null || reference === null) return false;\n const prototype = Object.getPrototypeOf(value) as unknown;\n if (prototype !== Object.getPrototypeOf(reference)) return false;\n if (prototype === Array.prototype) {\n const a = value as unknown[], b = reference as unknown[], length = a.length;\n if (length !== b.length) return false;\n for (let index = 0; index < length; index++) if (!(index in a) || !(index in b) || !samePlainData(a[index], b[index], cleanArrays)) return false;\n // Holes are excluded above, so equal key counts exclude non-index properties as well.\n if (Object.keys(a).length !== length) return false;\n if (!cleanArrays.has(b)) { if (Object.keys(b).length !== length) return false; cleanArrays.add(b); }\n return true;\n }\n if (prototype !== Object.prototype && prototype !== null) return false;\n const a = value as Record<string, unknown>, b = reference as Record<string, unknown>, keys = Object.keys(a), referenceKeys = Object.keys(b);\n if (keys.length !== referenceKeys.length) return false;\n for (let index = 0; index < keys.length; index++) if (keys[index] !== referenceKeys[index]) return false;\n for (let index = 0; index < keys.length; index++) if (!samePlainData(a[keys[index]!], b[keys[index]!], cleanArrays)) return false;\n return true;\n}\n/**\n * Replaces a site's private copy of the shared state with the frame's reference values when every field is\n * strictly equal (a 2.0 performance change). All sites then share one engine-owned shared state, so its sampled\n * PSF is parsed and frozen once per frame and duplicate copies can be garbage-collected at once. `verified`\n * holds copies in the current tile already shown equal, so sites the supplier built from one object compare in\n * O(1). Returns false, changing nothing, when any field differs; the caller then serializes as before.\n */\nfunction adoptSharedState(environment: SiteEnvironment, reference: SharedStateReference, verified: unknown[]): boolean {\n const record = environment as unknown as Record<string, unknown>;\n for (let index = 0; index < SHARED_STATE_KEYS.length; index++) {\n const value = record[SHARED_STATE_KEYS[index]!];\n if (!(typeof value === \"object\" && value !== null && value === verified[index]) && !samePlainData(value, reference.values[index], reference.cleanArrays)) return false;\n }\n for (let index = 0; index < SHARED_STATE_KEYS.length; index++) {\n const key = SHARED_STATE_KEYS[index]!, value = record[key];\n if (value !== reference.values[index]) { verified[index] = value; record[key] = reference.values[index]; }\n }\n return true;\n}\n/**\n * Every radiance query the executors will make for these site plans, in their callback order: per site, per instant,\n * per group (spectral-major, spatial-minor), per tap, then per pupil ray. Pupil queries come from the executors' own\n * apertureRadianceQuery, which then hands the executor the same objects.\n */\nfunction tileQueries(plans:readonly SitePlan[]):NativeEnvironmentRadianceQuery[] {\n const queries:NativeEnvironmentRadianceQuery[]=[];\n const add=(planned:{request?:SceneRadianceEvaluationRequest;apertureRays?:readonly SensorApertureRay[]}):void=>{\n // A batch never has material taps (#394), so every planned tap carries its request.\n const tap=planned as {request:SceneRadianceEvaluationRequest;apertureRays?:readonly SensorApertureRay[]};\n if(tap.apertureRays===undefined){queries.push({request:tap.request});return;}\n // The executor later receives these same objects (apertureRadianceQuery), so they are built once.\n for(const ray of tap.apertureRays)queries.push(prebuildApertureRadianceQuery(tap.request,ray));\n };\n for(const p of plans){\n if(isLeanEnvironmentPlan(p)){for(const instant of p.instants)for(const tap of instant.taps)add(tap);}\n else for(const instant of p.instants)for(const group of instant.groups)for(const tap of group.taps)add(tap);\n }\n return queries;\n}\nfunction parseSceneBinding(value: unknown): NativeEnvironmentRawInput[\"sceneBinding\"] {\n const binding=requireAllowlistedRecord(value,[\"sceneStateId\",\"providerSceneId\",\"evidence\"],\"Invalid native scene binding.\");\n return freezeOwnedData({sceneStateId:requirePublicOpaqueId(binding.sceneStateId,\"Invalid scene-state ID.\"),providerSceneId:requirePublicOpaqueId(binding.providerSceneId,\"Invalid provider-scene ID.\"),evidence:parseEvidenceList(binding.evidence,\"nativeEnvironmentSceneBinding.evidence\")});\n}\n/**\n * Creates the native RAW task. Every tile is planned and checked against the limits before its radiance\n * callbacks run, and no partial output is ever returned.\n *\n * The task also yields to the host between sites inside a tile once about 8 ms of work has passed (one budget\n * shared with the tile loop). Cancellation is checked after each such yield, so cancel() takes effect within\n * about one site's work. Yield timing never changes tile requests, limit checks, callbacks or output.\n */\nexport function createNativeEnvironmentRawTask(input:NativeEnvironmentRawInput,provider:NativeEnvironmentRawProvider):NativeEnvironmentRawTask {\n return createNativeEnvironmentRawTaskWithCadence(input,provider,DEFAULT_HOST_YIELD_CADENCE);\n}\n/** Internal: the same task with an explicit host-yield timing. Timing never changes tiles, callbacks or output. Not exported from the package. */\n/** Validates a native environment input exactly as task creation does, before any callback. Internal (also the tabulated RAW path, #394). */\nexport function admitNativeEnvironmentInput(input:NativeEnvironmentRawInput):{plan:ReturnType<typeof calculateNativeRawPlan>;\n sceneBinding:NativeEnvironmentRawInput[\"sceneBinding\"];retention:NativeEnvironmentOpticalStageRetention|undefined;maximum:number} {\n const r=requireAllowlistedRecord(input,[\"raw\",\"sceneBinding\",\"maximumProviderEvaluations\",\"opticalStage\"],\"Invalid native environment input.\");\n const plan=calculateNativeRawPlan(input.raw),sceneBinding=parseSceneBinding(r.sceneBinding);\n const retention=r.opticalStage===undefined?undefined:parseNativeEnvironmentOpticalStageRetention(r.opticalStage);\n if(sceneBinding.sceneStateId!==plan.exposure.sceneStateId||plan.exposure.sceneTimeSeconds!==0||!plan.exposureWindow||\n typeof r.maximumProviderEvaluations!==\"number\"||!Number.isSafeInteger(r.maximumProviderEvaluations)||r.maximumProviderEvaluations<plan.pixelCount||r.maximumProviderEvaluations>nativeRawMaximumProviderEvaluations(plan))\n throw new InvalidConfigurationError(\"Native environment requires opening-reference scene binding, an explicit shutter event and bounded full-event query budget.\");\n return {plan,sceneBinding,retention,maximum:r.maximumProviderEvaluations};\n}\n/** Internal: a partition's row band, and the facts it records while running for the merge step. */\ninterface NativeEnvironmentPartitionProbe {\n readonly rows:NativeRawRowBand;\n /** Internal (2.3 region rendering): native columns [x, x + width); absent means every column. */\n readonly columns?:{readonly x:number;readonly width:number};\n /** Canonical string of the band's shared source/optical/motion state (the first site's). */\n shared?:string;\n /** The band's first parsed RAW site (its readout identity). */\n firstSite?:SensorRawProducerSiteInput;\n}\nexport function createNativeEnvironmentRawTaskWithCadence(input:NativeEnvironmentRawInput,provider:NativeEnvironmentRawProvider,\n cadence:HostYieldCadence,partition?:NativeEnvironmentPartitionProbe):NativeEnvironmentRawTask {\n const {plan,sceneBinding,retention,maximum}=admitNativeEnvironmentInput(input);\n if(partition&&retention)throw new InvalidConfigurationError(\"A native environment partition cannot retain the optical stage.\");\n if(!provider||typeof provider.readTile!==\"function\"||typeof provider.evaluateRadiance!==\"function\"||typeof provider.yieldControl!==\"function\"||\n (provider.evaluateApertureRadiance!==undefined&&typeof provider.evaluateApertureRadiance!==\"function\")||\n (provider.observePhotoTile!==undefined&&typeof provider.observePhotoTile!==\"function\")||\n (provider.evaluateRadianceBatch!==undefined&&typeof provider.evaluateRadianceBatch!==\"function\"))throw new InvalidConfigurationError(\"Native environment requires physical source callbacks and host yields.\");\n // 2.6: an engine-built evaluator (simulateCapture chart scenes) lets the lean path skip re-parsing the fixed parts of\n // its results; read once, so the checked function is the one bound. Never with a batch, whose results are the caller's.\n const evaluateFunction=provider.evaluateRadiance,internalEvaluator=provider.evaluateRadianceBatch===undefined&&isInternalSceneRadianceEvaluator(evaluateFunction);\n const internalSites=isInternalNativeTileReader(provider.readTile),read=provider.readTile.bind(provider),evaluate=evaluateFunction.bind(provider),aperture=provider.evaluateApertureRadiance?.bind(provider),yieldControl=provider.yieldControl.bind(provider);\n const observe=provider.observePhotoTile?.bind(provider),batch=provider.evaluateRadianceBatch?.bind(provider);\n let evaluations=0,shared:string|undefined,reference:SharedStateReference|undefined;\n const recorder=retention?createNativeEnvironmentOpticalStageRecorder(plan,sceneBinding,retention):undefined;\n const memo=createEnvironmentRawFrameCanonicalMemo(plan.frame,plan.exposureWindow!),gate=createHostYieldGate(cadence);\n const layout=plan.frame.colorSamplingProfile.layout,relationship=plan.frame.bindingProfile.relationship;\n const leanFrame={frameId:plan.frame.frameId,nativeWidth:plan.exposure.geometry.nativeRaster.pixelWidth,\n nativeHeight:plan.exposure.geometry.nativeRaster.pixelHeight,repeatWidth:layout.kind===\"periodic-mosaic\"?layout.repeatWidthSites:0,\n repeatHeight:layout.kind===\"periodic-mosaic\"?layout.repeatHeightSites:0,\n identityBinding:relationship.sitesPerNativeSampleX===1&&relationship.sitesPerNativeSampleY===1&&relationship.anchor===\"shared-native-top-left\"};\n // #394: an engine-built evaluator's key lookup lets verified templates skip its calls (never with a batch).\n const lean=createNativeEnvironmentLeanExecutor(leanFrame,internalEvaluator?internalRadianceAccess(evaluateFunction):undefined);\n let nativeWindow:Parameters<typeof createNativeEnvironmentSensorLean>[2];\n try{nativeWindow=prepareCaptureExposureWindowSampler({...plan.exposureWindow!,nativeRaster:plan.exposure.geometry.nativeRaster});}catch{nativeWindow=undefined;}\n const sensorLean=createNativeEnvironmentSensorLean(leanFrame,plan.frame,nativeWindow);\n const task=createNativeRawTaskWithCadence(input.raw,{\n async readTile(request,signal){\n const supplied=await read(request,signal);\n if(signal.aborted)throw new InvalidConfigurationError(\"Native environment acquisition aborted.\");\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))throw new InvalidConfigurationError(\"Physical source tile needs exact native coverage.\");\n // Private copy: planning takes each site environment as engine-owned plan data without copying it again. Sites from an\n // engine-built reader (#394: fresh records per call, never shown to supplied code or changed) are already the engine's own.\n const sites=(internalSites?tile.sites:structuredClone(tile.sites)) as SimulateEnvironmentSensorRawFrameInput[\"sites\"];\n // Yield to the host between sites on the shared time budget. Cancellation is honoured right after it.\n const pause=async():Promise<void>=>{\n if(!gate.due())return;\n await yieldControl(signal);\n if(signal.aborted)throw new InvalidConfigurationError(\"Native environment acquisition aborted.\");\n gate.restart();\n };\n let tileCount=0;\n const plans:SitePlan[]=[],verified:unknown[]=[];\n for(let j=0;j<sites.length;j++){\n if(j>0)await pause();\n const site=sites[j]!;\n requireAllowlistedRecord(site,[\"environment\",\"darkCurrentProfile\",\"operatingTemperatureC\",\"charge\",\"readout\"],\"Invalid physical site input.\");\n const e=site.environment,index=request.y*plan.exposure.geometry.nativeRaster.pixelWidth+request.x+j;\n if(e.temporalIntegrationId!==plan.frame.frameId+\":native:\"+index)throw new InvalidConfigurationError(\"Native environment IDs must bind the absolute native index.\");\n // A site strictly equal to the frame's first shared state adopts it and skips serialization; otherwise the\n // canonical comparison runs exactly as before and decides acceptance or the same error.\n let state:string;\n if(reference!==undefined&&adoptSharedState(e,reference,verified))state=reference.canonical;\n else{\n state=canonical({sceneBindings:e.sceneBindings,optics:e.optics,motion:e.motion,psf:e.psf,pupil:e.pupil,fieldThroughput:e.fieldThroughput});\n shared??=state;if(partition)partition.shared??=shared;if(state!==shared)throw new InvalidConfigurationError(\"Native event requires one shared source/optical/motion state.\");\n reference??={canonical:state,values:SHARED_STATE_KEYS.map(key=>(e as unknown as Record<string,unknown>)[key]),cleanArrays:new WeakSet()};\n }\n // A site matching a verified template gets a lean plan (identical requests and limit checks; see\n // native-environment-lean.ts). A template candidate keeps full query records for its self-check.\n // Otherwise only the photo signal is needed, so the plan keeps just each query's frozen request and image-plane point.\n const leanPlan=lean.plan(e,index);\n let p:SitePlan;\n if(typeof leanPlan===\"object\")p=leanPlan;\n else{\n p=planEnvironmentRawSite(site,index,plan.frame,sceneBinding,plan.exposureWindow!,\"engine-owned\",memo,leanPlan===\"candidate\"?\"full\":\"photo-only\");\n if(leanPlan===\"candidate\")lean.admitCandidate(e,index,p);\n }\n if(p.owned.pupil&&!aperture)throw new InvalidConfigurationError(\"Pupil capture requires origin-aware source visibility.\");\n recorder?.admit(index,e,state);\n tileCount+=p.count;\n if(tileCount>100_000||evaluations+tileCount>maximum)throw new InvalidConfigurationError(\"Native environment exceeds tile or full-event query budget.\");\n plans.push(p);\n }\n // Only value.photo is consumed, so per-evaluation diagnostics are not retained.\n const rawSites:(ReturnType<typeof composeNativeEnvironmentSensorSite>|object)[]=[],photos:PhotoSignal[]=[];\n sensorLean.beginTile();\n let evaluateCounted=(q:Parameters<typeof evaluate>[0]):ReturnType<typeof evaluate>=>{if(signal.aborted)throw new InvalidConfigurationError(\"Native source evaluation aborted.\");evaluations++;return evaluate(q);};\n let apertureCounted=aperture?(q:Parameters<typeof aperture>[0],ray:Parameters<typeof aperture>[1]):ReturnType<typeof evaluate>=>{if(signal.aborted)throw new InvalidConfigurationError(\"Native aperture evaluation aborted.\");evaluations++;return aperture(q,ray);}:undefined;\n let batched:{queries:readonly NativeEnvironmentRadianceQuery[];results:readonly SceneRadianceEvaluationResult[];next:number}|undefined;\n if(batch){\n // One call for the whole tile, with every planned query in per-query callback order (see tileQueries).\n const queries=tileQueries(plans);\n if(signal.aborted)throw new InvalidConfigurationError(\"Native source evaluation aborted.\");\n const results=await batch(Object.freeze(queries),signal);\n if(signal.aborted)throw new InvalidConfigurationError(\"Native source evaluation aborted.\");\n if(!Array.isArray(results)||results.length!==queries.length||Array.from({length:queries.length},(_,i)=>i in results).includes(false))\n throw new InvalidConfigurationError(\"Batched radiance must return one result per query, in query order.\");\n const current={queries,results:results as readonly SceneRadianceEvaluationResult[],next:0};\n batched=current;\n // The executors ask for each query in the same order; every step is checked against the planned query.\n const take=(q:Readonly<SceneRadianceEvaluationRequest>,ray:Readonly<SensorApertureRay>|undefined):SceneRadianceEvaluationResult=>{\n const k=current.next++,planned=current.queries[k];\n if(planned===undefined||planned.request.sampleId!==q.sampleId||(planned.apertureRay===undefined)!==(ray===undefined))\n throw new InvalidConfigurationError(\"Batched radiance results are out of step with the planned queries.\");\n evaluations++;\n return current.results[k]!;\n };\n evaluateCounted=(q):ReturnType<typeof evaluate>=>take(q,undefined);\n apertureCounted=aperture?(q,ray):ReturnType<typeof evaluate>=>take(q,ray):undefined;\n }\n for(let j=0;j<sites.length;j++){\n await pause();\n const index=request.y*plan.exposure.geometry.nativeRaster.pixelWidth+request.x+j;\n let p=plans[j]!,photoSignal:PhotoSignal|undefined;\n if(isLeanEnvironmentPlan(p)){\n // The full plan (deterministic, no callbacks) is built only when the lean path needs it.\n const fullPlan=():ReturnType<typeof planEnvironmentRawSite>=>planEnvironmentRawSite(sites[j]!,index,plan.frame,sceneBinding,plan.exposureWindow!,\"engine-owned\",memo,\"photo-only\");\n photoSignal=lean.execute(p,evaluateCounted,apertureCounted,fullPlan,internalEvaluator&&!batched,\n (n)=>{if(signal.aborted)throw new InvalidConfigurationError(\"Native source evaluation aborted.\");evaluations+=n;});\n // An unverified template: plan this site in full now and execute it in full.\n if(photoSignal===undefined)p=fullPlan();\n }\n if(photoSignal===undefined){\n const full=p as ReturnType<typeof planEnvironmentRawSite>,candidate=lean.isCandidate(index);\n const result=executeEnvironmentSensorPhotoSignal(full,evaluateCounted,apertureCounted,candidate?\"full\":\"photo-only\");\n if(candidate)lean.verifyCandidate(index,full,result);\n photoSignal=result.value.photo.value.photoSignal;\n }\n recorder?.record(index,photoSignal);\n photos.push(photoSignal);\n // A site matching a verified sensor template becomes a lean entry: every check its composition and RAW\n // parse would run has been evaluated (see native-environment-lean.ts). Otherwise compose it in full.\n const claimed=sensorLean.claim(sites[j]!,photoSignal,index);\n if(claimed)rawSites.push(claimed);\n else{rawSites.push(composeNativeEnvironmentSensorSite(sites[j]!,photoSignal));sensorLean.remember(index,sites[j]!,photoSignal);}\n }\n if(batched&&batched.next!==batched.queries.length)throw new InvalidConfigurationError(\"Batched radiance results are out of step with the planned queries.\");\n if(signal.aborted)throw new InvalidConfigurationError(\"Native photo observation aborted.\");\n if(observe)await observe(freezeOwnedData({...request,sites:photos.map((s,j)=>({nativeIndex:request.y*plan.exposure.geometry.nativeRaster.pixelWidth+request.x+j,\n expectedIncidentPhotonCount:s.expectedIncidentPhotonCount,expectedGeneratedElectronCount:s.expectedGeneratedElectronCount}))}),signal);\n return {...request,sites:rawSites as ReturnType<typeof composeNativeEnvironmentSensorSite>[]};\n },yieldControl\n },cadence,gate,sensorLean.hook,partition?{y:partition.rows.y,height:partition.rows.height,firstSite:(site):void=>{partition.firstSite=site;},\n ...(partition.columns?{x:partition.columns.x,width:partition.columns.width}:{})}:undefined);\n // The frame reference is needed only while tiles are read; release it once the event settles.\n const settle=():void=>{reference=undefined;};\n return {plan:task.plan,get state():NativeRawTaskState{return task.state;},get completedTileCount():number{return task.completedTileCount;},get providerEvaluationCount():number{return evaluations;},\n run:():Promise<void>=>(recorder?task.run().catch((error:unknown)=>{if(task.state===\"failed\"||task.state===\"cancelled\"||task.state===\"disposed\")recorder.discard();throw error;}):task.run()).finally(settle),\n cancel:():void=>{if(task.state!==\"transferred\")recorder?.discard();task.cancel();},dispose:():void=>{if(task.state!==\"transferred\")recorder?.discard();task.dispose();},\n takeOutput():NativeEnvironmentRawOutput{\n // Finish retention first so a retention failure never strands the transferred RAW.\n const opticalStage=recorder&&task.state===\"completed\"?recorder.finish(evaluations):undefined;\n const raw=task.takeOutput();\n const base={raw,sceneBinding,providerEvaluationCount:evaluations,upstreamOrigin:\"executed-environment-query-provider-optics-psf-eqe\" as const,providerTransportVerified:false as const,productionPlanActivated:false as const};\n return opticalStage?{...base,opticalStage}:base;\n }\n };\n}\n/**\n * Internal (not exported from the package; 2.3 `simulateCapture` `output.region`): the task for one rectangle of\n * native sites [x, x + width) × [y, y + height) of the whole-frame input. Every site keeps its absolute native index,\n * so its noise seeds, CFA phase, exposure window (rolling-shutter row timing) and value are those of the whole-frame\n * task; the output arrays hold just the rectangle, row-major, and `effectiveSaturationCodes` holds 0 for a CFA\n * phase the rectangle does not contain. Optical-stage retention is not supported.\n */\nexport function createNativeEnvironmentRawRegionTask(input:NativeEnvironmentRawInput,region:{x:number;y:number;width:number;height:number},\n provider:NativeEnvironmentRawProvider):NativeEnvironmentRawTask {\n const plan=calculateNativeRawPlan(input?.raw),native=plan.exposure.geometry.nativeRaster;\n const r=requireAllowlistedRecord(region,[\"x\",\"y\",\"width\",\"height\"],\"Invalid native RAW region.\");\n if(![r.x,r.y,r.width,r.height].every(v=>typeof v===\"number\"&&Number.isSafeInteger(v))||(r.width as number)<1||(r.x as number)<0||(r.x as number)+(r.width as number)>native.pixelWidth)\n throw new InvalidConfigurationError(\"Native RAW region must lie inside the native raster.\");\n const rows=parseRowBand({y:r.y,height:r.height},native.pixelHeight);\n return createNativeEnvironmentRawTaskWithCadence(input,provider,DEFAULT_HOST_YIELD_CADENCE,{rows,columns:{x:r.x as number,width:r.width as number}});\n}\n/** A band of whole native rows, [y, y + height), in absolute full-sensor coordinates. */\nexport interface NativeRawRowBand { y: number; height: number }\n/**\n * Splits a plan's native rows into at most `count` contiguous bands of nearly equal height (the first\n * `height % count` bands are one row taller), in row order. Deterministic: it depends only on the raster height and\n * `count`. Use one band per worker with createNativeEnvironmentRawPartitionTask.\n */\nexport function calculateNativeRawRowBands(plan:Pick<NativeRawPlan,\"exposure\">,count:number):NativeRawRowBand[] {\n if(plan!==null&&typeof plan===\"object\")rejectUnknownFields(plan,[\"schemaVersion\",\"exposure\",\"frame\",\"exposureWindow\",\"pixelCount\",\"outputBytes\",\"tileCount\",\n \"tileWidth\",\"upstreamRadiometryVerified\",\"seedSchedule\"],\"Native RAW plan\");\n const height=plan?.exposure?.geometry?.nativeRaster?.pixelHeight;\n if(typeof height!==\"number\"||!Number.isSafeInteger(height)||height<1)throw new InvalidConfigurationError(\"Native RAW partitioning requires a native RAW plan.\");\n if(typeof count!==\"number\"||!Number.isSafeInteger(count)||count<1||count>1024)throw new InvalidConfigurationError(\"Native RAW partition count must be an integer from 1 to 1024.\");\n const bands=Math.min(count,height),base=Math.floor(height/bands),extra=height%bands,result:NativeRawRowBand[]=[];\n for(let i=0,y=0;i<bands;i++){const h=base+(i<extra?1:0);result.push({y,height:h});y+=h;}\n return result;\n}\n/**\n * One partition's result: plain data and typed arrays only, so it can be posted from a worker (transfer the four\n * arrays' buffers). Merge every partition of a capture with composeNativeEnvironmentRawPartitions.\n */\nexport interface NativeEnvironmentRawPartition {\n rows: NativeRawRowBand;\n /** Canonical JSON of the capture input (raw, sceneBinding, maximumProviderEvaluations); the merge requires it to match. */\n inputCanonical: string;\n /** Canonical JSON of the band's shared source/optical/motion state; every partition must match. */\n sharedStateCanonical: string;\n /** Readout identity of the band's first site; every partition must match (one readout identity per frame). */\n readoutIdentity: { readoutProfileId: string; regimeId: string; fixedPatternProfileId: string | null; fixedPatternSeedUint32: number | null };\n /** The band's rows only, row-major, as in NativeRawOutput. */\n codes: Uint16Array;\n blackLevels: Uint16Array;\n digitalSaturationCodes: Uint16Array;\n saturationFlags: Uint8Array;\n /** Effective white code per CFA phase; 0 for a phase the band does not contain. */\n effectiveSaturationCodes: Uint16Array;\n providerEvaluationCount: number;\n}\nexport interface NativeEnvironmentRawPartitionTask extends Omit<NativeRawTask,\"takeOutput\"> {\n readonly rows: NativeRawRowBand;\n readonly providerEvaluationCount: number;\n takeOutput(): NativeEnvironmentRawPartition;\n}\nfunction inputCanonical(input:NativeEnvironmentRawInput):string {\n return canonical({raw:input.raw,sceneBinding:input.sceneBinding,maximumProviderEvaluations:input.maximumProviderEvaluations});\n}\nfunction parseRowBand(value:unknown,height:number):NativeRawRowBand {\n const band=requireAllowlistedRecord(value,[\"y\",\"height\"],\"Invalid native RAW row band.\");\n if(typeof band.y!==\"number\"||typeof band.height!==\"number\"||!Number.isSafeInteger(band.y)||!Number.isSafeInteger(band.height)||\n band.y<0||band.height<1||band.y+band.height>height)throw new InvalidConfigurationError(\"Native RAW row band must lie inside the native raster.\");\n return {y:band.y,height:band.height};\n}\n/**\n * Creates the task for one row band of a native environment capture (opt-in parallel execution, 2.0).\n *\n * Run one partition per worker (or one after another) with the same input, each worker using its own provider, then\n * merge them with composeNativeEnvironmentRawPartitions. The merged output is byte-identical to the single\n * createNativeEnvironmentRawTask output for the same input and a deterministic provider: noise seeds use absolute\n * native indices, and tiles, plans and per-site values are those of the whole-frame task.\n *\n * Each partition checks the same inputs and limits before its callbacks. maximumProviderEvaluations bounds each\n * partition's own work; the merge also rejects a total above it. Frame-wide checks that span sites (one shared\n * state, one readout identity, one white level per CFA phase) run inside each band and again across bands in the\n * merge. Callbacks are split across partitions, and when several partitions fail, which error is seen first depends\n * on the caller's scheduling. Optical-stage retention is not supported in a partition.\n *\n * The package bundles no worker code: the caller creates workers (Web Workers or Node worker threads), runs this\n * task inside each and posts the partition back.\n */\nexport function createNativeEnvironmentRawPartitionTask(input:NativeEnvironmentRawInput,rows:NativeRawRowBand,\n provider:NativeEnvironmentRawProvider):NativeEnvironmentRawPartitionTask {\n const plan=calculateNativeRawPlan(input?.raw),band=parseRowBand(rows,plan.exposure.geometry.nativeRaster.pixelHeight);\n const probe:NativeEnvironmentPartitionProbe={rows:band};\n const task=createNativeEnvironmentRawTaskWithCadence(input,provider,DEFAULT_HOST_YIELD_CADENCE,probe),text=inputCanonical(input);\n return {plan:task.plan,rows:band,get state():NativeRawTaskState{return task.state;},get completedTileCount():number{return task.completedTileCount;},\n get providerEvaluationCount():number{return task.providerEvaluationCount;},run:():Promise<void>=>task.run(),cancel:():void=>task.cancel(),dispose:():void=>task.dispose(),\n takeOutput():NativeEnvironmentRawPartition{\n if(task.state!==\"completed\"||probe.shared===undefined||probe.firstSite===undefined)throw new InvalidConfigurationError(\"Native RAW output unavailable.\");\n const site=probe.firstSite,sharedStateCanonical=probe.shared,output=task.takeOutput(),raw=output.raw;\n return {rows:{...band},inputCanonical:text,sharedStateCanonical,readoutIdentity:{readoutProfileId:site.readoutProfile.profileId,regimeId:site.regimeId,\n fixedPatternProfileId:site.fixedPatternNoise?.profileId??null,fixedPatternSeedUint32:site.fixedPatternNoise?.sensorInstanceSeedUint32??null},\n codes:raw.codes,blackLevels:raw.blackLevels,digitalSaturationCodes:raw.digitalSaturationCodes,saturationFlags:raw.saturationFlags,\n effectiveSaturationCodes:raw.effectiveSaturationCodes,providerEvaluationCount:output.providerEvaluationCount};\n }\n };\n}\n/**\n * Assembles the partitions of one capture into the output createNativeEnvironmentRawTask would have returned for\n * the same input (byte-identical RAW arrays and white levels, the summed provider evaluation count).\n *\n * The partitions must be in row order and cover every native row exactly once, and each must come from\n * createNativeEnvironmentRawPartitionTask with this same input. It rejects, with InvalidConfigurationError, a\n * different input, a gap or overlap, wrong array types or lengths, a second shared state or readout identity, two\n * white levels for one CFA phase, a missing phase, or a total evaluation count above the input's budget. It cannot\n * verify how a partition was computed: posted partitions are the caller's own data.\n */\nexport function composeNativeEnvironmentRawPartitions(input:NativeEnvironmentRawInput,partitions:readonly NativeEnvironmentRawPartition[]):NativeEnvironmentRawOutput {\n const {plan,sceneBinding,retention,maximum}=admitNativeEnvironmentInput(input);\n if(retention)throw new InvalidConfigurationError(\"A native environment partition cannot retain the optical stage.\");\n const native=plan.exposure.geometry.nativeRaster,width=native.pixelWidth,layout=plan.frame.colorSamplingProfile.layout;\n if(layout.kind!==\"periodic-mosaic\")throw new InvalidConfigurationError(\"Native RAW requires periodic CFA.\");\n const phases=layout.repeatWidthSites*layout.repeatHeightSites,text=inputCanonical(input);\n if(!Array.isArray(partitions)||partitions.length<1||partitions.length>native.pixelHeight||Array.from({length:partitions.length},(_,i)=>i in partitions).includes(false))\n throw new InvalidConfigurationError(\"Native RAW merge requires a dense list of partitions.\");\n const codes=new Uint16Array(plan.pixelCount),blackLevels=new Uint16Array(plan.pixelCount),digitalSaturationCodes=new Uint16Array(plan.pixelCount),saturationFlags=new Uint8Array(plan.pixelCount);\n const white=createPhaseWhiteLevelAccumulator(width,layout.repeatWidthSites,layout.repeatHeightSites);\n let y=0,total=0,shared:string|undefined,identity:string|undefined;\n for(const value of partitions){\n const p=requireAllowlistedRecord(value,[\"rows\",\"inputCanonical\",\"sharedStateCanonical\",\"readoutIdentity\",\"codes\",\"blackLevels\",\"digitalSaturationCodes\",\n \"saturationFlags\",\"effectiveSaturationCodes\",\"providerEvaluationCount\"],\"Invalid native RAW partition.\");\n const band=parseRowBand(p.rows,native.pixelHeight),length=band.height*width;\n if(band.y!==y)throw new InvalidConfigurationError(\"Native RAW partitions must cover every row once, in row order.\");\n if(p.inputCanonical!==text)throw new InvalidConfigurationError(\"Native RAW partition was computed from a different input.\");\n if(!(p.codes instanceof Uint16Array)||!(p.blackLevels instanceof Uint16Array)||!(p.digitalSaturationCodes instanceof Uint16Array)||\n !(p.saturationFlags instanceof Uint8Array)||!(p.effectiveSaturationCodes instanceof Uint16Array)||p.codes.length!==length||p.blackLevels.length!==length||\n p.digitalSaturationCodes.length!==length||p.saturationFlags.length!==length||p.effectiveSaturationCodes.length!==phases||\n typeof p.providerEvaluationCount!==\"number\"||!Number.isSafeInteger(p.providerEvaluationCount)||p.providerEvaluationCount<0||typeof p.sharedStateCanonical!==\"string\")\n throw new InvalidConfigurationError(\"Invalid native RAW partition arrays.\");\n const id=requireAllowlistedRecord(p.readoutIdentity,[\"readoutProfileId\",\"regimeId\",\"fixedPatternProfileId\",\"fixedPatternSeedUint32\"],\"Invalid native RAW partition identity.\");\n const idText=canonical(id);\n shared??=p.sharedStateCanonical;identity??=idText;\n if(p.sharedStateCanonical!==shared)throw new InvalidConfigurationError(\"Native event requires one shared source/optical/motion state.\");\n if(idText!==identity)throw new InvalidConfigurationError(\"Frame requires one readout identity/regime, one fixed-pattern identity and a positive uint16 RAW code span.\");\n const offset=band.y*width;\n codes.set(p.codes,offset);blackLevels.set(p.blackLevels,offset);digitalSaturationCodes.set(p.digitalSaturationCodes,offset);saturationFlags.set(p.saturationFlags,offset);\n for(let phase=0;phase<phases;phase++)white.recordPhase(phase,p.effectiveSaturationCodes[phase]!);\n total+=p.providerEvaluationCount;y+=band.height;\n }\n if(y!==native.pixelHeight)throw new InvalidConfigurationError(\"Native RAW partitions must cover every row once, in row order.\");\n if(total>maximum)throw new InvalidConfigurationError(\"Native environment exceeds tile or full-event query budget.\");\n const raw:NativeRawOutput={plan,codes,blackLevels,digitalSaturationCodes,saturationFlags,effectiveSaturationCodes:white.finish()};\n return {raw,sceneBinding,providerEvaluationCount:total,upstreamOrigin:\"executed-environment-query-provider-optics-psf-eqe\",providerTransportVerified:false,productionPlanActivated:false};\n}\n/**\n * Re-runs only the sensor stage from a retained optical stage. No radiance callback is called.\n *\n * Use it when only post-optics settings change: noise seed, ISO and its readout regime and gain,\n * fixed-pattern noise, charge, dark-current and capacity profiles, white-balance intent, capture identity\n * or tile width. White balance and rendering are then applied by createNativeRawDevelopmentTask as usual.\n *\n * RAW codes are bit-identical to a full createNativeEnvironmentRawTask with the same final inputs, as long\n * as the radiance provider is a deterministic function of its request.\n *\n * Any optical difference is rejected with InvalidConfigurationError before output. That includes scene\n * binding, geometry or orientation, focal length, aperture, shutter or exposure window, focus,\n * frame/CFA/binding profiles, and any site environment field such as PSF, field throughput, pupil, motion,\n * spectral or temporal sampling and provider profiles.\n *\n * providerEvaluationCount is 0. The caller still owns the stage; it is not used up.\n */\nexport function createNativeEnvironmentSensorStageTask(input:NativeEnvironmentSensorStageInput,opticalStage:NativeEnvironmentOpticalStage,\n provider:NativeEnvironmentSensorStageProvider):NativeEnvironmentRawTask {\n const {task,sceneBinding}=createSensorStageRawTask(input,opticalStage,provider,parseSceneBinding);\n return {plan:task.plan,get state():NativeRawTaskState{return task.state;},get completedTileCount():number{return task.completedTileCount;},get providerEvaluationCount():number{return 0;},\n run:():Promise<void>=>task.run(),cancel:():void=>task.cancel(),dispose:():void=>task.dispose(),\n takeOutput():NativeEnvironmentRawOutput{return {raw:task.takeOutput(),sceneBinding,providerEvaluationCount:0,upstreamOrigin:\"executed-environment-query-provider-optics-psf-eqe\",providerTransportVerified:false,productionPlanActivated:false};}\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"native-environment-raw.js","sourceRoot":"","sources":["../../src/capture/native-environment-raw.ts"],"names":[],"mappings":"AAAA,sCAAsC;AAEtC;;;GAGG;AACH,OAAO,EAAC,sBAAsB,EAAC,0BAA0B,EAAC,gCAAgC,EAAC,MAAM,wCAAwC,CAAC;AAC1I,OAAO,EAAE,sBAAsB,EAAE,8BAA8B,EAAE,mCAAmC,EACN,MAAM,iBAAiB,CAAC;AACtH,OAAO,EAAE,gCAAgC,EAAE,MAAM,sBAAsB,CAAC;AAExE,OAAO,EAAE,sC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AO,IAAI,CAAC,KAAK,CAAC,CAAA,CAAC,EAAC,IAAI,kBAAkB,KAAU,OAAO,IAAI,CAAC,kBAAkB,CAAC,CAAA,CAAC,EAAC,IAAI,uBAAuB,KAAU,OAAO,CAAC,CAAC,CAAA,CAAC;QACxL,GAAG,EAAC,GAAgB,EAAE,CAAA,IAAI,CAAC,GAAG,EAAE,EAAC,MAAM,EAAC,GAAO,EAAE,CAAA,IAAI,CAAC,MAAM,EAAE,EAAC,OAAO,EAAC,GAAO,EAAE,CAAA,IAAI,CAAC,OAAO,EAAE;QAC9F,UAAU,KAA8B,OAAO,EAAC,GAAG,EAAC,IAAI,CAAC,UAAU,EAAE,EAAC,YAAY,EAAC,uBAAuB,EAAC,CAAC,EAAC,cAAc,EAAC,oDAAoD,EAAC,yBAAyB,EAAC,KAAK,EAAC,uBAAuB,EAAC,KAAK,EAAC,CAAC,CAAA,CAAC;KAClP,CAAC;AACJ,CAAC","sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Native RAW capture from a scene-radiance provider: source radiance → optics → EQE (external quantum\n * efficiency) → packed RAW codes for the full native sensor, within fixed work limits.\n */\nimport {internalRadianceAccess,isInternalNativeTileReader,isInternalSceneRadianceEvaluator} from \"../core/internal-radiance-evaluator.js\";\nimport { calculateNativeRawPlan, createNativeRawTaskWithCadence, nativeRawMaximumProviderEvaluations, type NativeRawInput, type NativeRawOutput,\n type NativeRawPlan, type NativeRawTask, type NativeRawTileRequest, type NativeRawTaskState } from \"./native-raw.js\";\nimport { createPhaseWhiteLevelAccumulator } from \"./raw-white-level.js\";\nimport type { SensorRawProducerSiteInput } from \"./sensor-raw-producer.js\";\nimport { createEnvironmentRawFrameCanonicalMemo, planEnvironmentRawSite, type SimulateEnvironmentSensorRawFrameInput } from \"./environment-raw-producer.js\";\nimport { DEFAULT_HOST_YIELD_CADENCE, createHostYieldGate, type HostYieldCadence } from \"./host-yield-cadence.js\";\nimport { executeEnvironmentSensorPhotoSignal, prebuildApertureRadianceQuery } from \"../sensor/environment-photo-signal.js\";\nimport { composeNativeEnvironmentSensorSite, createNativeEnvironmentOpticalStageRecorder, createSensorStageRawTask, parseNativeEnvironmentOpticalStageRetention, type NativeEnvironmentOpticalStage, type NativeEnvironmentOpticalStageRetention, type NativeEnvironmentSensorStageInput, type NativeEnvironmentSensorStageProvider, canonical } from \"./native-environment-optical-stage.js\";\nimport { parseEvidenceList } from \"../core/evidence-provenance.js\";\nimport { rejectUnknownFields, requireAllowlistedRecord, requirePublicOpaqueId } from \"../core/record-validation.js\";\nimport { freezeOwnedData } from \"../core/owned-data.js\";\nimport { InvalidConfigurationError } from \"../core/configuration-error.js\";\nimport { createNativeEnvironmentLeanExecutor, createNativeEnvironmentSensorLean, isLeanEnvironmentPlan,\n type LeanEnvironmentPlan } from \"./native-environment-lean.js\";\nimport { prepareCaptureExposureWindowSampler } from \"../sensor/exposure-window.js\";\nimport type { SensorEqeTemporalPhotoSignal } from \"../sensor/temporal-photo-signal.js\";\nimport type { SceneRadianceEvaluationRequest, SceneRadianceEvaluationResult } from \"../schema/scene-radiance.js\";\nimport type { SensorApertureRay } from \"../optics/sensor-aperture-rays.js\";\n\ntype SitePlan = ReturnType<typeof planEnvironmentRawSite> | LeanEnvironmentPlan;\ntype PhotoSignal = SensorEqeTemporalPhotoSignal;\n\nexport interface NativeEnvironmentRawInput {\n raw: NativeRawInput;\n sceneBinding: SimulateEnvironmentSensorRawFrameInput[\"sceneBinding\"];\n /** Budget of provider calls for the whole capture, checked before work starts; at most 2 billion. Staying within it does not imply convergence. */\n maximumProviderEvaluations: number;\n /**\n * Optional: keep the optical stage (per-site expected photo signal, tied to every optical input) on the\n * output, for createNativeEnvironmentSensorStageTask. If omitted, behaviour and output shape are unchanged.\n */\n opticalStage?: NativeEnvironmentOpticalStageRetention;\n}\nexport interface NativeEnvironmentRawTile extends NativeRawTileRequest {\n sites: SimulateEnvironmentSensorRawFrameInput[\"sites\"];\n}\n/** One radiance query of a batch: the frozen provider request and, for an ideal-pupil ray, its frozen aperture ray. */\nexport interface NativeEnvironmentRadianceQuery {\n request: Readonly<SceneRadianceEvaluationRequest>;\n apertureRay?: Readonly<SensorApertureRay>;\n}\nexport interface NativeEnvironmentRawProvider {\n /** Supplies physical site profiles, not photo counts or precomputed RAW codes. */\n readTile(request: Readonly<NativeRawTileRequest>,signal:AbortSignal):Promise<NativeEnvironmentRawTile>;\n evaluateRadiance: SimulateEnvironmentSensorRawFrameInput[\"evaluateRadiance\"];\n evaluateApertureRadiance?: SimulateEnvironmentSensorRawFrameInput[\"evaluateApertureRadiance\"];\n /**\n * Optional batched light sampling (2.0, additive). When present, the engine makes one call per tile instead of one\n * evaluateRadiance or evaluateApertureRadiance call per query. `queries` holds every query of the tile's sites, in\n * exactly the order the per-query callbacks would be made, each with the same frozen request (and aperture ray).\n * Return one result per query, in the same order; a promise is allowed (for example a GPU readback). Each result\n * is validated by the same parser and binding checks as a per-query result, so for the same results the output is\n * byte-identical. The per-query evaluators stay required as the reference contract, but are not called.\n */\n evaluateRadianceBatch?(queries:readonly NativeEnvironmentRadianceQuery[],signal:AbortSignal):\n readonly SceneRadianceEvaluationResult[]|Promise<readonly SceneRadianceEvaluationResult[]>;\n /** Optional, bounded diagnostic callback. Counts are expected values before any noise, clipping or ADC (analogue-to-digital conversion). */\n observePhotoTile?(tile:Readonly<NativeEnvironmentPhotoTile>,signal:AbortSignal):void|Promise<void>;\n yieldControl(signal:AbortSignal):Promise<void>;\n}\nexport interface NativeEnvironmentPhotoTile extends NativeRawTileRequest {\n sites:readonly {nativeIndex:number;expectedIncidentPhotonCount:number;expectedGeneratedElectronCount:number}[];\n}\nexport interface NativeEnvironmentRawOutput {\n raw: NativeRawOutput;\n sceneBinding: NativeEnvironmentRawInput[\"sceneBinding\"];\n providerEvaluationCount: number;\n upstreamOrigin: \"executed-environment-query-provider-optics-psf-eqe\";\n providerTransportVerified: false;\n productionPlanActivated: false;\n /** Present only when NativeEnvironmentRawInput.opticalStage was requested. The caller owns and disposes it. */\n opticalStage?: NativeEnvironmentOpticalStage;\n}\nexport interface NativeEnvironmentRawTask extends Omit<NativeRawTask,\"takeOutput\"> {\n readonly providerEvaluationCount: number;\n takeOutput(): NativeEnvironmentRawOutput;\n}\n/** Site-environment fields that one native event shares across every site (same set as the optical-stage binding). */\nconst SHARED_STATE_KEYS = [\"sceneBindings\",\"optics\",\"motion\",\"psf\",\"pupil\",\"fieldThroughput\"] as const;\ntype SiteEnvironment = SimulateEnvironmentSensorRawFrameInput[\"sites\"][number][\"environment\"];\n/** The frame's first accepted shared state: its canonical string and its engine-owned (cloned) values. */\ninterface SharedStateReference {\n readonly canonical: string;\n readonly values: readonly unknown[];\n /** Arrays of the reference already checked to carry no holes or extra properties. */\n readonly cleanArrays: WeakSet<object>;\n}\n/**\n * Strict structural equality of structured-clone output against the reference: Object.is for primitives (0 and\n * -0 differ), identical prototypes limited to plain records and arrays, identical own keys in identical order,\n * and arrays with no holes or non-index properties. Anything else is unequal unless it is the same reference.\n * Equal values therefore serialize to the same canonical string and are interchangeable for every reader, so a\n * site may adopt the reference values. Recursion is bounded by the reference, which serialized without error.\n */\nfunction samePlainData(value: unknown, reference: unknown, cleanArrays: WeakSet<object>): boolean {\n if (Object.is(value, reference)) return true;\n if (typeof value !== \"object\" || typeof reference !== \"object\" || value === null || reference === null) return false;\n const prototype = Object.getPrototypeOf(value) as unknown;\n if (prototype !== Object.getPrototypeOf(reference)) return false;\n if (prototype === Array.prototype) {\n const a = value as unknown[], b = reference as unknown[], length = a.length;\n if (length !== b.length) return false;\n for (let index = 0; index < length; index++) if (!(index in a) || !(index in b) || !samePlainData(a[index], b[index], cleanArrays)) return false;\n // Holes are excluded above, so equal key counts exclude non-index properties as well.\n if (Object.keys(a).length !== length) return false;\n if (!cleanArrays.has(b)) { if (Object.keys(b).length !== length) return false; cleanArrays.add(b); }\n return true;\n }\n if (prototype !== Object.prototype && prototype !== null) return false;\n const a = value as Record<string, unknown>, b = reference as Record<string, unknown>, keys = Object.keys(a), referenceKeys = Object.keys(b);\n if (keys.length !== referenceKeys.length) return false;\n for (let index = 0; index < keys.length; index++) if (keys[index] !== referenceKeys[index]) return false;\n for (let index = 0; index < keys.length; index++) if (!samePlainData(a[keys[index]!], b[keys[index]!], cleanArrays)) return false;\n return true;\n}\n/**\n * Replaces a site's private copy of the shared state with the frame's reference values when every field is\n * strictly equal (a 2.0 performance change). All sites then share one engine-owned shared state, so its sampled\n * PSF is parsed and frozen once per frame and duplicate copies can be garbage-collected at once. `verified`\n * holds copies in the current tile already shown equal, so sites the supplier built from one object compare in\n * O(1). Returns false, changing nothing, when any field differs; the caller then serializes as before.\n */\nfunction adoptSharedState(environment: SiteEnvironment, reference: SharedStateReference, verified: unknown[]): boolean {\n const record = environment as unknown as Record<string, unknown>;\n for (let index = 0; index < SHARED_STATE_KEYS.length; index++) {\n const value = record[SHARED_STATE_KEYS[index]!];\n if (!(typeof value === \"object\" && value !== null && value === verified[index]) && !samePlainData(value, reference.values[index], reference.cleanArrays)) return false;\n }\n for (let index = 0; index < SHARED_STATE_KEYS.length; index++) {\n const key = SHARED_STATE_KEYS[index]!, value = record[key];\n if (value !== reference.values[index]) { verified[index] = value; record[key] = reference.values[index]; }\n }\n return true;\n}\n/**\n * Every radiance query the executors will make for these site plans, in their callback order: per site, per instant,\n * per group (spectral-major, spatial-minor), per tap, then per pupil ray. Pupil queries come from the executors' own\n * apertureRadianceQuery, which then hands the executor the same objects.\n */\nfunction tileQueries(plans:readonly SitePlan[]):NativeEnvironmentRadianceQuery[] {\n const queries:NativeEnvironmentRadianceQuery[]=[];\n const add=(planned:{request?:SceneRadianceEvaluationRequest;apertureRays?:readonly SensorApertureRay[]}):void=>{\n // A batch never has material taps (#394), so every planned tap carries its request.\n const tap=planned as {request:SceneRadianceEvaluationRequest;apertureRays?:readonly SensorApertureRay[]};\n if(tap.apertureRays===undefined){queries.push({request:tap.request});return;}\n // The executor later receives these same objects (apertureRadianceQuery), so they are built once.\n for(const ray of tap.apertureRays)queries.push(prebuildApertureRadianceQuery(tap.request,ray));\n };\n for(const p of plans){\n if(isLeanEnvironmentPlan(p)){for(const instant of p.instants)for(const tap of instant.taps)add(tap);}\n else for(const instant of p.instants)for(const group of instant.groups)for(const tap of group.taps)add(tap);\n }\n return queries;\n}\nfunction parseSceneBinding(value: unknown): NativeEnvironmentRawInput[\"sceneBinding\"] {\n const binding=requireAllowlistedRecord(value,[\"sceneStateId\",\"providerSceneId\",\"evidence\"],\"Invalid native scene binding.\");\n return freezeOwnedData({sceneStateId:requirePublicOpaqueId(binding.sceneStateId,\"Invalid scene-state ID.\"),providerSceneId:requirePublicOpaqueId(binding.providerSceneId,\"Invalid provider-scene ID.\"),evidence:parseEvidenceList(binding.evidence,\"nativeEnvironmentSceneBinding.evidence\")});\n}\n/**\n * Creates the native RAW task. Every tile is planned and checked against the limits before its radiance\n * callbacks run, and no partial output is ever returned.\n *\n * The task also yields to the host between sites inside a tile once about 8 ms of work has passed (one budget\n * shared with the tile loop). Cancellation is checked after each such yield, so cancel() takes effect within\n * about one site's work. Yield timing never changes tile requests, limit checks, callbacks or output.\n */\nexport function createNativeEnvironmentRawTask(input:NativeEnvironmentRawInput,provider:NativeEnvironmentRawProvider):NativeEnvironmentRawTask {\n return createNativeEnvironmentRawTaskWithCadence(input,provider,DEFAULT_HOST_YIELD_CADENCE);\n}\n/** Internal: the same task with an explicit host-yield timing. Timing never changes tiles, callbacks or output. Not exported from the package. */\n/** Validates a native environment input exactly as task creation does, before any callback. Internal (also the tabulated RAW path, #394). */\nexport function admitNativeEnvironmentInput(input:NativeEnvironmentRawInput):{plan:ReturnType<typeof calculateNativeRawPlan>;\n sceneBinding:NativeEnvironmentRawInput[\"sceneBinding\"];retention:NativeEnvironmentOpticalStageRetention|undefined;maximum:number} {\n const r=requireAllowlistedRecord(input,[\"raw\",\"sceneBinding\",\"maximumProviderEvaluations\",\"opticalStage\"],\"Invalid native environment input.\");\n const plan=calculateNativeRawPlan(input.raw),sceneBinding=parseSceneBinding(r.sceneBinding);\n const retention=r.opticalStage===undefined?undefined:parseNativeEnvironmentOpticalStageRetention(r.opticalStage);\n if(sceneBinding.sceneStateId!==plan.exposure.sceneStateId||plan.exposure.sceneTimeSeconds!==0||!plan.exposureWindow||\n typeof r.maximumProviderEvaluations!==\"number\"||!Number.isSafeInteger(r.maximumProviderEvaluations)||r.maximumProviderEvaluations<plan.pixelCount||r.maximumProviderEvaluations>nativeRawMaximumProviderEvaluations(plan))\n throw new InvalidConfigurationError(\"Native environment requires opening-reference scene binding, an explicit shutter event and bounded full-event query budget.\");\n return {plan,sceneBinding,retention,maximum:r.maximumProviderEvaluations};\n}\n/** Internal: a partition's row band, and the facts it records while running for the merge step. */\ninterface NativeEnvironmentPartitionProbe {\n readonly rows:NativeRawRowBand;\n /** Internal (2.3 region rendering): native columns [x, x + width); absent means every column. */\n readonly columns?:{readonly x:number;readonly width:number};\n /** Canonical string of the band's shared source/optical/motion state (the first site's). */\n shared?:string;\n /** The band's first parsed RAW site (its readout identity). */\n firstSite?:SensorRawProducerSiteInput;\n}\nexport function createNativeEnvironmentRawTaskWithCadence(input:NativeEnvironmentRawInput,provider:NativeEnvironmentRawProvider,\n cadence:HostYieldCadence,partition?:NativeEnvironmentPartitionProbe):NativeEnvironmentRawTask {\n const {plan,sceneBinding,retention,maximum}=admitNativeEnvironmentInput(input);\n if(partition&&retention)throw new InvalidConfigurationError(\"A native environment partition cannot retain the optical stage.\");\n if(!provider||typeof provider.readTile!==\"function\"||typeof provider.evaluateRadiance!==\"function\"||typeof provider.yieldControl!==\"function\"||\n (provider.evaluateApertureRadiance!==undefined&&typeof provider.evaluateApertureRadiance!==\"function\")||\n (provider.observePhotoTile!==undefined&&typeof provider.observePhotoTile!==\"function\")||\n (provider.evaluateRadianceBatch!==undefined&&typeof provider.evaluateRadianceBatch!==\"function\"))throw new InvalidConfigurationError(\"Native environment requires physical source callbacks and host yields.\");\n // 2.6: an engine-built evaluator (simulateCapture chart scenes) lets the lean path skip re-parsing the fixed parts of\n // its results; read once, so the checked function is the one bound. Never with a batch, whose results are the caller's.\n const evaluateFunction=provider.evaluateRadiance,internalEvaluator=provider.evaluateRadianceBatch===undefined&&isInternalSceneRadianceEvaluator(evaluateFunction);\n const internalSites=isInternalNativeTileReader(provider.readTile),read=provider.readTile.bind(provider),evaluate=evaluateFunction.bind(provider),aperture=provider.evaluateApertureRadiance?.bind(provider),yieldControl=provider.yieldControl.bind(provider);\n const observe=provider.observePhotoTile?.bind(provider),batch=provider.evaluateRadianceBatch?.bind(provider);\n let evaluations=0,shared:string|undefined,reference:SharedStateReference|undefined;\n const recorder=retention?createNativeEnvironmentOpticalStageRecorder(plan,sceneBinding,retention):undefined;\n const memo=createEnvironmentRawFrameCanonicalMemo(plan.frame,plan.exposureWindow!),gate=createHostYieldGate(cadence);\n const layout=plan.frame.colorSamplingProfile.layout,relationship=plan.frame.bindingProfile.relationship;\n const leanFrame={frameId:plan.frame.frameId,nativeWidth:plan.exposure.geometry.nativeRaster.pixelWidth,\n nativeHeight:plan.exposure.geometry.nativeRaster.pixelHeight,repeatWidth:layout.kind===\"periodic-mosaic\"?layout.repeatWidthSites:0,\n repeatHeight:layout.kind===\"periodic-mosaic\"?layout.repeatHeightSites:0,\n identityBinding:relationship.sitesPerNativeSampleX===1&&relationship.sitesPerNativeSampleY===1&&relationship.anchor===\"shared-native-top-left\"};\n // #394: an engine-built evaluator's key lookup lets verified templates skip its calls (never with a batch).\n const lean=createNativeEnvironmentLeanExecutor(leanFrame,internalEvaluator?internalRadianceAccess(evaluateFunction):undefined);\n let nativeWindow:Parameters<typeof createNativeEnvironmentSensorLean>[2];\n try{nativeWindow=prepareCaptureExposureWindowSampler({...plan.exposureWindow!,nativeRaster:plan.exposure.geometry.nativeRaster});}catch{nativeWindow=undefined;}\n const sensorLean=createNativeEnvironmentSensorLean(leanFrame,plan.frame,nativeWindow);\n const task=createNativeRawTaskWithCadence(input.raw,{\n async readTile(request,signal){\n const supplied=await read(request,signal);\n if(signal.aborted)throw new InvalidConfigurationError(\"Native environment acquisition aborted.\");\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))throw new InvalidConfigurationError(\"Physical source tile needs exact native coverage.\");\n // Private copy: planning takes each site environment as engine-owned plan data without copying it again. Sites from an\n // engine-built reader (#394: fresh records per call, never shown to supplied code or changed) are already the engine's own.\n const sites=(internalSites?tile.sites:structuredClone(tile.sites)) as SimulateEnvironmentSensorRawFrameInput[\"sites\"];\n // Yield to the host between sites on the shared time budget. Cancellation is honoured right after it.\n const pause=async():Promise<void>=>{\n if(!gate.due())return;\n await yieldControl(signal);\n if(signal.aborted)throw new InvalidConfigurationError(\"Native environment acquisition aborted.\");\n gate.restart();\n };\n let tileCount=0;\n const plans:SitePlan[]=[],verified:unknown[]=[];\n for(let j=0;j<sites.length;j++){\n if(j>0)await pause();\n const site=sites[j]!;\n requireAllowlistedRecord(site,[\"environment\",\"darkCurrentProfile\",\"operatingTemperatureC\",\"charge\",\"readout\"],\"Invalid physical site input.\");\n const e=site.environment,index=request.y*plan.exposure.geometry.nativeRaster.pixelWidth+request.x+j;\n if(e.temporalIntegrationId!==plan.frame.frameId+\":native:\"+index)throw new InvalidConfigurationError(\"Native environment IDs must bind the absolute native index.\");\n // A site strictly equal to the frame's first shared state adopts it and skips serialization; otherwise the\n // canonical comparison runs exactly as before and decides acceptance or the same error.\n let state:string;\n if(reference!==undefined&&adoptSharedState(e,reference,verified))state=reference.canonical;\n else{\n state=canonical({sceneBindings:e.sceneBindings,optics:e.optics,motion:e.motion,psf:e.psf,pupil:e.pupil,fieldThroughput:e.fieldThroughput});\n shared??=state;if(partition)partition.shared??=shared;if(state!==shared)throw new InvalidConfigurationError(\"Native event requires one shared source/optical/motion state.\");\n reference??={canonical:state,values:SHARED_STATE_KEYS.map(key=>(e as unknown as Record<string,unknown>)[key]),cleanArrays:new WeakSet()};\n }\n // A site matching a verified template gets a lean plan (identical requests and limit checks; see\n // native-environment-lean.ts). A template candidate keeps full query records for its self-check.\n // Otherwise only the photo signal is needed, so the plan keeps just each query's frozen request and image-plane point.\n const leanPlan=lean.plan(e,index);\n let p:SitePlan;\n if(typeof leanPlan===\"object\")p=leanPlan;\n else{\n p=planEnvironmentRawSite(site,index,plan.frame,sceneBinding,plan.exposureWindow!,\"engine-owned\",memo,leanPlan===\"candidate\"?\"full\":\"photo-only\");\n if(leanPlan===\"candidate\")lean.admitCandidate(e,index,p);\n }\n if(p.owned.pupil&&!aperture)throw new InvalidConfigurationError(\"Pupil capture requires origin-aware source visibility.\");\n recorder?.admit(index,e,state);\n tileCount+=p.count;\n if(tileCount>100_000||evaluations+tileCount>maximum)throw new InvalidConfigurationError(\"Native environment exceeds tile or full-event query budget.\");\n plans.push(p);\n }\n // Only value.photo is consumed, so per-evaluation diagnostics are not retained.\n const rawSites:(ReturnType<typeof composeNativeEnvironmentSensorSite>|object)[]=[],photos:PhotoSignal[]=[];\n sensorLean.beginTile();\n let evaluateCounted=(q:Parameters<typeof evaluate>[0]):ReturnType<typeof evaluate>=>{if(signal.aborted)throw new InvalidConfigurationError(\"Native source evaluation aborted.\");evaluations++;return evaluate(q);};\n let apertureCounted=aperture?(q:Parameters<typeof aperture>[0],ray:Parameters<typeof aperture>[1]):ReturnType<typeof evaluate>=>{if(signal.aborted)throw new InvalidConfigurationError(\"Native aperture evaluation aborted.\");evaluations++;return aperture(q,ray);}:undefined;\n let batched:{queries:readonly NativeEnvironmentRadianceQuery[];results:readonly SceneRadianceEvaluationResult[];next:number}|undefined;\n if(batch){\n // One call for the whole tile, with every planned query in per-query callback order (see tileQueries).\n const queries=tileQueries(plans);\n if(signal.aborted)throw new InvalidConfigurationError(\"Native source evaluation aborted.\");\n const results=await batch(Object.freeze(queries),signal);\n if(signal.aborted)throw new InvalidConfigurationError(\"Native source evaluation aborted.\");\n if(!Array.isArray(results)||results.length!==queries.length||Array.from({length:queries.length},(_,i)=>i in results).includes(false))\n throw new InvalidConfigurationError(\"Batched radiance must return one result per query, in query order.\");\n const current={queries,results:results as readonly SceneRadianceEvaluationResult[],next:0};\n batched=current;\n // The executors ask for each query in the same order; every step is checked against the planned query.\n const take=(q:Readonly<SceneRadianceEvaluationRequest>,ray:Readonly<SensorApertureRay>|undefined):SceneRadianceEvaluationResult=>{\n const k=current.next++,planned=current.queries[k];\n if(planned===undefined||planned.request.sampleId!==q.sampleId||(planned.apertureRay===undefined)!==(ray===undefined))\n throw new InvalidConfigurationError(\"Batched radiance results are out of step with the planned queries.\");\n evaluations++;\n return current.results[k]!;\n };\n evaluateCounted=(q):ReturnType<typeof evaluate>=>take(q,undefined);\n apertureCounted=aperture?(q,ray):ReturnType<typeof evaluate>=>take(q,ray):undefined;\n }\n for(let j=0;j<sites.length;j++){\n await pause();\n const index=request.y*plan.exposure.geometry.nativeRaster.pixelWidth+request.x+j;\n let p=plans[j]!,photoSignal:PhotoSignal|undefined;\n if(isLeanEnvironmentPlan(p)){\n // The full plan (deterministic, no callbacks) is built only when the lean path needs it.\n const fullPlan=():ReturnType<typeof planEnvironmentRawSite>=>planEnvironmentRawSite(sites[j]!,index,plan.frame,sceneBinding,plan.exposureWindow!,\"engine-owned\",memo,\"photo-only\");\n photoSignal=lean.execute(p,evaluateCounted,apertureCounted,fullPlan,internalEvaluator&&!batched,\n (n)=>{if(signal.aborted)throw new InvalidConfigurationError(\"Native source evaluation aborted.\");evaluations+=n;});\n // An unverified template: plan this site in full now and execute it in full.\n if(photoSignal===undefined)p=fullPlan();\n }\n if(photoSignal===undefined){\n const full=p as ReturnType<typeof planEnvironmentRawSite>,candidate=lean.isCandidate(index);\n const result=executeEnvironmentSensorPhotoSignal(full,evaluateCounted,apertureCounted,candidate?\"full\":\"photo-only\");\n if(candidate)lean.verifyCandidate(index,full,result);\n photoSignal=result.value.photo.value.photoSignal;\n }\n recorder?.record(index,photoSignal);\n photos.push(photoSignal);\n // A site matching a verified sensor template becomes a lean entry: every check its composition and RAW\n // parse would run has been evaluated (see native-environment-lean.ts). Otherwise compose it in full.\n const claimed=sensorLean.claim(sites[j]!,photoSignal,index);\n if(claimed)rawSites.push(claimed);\n else{rawSites.push(composeNativeEnvironmentSensorSite(sites[j]!,photoSignal));sensorLean.remember(index,sites[j]!,photoSignal);}\n }\n if(batched&&batched.next!==batched.queries.length)throw new InvalidConfigurationError(\"Batched radiance results are out of step with the planned queries.\");\n if(signal.aborted)throw new InvalidConfigurationError(\"Native photo observation aborted.\");\n if(observe)await observe(freezeOwnedData({...request,sites:photos.map((s,j)=>({nativeIndex:request.y*plan.exposure.geometry.nativeRaster.pixelWidth+request.x+j,\n expectedIncidentPhotonCount:s.expectedIncidentPhotonCount,expectedGeneratedElectronCount:s.expectedGeneratedElectronCount}))}),signal);\n return {...request,sites:rawSites as ReturnType<typeof composeNativeEnvironmentSensorSite>[]};\n },yieldControl\n },cadence,gate,sensorLean.hook,partition?{y:partition.rows.y,height:partition.rows.height,firstSite:(site):void=>{partition.firstSite=site;},\n ...(partition.columns?{x:partition.columns.x,width:partition.columns.width}:{})}:undefined);\n // The frame reference is needed only while tiles are read; release it once the event settles.\n const settle=():void=>{reference=undefined;};\n return {plan:task.plan,get state():NativeRawTaskState{return task.state;},get completedTileCount():number{return task.completedTileCount;},get providerEvaluationCount():number{return evaluations;},\n run:():Promise<void>=>(recorder?task.run().catch((error:unknown)=>{if(task.state===\"failed\"||task.state===\"cancelled\"||task.state===\"disposed\")recorder.discard();throw error;}):task.run()).finally(settle),\n cancel:():void=>{if(task.state!==\"transferred\")recorder?.discard();task.cancel();},dispose:():void=>{if(task.state!==\"transferred\")recorder?.discard();task.dispose();},\n takeOutput():NativeEnvironmentRawOutput{\n // Finish retention first so a retention failure never strands the transferred RAW.\n const opticalStage=recorder&&task.state===\"completed\"?recorder.finish(evaluations):undefined;\n const raw=task.takeOutput();\n const base={raw,sceneBinding,providerEvaluationCount:evaluations,upstreamOrigin:\"executed-environment-query-provider-optics-psf-eqe\" as const,providerTransportVerified:false as const,productionPlanActivated:false as const};\n return opticalStage?{...base,opticalStage}:base;\n }\n };\n}\n/**\n * Internal (not exported from the package; 2.3 `simulateCapture` `output.region`): the task for one rectangle of\n * native sites [x, x + width) × [y, y + height) of the whole-frame input. Every site keeps its absolute native index,\n * so its noise seeds, CFA phase, exposure window (rolling-shutter row timing) and value are those of the whole-frame\n * task; the output arrays hold just the rectangle, row-major, and `effectiveSaturationCodes` holds 0 for a CFA\n * phase the rectangle does not contain. Optical-stage retention is not supported.\n */\nexport function createNativeEnvironmentRawRegionTask(input:NativeEnvironmentRawInput,region:{x:number;y:number;width:number;height:number},\n provider:NativeEnvironmentRawProvider):NativeEnvironmentRawTask {\n const plan=calculateNativeRawPlan(input?.raw),native=plan.exposure.geometry.nativeRaster;\n const r=requireAllowlistedRecord(region,[\"x\",\"y\",\"width\",\"height\"],\"Invalid native RAW region.\");\n if(![r.x,r.y,r.width,r.height].every(v=>typeof v===\"number\"&&Number.isSafeInteger(v))||(r.width as number)<1||(r.x as number)<0||(r.x as number)+(r.width as number)>native.pixelWidth)\n throw new InvalidConfigurationError(\"Native RAW region must lie inside the native raster.\");\n const rows=parseRowBand({y:r.y,height:r.height},native.pixelHeight);\n return createNativeEnvironmentRawTaskWithCadence(input,provider,DEFAULT_HOST_YIELD_CADENCE,{rows,columns:{x:r.x as number,width:r.width as number}});\n}\n/** A band of whole native rows, [y, y + height), in absolute full-sensor coordinates. */\nexport interface NativeRawRowBand { y: number; height: number }\n/**\n * Splits a plan's native rows into at most `count` contiguous bands of nearly equal height (the first\n * `height % count` bands are one row taller), in row order. Deterministic: it depends only on the raster height and\n * `count`. Use one band per worker with createNativeEnvironmentRawPartitionTask.\n */\nexport function calculateNativeRawRowBands(plan:Pick<NativeRawPlan,\"exposure\">,count:number):NativeRawRowBand[] {\n if(plan!==null&&typeof plan===\"object\")rejectUnknownFields(plan,[\"schemaVersion\",\"exposure\",\"frame\",\"exposureWindow\",\"pixelCount\",\"outputBytes\",\"tileCount\",\n \"tileWidth\",\"upstreamRadiometryVerified\",\"seedSchedule\"],\"Native RAW plan\");\n const height=plan?.exposure?.geometry?.nativeRaster?.pixelHeight;\n if(typeof height!==\"number\"||!Number.isSafeInteger(height)||height<1)throw new InvalidConfigurationError(\"Native RAW partitioning requires a native RAW plan.\");\n if(typeof count!==\"number\"||!Number.isSafeInteger(count)||count<1||count>1024)throw new InvalidConfigurationError(\"Native RAW partition count must be an integer from 1 to 1024.\");\n const bands=Math.min(count,height),base=Math.floor(height/bands),extra=height%bands,result:NativeRawRowBand[]=[];\n for(let i=0,y=0;i<bands;i++){const h=base+(i<extra?1:0);result.push({y,height:h});y+=h;}\n return result;\n}\n/**\n * One partition's result: plain data and typed arrays only, so it can be posted from a worker (transfer the four\n * arrays' buffers). Merge every partition of a capture with composeNativeEnvironmentRawPartitions.\n */\nexport interface NativeEnvironmentRawPartition {\n rows: NativeRawRowBand;\n /** Canonical JSON of the capture input (raw, sceneBinding, maximumProviderEvaluations); the merge requires it to match. */\n inputCanonical: string;\n /** Canonical JSON of the band's shared source/optical/motion state; every partition must match. */\n sharedStateCanonical: string;\n /** Readout identity of the band's first site; every partition must match (one readout identity per frame). */\n readoutIdentity: { readoutProfileId: string; regimeId: string; fixedPatternProfileId: string | null; fixedPatternSeedUint32: number | null };\n /** The band's rows only, row-major, as in NativeRawOutput. */\n codes: Uint16Array;\n blackLevels: Uint16Array;\n digitalSaturationCodes: Uint16Array;\n saturationFlags: Uint8Array;\n /** Effective white code per CFA phase; 0 for a phase the band does not contain. */\n effectiveSaturationCodes: Uint16Array;\n providerEvaluationCount: number;\n}\nexport interface NativeEnvironmentRawPartitionTask extends Omit<NativeRawTask,\"takeOutput\"> {\n readonly rows: NativeRawRowBand;\n readonly providerEvaluationCount: number;\n takeOutput(): NativeEnvironmentRawPartition;\n}\nfunction inputCanonical(input:NativeEnvironmentRawInput):string {\n return canonical({raw:input.raw,sceneBinding:input.sceneBinding,maximumProviderEvaluations:input.maximumProviderEvaluations});\n}\nfunction parseRowBand(value:unknown,height:number):NativeRawRowBand {\n const band=requireAllowlistedRecord(value,[\"y\",\"height\"],\"Invalid native RAW row band.\");\n if(typeof band.y!==\"number\"||typeof band.height!==\"number\"||!Number.isSafeInteger(band.y)||!Number.isSafeInteger(band.height)||\n band.y<0||band.height<1||band.y+band.height>height)throw new InvalidConfigurationError(\"Native RAW row band must lie inside the native raster.\");\n return {y:band.y,height:band.height};\n}\n/**\n * Creates the task for one row band of a native environment capture (opt-in parallel execution, 2.0).\n *\n * Run one partition per worker (or one after another) with the same input, each worker using its own provider, then\n * merge them with composeNativeEnvironmentRawPartitions. The merged output is byte-identical to the single\n * createNativeEnvironmentRawTask output for the same input and a deterministic provider: noise seeds use absolute\n * native indices, and tiles, plans and per-site values are those of the whole-frame task.\n *\n * Each partition checks the same inputs and limits before its callbacks. maximumProviderEvaluations bounds each\n * partition's own work; the merge also rejects a total above it. Frame-wide checks that span sites (one shared\n * state, one readout identity, one white level per CFA phase) run inside each band and again across bands in the\n * merge. Callbacks are split across partitions, and when several partitions fail, which error is seen first depends\n * on the caller's scheduling. Optical-stage retention is not supported in a partition.\n *\n * The package bundles no worker code: the caller creates workers (Web Workers or Node worker threads), runs this\n * task inside each and posts the partition back.\n */\nexport function createNativeEnvironmentRawPartitionTask(input:NativeEnvironmentRawInput,rows:NativeRawRowBand,\n provider:NativeEnvironmentRawProvider):NativeEnvironmentRawPartitionTask {\n const plan=calculateNativeRawPlan(input?.raw),band=parseRowBand(rows,plan.exposure.geometry.nativeRaster.pixelHeight);\n const probe:NativeEnvironmentPartitionProbe={rows:band};\n const task=createNativeEnvironmentRawTaskWithCadence(input,provider,DEFAULT_HOST_YIELD_CADENCE,probe),text=inputCanonical(input);\n return {plan:task.plan,rows:band,get state():NativeRawTaskState{return task.state;},get completedTileCount():number{return task.completedTileCount;},\n get providerEvaluationCount():number{return task.providerEvaluationCount;},run:():Promise<void>=>task.run(),cancel:():void=>task.cancel(),dispose:():void=>task.dispose(),\n takeOutput():NativeEnvironmentRawPartition{\n if(task.state!==\"completed\"||probe.shared===undefined||probe.firstSite===undefined)throw new InvalidConfigurationError(\"Native RAW output unavailable.\");\n const site=probe.firstSite,sharedStateCanonical=probe.shared,output=task.takeOutput(),raw=output.raw;\n return {rows:{...band},inputCanonical:text,sharedStateCanonical,readoutIdentity:{readoutProfileId:site.readoutProfile.profileId,regimeId:site.regimeId,\n fixedPatternProfileId:site.fixedPatternNoise?.profileId??null,fixedPatternSeedUint32:site.fixedPatternNoise?.sensorInstanceSeedUint32??null},\n codes:raw.codes,blackLevels:raw.blackLevels,digitalSaturationCodes:raw.digitalSaturationCodes,saturationFlags:raw.saturationFlags,\n effectiveSaturationCodes:raw.effectiveSaturationCodes,providerEvaluationCount:output.providerEvaluationCount};\n }\n };\n}\n/**\n * Assembles the partitions of one capture into the output createNativeEnvironmentRawTask would have returned for\n * the same input (byte-identical RAW arrays and white levels, the summed provider evaluation count).\n *\n * The partitions must be in row order and cover every native row exactly once, and each must come from\n * createNativeEnvironmentRawPartitionTask with this same input. It rejects, with InvalidConfigurationError, a\n * different input, a gap or overlap, wrong array types or lengths, a second shared state or readout identity, two\n * white levels for one CFA phase, a missing phase, or a total evaluation count above the input's budget. It cannot\n * verify how a partition was computed: posted partitions are the caller's own data.\n */\nexport function composeNativeEnvironmentRawPartitions(input:NativeEnvironmentRawInput,partitions:readonly NativeEnvironmentRawPartition[]):NativeEnvironmentRawOutput {\n const {plan,sceneBinding,retention,maximum}=admitNativeEnvironmentInput(input);\n if(retention)throw new InvalidConfigurationError(\"A native environment partition cannot retain the optical stage.\");\n const native=plan.exposure.geometry.nativeRaster,width=native.pixelWidth,layout=plan.frame.colorSamplingProfile.layout;\n if(layout.kind!==\"periodic-mosaic\")throw new InvalidConfigurationError(\"Native RAW requires periodic CFA.\");\n const phases=layout.repeatWidthSites*layout.repeatHeightSites,text=inputCanonical(input);\n if(!Array.isArray(partitions)||partitions.length<1||partitions.length>native.pixelHeight||Array.from({length:partitions.length},(_,i)=>i in partitions).includes(false))\n throw new InvalidConfigurationError(\"Native RAW merge requires a dense list of partitions.\");\n const codes=new Uint16Array(plan.pixelCount),blackLevels=new Uint16Array(plan.pixelCount),digitalSaturationCodes=new Uint16Array(plan.pixelCount),saturationFlags=new Uint8Array(plan.pixelCount);\n const white=createPhaseWhiteLevelAccumulator(width,layout.repeatWidthSites,layout.repeatHeightSites);\n let y=0,total=0,shared:string|undefined,identity:string|undefined;\n for(const value of partitions){\n const p=requireAllowlistedRecord(value,[\"rows\",\"inputCanonical\",\"sharedStateCanonical\",\"readoutIdentity\",\"codes\",\"blackLevels\",\"digitalSaturationCodes\",\n \"saturationFlags\",\"effectiveSaturationCodes\",\"providerEvaluationCount\"],\"Invalid native RAW partition.\");\n const band=parseRowBand(p.rows,native.pixelHeight),length=band.height*width;\n if(band.y!==y)throw new InvalidConfigurationError(\"Native RAW partitions must cover every row once, in row order.\");\n if(p.inputCanonical!==text)throw new InvalidConfigurationError(\"Native RAW partition was computed from a different input.\");\n if(!(p.codes instanceof Uint16Array)||!(p.blackLevels instanceof Uint16Array)||!(p.digitalSaturationCodes instanceof Uint16Array)||\n !(p.saturationFlags instanceof Uint8Array)||!(p.effectiveSaturationCodes instanceof Uint16Array)||p.codes.length!==length||p.blackLevels.length!==length||\n p.digitalSaturationCodes.length!==length||p.saturationFlags.length!==length||p.effectiveSaturationCodes.length!==phases||\n typeof p.providerEvaluationCount!==\"number\"||!Number.isSafeInteger(p.providerEvaluationCount)||p.providerEvaluationCount<0||typeof p.sharedStateCanonical!==\"string\")\n throw new InvalidConfigurationError(\"Invalid native RAW partition arrays.\");\n const id=requireAllowlistedRecord(p.readoutIdentity,[\"readoutProfileId\",\"regimeId\",\"fixedPatternProfileId\",\"fixedPatternSeedUint32\"],\"Invalid native RAW partition identity.\");\n const idText=canonical(id);\n shared??=p.sharedStateCanonical;identity??=idText;\n if(p.sharedStateCanonical!==shared)throw new InvalidConfigurationError(\"Native event requires one shared source/optical/motion state.\");\n if(idText!==identity)throw new InvalidConfigurationError(\"Frame requires one readout identity/regime, one fixed-pattern identity and a positive uint16 RAW code span.\");\n const offset=band.y*width;\n codes.set(p.codes,offset);blackLevels.set(p.blackLevels,offset);digitalSaturationCodes.set(p.digitalSaturationCodes,offset);saturationFlags.set(p.saturationFlags,offset);\n for(let phase=0;phase<phases;phase++)white.recordPhase(phase,p.effectiveSaturationCodes[phase]!);\n total+=p.providerEvaluationCount;y+=band.height;\n }\n if(y!==native.pixelHeight)throw new InvalidConfigurationError(\"Native RAW partitions must cover every row once, in row order.\");\n if(total>maximum)throw new InvalidConfigurationError(\"Native environment exceeds tile or full-event query budget.\");\n const raw:NativeRawOutput={plan,codes,blackLevels,digitalSaturationCodes,saturationFlags,effectiveSaturationCodes:white.finish()};\n return {raw,sceneBinding,providerEvaluationCount:total,upstreamOrigin:\"executed-environment-query-provider-optics-psf-eqe\",providerTransportVerified:false,productionPlanActivated:false};\n}\n/**\n * Re-runs only the sensor stage from a retained optical stage. No radiance callback is called.\n *\n * Use it when only post-optics settings change: noise seed, ISO and its readout regime and gain,\n * fixed-pattern noise, charge, dark-current and capacity profiles, white-balance intent, capture identity\n * or tile width. White balance and rendering are then applied by createNativeRawDevelopmentTask as usual.\n *\n * RAW codes are bit-identical to a full createNativeEnvironmentRawTask with the same final inputs, as long\n * as the radiance provider is a deterministic function of its request.\n *\n * Any optical difference is rejected with InvalidConfigurationError before output. That includes scene\n * binding, geometry or orientation, focal length, aperture, shutter or exposure window, focus,\n * frame/CFA/binding profiles, and any site environment field such as PSF, field throughput, pupil, motion,\n * spectral or temporal sampling and provider profiles.\n *\n * providerEvaluationCount is 0. The caller still owns the stage; it is not used up.\n */\nexport function createNativeEnvironmentSensorStageTask(input:NativeEnvironmentSensorStageInput,opticalStage:NativeEnvironmentOpticalStage,\n provider:NativeEnvironmentSensorStageProvider):NativeEnvironmentRawTask {\n const {task,sceneBinding}=createSensorStageRawTask(input,opticalStage,provider,parseSceneBinding);\n return {plan:task.plan,get state():NativeRawTaskState{return task.state;},get completedTileCount():number{return task.completedTileCount;},get providerEvaluationCount():number{return 0;},\n run:():Promise<void>=>task.run(),cancel:():void=>task.cancel(),dispose:():void=>task.dispose(),\n takeOutput():NativeEnvironmentRawOutput{return {raw:task.takeOutput(),sceneBinding,providerEvaluationCount:0,upstreamOrigin:\"executed-environment-query-provider-optics-psf-eqe\",providerTransportVerified:false,productionPlanActivated:false};}\n };\n}\n"]}
|