@photivra/engine 2.8.0 → 2.9.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.
Files changed (53) hide show
  1. package/CHANGELOG.md +92 -5
  2. package/CITATION.cff +1 -1
  3. package/README.md +8 -6
  4. package/SECURITY.md +1 -1
  5. package/dist/capture/export-jpeg.d.ts +19 -0
  6. package/dist/capture/export-jpeg.js +190 -95
  7. package/dist/capture/export-jpeg.js.map +1 -1
  8. package/dist/capture/native-environment-lean.js +19 -9
  9. package/dist/capture/native-environment-lean.js.map +1 -1
  10. package/dist/core/version.d.ts +1 -1
  11. package/dist/core/version.js +1 -1
  12. package/dist/core/version.js.map +1 -1
  13. package/dist/facade/diffraction-provider.js +3 -10
  14. package/dist/facade/diffraction-provider.js.map +1 -1
  15. package/dist/facade/expected-signal-setup.d.ts +1 -1
  16. package/dist/facade/expected-signal-setup.js +2 -6
  17. package/dist/facade/expected-signal-setup.js.map +1 -1
  18. package/dist/facade/expected-signal.d.ts +4 -1
  19. package/dist/facade/expected-signal.js +151 -31
  20. package/dist/facade/expected-signal.js.map +1 -1
  21. package/dist/facade/scene-radiance.d.ts +4 -1
  22. package/dist/facade/scene-radiance.js +4 -4
  23. package/dist/facade/scene-radiance.js.map +1 -1
  24. package/dist/facade/simulate-capture.d.ts +26 -1
  25. package/dist/facade/simulate-capture.js +151 -26
  26. package/dist/facade/simulate-capture.js.map +1 -1
  27. package/dist/facade/simulate-display-view.js +2 -1
  28. package/dist/facade/simulate-display-view.js.map +1 -1
  29. package/dist/index.d.ts +4 -3
  30. package/dist/index.js +2 -2
  31. package/dist/index.js.map +1 -1
  32. package/dist/optics/diffraction-psf-profile.d.ts +19 -17
  33. package/dist/optics/diffraction-psf-profile.js +49 -18
  34. package/dist/optics/diffraction-psf-profile.js.map +1 -1
  35. package/dist/optics/site-diffraction-kernel.d.ts +5 -0
  36. package/dist/optics/site-diffraction-kernel.js +32 -0
  37. package/dist/optics/site-diffraction-kernel.js.map +1 -0
  38. package/dist/output/print-jpeg.d.ts +28 -1
  39. package/dist/output/print-jpeg.js +148 -48
  40. package/dist/output/print-jpeg.js.map +1 -1
  41. package/dist/sensor/stochastic-seed.d.ts +12 -0
  42. package/dist/sensor/stochastic-seed.js +25 -0
  43. package/dist/sensor/stochastic-seed.js.map +1 -1
  44. package/docs/API_REFERENCE.md +8 -1
  45. package/docs/QUICK_START.md +59 -0
  46. package/docs/api/capture-export-jpeg.md +10 -0
  47. package/docs/api/core-version.md +1 -1
  48. package/docs/api/exports.json +37 -2
  49. package/docs/api/facade-scene-radiance.md +2 -1
  50. package/docs/api/facade-simulate-capture.md +28 -0
  51. package/docs/api/optics-diffraction-psf-profile.md +1 -1
  52. package/docs/api/output-print-jpeg.md +41 -0
  53. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"scene-radiance.js","sourceRoot":"","sources":["../../src/facade/scene-radiance.ts"],"names":[],"mappings":"AAAA,sCAAsC;AAEtC;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAC3E,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EAAE,qCAAqC,EAAE,2BAA2B,EACtC,MAAM,sCAAsC,CAAC;AAClF,OAAO,EAAE,4BAA4B,EAAE,yBAAyB,EAAE,uBAAuB,EAAE,iCAAiC,EAAE,oCAAoC,EAChK,+BAA+B,EAAyB,MAAM,yBAAyB,CAAC;AAI1F,OAAO,EAAE,oBAAoB,EAAE,iBAAiB,EAAmE,MAAM,mBAAmB,CAAC;AAE7I,+DAA+D;AAC/D,MAAM,CAAC,MAAM,2CAA2C,GAAG,GAAG,CAAC;AAC/D,yFAAyF;AACzF,MAAM,CAAC,MAAM,gCAAgC,GAAG,MAAM,CAAC,MAAM,CAAC,EAAE,OAAO,EAAE,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,CAAC,CAAC;AAuB9F,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CAAC;QAAE,IAAI,GAAG,KAAK,MAAM,IAAI,GAAG,KAAK,SAAS,IAAI,GAAG,KAAK,UAAU;YAAE,MAAM,IAAI,yBAAyB,CAAC,uBAAuB,GAAG,GAAG,GAAG,GAAG,CAAC,CAAC;IAC/K,IAAI,CAAC,MAAM,CAAC,IAAI,KAAK,sBAAsB,IAAI,MAAM,CAAC,IAAI,KAAK,mBAAmB,CAAC,IAAI,OAAO,MAAM,CAAC,QAAQ,KAAK,UAAU;QAC1H,OAAO,MAAM,CAAC,OAAO,KAAK,QAAQ,IAAI,CAAC,oCAAoC,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC;QAAE,MAAM,IAAI,yBAAyB,CAAC,uEAAuE,CAAC,CAAC;IACjN,OAAO,MAAiE,CAAC;AAC3E,CAAC","sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Turns a facade scene and an illuminant into a scene radiance provider for the existing native\n * environment RAW contract (`NativeEnvironmentRawProvider.evaluateRadiance` and, for pupil sampling,\n * `evaluateApertureRadiance`). The scene is an engine chart, a caller reflectance function or a caller\n * radiance function.\n *\n * Geometry: one plane perpendicular to the optical axis at `distanceM` in front of the camera. A query's\n * outgoing direction o (scene toward camera, see docs/SENSOR_ENVIRONMENT_QUERY.md) gives the look\n * direction l = -o; the plane point is l·distanceM/l.z. With a pupil ray, the plane point is the ray from\n * its lens origin to z = distanceM.\n *\n * Radiometry: a Lambertian reflector of reflectance ρ(λ) under irradiance E(λ) has radiance\n * L(λ) = ρ(λ)·E(λ)/π (W·m⁻²·sr⁻¹·nm⁻¹). The illuminant spectral shape S(λ) is scaled so that the\n * plane illuminance is E_v = K_m ∫ E(λ) V(λ) dλ with K_m = 683 lm/W (CIE photometric definition) and\n * V(λ) = ȳ(λ) from the engine's analytic CIE 1931 fit. The light is uniform\n * over the plane, with no shadows. Inter-reflection, gloss and fluorescence are not modelled.\n * @see docs/QUICK_START.md\n */\n\nimport { InvalidConfigurationError } from \"../core/configuration-error.js\";\nimport { requireInputObject } from \"../core/record-validation.js\";\nimport { estimateCie1931ColorMatchingFunctions, prepareColorimetricSpectrum, type ColorimetricSpectrum,\n type PreparedColorimetricSpectrum } from \"../color/color-matching-functions.js\";\nimport { createCieIlluminantASpectrum, createCieDaylightSpectrum, createPlanckianSpectrum, createPortableCieDaylightSpectrum, createPortableCieIlluminantASpectrum,\n createPortablePlanckianSpectrum, type CieDaylightBasis } from \"../color/illuminants.js\";\nimport type { SceneRadianceEvaluationRequest, SceneRadianceEvaluationResult } from \"../schema/scene-radiance.js\";\nimport type { EvidenceProvenance } from \"../core/evidence-provenance.js\";\nimport type { SensorApertureRay } from \"../optics/sensor-aperture-rays.js\";\nimport { resolveChartMaterial, resolveChartScene, type ChartReflectance, type ChartScene, type ResolvedChartScene } from \"./chart-scenes.js\";\n\n/** CIE maximum luminous efficacy for photopic vision, lm/W. */\nexport const PHOTOPIC_MAXIMUM_LUMINOUS_EFFICACY_LM_PER_W = 683;\n/** Wavelength range of every facade spectrum and of the facade sensor quadrature, nm. */\nexport const FACADE_SPECTRAL_RANGE_NANOMETERS = Object.freeze({ minimum: 380, maximum: 780 });\n\n/**\n * Illuminant choices. CIE D65 is not bundled: its S0/S1/S2 basis tables must come from the caller\n * (`daylight`). `planckian` is Planck's law; `cie-a` is CIE illuminant A from its defining formula.\n */\nexport type CaptureIlluminant =\n | \"cie-a\"\n | { kind: \"planckian\"; temperatureKelvin: number }\n | { kind: \"cie-a\" }\n | { kind: \"daylight\"; correlatedColorTemperatureKelvin: number; basis: CieDaylightBasis }\n | { kind: \"spectrum\"; spectrum: ColorimetricSpectrum; label?: string };\n\nexport interface ResolvedCaptureIlluminant {\n /** Short public description, for example \"planckian-6500K\". */\n id: string;\n description: string;\n /** Relative spectral shape (arbitrary scale) over at least 380-780 nm. */\n shape: PreparedColorimetricSpectrum;\n /** Original spectrum, for colorimetric white-balance calculations. */\n spectrum: ColorimetricSpectrum;\n}\n\nexport function resolveCaptureIlluminant(value: CaptureIlluminant): ResolvedCaptureIlluminant {\n return resolveIlluminant(value, CAPTURE_SPECTRA);\n}\n/**\n * The spectrum constructors of the engine's own illuminant formulas: the capture's, or the portable ones (the display view).\n * They are passed in rather than chosen inside {@link resolveIlluminant}, so a bundle that only captures does not contain the\n * portable ones.\n */\ninterface IlluminantSpectra { planckian: typeof createPlanckianSpectrum; cieA: typeof createCieIlluminantASpectrum; daylight: typeof createCieDaylightSpectrum }\nconst CAPTURE_SPECTRA: IlluminantSpectra = { planckian: createPlanckianSpectrum, cieA: createCieIlluminantASpectrum, daylight: createCieDaylightSpectrum };\n/**\n * Internal (not exported from the package): {@link resolveCaptureIlluminant} with the engine's own formulas (Planckian,\n * CIE A, daylight locus) evaluated with the portable power and e^x − 1 (`portablePow`, `portableExpm1`), so the spectrum\n * has the same bits in every JavaScript engine. The display view uses it; captures keep {@link resolveCaptureIlluminant}.\n * A caller spectrum is the caller's own.\n */\nexport function resolvePortableCaptureIlluminant(value: CaptureIlluminant): ResolvedCaptureIlluminant {\n return resolveIlluminant(value, { planckian: createPortablePlanckianSpectrum, cieA: createPortableCieIlluminantASpectrum, daylight: createPortableCieDaylightSpectrum });\n}\nfunction resolveIlluminant(value: CaptureIlluminant, spectra: IlluminantSpectra): ResolvedCaptureIlluminant {\n if (value === \"cie-a\") return resolveIlluminant({ kind: \"cie-a\" }, spectra);\n requireInputObject(value, \"illuminant\");\n const record = value as unknown as Record<string, unknown>;\n const allowed: Record<string, readonly string[]> = { planckian: [\"kind\", \"temperatureKelvin\"], \"cie-a\": [\"kind\"],\n daylight: [\"kind\", \"correlatedColorTemperatureKelvin\", \"basis\"], spectrum: [\"kind\", \"spectrum\", \"label\"] };\n const keys = typeof record.kind === \"string\" ? allowed[record.kind] : undefined;\n if (!keys) throw new InvalidConfigurationError(\"Unknown illuminant kind.\");\n for (const key of Object.keys(record)) if (!keys.includes(key)) throw new InvalidConfigurationError(\"Unknown illuminant field: \" + key + \".\");\n let spectrum: ColorimetricSpectrum, id: string, description: string;\n try {\n switch (value.kind) {\n case \"planckian\": {\n const t = value.temperatureKelvin;\n if (typeof t !== \"number\" || !Number.isFinite(t) || t < 1000 || t > 25000) throw new InvalidConfigurationError(\"Planckian temperature must be 1000-25000 K.\");\n spectrum = spectra.planckian({ temperatureKelvin: t, wavelengthRangeNanometers: { ...FACADE_SPECTRAL_RANGE_NANOMETERS } });\n id = \"planckian-\" + t + \"K\"; description = \"Planck blackbody spectrum at \" + t + \" K (Planck's law).\";\n break;\n }\n case \"cie-a\":\n spectrum = spectra.cieA(); id = \"cie-a\"; description = \"CIE standard illuminant A from its defining formula: Planck's law with c2 = 1.435e-2 m·K and T = 2848 K, 100 at 560 nm.\";\n break;\n case \"daylight\":\n spectrum = spectra.daylight({ correlatedColorTemperatureKelvin: value.correlatedColorTemperatureKelvin, coefficientRounding: \"cie-three-decimals\", basis: value.basis });\n id = \"cie-daylight-\" + value.correlatedColorTemperatureKelvin + \"K\"; description = \"CIE daylight from the caller's S0/S1/S2 basis (\" + value.basis.datasetId + \").\";\n break;\n case \"spectrum\":\n spectrum = value.spectrum; id = \"caller-spectrum\";\n description = \"Caller illuminant spectrum\" + (typeof value.label === \"string\" ? \" (\" + value.label + \")\" : \"\") + \".\";\n break;\n }\n } catch (error) {\n if (error instanceof InvalidConfigurationError) throw error;\n throw new InvalidConfigurationError(\"Invalid illuminant: \" + (error instanceof Error ? error.message : \"invalid\"));\n }\n let shape: PreparedColorimetricSpectrum;\n try { shape = prepareColorimetricSpectrum(spectrum, \"illuminant\"); } catch (error) {\n throw new InvalidConfigurationError(\"Invalid illuminant spectrum: \" + (error instanceof Error ? error.message : \"invalid\"));\n }\n const range = shape.wavelengthRangeNanometers;\n if (range.minimum > FACADE_SPECTRAL_RANGE_NANOMETERS.minimum || range.maximum < FACADE_SPECTRAL_RANGE_NANOMETERS.maximum)\n throw new InvalidConfigurationError(\"The illuminant spectrum must cover 380-780 nm.\");\n for (let nm = FACADE_SPECTRAL_RANGE_NANOMETERS.minimum; nm <= FACADE_SPECTRAL_RANGE_NANOMETERS.maximum; nm += 1) {\n const s = shape.evaluate(nm);\n if (!(s >= 0)) throw new InvalidConfigurationError(\"The illuminant spectrum must be non-negative over 380-780 nm.\");\n }\n return Object.freeze({ id, description, shape, spectrum });\n}\n\n/**\n * Factor k such that k·S(λ) (W·m⁻²·nm⁻¹) gives `illuminanceLux` on the plane: E_v = 683 ∫ k S ȳ dλ,\n * integrated with the 1 nm trapezoid rule over 380-780 nm (ȳ outside this range is below 4e-5 of its peak).\n */\nexport function calculateIlluminantIrradianceScale(shape: PreparedColorimetricSpectrum, illuminanceLux: number): number {\n if (typeof shape !== \"object\" || shape === null || typeof shape.evaluate !== \"function\") throw new InvalidConfigurationError(\"A prepared illuminant spectrum is required.\");\n if (typeof illuminanceLux !== \"number\" || !Number.isFinite(illuminanceLux) || illuminanceLux <= 0 || illuminanceLux > 1e7)\n throw new InvalidConfigurationError(\"Illuminance must be a positive number of lux up to 1e7.\");\n let sum = 0;\n for (let nm = FACADE_SPECTRAL_RANGE_NANOMETERS.minimum; nm <= FACADE_SPECTRAL_RANGE_NANOMETERS.maximum; nm++) {\n const w = nm === FACADE_SPECTRAL_RANGE_NANOMETERS.minimum || nm === FACADE_SPECTRAL_RANGE_NANOMETERS.maximum ? 0.5 : 1;\n sum += w * shape.evaluate(nm) * estimateCie1931ColorMatchingFunctions(nm).y;\n }\n if (!(sum > 0)) throw new InvalidConfigurationError(\"The illuminant has no luminous power.\");\n return illuminanceLux / (PHOTOPIC_MAXIMUM_LUMINOUS_EFFICACY_LM_PER_W * sum);\n}\n\n/** A point of the scene plane passed to caller scene functions. */\nexport interface ScenePlanePoint {\n /** Metres on the plane, from the optical axis: +x right, +y up (as seen from the camera). */\n xM: number;\n yM: number;\n /** The same point in frame units (u = ±1 at the left/right frame edges, v up on the same scale). */\n u: number;\n v: number;\n wavelengthNanometers: number;\n /**\n * 2.3, only with a fixed-size chart (`chartSize`): the point in chart-local frame units (±1 at the chart's\n * left/right edges, v up on the same scale, ±chart height/width at its top/bottom). The function is then\n * called only for points on the chart; the surround is the placement's surround reflectance.\n */\n chartU?: number;\n chartV?: number;\n}\n/** Caller Lambertian reflectance (in [0, 1]) lit by the facade illuminant. */\nexport interface CallerReflectanceScene { kind: \"reflectance-function\"; sceneId: string; evaluate(point: Readonly<ScenePlanePoint>): number }\n/** Caller absolute spectral radiance in W·m⁻²·sr⁻¹·nm⁻¹; the facade illuminant is not used. */\nexport interface CallerRadianceScene { kind: \"radiance-function\"; sceneId: string; evaluate(point: Readonly<ScenePlanePoint>): number }\n/** 2.7: a scene-plane point without a wavelength, passed to a material scene's `materialAt`. */\nexport type SceneMaterialPoint = Omit<ScenePlanePoint, \"wavelengthNanometers\">;\n/**\n * 2.7 (#386): a piecewise-constant caller scene, lit by the facade illuminant like a reflectance function. `materials` are\n * reflectances as a chart's patches take them (a neutral number in [0, 1] or a reflectance spectrum covering 380–780 nm, at\n * most {@link CALLER_MATERIAL_SCENE_MAX_MATERIALS}); `materialAt` returns the index of the material at a plane point (an\n * integer from 0 to materials.length − 1). The radiance at a point is that material's, exactly as for a reflectance function\n * returning its reflectance, but renderers can tabulate each material once: the display view then takes the chart path.\n */\nexport interface CallerMaterialScene {\n kind: \"material-function\";\n sceneId: string;\n materials: readonly ChartReflectance[];\n materialAt(point: Readonly<SceneMaterialPoint>): number;\n}\n/** Most materials a {@link CallerMaterialScene} may list. */\nexport const CALLER_MATERIAL_SCENE_MAX_MATERIALS = 65_536;\n/** Internal: a validated material scene with its materials prepared (and the caller inputs, for the scene digest). */\nexport interface ResolvedCallerMaterialScene {\n kind: \"material-function\";\n sceneId: string;\n materials: ResolvedChartScene[\"materials\"];\n materialInputs: readonly unknown[];\n materialAt(point: Readonly<SceneMaterialPoint>): number;\n}\n/** Internal: a validated caller scene. */\nexport type ResolvedCallerScene = CallerReflectanceScene | CallerRadianceScene | ResolvedCallerMaterialScene;\n\nexport interface PlanarSceneGeometry {\n distanceM: number;\n /** Metres per frame unit on the plane (half the framed width). */\n metresPerFrameUnit: number;\n /**\n * 2.3, opt-in fixed-size chart: the chart is `widthM` × `heightM` on the plane, centred on the optical axis;\n * outside it the plane is a neutral Lambertian surround of `surroundReflectance`, lit by the same illuminant.\n * A chart preset is then resolved in its own frame (aspect heightM / widthM). Without it the chart fills the frame.\n */\n chart?: { widthM: number; heightM: number; surroundReflectance: number };\n}\n\nexport interface PlanarSceneRadianceProvider {\n sceneId: string;\n providerProfileId: string;\n evaluateRadiance(request: Readonly<SceneRadianceEvaluationRequest>): SceneRadianceEvaluationResult;\n evaluateApertureRadiance(request: Readonly<SceneRadianceEvaluationRequest>, ray: Readonly<SensorApertureRay>): SceneRadianceEvaluationResult;\n /** Spectral radiance at a plane point (frame units), the same value the callbacks return. */\n radianceAt(u: number, v: number, wavelengthNanometers: number): number;\n /**\n * 2.3, chart scenes only: the chart material at a plane point (frame units), or `materials.length` for the\n * surround of a fixed-size chart; `materialRadiance` gives that material's spectral radiance, the same value\n * `radianceAt` returns at its points.\n */\n chartMaterialAt?(u: number, v: number): number;\n materialRadiance?(material: number, wavelengthNanometers: number): number;\n}\n\n/**\n * Internal (#394, not exported from the package): per provider of a chart preset or caller material scene, the material its\n * `evaluateRadiance` reads for an environment-direction query with a given outgoing direction (the same plane-point\n * arithmetic), or undefined where `evaluateRadiance` would throw. Its radiance is `materialRadiance(material, wavelength)`.\n */\nconst MATERIAL_OF_DIRECTION = new WeakMap<PlanarSceneRadianceProvider, (direction: Readonly<{ x: number; y: number; z: number }>) => number | undefined>();\n\n/** Internal (#394): the material lookup of a provider built by {@link buildPlanarSceneRadianceProvider}, if it has one. */\nexport function planarProviderMaterialOfDirection(provider: PlanarSceneRadianceProvider):\n ((direction: Readonly<{ x: number; y: number; z: number }>) => number | undefined) | undefined {\n return MATERIAL_OF_DIRECTION.get(provider);\n}\n\nconst UNCERTAINTY = Object.freeze({ kind: \"not-quantified\" as const, limitation: \"Analytic planar Lambertian scene; no measured scene, BRDF or illumination.\" });\n\n/** Most distinct wavelengths {@link tabulatedSpectrum} keeps; later ones are evaluated on every call. */\nconst TABULATED_SPECTRUM_MAX_ENTRIES = 4096;\n\n/**\n * Internal (#385): `spectrum.evaluate` remembered per distinct wavelength. A prepared spectrum is a pure function of the\n * wavelength, so the table returns the same double the call would; renderers ask for the same few spectral nodes millions\n * of times, and the illuminant's formula (two transcendental evaluations) was about 30 % of a caller-scene display view.\n */\nexport function tabulatedSpectrum(spectrum: Readonly<PreparedColorimetricSpectrum>): (wavelengthNanometers: number) => number {\n const table = new Map<number, number>();\n return (nm) => {\n let value = table.get(nm);\n if (value === undefined) {\n value = spectrum.evaluate(nm);\n if (table.size < TABULATED_SPECTRUM_MAX_ENTRIES) table.set(nm, value);\n }\n return value;\n };\n}\n\n/**\n * Wraps a chart or caller scene as a provider for the native environment RAW task. `irradianceScale` is\n * from {@link calculateIlluminantIrradianceScale}; caller radiance scenes ignore the illuminant.\n */\nexport function buildPlanarSceneRadianceProvider(input: {\n scene: ResolvedChartScene | ResolvedCallerScene;\n sceneId: string;\n providerProfileId: string;\n illuminant: ResolvedCaptureIlluminant;\n irradianceScale: number;\n geometry: PlanarSceneGeometry;\n evidence: readonly EvidenceProvenance[];\n limitations: readonly string[];\n}): PlanarSceneRadianceProvider {\n const { scene, illuminant, irradianceScale, geometry } = input;\n const scale = geometry.metresPerFrameUnit, distance = geometry.distanceM, sceneId = input.sceneId, providerProfileId = input.providerProfileId;\n const evidence = input.evidence, limitations = input.limitations;\n const caller = \"kind\" in scene ? scene : undefined, chart = caller ? undefined : scene as ResolvedChartScene;\n const materialScene = caller?.kind === \"material-function\" ? caller : undefined, materials = chart ? chart.materials : materialScene?.materials;\n const placed = geometry.chart, half = placed ? placed.widthM / 2 : 0, chartAspect = placed ? placed.heightM / placed.widthM : 0;\n const shapeAt = tabulatedSpectrum(illuminant.shape);\n /** A material scene's material at a frame point: the caller's index, or `materials.length` for a fixed-size chart's surround. */\n function callerMaterialAt(u: number, v: number): number {\n const xM = u * scale, yM = v * scale;\n let point: SceneMaterialPoint;\n if (placed) {\n const cu = xM / half, cv = yM / half;\n if (!(Math.abs(cu) <= 1 && Math.abs(cv) <= chartAspect)) return materialScene!.materials.length;\n point = Object.freeze({ xM, yM, u, v, chartU: cu, chartV: cv });\n } else point = Object.freeze({ xM, yM, u, v });\n const index = materialScene!.materialAt(point);\n if (!Number.isInteger(index) || index < 0 || index >= materialScene!.materials.length) throw new InvalidConfigurationError(\"Scene materialAt must return an index into its materials.\");\n return index;\n }\n function radianceAt(u: number, v: number, nm: number): number {\n if (materialScene) return materialRadianceOf(callerMaterialAt(u, v), nm);\n if (placed) {\n // Fixed-size chart (2.3): chart-local frame units from the plane point in metres.\n const xM = u * scale, yM = v * scale, cu = xM / half, cv = yM / half;\n if (!(Math.abs(cu) <= 1 && Math.abs(cv) <= chartAspect)) return placed.surroundReflectance * irradianceScale * shapeAt(nm) / Math.PI;\n if (chart) return chart.reflectanceAt(cu, cv, nm) * irradianceScale * shapeAt(nm) / Math.PI;\n return callerValue(Object.freeze({ xM, yM, u, v, wavelengthNanometers: nm, chartU: cu, chartV: cv }), nm);\n }\n if (chart) return chart.reflectanceAt(u, v, nm) * irradianceScale * shapeAt(nm) / Math.PI;\n return callerValue(Object.freeze({ xM: u * scale, yM: v * scale, u, v, wavelengthNanometers: nm }), nm);\n }\n function callerValue(point: Readonly<ScenePlanePoint>, nm: number): number {\n const value = (caller as CallerReflectanceScene | CallerRadianceScene).evaluate(point);\n if (caller!.kind === \"reflectance-function\") {\n if (typeof value !== \"number\" || !Number.isFinite(value) || value < 0 || value > 1) throw new InvalidConfigurationError(\"Scene reflectance function must return a value in [0, 1].\");\n return value * irradianceScale * shapeAt(nm) / Math.PI;\n }\n if (typeof value !== \"number\" || !Number.isFinite(value) || value < 0) throw new InvalidConfigurationError(\"Scene radiance function must return a finite non-negative radiance.\");\n return value;\n }\n function result(request: Readonly<SceneRadianceEvaluationRequest>, radiance: number): SceneRadianceEvaluationResult {\n return { schemaVersion: \"0.1.0\", sampleId: request.sampleId, sceneId, providerProfileId, wavelengthNanometers: request.wavelengthNanometers,\n wavelengthBasis: request.wavelengthBasis as SceneRadianceEvaluationResult[\"wavelengthBasis\"], quantity: \"outgoing-spectral-radiance\", unit: \"W/m^2/sr/nm\",\n spectralRadianceWattsPerSquareMeterSteradianNanometer: radiance, scientificStatus: \"approximation\", uncertainty: UNCERTAINTY, evidence, limitations };\n }\n /** Spectral radiance of material `material` (`materials.length`: a fixed-size chart's surround), in the chart's expression order. */\n function materialRadianceOf(material: number, nm: number): number {\n const m = materials![material];\n let value: number;\n if (m === undefined) value = placed ? placed.surroundReflectance : NaN;\n else if (m.kind === \"neutral\") value = m.reflectance;\n else {\n value = m.spectrum.evaluate(nm);\n if (!(value >= 0 && value <= 1)) throw new InvalidConfigurationError(\"Chart reflectance spectrum left [0, 1].\");\n }\n if (!(value >= 0)) throw new InvalidConfigurationError(\"Unknown chart material.\");\n return value * irradianceScale * shapeAt(nm) / Math.PI;\n }\n function chartMaterialAt(u: number, v: number): number {\n if (!placed) return chart!.materialAt(u, v);\n const cu = u * scale / half, cv = v * scale / half;\n return Math.abs(cu) <= 1 && Math.abs(cv) <= chartAspect ? chart!.materialAt(cu, cv) : chart!.materials.length;\n }\n const chartAccess = chart ? { chartMaterialAt, materialRadiance: materialRadianceOf } :\n materialScene ? { chartMaterialAt: callerMaterialAt, materialRadiance: materialRadianceOf } : {};\n // #394: evaluateRadiance's own plane-point arithmetic; radianceAt is then materialRadianceOf(material, nm) for both scene forms.\n const materialAtPoint = chart ? chartMaterialAt : materialScene ? callerMaterialAt : undefined;\n const materialOfDirection = materialAtPoint === undefined ? undefined : (o: Readonly<{ x: number; y: number; z: number }>): number | undefined => {\n const lz = -o.z;\n if (!(lz > 0)) return undefined;\n const t = distance / lz;\n return materialAtPoint(-o.x * t / scale, -o.y * t / scale);\n };\n const provider: PlanarSceneRadianceProvider = {\n sceneId, providerProfileId, radianceAt, ...chartAccess,\n evaluateRadiance(request): SceneRadianceEvaluationResult {\n const target = request.target;\n if (target.kind !== \"environment-direction\") throw new InvalidConfigurationError(\"Planar scene provider needs environment-direction queries.\");\n const o = target.outgoingDirectionUnitVector, lz = -o.z;\n if (!(lz > 0)) throw new InvalidConfigurationError(\"Planar scene query does not point toward the scene plane.\");\n const t = distance / lz;\n return result(request, radianceAt(-o.x * t / scale, -o.y * t / scale, request.wavelengthNanometers));\n },\n evaluateApertureRadiance(request, ray): SceneRadianceEvaluationResult {\n const d = ray.directionUnitVector, origin = ray.originM;\n if (!(d.z > 0)) throw new InvalidConfigurationError(\"Planar scene pupil ray does not point toward the scene plane.\");\n const t = (distance - origin.z) / d.z;\n return result(request, radianceAt((origin.x + d.x * t) / scale, (origin.y + d.y * t) / scale, request.wavelengthNanometers));\n }\n };\n if (materialOfDirection) MATERIAL_OF_DIRECTION.set(provider, materialOfDirection);\n return provider;\n}\n\n/** 2.3: a chart's physical size on the scene plane (`simulateCapture` `chartSize`, `createPlanarSceneRadianceProvider` `chartSize`). */\nexport interface ChartSizeOption {\n /** Chart width in metres, (0, 10 000]. */\n widthM: number;\n /** Chart height in metres. Default: widthM × the frame aspect (height / width), so the chart has the frame's shape. */\n heightM?: number;\n /** Neutral reflectance of the plane around the chart, lit by the same illuminant. Default 0.18. */\n surroundReflectance?: number;\n}\n/** Default surround of a fixed-size chart: an 18 % grey plane. */\nexport const CHART_SIZE_DEFAULT_SURROUND_REFLECTANCE = 0.18;\n/** Internal: validates a chart size and fills its defaults; `defaulted` names the fields taken from defaults. */\nexport function resolveChartSizeOption(value: unknown, frameAspect: number): { widthM: number; heightM: number; surroundReflectance: number; defaulted: (\"heightM\" | \"surroundReflectance\")[] } {\n requireInputObject(value, \"chartSize\");\n const record = value as Record<string, unknown>;\n for (const key of Object.keys(record)) if (![\"widthM\", \"heightM\", \"surroundReflectance\"].includes(key)) throw new InvalidConfigurationError(\"Unknown chartSize field: \" + key + \".\");\n const size = (x: unknown, name: string): number => {\n if (typeof x !== \"number\" || !Number.isFinite(x) || x <= 0 || x > 10_000) throw new InvalidConfigurationError(\"chartSize.\" + name + \" must be a positive number of metres up to 10000.\");\n return x;\n };\n const defaulted: (\"heightM\" | \"surroundReflectance\")[] = [];\n const widthM = size(record.widthM, \"widthM\");\n const heightM = record.heightM === undefined ? (defaulted.push(\"heightM\"), widthM * frameAspect) : size(record.heightM, \"heightM\");\n const surround = record.surroundReflectance === undefined ? (defaulted.push(\"surroundReflectance\"), CHART_SIZE_DEFAULT_SURROUND_REFLECTANCE) : record.surroundReflectance;\n if (typeof surround !== \"number\" || !Number.isFinite(surround) || surround < 0 || surround > 1) throw new InvalidConfigurationError(\"chartSize.surroundReflectance must be a reflectance in [0, 1].\");\n return { widthM, heightM, surroundReflectance: surround, defaulted };\n}\n\n/**\n * Public scene-preset provider. Places an engine chart (or a caller reflectance or radiance function) on\n * a plane `distanceM` in front of the camera and `framedWidthM` wide (frame units u = ±1 at its edges),\n * lit by `illuminant` at `illuminanceLux`. The returned `evaluateRadiance` and `evaluateApertureRadiance`\n * follow the native environment RAW provider contract. They answer requests for scene `sceneId` and\n * provider `providerProfileId`.\n */\nexport function createPlanarSceneRadianceProvider(input: {\n scene: ChartScene | CallerReflectanceScene | CallerRadianceScene | CallerMaterialScene;\n illuminant: CaptureIlluminant;\n illuminanceLux: number;\n distanceM: number;\n framedWidthM: number;\n /** Frame height / width. */\n aspect: number;\n sceneId: string;\n providerProfileId: string;\n /**\n * 2.3, opt-in: place the chart at this physical size, centred, instead of filling the frame; the chart preset\n * is resolved with aspect heightM / widthM and the rest of the plane is the surround.\n */\n chartSize?: ChartSizeOption;\n}): PlanarSceneRadianceProvider & { chart: ResolvedChartScene | null } {\n requireInputObject(input, \"createPlanarSceneRadianceProvider input\");\n const keys = [\"scene\", \"illuminant\", \"illuminanceLux\", \"distanceM\", \"framedWidthM\", \"aspect\", \"sceneId\", \"providerProfileId\", \"chartSize\"];\n for (const key of Object.keys(input)) if (!keys.includes(key)) throw new InvalidConfigurationError(\"createPlanarSceneRadianceProvider input has unknown field \\\"\" + key + \"\\\".\");\n for (const key of [\"illuminanceLux\", \"distanceM\", \"framedWidthM\", \"aspect\"] as const) {\n const value = input[key];\n if (typeof value !== \"number\" || !Number.isFinite(value) || value <= 0) throw new InvalidConfigurationError(key + \" must be a positive finite number.\");\n }\n for (const key of [\"sceneId\", \"providerProfileId\"] as const) if (typeof input[key] !== \"string\" || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(input[key])) throw new InvalidConfigurationError(key + \" must be a public opaque ID.\");\n requireInputObject(input.scene, \"scene\");\n const caller = \"kind\" in input.scene ? requireCallerScene(input.scene) : undefined;\n const size = input.chartSize === undefined ? undefined : resolveChartSizeOption(input.chartSize, input.aspect);\n const chart = caller ? null : resolveChartScene({ scene: input.scene as ChartScene, aspect: size ? size.heightM / size.widthM : input.aspect });\n const illuminant = resolveCaptureIlluminant(input.illuminant);\n const provider = buildPlanarSceneRadianceProvider({ scene: chart ?? caller!, sceneId: input.sceneId, providerProfileId: input.providerProfileId, illuminant,\n irradianceScale: calculateIlluminantIrradianceScale(illuminant.shape, input.illuminanceLux),\n geometry: { distanceM: input.distanceM, metresPerFrameUnit: input.framedWidthM / 2,\n ...(size ? { chart: { widthM: size.widthM, heightM: size.heightM, surroundReflectance: size.surroundReflectance } } : {}) },\n evidence: [{ sourceOrigin: \"photivra\", sourceReference: \"photivra:planar-scene-provider\", reuseStatus: \"photivra-owned\" }],\n limitations: [\"Planar Lambertian scene under uniform illumination; no shadows, inter-reflection, gloss or fluorescence.\"] });\n return { ...provider, chart };\n}\n\n/** Validates a caller scene record (a function scene as given; a material scene with its materials prepared). */\nexport function requireCallerScene(value: unknown): ResolvedCallerScene {\n requireInputObject(value, \"scene\");\n const record = value as Record<string, unknown>;\n if (record.kind === \"material-function\") {\n for (const key of Object.keys(record)) if (key !== \"kind\" && key !== \"sceneId\" && key !== \"materials\" && key !== \"materialAt\") throw new InvalidConfigurationError(\"Unknown scene field: \" + key + \".\");\n if (typeof record.materialAt !== \"function\" || typeof record.sceneId !== \"string\" || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/.test(record.sceneId) ||\n !Array.isArray(record.materials) || record.materials.length < 1 || record.materials.length > CALLER_MATERIAL_SCENE_MAX_MATERIALS)\n throw new InvalidConfigurationError(\"A material scene needs a public sceneId, 1 to \" + CALLER_MATERIAL_SCENE_MAX_MATERIALS + \" materials and a materialAt function.\");\n const inputs = [...record.materials as unknown[]];\n return Object.freeze({ kind: \"material-function\" as const, sceneId: record.sceneId, materialAt: record.materialAt as ResolvedCallerMaterialScene[\"materialAt\"],\n materials: Object.freeze(inputs.map((m, index) => resolveChartMaterial(m, \"scene.materials[\" + index + \"]\"))),\n materialInputs: Object.freeze(inputs.map((m) => (typeof m === \"number\" ? undefined : m))) });\n }\n for (const key of Object.keys(record)) if (key !== \"kind\" && key !== \"sceneId\" && key !== \"evaluate\") throw new InvalidConfigurationError(\"Unknown scene field: \" + key + \".\");\n if ((record.kind !== \"reflectance-function\" && record.kind !== \"radiance-function\") || typeof record.evaluate !== \"function\" ||\n typeof record.sceneId !== \"string\" || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/.test(record.sceneId)) throw new InvalidConfigurationError(\"A caller scene needs kind, a public sceneId and an evaluate function.\");\n return record as unknown as CallerReflectanceScene | CallerRadianceScene;\n}\n"]}
1
+ {"version":3,"file":"scene-radiance.js","sourceRoot":"","sources":["../../src/facade/scene-radiance.ts"],"names":[],"mappings":"AAAA,sCAAsC;AAEtC;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAC3E,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EAAE,qCAAqC,EAAE,2BAA2B,EACtC,MAAM,sCAAsC,CAAC;AAClF,OAAO,EAAE,4BAA4B,EAAE,yBAAyB,EAAE,uBAAuB,EAAE,iCAAiC,EAAE,oCAA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AC,CAAC,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,KAAK,QAAQ,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;IACjG,CAAC;IACD,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC;QAAE,IAAI,GAAG,KAAK,MAAM,IAAI,GAAG,KAAK,SAAS,IAAI,GAAG,KAAK,UAAU;YAAE,MAAM,IAAI,yBAAyB,CAAC,uBAAuB,GAAG,GAAG,GAAG,GAAG,CAAC,CAAC;IAC/K,IAAI,CAAC,MAAM,CAAC,IAAI,KAAK,sBAAsB,IAAI,MAAM,CAAC,IAAI,KAAK,mBAAmB,CAAC,IAAI,OAAO,MAAM,CAAC,QAAQ,KAAK,UAAU;QAC1H,OAAO,MAAM,CAAC,OAAO,KAAK,QAAQ,IAAI,CAAC,oCAAoC,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC;QAAE,MAAM,IAAI,yBAAyB,CAAC,uEAAuE,CAAC,CAAC;IACjN,OAAO,MAAiE,CAAC;AAC3E,CAAC","sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Turns a facade scene and an illuminant into a scene radiance provider for the existing native\n * environment RAW contract (`NativeEnvironmentRawProvider.evaluateRadiance` and, for pupil sampling,\n * `evaluateApertureRadiance`). The scene is an engine chart, a caller reflectance function or a caller\n * radiance function.\n *\n * Geometry: one plane perpendicular to the optical axis at `distanceM` in front of the camera. A query's\n * outgoing direction o (scene toward camera, see docs/SENSOR_ENVIRONMENT_QUERY.md) gives the look\n * direction l = -o; the plane point is l·distanceM/l.z. With a pupil ray, the plane point is the ray from\n * its lens origin to z = distanceM.\n *\n * Radiometry: a Lambertian reflector of reflectance ρ(λ) under irradiance E(λ) has radiance\n * L(λ) = ρ(λ)·E(λ)/π (W·m⁻²·sr⁻¹·nm⁻¹). The illuminant spectral shape S(λ) is scaled so that the\n * plane illuminance is E_v = K_m ∫ E(λ) V(λ) dλ with K_m = 683 lm/W (CIE photometric definition) and\n * V(λ) = ȳ(λ) from the engine's analytic CIE 1931 fit. The light is uniform\n * over the plane, with no shadows. Inter-reflection, gloss and fluorescence are not modelled.\n * @see docs/QUICK_START.md\n */\n\nimport { InvalidConfigurationError } from \"../core/configuration-error.js\";\nimport { requireInputObject } from \"../core/record-validation.js\";\nimport { estimateCie1931ColorMatchingFunctions, prepareColorimetricSpectrum, type ColorimetricSpectrum,\n type PreparedColorimetricSpectrum } from \"../color/color-matching-functions.js\";\nimport { createCieIlluminantASpectrum, createCieDaylightSpectrum, createPlanckianSpectrum, createPortableCieDaylightSpectrum, createPortableCieIlluminantASpectrum,\n createPortablePlanckianSpectrum, type CieDaylightBasis } from \"../color/illuminants.js\";\nimport type { SceneRadianceEvaluationRequest, SceneRadianceEvaluationResult } from \"../schema/scene-radiance.js\";\nimport type { EvidenceProvenance } from \"../core/evidence-provenance.js\";\nimport type { SensorApertureRay } from \"../optics/sensor-aperture-rays.js\";\nimport { resolveChartMaterial, resolveChartScene, type ChartReflectance, type ChartScene, type ResolvedChartScene } from \"./chart-scenes.js\";\n\n/** CIE maximum luminous efficacy for photopic vision, lm/W. */\nexport const PHOTOPIC_MAXIMUM_LUMINOUS_EFFICACY_LM_PER_W = 683;\n/** Wavelength range of every facade spectrum and of the facade sensor quadrature, nm. */\nexport const FACADE_SPECTRAL_RANGE_NANOMETERS = Object.freeze({ minimum: 380, maximum: 780 });\n\n/**\n * Illuminant choices. CIE D65 is not bundled: its S0/S1/S2 basis tables must come from the caller\n * (`daylight`). `planckian` is Planck's law; `cie-a` is CIE illuminant A from its defining formula.\n */\nexport type CaptureIlluminant =\n | \"cie-a\"\n | { kind: \"planckian\"; temperatureKelvin: number }\n | { kind: \"cie-a\" }\n | { kind: \"daylight\"; correlatedColorTemperatureKelvin: number; basis: CieDaylightBasis }\n | { kind: \"spectrum\"; spectrum: ColorimetricSpectrum; label?: string };\n\nexport interface ResolvedCaptureIlluminant {\n /** Short public description, for example \"planckian-6500K\". */\n id: string;\n description: string;\n /** Relative spectral shape (arbitrary scale) over at least 380-780 nm. */\n shape: PreparedColorimetricSpectrum;\n /** Original spectrum, for colorimetric white-balance calculations. */\n spectrum: ColorimetricSpectrum;\n}\n\nexport function resolveCaptureIlluminant(value: CaptureIlluminant): ResolvedCaptureIlluminant {\n return resolveIlluminant(value, CAPTURE_SPECTRA);\n}\n/**\n * The spectrum constructors of the engine's own illuminant formulas: the capture's, or the portable ones (the display view).\n * They are passed in rather than chosen inside {@link resolveIlluminant}, so a bundle that only captures does not contain the\n * portable ones.\n */\ninterface IlluminantSpectra { planckian: typeof createPlanckianSpectrum; cieA: typeof createCieIlluminantASpectrum; daylight: typeof createCieDaylightSpectrum }\nconst CAPTURE_SPECTRA: IlluminantSpectra = { planckian: createPlanckianSpectrum, cieA: createCieIlluminantASpectrum, daylight: createCieDaylightSpectrum };\n/**\n * Internal (not exported from the package): {@link resolveCaptureIlluminant} with the engine's own formulas (Planckian,\n * CIE A, daylight locus) evaluated with the portable power and e^x − 1 (`portablePow`, `portableExpm1`), so the spectrum\n * has the same bits in every JavaScript engine. The display view uses it; captures keep {@link resolveCaptureIlluminant}.\n * A caller spectrum is the caller's own.\n */\nexport function resolvePortableCaptureIlluminant(value: CaptureIlluminant): ResolvedCaptureIlluminant {\n return resolveIlluminant(value, { planckian: createPortablePlanckianSpectrum, cieA: createPortableCieIlluminantASpectrum, daylight: createPortableCieDaylightSpectrum });\n}\nfunction resolveIlluminant(value: CaptureIlluminant, spectra: IlluminantSpectra): ResolvedCaptureIlluminant {\n if (value === \"cie-a\") return resolveIlluminant({ kind: \"cie-a\" }, spectra);\n requireInputObject(value, \"illuminant\");\n const record = value as unknown as Record<string, unknown>;\n const allowed: Record<string, readonly string[]> = { planckian: [\"kind\", \"temperatureKelvin\"], \"cie-a\": [\"kind\"],\n daylight: [\"kind\", \"correlatedColorTemperatureKelvin\", \"basis\"], spectrum: [\"kind\", \"spectrum\", \"label\"] };\n const keys = typeof record.kind === \"string\" ? allowed[record.kind] : undefined;\n if (!keys) throw new InvalidConfigurationError(\"Unknown illuminant kind.\");\n for (const key of Object.keys(record)) if (!keys.includes(key)) throw new InvalidConfigurationError(\"Unknown illuminant field: \" + key + \".\");\n let spectrum: ColorimetricSpectrum, id: string, description: string;\n try {\n switch (value.kind) {\n case \"planckian\": {\n const t = value.temperatureKelvin;\n if (typeof t !== \"number\" || !Number.isFinite(t) || t < 1000 || t > 25000) throw new InvalidConfigurationError(\"Planckian temperature must be 1000-25000 K.\");\n spectrum = spectra.planckian({ temperatureKelvin: t, wavelengthRangeNanometers: { ...FACADE_SPECTRAL_RANGE_NANOMETERS } });\n id = \"planckian-\" + t + \"K\"; description = \"Planck blackbody spectrum at \" + t + \" K (Planck's law).\";\n break;\n }\n case \"cie-a\":\n spectrum = spectra.cieA(); id = \"cie-a\"; description = \"CIE standard illuminant A from its defining formula: Planck's law with c2 = 1.435e-2 m·K and T = 2848 K, 100 at 560 nm.\";\n break;\n case \"daylight\":\n spectrum = spectra.daylight({ correlatedColorTemperatureKelvin: value.correlatedColorTemperatureKelvin, coefficientRounding: \"cie-three-decimals\", basis: value.basis });\n id = \"cie-daylight-\" + value.correlatedColorTemperatureKelvin + \"K\"; description = \"CIE daylight from the caller's S0/S1/S2 basis (\" + value.basis.datasetId + \").\";\n break;\n case \"spectrum\":\n spectrum = value.spectrum; id = \"caller-spectrum\";\n description = \"Caller illuminant spectrum\" + (typeof value.label === \"string\" ? \" (\" + value.label + \")\" : \"\") + \".\";\n break;\n }\n } catch (error) {\n if (error instanceof InvalidConfigurationError) throw error;\n throw new InvalidConfigurationError(\"Invalid illuminant: \" + (error instanceof Error ? error.message : \"invalid\"));\n }\n let shape: PreparedColorimetricSpectrum;\n try { shape = prepareColorimetricSpectrum(spectrum, \"illuminant\"); } catch (error) {\n throw new InvalidConfigurationError(\"Invalid illuminant spectrum: \" + (error instanceof Error ? error.message : \"invalid\"));\n }\n const range = shape.wavelengthRangeNanometers;\n if (range.minimum > FACADE_SPECTRAL_RANGE_NANOMETERS.minimum || range.maximum < FACADE_SPECTRAL_RANGE_NANOMETERS.maximum)\n throw new InvalidConfigurationError(\"The illuminant spectrum must cover 380-780 nm.\");\n for (let nm = FACADE_SPECTRAL_RANGE_NANOMETERS.minimum; nm <= FACADE_SPECTRAL_RANGE_NANOMETERS.maximum; nm += 1) {\n const s = shape.evaluate(nm);\n if (!(s >= 0)) throw new InvalidConfigurationError(\"The illuminant spectrum must be non-negative over 380-780 nm.\");\n }\n return Object.freeze({ id, description, shape, spectrum });\n}\n\n/**\n * Factor k such that k·S(λ) (W·m⁻²·nm⁻¹) gives `illuminanceLux` on the plane: E_v = 683 ∫ k S ȳ dλ,\n * integrated with the 1 nm trapezoid rule over 380-780 nm (ȳ outside this range is below 4e-5 of its peak).\n */\nexport function calculateIlluminantIrradianceScale(shape: PreparedColorimetricSpectrum, illuminanceLux: number): number {\n if (typeof shape !== \"object\" || shape === null || typeof shape.evaluate !== \"function\") throw new InvalidConfigurationError(\"A prepared illuminant spectrum is required.\");\n if (typeof illuminanceLux !== \"number\" || !Number.isFinite(illuminanceLux) || illuminanceLux <= 0 || illuminanceLux > 1e7)\n throw new InvalidConfigurationError(\"Illuminance must be a positive number of lux up to 1e7.\");\n let sum = 0;\n for (let nm = FACADE_SPECTRAL_RANGE_NANOMETERS.minimum; nm <= FACADE_SPECTRAL_RANGE_NANOMETERS.maximum; nm++) {\n const w = nm === FACADE_SPECTRAL_RANGE_NANOMETERS.minimum || nm === FACADE_SPECTRAL_RANGE_NANOMETERS.maximum ? 0.5 : 1;\n sum += w * shape.evaluate(nm) * estimateCie1931ColorMatchingFunctions(nm).y;\n }\n if (!(sum > 0)) throw new InvalidConfigurationError(\"The illuminant has no luminous power.\");\n return illuminanceLux / (PHOTOPIC_MAXIMUM_LUMINOUS_EFFICACY_LM_PER_W * sum);\n}\n\n/**\n * A point of the scene plane passed to caller scene functions: a new object for every call, which the engine does not read\n * after the call (not frozen: freezing cost about 40 % of a chart lookup).\n */\nexport interface ScenePlanePoint {\n /** Metres on the plane, from the optical axis: +x right, +y up (as seen from the camera). */\n xM: number;\n yM: number;\n /** The same point in frame units (u = ±1 at the left/right frame edges, v up on the same scale). */\n u: number;\n v: number;\n wavelengthNanometers: number;\n /**\n * 2.3, only with a fixed-size chart (`chartSize`): the point in chart-local frame units (±1 at the chart's\n * left/right edges, v up on the same scale, ±chart height/width at its top/bottom). The function is then\n * called only for points on the chart; the surround is the placement's surround reflectance.\n */\n chartU?: number;\n chartV?: number;\n}\n/** Caller Lambertian reflectance (in [0, 1]) lit by the facade illuminant. */\nexport interface CallerReflectanceScene { kind: \"reflectance-function\"; sceneId: string; evaluate(point: Readonly<ScenePlanePoint>): number }\n/** Caller absolute spectral radiance in W·m⁻²·sr⁻¹·nm⁻¹; the facade illuminant is not used. */\nexport interface CallerRadianceScene { kind: \"radiance-function\"; sceneId: string; evaluate(point: Readonly<ScenePlanePoint>): number }\n/** 2.7: a scene-plane point without a wavelength, passed to a material scene's `materialAt`. */\nexport type SceneMaterialPoint = Omit<ScenePlanePoint, \"wavelengthNanometers\">;\n/**\n * 2.7 (#386): a piecewise-constant caller scene, lit by the facade illuminant like a reflectance function. `materials` are\n * reflectances as a chart's patches take them (a neutral number in [0, 1] or a reflectance spectrum covering 380–780 nm, at\n * most {@link CALLER_MATERIAL_SCENE_MAX_MATERIALS}); `materialAt` returns the index of the material at a plane point (an\n * integer from 0 to materials.length − 1). The radiance at a point is that material's, exactly as for a reflectance function\n * returning its reflectance, but renderers can tabulate each material once: the display view then takes the chart path.\n */\nexport interface CallerMaterialScene {\n kind: \"material-function\";\n sceneId: string;\n materials: readonly ChartReflectance[];\n materialAt(point: Readonly<SceneMaterialPoint>): number;\n}\n/** Most materials a {@link CallerMaterialScene} may list. */\nexport const CALLER_MATERIAL_SCENE_MAX_MATERIALS = 65_536;\n/** Internal: a validated material scene with its materials prepared (and the caller inputs, for the scene digest). */\nexport interface ResolvedCallerMaterialScene {\n kind: \"material-function\";\n sceneId: string;\n materials: ResolvedChartScene[\"materials\"];\n materialInputs: readonly unknown[];\n materialAt(point: Readonly<SceneMaterialPoint>): number;\n}\n/** Internal: a validated caller scene. */\nexport type ResolvedCallerScene = CallerReflectanceScene | CallerRadianceScene | ResolvedCallerMaterialScene;\n\nexport interface PlanarSceneGeometry {\n distanceM: number;\n /** Metres per frame unit on the plane (half the framed width). */\n metresPerFrameUnit: number;\n /**\n * 2.3, opt-in fixed-size chart: the chart is `widthM` × `heightM` on the plane, centred on the optical axis;\n * outside it the plane is a neutral Lambertian surround of `surroundReflectance`, lit by the same illuminant.\n * A chart preset is then resolved in its own frame (aspect heightM / widthM). Without it the chart fills the frame.\n */\n chart?: { widthM: number; heightM: number; surroundReflectance: number };\n}\n\nexport interface PlanarSceneRadianceProvider {\n sceneId: string;\n providerProfileId: string;\n evaluateRadiance(request: Readonly<SceneRadianceEvaluationRequest>): SceneRadianceEvaluationResult;\n evaluateApertureRadiance(request: Readonly<SceneRadianceEvaluationRequest>, ray: Readonly<SensorApertureRay>): SceneRadianceEvaluationResult;\n /** Spectral radiance at a plane point (frame units), the same value the callbacks return. */\n radianceAt(u: number, v: number, wavelengthNanometers: number): number;\n /**\n * 2.3, chart scenes only: the chart material at a plane point (frame units), or `materials.length` for the\n * surround of a fixed-size chart; `materialRadiance` gives that material's spectral radiance, the same value\n * `radianceAt` returns at its points.\n */\n chartMaterialAt?(u: number, v: number): number;\n materialRadiance?(material: number, wavelengthNanometers: number): number;\n}\n\n/**\n * Internal (#394, not exported from the package): per provider of a chart preset or caller material scene, the material its\n * `evaluateRadiance` reads for an environment-direction query with a given outgoing direction (the same plane-point\n * arithmetic), or undefined where `evaluateRadiance` would throw. Its radiance is `materialRadiance(material, wavelength)`.\n */\nconst MATERIAL_OF_DIRECTION = new WeakMap<PlanarSceneRadianceProvider, (direction: Readonly<{ x: number; y: number; z: number }>) => number | undefined>();\n\n/** Internal (#394): the material lookup of a provider built by {@link buildPlanarSceneRadianceProvider}, if it has one. */\nexport function planarProviderMaterialOfDirection(provider: PlanarSceneRadianceProvider):\n ((direction: Readonly<{ x: number; y: number; z: number }>) => number | undefined) | undefined {\n return MATERIAL_OF_DIRECTION.get(provider);\n}\n\nconst UNCERTAINTY = Object.freeze({ kind: \"not-quantified\" as const, limitation: \"Analytic planar Lambertian scene; no measured scene, BRDF or illumination.\" });\n\n/** Most distinct wavelengths {@link tabulatedSpectrum} keeps; later ones are evaluated on every call. */\nconst TABULATED_SPECTRUM_MAX_ENTRIES = 4096;\n\n/**\n * Internal (#385): `spectrum.evaluate` remembered per distinct wavelength. A prepared spectrum is a pure function of the\n * wavelength, so the table returns the same double the call would; renderers ask for the same few spectral nodes millions\n * of times, and the illuminant's formula (two transcendental evaluations) was about 30 % of a caller-scene display view.\n */\nexport function tabulatedSpectrum(spectrum: Readonly<PreparedColorimetricSpectrum>): (wavelengthNanometers: number) => number {\n const table = new Map<number, number>();\n return (nm) => {\n let value = table.get(nm);\n if (value === undefined) {\n value = spectrum.evaluate(nm);\n if (table.size < TABULATED_SPECTRUM_MAX_ENTRIES) table.set(nm, value);\n }\n return value;\n };\n}\n\n/**\n * Wraps a chart or caller scene as a provider for the native environment RAW task. `irradianceScale` is\n * from {@link calculateIlluminantIrradianceScale}; caller radiance scenes ignore the illuminant.\n */\nexport function buildPlanarSceneRadianceProvider(input: {\n scene: ResolvedChartScene | ResolvedCallerScene;\n sceneId: string;\n providerProfileId: string;\n illuminant: ResolvedCaptureIlluminant;\n irradianceScale: number;\n geometry: PlanarSceneGeometry;\n evidence: readonly EvidenceProvenance[];\n limitations: readonly string[];\n}): PlanarSceneRadianceProvider {\n const { scene, illuminant, irradianceScale, geometry } = input;\n const scale = geometry.metresPerFrameUnit, distance = geometry.distanceM, sceneId = input.sceneId, providerProfileId = input.providerProfileId;\n const evidence = input.evidence, limitations = input.limitations;\n const caller = \"kind\" in scene ? scene : undefined, chart = caller ? undefined : scene as ResolvedChartScene;\n const materialScene = caller?.kind === \"material-function\" ? caller : undefined, materials = chart ? chart.materials : materialScene?.materials;\n const placed = geometry.chart, half = placed ? placed.widthM / 2 : 0, chartAspect = placed ? placed.heightM / placed.widthM : 0;\n const shapeAt = tabulatedSpectrum(illuminant.shape);\n /** A material scene's material at a frame point: the caller's index, or `materials.length` for a fixed-size chart's surround. */\n function callerMaterialAt(u: number, v: number): number {\n const xM = u * scale, yM = v * scale;\n let point: SceneMaterialPoint;\n if (placed) {\n const cu = xM / half, cv = yM / half;\n if (!(Math.abs(cu) <= 1 && Math.abs(cv) <= chartAspect)) return materialScene!.materials.length;\n point = { xM, yM, u, v, chartU: cu, chartV: cv };\n } else point = { xM, yM, u, v };\n const index = materialScene!.materialAt(point);\n if (!Number.isInteger(index) || index < 0 || index >= materialScene!.materials.length) throw new InvalidConfigurationError(\"Scene materialAt must return an index into its materials.\");\n return index;\n }\n function radianceAt(u: number, v: number, nm: number): number {\n if (materialScene) return materialRadianceOf(callerMaterialAt(u, v), nm);\n if (placed) {\n // Fixed-size chart (2.3): chart-local frame units from the plane point in metres.\n const xM = u * scale, yM = v * scale, cu = xM / half, cv = yM / half;\n if (!(Math.abs(cu) <= 1 && Math.abs(cv) <= chartAspect)) return placed.surroundReflectance * irradianceScale * shapeAt(nm) / Math.PI;\n if (chart) return chart.reflectanceAt(cu, cv, nm) * irradianceScale * shapeAt(nm) / Math.PI;\n return callerValue({ xM, yM, u, v, wavelengthNanometers: nm, chartU: cu, chartV: cv }, nm);\n }\n if (chart) return chart.reflectanceAt(u, v, nm) * irradianceScale * shapeAt(nm) / Math.PI;\n return callerValue({ xM: u * scale, yM: v * scale, u, v, wavelengthNanometers: nm }, nm);\n }\n function callerValue(point: Readonly<ScenePlanePoint>, nm: number): number {\n const value = (caller as CallerReflectanceScene | CallerRadianceScene).evaluate(point);\n if (caller!.kind === \"reflectance-function\") {\n if (typeof value !== \"number\" || !Number.isFinite(value) || value < 0 || value > 1) throw new InvalidConfigurationError(\"Scene reflectance function must return a value in [0, 1].\");\n return value * irradianceScale * shapeAt(nm) / Math.PI;\n }\n if (typeof value !== \"number\" || !Number.isFinite(value) || value < 0) throw new InvalidConfigurationError(\"Scene radiance function must return a finite non-negative radiance.\");\n return value;\n }\n function result(request: Readonly<SceneRadianceEvaluationRequest>, radiance: number): SceneRadianceEvaluationResult {\n return { schemaVersion: \"0.1.0\", sampleId: request.sampleId, sceneId, providerProfileId, wavelengthNanometers: request.wavelengthNanometers,\n wavelengthBasis: request.wavelengthBasis as SceneRadianceEvaluationResult[\"wavelengthBasis\"], quantity: \"outgoing-spectral-radiance\", unit: \"W/m^2/sr/nm\",\n spectralRadianceWattsPerSquareMeterSteradianNanometer: radiance, scientificStatus: \"approximation\", uncertainty: UNCERTAINTY, evidence, limitations };\n }\n /** Spectral radiance of material `material` (`materials.length`: a fixed-size chart's surround), in the chart's expression order. */\n function materialRadianceOf(material: number, nm: number): number {\n const m = materials![material];\n let value: number;\n if (m === undefined) value = placed ? placed.surroundReflectance : NaN;\n else if (m.kind === \"neutral\") value = m.reflectance;\n else {\n value = m.spectrum.evaluate(nm);\n if (!(value >= 0 && value <= 1)) throw new InvalidConfigurationError(\"Chart reflectance spectrum left [0, 1].\");\n }\n if (!(value >= 0)) throw new InvalidConfigurationError(\"Unknown chart material.\");\n return value * irradianceScale * shapeAt(nm) / Math.PI;\n }\n function chartMaterialAt(u: number, v: number): number {\n if (!placed) return chart!.materialAt(u, v);\n const cu = u * scale / half, cv = v * scale / half;\n return Math.abs(cu) <= 1 && Math.abs(cv) <= chartAspect ? chart!.materialAt(cu, cv) : chart!.materials.length;\n }\n const chartAccess = chart ? { chartMaterialAt, materialRadiance: materialRadianceOf } :\n materialScene ? { chartMaterialAt: callerMaterialAt, materialRadiance: materialRadianceOf } : {};\n // #394: evaluateRadiance's own plane-point arithmetic; radianceAt is then materialRadianceOf(material, nm) for both scene forms.\n const materialAtPoint = chart ? chartMaterialAt : materialScene ? callerMaterialAt : undefined;\n const materialOfDirection = materialAtPoint === undefined ? undefined : (o: Readonly<{ x: number; y: number; z: number }>): number | undefined => {\n const lz = -o.z;\n if (!(lz > 0)) return undefined;\n const t = distance / lz;\n return materialAtPoint(-o.x * t / scale, -o.y * t / scale);\n };\n const provider: PlanarSceneRadianceProvider = {\n sceneId, providerProfileId, radianceAt, ...chartAccess,\n evaluateRadiance(request): SceneRadianceEvaluationResult {\n const target = request.target;\n if (target.kind !== \"environment-direction\") throw new InvalidConfigurationError(\"Planar scene provider needs environment-direction queries.\");\n const o = target.outgoingDirectionUnitVector, lz = -o.z;\n if (!(lz > 0)) throw new InvalidConfigurationError(\"Planar scene query does not point toward the scene plane.\");\n const t = distance / lz;\n return result(request, radianceAt(-o.x * t / scale, -o.y * t / scale, request.wavelengthNanometers));\n },\n evaluateApertureRadiance(request, ray): SceneRadianceEvaluationResult {\n const d = ray.directionUnitVector, origin = ray.originM;\n if (!(d.z > 0)) throw new InvalidConfigurationError(\"Planar scene pupil ray does not point toward the scene plane.\");\n const t = (distance - origin.z) / d.z;\n return result(request, radianceAt((origin.x + d.x * t) / scale, (origin.y + d.y * t) / scale, request.wavelengthNanometers));\n }\n };\n if (materialOfDirection) MATERIAL_OF_DIRECTION.set(provider, materialOfDirection);\n return provider;\n}\n\n/** 2.3: a chart's physical size on the scene plane (`simulateCapture` `chartSize`, `createPlanarSceneRadianceProvider` `chartSize`). */\nexport interface ChartSizeOption {\n /** Chart width in metres, (0, 10 000]. */\n widthM: number;\n /** Chart height in metres. Default: widthM × the frame aspect (height / width), so the chart has the frame's shape. */\n heightM?: number;\n /** Neutral reflectance of the plane around the chart, lit by the same illuminant. Default 0.18. */\n surroundReflectance?: number;\n}\n/** Default surround of a fixed-size chart: an 18 % grey plane. */\nexport const CHART_SIZE_DEFAULT_SURROUND_REFLECTANCE = 0.18;\n/** Internal: validates a chart size and fills its defaults; `defaulted` names the fields taken from defaults. */\nexport function resolveChartSizeOption(value: unknown, frameAspect: number): { widthM: number; heightM: number; surroundReflectance: number; defaulted: (\"heightM\" | \"surroundReflectance\")[] } {\n requireInputObject(value, \"chartSize\");\n const record = value as Record<string, unknown>;\n for (const key of Object.keys(record)) if (![\"widthM\", \"heightM\", \"surroundReflectance\"].includes(key)) throw new InvalidConfigurationError(\"Unknown chartSize field: \" + key + \".\");\n const size = (x: unknown, name: string): number => {\n if (typeof x !== \"number\" || !Number.isFinite(x) || x <= 0 || x > 10_000) throw new InvalidConfigurationError(\"chartSize.\" + name + \" must be a positive number of metres up to 10000.\");\n return x;\n };\n const defaulted: (\"heightM\" | \"surroundReflectance\")[] = [];\n const widthM = size(record.widthM, \"widthM\");\n const heightM = record.heightM === undefined ? (defaulted.push(\"heightM\"), widthM * frameAspect) : size(record.heightM, \"heightM\");\n const surround = record.surroundReflectance === undefined ? (defaulted.push(\"surroundReflectance\"), CHART_SIZE_DEFAULT_SURROUND_REFLECTANCE) : record.surroundReflectance;\n if (typeof surround !== \"number\" || !Number.isFinite(surround) || surround < 0 || surround > 1) throw new InvalidConfigurationError(\"chartSize.surroundReflectance must be a reflectance in [0, 1].\");\n return { widthM, heightM, surroundReflectance: surround, defaulted };\n}\n\n/**\n * Public scene-preset provider. Places an engine chart (or a caller reflectance or radiance function) on\n * a plane `distanceM` in front of the camera and `framedWidthM` wide (frame units u = ±1 at its edges),\n * lit by `illuminant` at `illuminanceLux`. The returned `evaluateRadiance` and `evaluateApertureRadiance`\n * follow the native environment RAW provider contract. They answer requests for scene `sceneId` and\n * provider `providerProfileId`.\n */\nexport function createPlanarSceneRadianceProvider(input: {\n scene: ChartScene | CallerReflectanceScene | CallerRadianceScene | CallerMaterialScene;\n illuminant: CaptureIlluminant;\n illuminanceLux: number;\n distanceM: number;\n framedWidthM: number;\n /** Frame height / width. */\n aspect: number;\n sceneId: string;\n providerProfileId: string;\n /**\n * 2.3, opt-in: place the chart at this physical size, centred, instead of filling the frame; the chart preset\n * is resolved with aspect heightM / widthM and the rest of the plane is the surround.\n */\n chartSize?: ChartSizeOption;\n}): PlanarSceneRadianceProvider & { chart: ResolvedChartScene | null } {\n requireInputObject(input, \"createPlanarSceneRadianceProvider input\");\n const keys = [\"scene\", \"illuminant\", \"illuminanceLux\", \"distanceM\", \"framedWidthM\", \"aspect\", \"sceneId\", \"providerProfileId\", \"chartSize\"];\n for (const key of Object.keys(input)) if (!keys.includes(key)) throw new InvalidConfigurationError(\"createPlanarSceneRadianceProvider input has unknown field \\\"\" + key + \"\\\".\");\n for (const key of [\"illuminanceLux\", \"distanceM\", \"framedWidthM\", \"aspect\"] as const) {\n const value = input[key];\n if (typeof value !== \"number\" || !Number.isFinite(value) || value <= 0) throw new InvalidConfigurationError(key + \" must be a positive finite number.\");\n }\n for (const key of [\"sceneId\", \"providerProfileId\"] as const) if (typeof input[key] !== \"string\" || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(input[key])) throw new InvalidConfigurationError(key + \" must be a public opaque ID.\");\n requireInputObject(input.scene, \"scene\");\n const caller = \"kind\" in input.scene ? requireCallerScene(input.scene) : undefined;\n const size = input.chartSize === undefined ? undefined : resolveChartSizeOption(input.chartSize, input.aspect);\n const chart = caller ? null : resolveChartScene({ scene: input.scene as ChartScene, aspect: size ? size.heightM / size.widthM : input.aspect });\n const illuminant = resolveCaptureIlluminant(input.illuminant);\n const provider = buildPlanarSceneRadianceProvider({ scene: chart ?? caller!, sceneId: input.sceneId, providerProfileId: input.providerProfileId, illuminant,\n irradianceScale: calculateIlluminantIrradianceScale(illuminant.shape, input.illuminanceLux),\n geometry: { distanceM: input.distanceM, metresPerFrameUnit: input.framedWidthM / 2,\n ...(size ? { chart: { widthM: size.widthM, heightM: size.heightM, surroundReflectance: size.surroundReflectance } } : {}) },\n evidence: [{ sourceOrigin: \"photivra\", sourceReference: \"photivra:planar-scene-provider\", reuseStatus: \"photivra-owned\" }],\n limitations: [\"Planar Lambertian scene under uniform illumination; no shadows, inter-reflection, gloss or fluorescence.\"] });\n return { ...provider, chart };\n}\n\n/** Validates a caller scene record (a function scene as given; a material scene with its materials prepared). */\nexport function requireCallerScene(value: unknown): ResolvedCallerScene {\n requireInputObject(value, \"scene\");\n const record = value as Record<string, unknown>;\n if (record.kind === \"material-function\") {\n for (const key of Object.keys(record)) if (key !== \"kind\" && key !== \"sceneId\" && key !== \"materials\" && key !== \"materialAt\") throw new InvalidConfigurationError(\"Unknown scene field: \" + key + \".\");\n if (typeof record.materialAt !== \"function\" || typeof record.sceneId !== \"string\" || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/.test(record.sceneId) ||\n !Array.isArray(record.materials) || record.materials.length < 1 || record.materials.length > CALLER_MATERIAL_SCENE_MAX_MATERIALS)\n throw new InvalidConfigurationError(\"A material scene needs a public sceneId, 1 to \" + CALLER_MATERIAL_SCENE_MAX_MATERIALS + \" materials and a materialAt function.\");\n const inputs = [...record.materials as unknown[]];\n return Object.freeze({ kind: \"material-function\" as const, sceneId: record.sceneId, materialAt: record.materialAt as ResolvedCallerMaterialScene[\"materialAt\"],\n materials: Object.freeze(inputs.map((m, index) => resolveChartMaterial(m, \"scene.materials[\" + index + \"]\"))),\n materialInputs: Object.freeze(inputs.map((m) => (typeof m === \"number\" ? undefined : m))) });\n }\n for (const key of Object.keys(record)) if (key !== \"kind\" && key !== \"sceneId\" && key !== \"evaluate\") throw new InvalidConfigurationError(\"Unknown scene field: \" + key + \".\");\n if ((record.kind !== \"reflectance-function\" && record.kind !== \"radiance-function\") || typeof record.evaluate !== \"function\" ||\n typeof record.sceneId !== \"string\" || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/.test(record.sceneId)) throw new InvalidConfigurationError(\"A caller scene needs kind, a public sceneId and an evaluate function.\");\n return record as unknown as CallerReflectanceScene | CallerRadianceScene;\n}\n"]}
@@ -18,6 +18,7 @@ import type { CalculateSensorPsfIrradianceQuadratureInput } from "../optics/sens
18
18
  import type { CalculateEnvironmentSensorPhotoSignalInput } from "../sensor/environment-photo-signal.js";
19
19
  import { type DiffractionLimitedPsfProfile } from "../optics/diffraction-psf-profile.js";
20
20
  import { type AntiAliasingPointSplitComponent } from "../sensor/optical-stack.js";
21
+ import { type NativeRawDng } from "../capture/native-raw-dng.js";
21
22
  import { type ChartScene, type ResolvedChartScene } from "./chart-scenes.js";
22
23
  import { type ChartSizeOption, type CaptureIlluminant, type CallerMaterialScene, type CallerRadianceScene, type CallerReflectanceScene, type ResolvedCallerScene, type PlanarSceneRadianceProvider, type ResolvedCaptureIlluminant } from "./scene-radiance.js";
23
24
  /** Version of how the facade builds requests. It changes whenever the same input would build a different request. */
@@ -493,6 +494,30 @@ export declare function bilinearPhaseProfiles(): RawFrameReconstructionPhaseProf
493
494
  * underlying request/plan, provenance and every assumption made. See docs/QUICK_START.md.
494
495
  */
495
496
  export declare function simulateCapture(options: SimulateCaptureOptions): Promise<SimulateCaptureResult>;
497
+ /** One part of a whole-frame DNG (#391): a region render's packed RAW and where its native sites lie (`result.raw`, `result.region`). */
498
+ export interface SimulateCaptureDngPart {
499
+ raw: Pick<NativeRawOutput, "codes" | "blackLevels" | "digitalSaturationCodes" | "saturationFlags" | "effectiveSaturationCodes">;
500
+ region: {
501
+ nativeRect: {
502
+ x: number;
503
+ y: number;
504
+ width: number;
505
+ height: number;
506
+ };
507
+ };
508
+ }
509
+ /**
510
+ * Writes the whole-frame DNG of `options` (`output.format: "dng"`, no `output.region`) from the packed RAW of region renders of
511
+ * the same request (#391), so the RAW can render in parallel. A region render's native sites are the same sites as the whole
512
+ * render's (each site's seeds come from its index in the whole raster), so the joined RAW is the whole render's RAW, and the
513
+ * request is resolved and written exactly as `simulateCapture` writes its DNG: the bytes are the same. The parts must cover
514
+ * every native site of the frame; where they overlap (each region carries the demosaic margin) their sites must agree. Region
515
+ * renders of the request with any format serve (a region's own `output.format` does not change its RAW). A region cannot take
516
+ * `output.whiteBalance: "auto"` or `output.dng`: render the parts with a fixed white balance (the RAW codes do not depend on the
517
+ * white-balance intent) and pass the DNG's own options here, where auto white balance is measured over the joined frame.
518
+ * @returns The DNG (its `bytes` are those of `SimulateCaptureResult.image.dng` for the same options), with its stored levels and identifiers.
519
+ */
520
+ export declare function serializeSimulatedCaptureDngFromParts(options: SimulateCaptureOptions, parts: readonly SimulateCaptureDngPart[]): Promise<NativeRawDng>;
496
521
  /**
497
522
  * The ideal reference of a capture request (2.3): the same scene, framing, chart size, output size, region and pixel
498
523
  * grid as `simulateCapture(options)` would use, rendered with no camera effects (no lens blur, diffraction, defocus,
@@ -750,7 +775,7 @@ export declare const DISPLAY_VIEW_WITHOUT_VIEW: unique symbol;
750
775
  * Internal: the request path shared by {@link simulateCapture}, {@link simulateIdealReference} and the display view, whose renderer is
751
776
  * passed in; for a display view the renderer's value is returned (a result, or a prepared view with DISPLAY_VIEW_WITHOUT_VIEW).
752
777
  */
753
- export declare function runCapture(options: SimulateCaptureOptions, run: "capture" | "ideal-reference" | "display-view", viewOption?: unknown, renderView?: (context: DisplayViewRunContext) => Promise<unknown>): Promise<unknown>;
778
+ export declare function runCapture(options: SimulateCaptureOptions, run: "capture" | "ideal-reference" | "display-view" | "dng-from-parts", viewOption?: unknown, renderView?: (context: DisplayViewRunContext) => Promise<unknown>): Promise<unknown>;
754
779
  /** Chart preset ids accepted by `simulateCapture({ scene: { preset } })`. */
755
780
  export declare const SIMULATE_CAPTURE_CHART_PRESETS: readonly ("composite" | "uniform" | "patches" | "slanted-edge" | "siemens-star" | "step-wedge" | "grey-ramp" | "checkerboard" | "point-grid" | "dead-leaves" | "bar-groups" | "hyperbolic-wedge" | "zone-plate" | "slanted-squares" | "line-grid" | "fiducial")[];
756
781
  export {};
@@ -74,7 +74,7 @@ import { calculateSensorSpectralQuadrature } from "../sensor/spectral-quadrature
74
74
  import { createDiffractionLimitedPsfProfile } from "../optics/diffraction-psf-profile.js";
75
75
  import { createDiffractedPlanarProvider } from "./diffraction-provider.js";
76
76
  import { resolveGenericPrimeLens } from "../equipment/generic-prime-lenses.js";
77
- import { calculateEnvironmentSensorPhotoSignal } from "../sensor/environment-photo-signal.js";
77
+ import { executeEnvironmentSensorPhotoSignal, planEnvironmentSensorPhotoSignal } from "../sensor/environment-photo-signal.js";
78
78
  import { calculateSiteEffectiveSaturationCode } from "../capture/raw-white-level.js";
79
79
  import { prepareSensorColorDevelopment } from "../color/sensor-color-development.js";
80
80
  import { resolveAntiAliasingSpatialKernel } from "../sensor/optical-stack.js";
@@ -142,6 +142,9 @@ const AHD_VALUE_REACH = 3;
142
142
  /** Anti-aliasing filter limits: split points, and the largest offset in sites (bounds the scene work and the convolution margin). */
143
143
  const AA_MAXIMUM_COMPONENTS = 16;
144
144
  const AA_MAXIMUM_OFFSET_SITES = 4;
145
+ /** Channel responses kept across calls (`axisChannelResponse`): one entry per distinct sensor, exposure and optics state. */
146
+ const CHANNEL_RESPONSE_CACHE_SIZE = 8;
147
+ const channelResponseCache = new Map();
145
148
  /** Default birefringent separation in sites: the two-spot MTF |cos(π·f·d)| then has its first zero at Nyquist, f = 1/(2·pitch). */
146
149
  const AA_DEFAULT_SEPARATION_SITES = 1;
147
150
  /** Parses `sensor.antiAliasing` into engine point-splitting components (offsets in µm, +x right, +y down). */
@@ -406,14 +409,29 @@ async function developAhd(v, raw, repeatWidth, repeatHeight, width, height, at,
406
409
  host.onDemosaicMs?.(clockMs() - demosaicStarted);
407
410
  const demosaiced = task.takeOutput().data, rgb = new Float64Array(width * height * 3);
408
411
  const counts = { saturatedPixelCount: 0, whiteBalanceClippedSampleCount: 0, reconstructedPixelCount: 0 };
412
+ // #420: a pixel is clipped when a saturated site lies within AHD_VALUE_REACH of it, clipped to the raster. The sites within
413
+ // that reach of each column are found once per row (`near`, a horizontal dilation of `saturated`), so a pixel reads one
414
+ // column of 2·reach + 1 rows instead of the whole square; with no saturated site at all no pixel is clipped.
415
+ let anySaturated = false;
416
+ for (let k = 0; k < saturated.length && !anySaturated; k++)
417
+ anySaturated = saturated[k] !== 0;
418
+ const near = anySaturated ? new Uint8Array(W * H) : undefined;
419
+ if (near)
420
+ for (let y = 0; y < H; y++) {
421
+ const row = y * W;
422
+ for (let x = 0; x < W; x++)
423
+ if (saturated[row + x] !== 0)
424
+ near.fill(1, row + Math.max(0, x - AHD_VALUE_REACH), row + Math.min(W, x + AHD_VALUE_REACH + 1));
425
+ }
409
426
  for (let y = 0; y < height; y++) {
410
- for (let x = 0; x < width; x++) {
411
- const p = at(x, y), i = p.y * W + p.x;
427
+ // The oriented-to-native map is affine in x with whole-site steps (as the bilinear path's developRun uses): two points give the row.
428
+ const first = at(0, y), second = width > 1 ? at(1, y) : first, stepX = second.x - first.x, stepY = second.y - first.y;
429
+ for (let x = 0, px = first.x, py = first.y; x < width; x++, px += stepX, py += stepY) {
430
+ const i = py * W + px;
412
431
  let clipped = false;
413
- for (let dy = -AHD_VALUE_REACH; dy <= AHD_VALUE_REACH && !clipped; dy++)
414
- for (let dx = -AHD_VALUE_REACH; dx <= AHD_VALUE_REACH; dx++) {
415
- const sx = p.x + dx, sy = p.y + dy;
416
- if (sx >= 0 && sy >= 0 && sx < W && sy < H && saturated[sy * W + sx] !== 0) {
432
+ if (near)
433
+ for (let sy = Math.max(0, py - AHD_VALUE_REACH), last = Math.min(H - 1, py + AHD_VALUE_REACH); sy <= last; sy++) {
434
+ if (near[sy * W + px] !== 0) {
417
435
  clipped = true;
418
436
  break;
419
437
  }
@@ -482,6 +500,74 @@ function encodeSdrFromLinear(rgb, encoding, bitDepth, mapping) {
482
500
  export async function simulateCapture(options) {
483
501
  return await runCapture(options, "capture");
484
502
  }
503
+ /**
504
+ * Writes the whole-frame DNG of `options` (`output.format: "dng"`, no `output.region`) from the packed RAW of region renders of
505
+ * the same request (#391), so the RAW can render in parallel. A region render's native sites are the same sites as the whole
506
+ * render's (each site's seeds come from its index in the whole raster), so the joined RAW is the whole render's RAW, and the
507
+ * request is resolved and written exactly as `simulateCapture` writes its DNG: the bytes are the same. The parts must cover
508
+ * every native site of the frame; where they overlap (each region carries the demosaic margin) their sites must agree. Region
509
+ * renders of the request with any format serve (a region's own `output.format` does not change its RAW). A region cannot take
510
+ * `output.whiteBalance: "auto"` or `output.dng`: render the parts with a fixed white balance (the RAW codes do not depend on the
511
+ * white-balance intent) and pass the DNG's own options here, where auto white balance is measured over the joined frame.
512
+ * @returns The DNG (its `bytes` are those of `SimulateCaptureResult.image.dng` for the same options), with its stored levels and identifiers.
513
+ */
514
+ export async function serializeSimulatedCaptureDngFromParts(options, parts) {
515
+ return await runCapture(options, "dng-from-parts", parts);
516
+ }
517
+ /** The whole frame's packed RAW from region parts (see `serializeSimulatedCaptureDngFromParts`). */
518
+ function joinNativeRawParts(value, plan, width, height) {
519
+ if (!Array.isArray(value) || value.length === 0)
520
+ throw new InvalidConfigurationError("serializeSimulatedCaptureDngFromParts needs at least one part.");
521
+ const parts = value, count = width * height;
522
+ const codes = new Uint16Array(count), blackLevels = new Uint16Array(count), digitalSaturationCodes = new Uint16Array(count), saturationFlags = new Uint8Array(count);
523
+ const covered = new Uint8Array(count), white = new Uint16Array(4);
524
+ const bad = (k, what) => { throw new InvalidConfigurationError("DNG part " + k + ": " + what); };
525
+ parts.forEach((part, k) => {
526
+ const rect = part?.region?.nativeRect, raw = part?.raw;
527
+ if (!rect || !raw)
528
+ bad(k, "needs raw and region.nativeRect (a region render's result).");
529
+ const { x, y, width: w, height: h } = rect;
530
+ if (![x, y, w, h].every(Number.isSafeInteger) || x < 0 || y < 0 || w < 1 || h < 1 || x + w > width || y + h > height)
531
+ bad(k, "its nativeRect is not inside the frame's native raster.");
532
+ const n = w * h;
533
+ if (!(raw.codes instanceof Uint16Array) || raw.codes.length !== n || !(raw.blackLevels instanceof Uint16Array) || raw.blackLevels.length !== n ||
534
+ !(raw.digitalSaturationCodes instanceof Uint16Array) || raw.digitalSaturationCodes.length !== n || !(raw.saturationFlags instanceof Uint8Array) || raw.saturationFlags.length !== n)
535
+ bad(k, "its RAW arrays do not match its nativeRect.");
536
+ const phases = raw.effectiveSaturationCodes;
537
+ if (!(phases instanceof Uint16Array) || phases.length !== 4)
538
+ bad(k, "needs four per-phase white levels.");
539
+ // Per-phase white levels are in the whole raster's CFA phases (0 for a phase the part has no site of); all parts agree.
540
+ for (let phase = 0; phase < 4; phase++) {
541
+ const code = phases[phase];
542
+ if (code === 0)
543
+ continue;
544
+ if (white[phase] === 0)
545
+ white[phase] = code;
546
+ else if (white[phase] !== code)
547
+ bad(k, "its white level differs from another part's: not the same request.");
548
+ }
549
+ for (let row = 0; row < h; row++)
550
+ for (let column = 0; column < w; column++) {
551
+ const from = row * w + column, to = (y + row) * width + x + column;
552
+ if (covered[to]) {
553
+ if (codes[to] !== raw.codes[from] || blackLevels[to] !== raw.blackLevels[from] || digitalSaturationCodes[to] !== raw.digitalSaturationCodes[from] ||
554
+ saturationFlags[to] !== raw.saturationFlags[from])
555
+ bad(k, "a site differs from another part's at the same place: not the same request.");
556
+ continue;
557
+ }
558
+ covered[to] = 1;
559
+ codes[to] = raw.codes[from];
560
+ blackLevels[to] = raw.blackLevels[from];
561
+ digitalSaturationCodes[to] = raw.digitalSaturationCodes[from];
562
+ saturationFlags[to] = raw.saturationFlags[from];
563
+ }
564
+ });
565
+ if (covered.includes(0))
566
+ throw new InvalidConfigurationError("The DNG parts do not cover every native site of the frame.");
567
+ if (white.includes(0))
568
+ throw new InvalidConfigurationError("The DNG parts lack a white level for a CFA phase.");
569
+ return { plan, codes, blackLevels, digitalSaturationCodes, saturationFlags, effectiveSaturationCodes: white };
570
+ }
485
571
  /**
486
572
  * The ideal reference of a capture request (2.3): the same scene, framing, chart size, output size, region and pixel
487
573
  * grid as `simulateCapture(options)` would use, rendered with no camera effects (no lens blur, diffraction, defocus,
@@ -687,6 +773,8 @@ export async function runCapture(options, run, viewOption, renderView) {
687
773
  }
688
774
  else if (outputOptions.dng !== undefined)
689
775
  fail("output.dng applies only to output.format \"dng\".");
776
+ if (run === "dng-from-parts" && format !== "dng")
777
+ fail("serializeSimulatedCaptureDngFromParts needs output.format \"dng\".");
690
778
  const textMetadata = parseOutputTextMetadata(outputOptions.metadata, "output.metadata");
691
779
  if (textMetadata && format !== "jpeg" && format !== "png" && format !== "dng")
692
780
  fail("output.metadata applies only to output.format \"jpeg\", \"png\" or \"dng\".");
@@ -1313,13 +1401,16 @@ export async function runCapture(options, run, viewOption, renderView) {
1313
1401
  const yieldControl = createHostYield().yieldControl;
1314
1402
  const perSite = queriesPerSite * (diffraction && psf === diffractionPsf ? (2 * diffraction.kernelRadiusSamples + 1) ** 2 : 1);
1315
1403
  let diffractionMs = 0, demosaicMs, encodeMs;
1316
- const rawProvider = diffraction && diffractionObjectSpace ? createDiffractedPlanarProvider({ base: provider, psf: diffractionPsf.configuration.psf,
1404
+ const diffractedProvider = (window) => diffraction && diffractionObjectSpace ? createDiffractedPlanarProvider({ base: provider, psf: diffractionPsf.configuration.psf,
1317
1405
  wavelengthsNm: diffraction.profile.axes.wavelengthNm, kernelRadius: diffraction.kernelRadiusSamples, nativeWidth, nativeHeight, outputWidth: width,
1318
1406
  sitePitchMicrometers: pitch, distanceM: subjectDistanceM, metresPerFrameUnit, onConvolution: (ms) => { diffractionMs += ms; },
1319
1407
  // Region (2.6): convolve only the lattice the region's native sites query; the values are the whole render's.
1320
- ...(regionNative ? { window: regionNative } : {}),
1408
+ ...(window ? { window } : {}),
1321
1409
  // The environment queries each site at each aperture node minus each split offset (sites, +x right, +y down).
1322
1410
  ...(antiAliasing || boxSamples > 1 ? { queryOffsetsSites: apertureNodeOffsets(boxSamples).flatMap((node) => (antiAliasing ? antiAliasing.components : [{ offsetMicrometers: { x: 0, y: 0 } }]).map((c) => ({ x: node.x - c.offsetMicrometers.x / pitch, y: node.y - c.offsetMicrometers.y / pitch }))) } : {}) }) : provider;
1411
+ // Built on first use: a capture that takes the tabulated path (#394 step 2) never queries it, and its kernels cost a setup.
1412
+ let rawProviderBuilt;
1413
+ const rawProvider = () => (rawProviderBuilt ??= diffractedProvider(regionNative));
1323
1414
  if (antiAliasing && perSite > 100_000)
1324
1415
  fail("sensor.antiAliasing with these options needs " + perSite + " scene queries per site; the environment admits at most 100000.");
1325
1416
  const evaluations = nativeWidth * nativeHeight * perSite;
@@ -1335,7 +1426,7 @@ export async function runCapture(options, run, viewOption, renderView) {
1335
1426
  // is linear in the radiance node values and, for this planar scene, the same at every site (paraxial π/(4N_w²)).
1336
1427
  const cx = Math.floor(nativeWidth / 2) & ~1, cy = Math.floor(nativeHeight / 2) & ~1;
1337
1428
  const channelSites = { red: cy * nativeWidth + cx, green: cy * nativeWidth + Math.min(cx + 1, nativeWidth - 1), blue: Math.min(cy + 1, nativeHeight - 1) * nativeWidth + Math.min(cx + 1, nativeWidth - 1) };
1338
- const electronsPerRadiance = {};
1429
+ const environments = {};
1339
1430
  for (const channel of CHANNELS) {
1340
1431
  if (channelAt(channelSites[channel] % nativeWidth, Math.floor(channelSites[channel] / nativeWidth)) !== channel)
1341
1432
  fail(caller + " needs at least a 2 × 2 native raster.");
@@ -1346,13 +1437,36 @@ export async function runCapture(options, run, viewOption, renderView) {
1346
1437
  environment.temporalSampleCount = 1;
1347
1438
  delete environment.pupil;
1348
1439
  delete environment.lensFieldMapping;
1349
- const electrons = (radiance) => calculateEnvironmentSensorPhotoSignal({ ...environment,
1350
- evaluateRadiance: (request) => ({ ...provider.evaluateRadiance(request), spectralRadianceWattsPerSquareMeterSteradianNanometer: radiance(request.wavelengthNanometers) })
1351
- }).value
1352
- .photo.value.photoSignal.expectedGeneratedElectronCount;
1353
- const nodes = new Set();
1354
- electrons((nm) => { nodes.add(nm); return 1; });
1355
- electronsPerRadiance[channel] = new Map([...nodes].sort((a, b) => a - b).map((node) => [node, electrons((nm) => (nm === node ? 1 : 0))]));
1440
+ delete environment.evaluateRadiance;
1441
+ delete environment.evaluateApertureRadiance;
1442
+ environments[channel] = environment;
1443
+ }
1444
+ // The responses are a function of these records alone (the radiance is replaced per node), and a request split into region
1445
+ // tiles builds the same records for every tile, so they are kept across calls (the last CHANNEL_RESPONSE_CACHE_SIZE).
1446
+ const key = JSON.stringify(CHANNELS.map((c) => environments[c]));
1447
+ const copy = (responses) => Object.fromEntries(CHANNELS.map((c) => [c, new Map(responses[c])]));
1448
+ const cached = channelResponseCache.get(key);
1449
+ let electronsPerRadiance;
1450
+ if (cached) {
1451
+ channelResponseCache.delete(key);
1452
+ channelResponseCache.set(key, cached);
1453
+ electronsPerRadiance = copy(cached);
1454
+ }
1455
+ else {
1456
+ electronsPerRadiance = {};
1457
+ for (const channel of CHANNELS) {
1458
+ // Planned once per channel and executed per spectral node: calculateEnvironmentSensorPhotoSignal is this plan and execution.
1459
+ const photoPlan = planEnvironmentSensorPhotoSignal(environments[channel]);
1460
+ const electrons = (radiance) => executeEnvironmentSensorPhotoSignal(photoPlan, (request) => ({ ...provider.evaluateRadiance(request), spectralRadianceWattsPerSquareMeterSteradianNanometer: radiance(request.wavelengthNanometers) })).value
1461
+ .photo.value.photoSignal.expectedGeneratedElectronCount;
1462
+ const nodes = new Set();
1463
+ electrons((nm) => { nodes.add(nm); return 1; });
1464
+ electronsPerRadiance[channel] = new Map([...nodes].sort((a, b) => a - b).map((node) => [node, electrons((nm) => (nm === node ? 1 : 0))]));
1465
+ }
1466
+ // Callers get their own maps; the cached ones are never handed out.
1467
+ channelResponseCache.set(key, copy(electronsPerRadiance));
1468
+ if (channelResponseCache.size > CHANNEL_RESPONSE_CACHE_SIZE)
1469
+ channelResponseCache.delete(channelResponseCache.keys().next().value);
1356
1470
  }
1357
1471
  const wavelengths = [...new Set(CHANNELS.flatMap((c) => [...electronsPerRadiance[c].keys()]))].sort((a, b) => a - b);
1358
1472
  // 2. Electrons → normalized RAW signal: (code − black)/(white − black) = e·d/(G·(W − B)) for the linear readout
@@ -1482,13 +1596,17 @@ export async function runCapture(options, run, viewOption, renderView) {
1482
1596
  };
1483
1597
  const rawTick = progress("raw", regionNative ? regionNative.height * Math.ceil(regionNative.width / tileWidth) : plan.tileCount);
1484
1598
  // #394: siteInput builds fresh site records per call and never changes them, so the native task plans them without a copy.
1485
- const rawCallbacks = { readTile: markInternalNativeTileReader(async (request) => { const tile = await readTile(request); rawTick(); return tile; }),
1486
- evaluateRadiance: rawProvider.evaluateRadiance, ...(pupil ? { evaluateApertureRadiance: provider.evaluateApertureRadiance } : {}), yieldControl };
1599
+ const rawCallbacks = () => ({ readTile: markInternalNativeTileReader(async (request) => { const tile = await readTile(request); rawTick(); return tile; }),
1600
+ evaluateRadiance: rawProvider().evaluateRadiance, ...(pupil ? { evaluateApertureRadiance: provider.evaluateApertureRadiance } : {}), yieldControl });
1487
1601
  // #394 step 2: an engine-built planar scene (chart preset or caller material scene; still, rectilinear, no distortion, vignetting,
1488
1602
  // pupil rays or caller PSF) takes its expected electrons from the tabulated signal, verified per CFA phase against the chain.
1489
1603
  const tabulatedScene = chart !== undefined || callerScene?.kind === "material-function";
1604
+ // #391: a DNG from region parts takes the whole frame's RAW from the parts instead of rendering it.
1605
+ if (run === "dng-from-parts" && regionNative)
1606
+ fail("serializeSimulatedCaptureDngFromParts writes the whole frame: the options take no output.region.");
1607
+ const dngParts = run === "dng-from-parts" ? viewOption : undefined;
1490
1608
  let tabulated;
1491
- if (tabulatedScene && !pupil && !lensFieldMapping && !vignetting && !lensPsf && !rotating && (!diffraction || diffractionObjectSpace) && provider.chartMaterialAt && provider.materialRadiance) {
1609
+ if (dngParts === undefined && tabulatedScene && !pupil && !lensFieldMapping && !vignetting && !lensPsf && !rotating && (!diffraction || diffractionObjectSpace) && provider.chartMaterialAt && provider.materialRadiance) {
1492
1610
  const { electronsPerRadiance, wavelengths } = axisChannelResponse("simulateCapture");
1493
1611
  const perNode = CHANNELS.map((c) => Float64Array.from(wavelengths, (nm) => electronsPerRadiance[c].get(nm) ?? 0));
1494
1612
  const sceneMaterials = chart ? chart.materials : callerScene.materials, materialRadiance = provider.materialRadiance;
@@ -1498,11 +1616,16 @@ export async function runCapture(options, run, viewOption, renderView) {
1498
1616
  list: [...sceneMaterials.map((m, index) => (m.kind === "neutral" ? { neutral: m.reflectance } : { radiance: (nm) => materialRadiance(index, nm) })),
1499
1617
  ...(chartSize ? [{ neutral: chartSize.surroundReflectance }] : [])] },
1500
1618
  radianceAt: provider.radianceAt, imagingArea, focalLengthMm, focusDistanceM, subjectDistanceM, metresPerFrameUnit, caller: "simulateCapture" });
1501
- tabulated = await renderTabulatedNativeRaw({ input: environmentRaw, region: regionNative, siteInput, evaluateRadiance: rawProvider.evaluateRadiance,
1619
+ // The verification reads only the region's top-left 2 × 2 block, so its diffraction convolves only that block's lattice; the
1620
+ // window never changes a value (see diffraction-provider.ts), so the chain it runs is the whole render's.
1621
+ const verificationProvider = diffractedProvider({ x: regionNative?.x ?? 0, y: regionNative?.y ?? 0, width: 2, height: 2 });
1622
+ tabulated = await renderTabulatedNativeRaw({ input: environmentRaw, region: regionNative, siteInput, evaluateRadiance: verificationProvider.evaluateRadiance,
1502
1623
  electrons: createDisplayViewExpectedSignal(signalInput), onTile: rawTick, tileWidth, yieldControl: () => yieldControl(), checkAbort });
1503
1624
  }
1504
1625
  let rawOutput;
1505
- if (tabulated) {
1626
+ if (dngParts !== undefined)
1627
+ rawOutput = { raw: joinNativeRawParts(dngParts, plan, nativeWidth, nativeHeight), providerEvaluationCount: 0 };
1628
+ else if (tabulated) {
1506
1629
  rawOutput = { raw: tabulated.raw, providerEvaluationCount: tabulated.providerEvaluationCount };
1507
1630
  // The verification's relative difference itself is not reported: it is a last-bits quantity, and captures use the JavaScript
1508
1631
  // engine's own Math functions, so it differs between engines while the results are the same.
@@ -1512,8 +1635,8 @@ export async function runCapture(options, run, viewOption, renderView) {
1512
1635
  "diagnostics.providerEvaluationCount counts those sites' evaluator calls and the table's scene lookups.");
1513
1636
  }
1514
1637
  else {
1515
- const rawTask = regionNative ? createNativeEnvironmentRawRegionTask(environmentRaw, regionNative, rawCallbacks) :
1516
- createNativeEnvironmentRawTask(environmentRaw, rawCallbacks);
1638
+ const rawTask = regionNative ? createNativeEnvironmentRawRegionTask(environmentRaw, regionNative, rawCallbacks()) :
1639
+ createNativeEnvironmentRawTask(environmentRaw, rawCallbacks());
1517
1640
  await runTask(rawTask);
1518
1641
  rawOutput = rawTask.takeOutput();
1519
1642
  }
@@ -1550,7 +1673,7 @@ export async function runCapture(options, run, viewOption, renderView) {
1550
1673
  sampleSet: { imageStateId: "facade-pre-wb-raw", inputDomain: "relative-pre-wb-camera-linear-rgb", samples } });
1551
1674
  finalRawInput = { raw: buildRawInput(intentOf(whiteBalanceState)), sceneBinding, maximumProviderEvaluations: environmentRaw.maximumProviderEvaluations };
1552
1675
  const wbTick = progress("white-balance", plan.tileCount);
1553
- if (tabulated) {
1676
+ if (tabulated || dngParts !== undefined) {
1554
1677
  // #394: the RAW codes do not depend on the white-balance intent (it is development metadata), so the tabulated RAW is
1555
1678
  // kept with the plan of the measured intent instead of being rendered again.
1556
1679
  rawOutput = { ...rawOutput, raw: { ...rawOutput.raw, plan: calculateNativeRawPlan(finalRawInput.raw) } };
@@ -1562,7 +1685,7 @@ export async function runCapture(options, run, viewOption, renderView) {
1562
1685
  // retained optical stage, and is faster: retaining the optical stage takes the first pass off the lean executor.
1563
1686
  const wbTask = createNativeEnvironmentRawTask(finalRawInput, {
1564
1687
  readTile: markInternalNativeTileReader(async (request) => { const tile = await readTile(request); wbTick(); return tile; }),
1565
- evaluateRadiance: rawProvider.evaluateRadiance, ...(pupil ? { evaluateApertureRadiance: provider.evaluateApertureRadiance } : {}), yieldControl
1688
+ evaluateRadiance: rawProvider().evaluateRadiance, ...(pupil ? { evaluateApertureRadiance: provider.evaluateApertureRadiance } : {}), yieldControl
1566
1689
  });
1567
1690
  await runTask(wbTask);
1568
1691
  rawOutput = wbTask.takeOutput();
@@ -1591,6 +1714,8 @@ export async function runCapture(options, run, viewOption, renderView) {
1591
1714
  assume("output.dng", "model", { writer: "serializeNativeRawDng", schemaVersion: dng.schemaVersion, whiteLevel: dng.whiteLevel, blackLevels: dng.blackLevels,
1592
1715
  noiseProfile: dng.noiseProfile, unrepresentedSaturationFlagCount: dng.unrepresentedSaturationFlagCount }, "Lossless uncompressed 16-bit CFA DNG of exactly the packed native RAW codes: per-phase BlackLevel, WhiteLevel = smallest per-phase effective white, ActiveArea and DefaultCrop from the capture geometry, ColorMatrix1/ForwardMatrix1 from the facade's diagonal camera→XYZ profile (D65), AsShotNeutral from the white-balance intent, BaselineExposure 0, and NoiseProfile from each channel's readout regime (conversion gain ÷ digital gain, combined read noise; Poisson + Gaussian + quantization only). No linear master or developed image is declared; saturation flags below WhiteLevel are not representable and are counted.");
1593
1716
  }
1717
+ if (dngParts !== undefined)
1718
+ return dng;
1594
1719
  // Development
1595
1720
  const development = { phaseProfiles, colorProfile,
1596
1721
  whiteBalance: developmentWhiteBalance, rendering, highlightMode, ...(mirrorBorder ? { borderHandling: "mirror" } : {}),