@photivra/engine 2.14.1 → 2.16.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 (80) hide show
  1. package/CHANGELOG.md +69 -1
  2. package/CITATION.cff +1 -1
  3. package/README.md +6 -6
  4. package/SECURITY.md +1 -1
  5. package/THIRD_PARTY.md +14 -0
  6. package/dist/capture/native-environment-lean.js +1 -1
  7. package/dist/capture/native-environment-lean.js.map +1 -1
  8. package/dist/capture/native-raw-development.d.ts +15 -0
  9. package/dist/capture/native-raw-development.js +12 -6
  10. package/dist/capture/native-raw-development.js.map +1 -1
  11. package/dist/capture/raw-development-kernel.d.ts +10 -3
  12. package/dist/capture/raw-development-kernel.js +25 -6
  13. package/dist/capture/raw-development-kernel.js.map +1 -1
  14. package/dist/core/internal-radiance-evaluator.d.ts +5 -2
  15. package/dist/core/internal-radiance-evaluator.js.map +1 -1
  16. package/dist/core/version.d.ts +1 -1
  17. package/dist/core/version.js +1 -1
  18. package/dist/core/version.js.map +1 -1
  19. package/dist/facade/defocus-image-space-provider.d.ts +109 -0
  20. package/dist/facade/defocus-image-space-provider.js +359 -0
  21. package/dist/facade/defocus-image-space-provider.js.map +1 -0
  22. package/dist/facade/diffraction-provider.d.ts +16 -0
  23. package/dist/facade/diffraction-provider.js +3 -3
  24. package/dist/facade/diffraction-provider.js.map +1 -1
  25. package/dist/facade/display-view.d.ts +21 -0
  26. package/dist/facade/display-view.js +66 -8
  27. package/dist/facade/display-view.js.map +1 -1
  28. package/dist/facade/simulate-capture.d.ts +112 -3
  29. package/dist/facade/simulate-capture.js +235 -48
  30. package/dist/facade/simulate-capture.js.map +1 -1
  31. package/dist/facade/simulate-display-view.js +7 -3
  32. package/dist/facade/simulate-display-view.js.map +1 -1
  33. package/dist/gpu/display-view-quality-gpu.d.ts +2 -0
  34. package/dist/gpu/display-view-quality-gpu.js +57 -13
  35. package/dist/gpu/display-view-quality-gpu.js.map +1 -1
  36. package/dist/gpu/display-view-speed-gpu.d.ts +2 -0
  37. package/dist/gpu/display-view-speed-gpu.js +45 -16
  38. package/dist/gpu/display-view-speed-gpu.js.map +1 -1
  39. package/dist/gpu/image-kernel-accelerator.js +3 -0
  40. package/dist/gpu/image-kernel-accelerator.js.map +1 -1
  41. package/dist/gpu/wgsl-display-view-quality-kernel.d.ts +4 -0
  42. package/dist/gpu/wgsl-display-view-quality-kernel.js +53 -2
  43. package/dist/gpu/wgsl-display-view-quality-kernel.js.map +1 -1
  44. package/dist/gpu/wgsl-display-view-speed-kernel.d.ts +15 -0
  45. package/dist/gpu/wgsl-display-view-speed-kernel.js +42 -1
  46. package/dist/gpu/wgsl-display-view-speed-kernel.js.map +1 -1
  47. package/dist/index.d.ts +3 -2
  48. package/dist/index.js +2 -1
  49. package/dist/index.js.map +1 -1
  50. package/dist/optics/defocus-disc-kernel.d.ts +91 -1
  51. package/dist/optics/defocus-disc-kernel.js +59 -5
  52. package/dist/optics/defocus-disc-kernel.js.map +1 -1
  53. package/dist/optics/diffraction-psf-profile.d.ts +9 -4
  54. package/dist/optics/diffraction-psf-profile.js +14 -6
  55. package/dist/optics/diffraction-psf-profile.js.map +1 -1
  56. package/dist/optics/lens-psf-kernels.d.ts +13 -2
  57. package/dist/optics/lens-psf-kernels.js +23 -6
  58. package/dist/optics/lens-psf-kernels.js.map +1 -1
  59. package/dist/optics/sensor-environment-query.d.ts +31 -0
  60. package/dist/optics/sensor-environment-query.js +45 -13
  61. package/dist/optics/sensor-environment-query.js.map +1 -1
  62. package/dist/optics/site-diffraction-kernel.d.ts +1 -1
  63. package/dist/optics/site-diffraction-kernel.js +37 -17
  64. package/dist/optics/site-diffraction-kernel.js.map +1 -1
  65. package/dist/processing/development-detail.d.ts +132 -0
  66. package/dist/processing/development-detail.js +325 -0
  67. package/dist/processing/development-detail.js.map +1 -0
  68. package/docs/AGENT_GUIDE.md +1 -0
  69. package/docs/API_REFERENCE.md +17 -1
  70. package/docs/QUICK_START.md +210 -16
  71. package/docs/USAGE.md +31 -3
  72. package/docs/api/capture-native-raw-development.md +16 -0
  73. package/docs/api/core-version.md +1 -1
  74. package/docs/api/exports.json +47 -2
  75. package/docs/api/facade-simulate-capture.md +129 -4
  76. package/docs/api/optics-defocus-disc-kernel.md +87 -0
  77. package/docs/api/optics-diffraction-psf-profile.md +6 -3
  78. package/docs/api/optics-lens-psf-kernels.md +3 -2
  79. package/llms.txt +1 -0
  80. package/package.json +1 -1
@@ -34,8 +34,11 @@ import { requireAllowlistedRecord } from "../core/record-validation.js";
34
34
  import { IRRADIANCE_CONVOLUTION_LIMITS } from "./irradiance-convolution.js";
35
35
  import { markEngineOwnedLensSampledPsfProfile, resolveLensSampledPsf } from "./lens-psf-profile.js";
36
36
  export const LENS_PSF_CONVOLUTION_KERNELS_SCHEMA_VERSION = "0.1.0";
37
- /** At most this many wavelengths per call. */
38
- export const LENS_PSF_CONVOLUTION_KERNELS_MAXIMUM_WAVELENGTHS = 64;
37
+ /**
38
+ * At most this many wavelengths per call: 400, the finest spectral sampling of `simulateCapture` (1 nm over 380–780 nm),
39
+ * as `DIFFRACTION_LIMITED_PSF_PROFILE_LIMITS.maximumWavelengths` (64 before 2.15.0). The work is linear in the count.
40
+ */
41
+ export const LENS_PSF_CONVOLUTION_KERNELS_MAXIMUM_WAVELENGTHS = 400;
39
42
  function positive(value, message) {
40
43
  if (typeof value !== "number" || !(value > 0 && value <= Number.MAX_VALUE))
41
44
  throw new InvalidConfigurationError(message);
@@ -53,6 +56,19 @@ function integer(value, minimum, maximum, message) {
53
56
  * @see docs/WEBGPU.md, "Kernels from a lens PSF profile".
54
57
  */
55
58
  export function resolveLensPsfConvolutionKernels(input) {
59
+ return resolveKernels(input, undefined);
60
+ }
61
+ /**
62
+ * Internal (not exported from the package): `resolveLensPsfConvolutionKernels` with `ownedProfile` used in place of a fresh
63
+ * private clone of `input.psf.profile`. `ownedProfile` must be a structured clone of that profile that no caller code can
64
+ * reach, already passed to `markEngineOwnedLensSampledPsfProfile`; repeated calls then share one parse (the clone is frozen
65
+ * and its parse cached on the first resolve), so N one-wavelength calls cost O(N) instead of O(N²) (2.15.0).
66
+ * The values are the same: the public function parses its own clone the same way.
67
+ */
68
+ export function resolveLensPsfConvolutionKernelsWithOwnedProfile(input, ownedProfile) {
69
+ return resolveKernels(input, ownedProfile);
70
+ }
71
+ function resolveKernels(input, ownedProfile) {
56
72
  const r = requireAllowlistedRecord(input, ["schemaVersion", "psf", "spectralWeights", "grid", "patchWidth", "patchHeight", "kernelRadius"], "Invalid lens PSF convolution kernel input.");
57
73
  if (r.schemaVersion !== LENS_PSF_CONVOLUTION_KERNELS_SCHEMA_VERSION)
58
74
  throw new InvalidConfigurationError("Unsupported lens PSF convolution kernel schema.");
@@ -71,7 +87,7 @@ export function resolveLensPsfConvolutionKernels(input) {
71
87
  throw new InvalidConfigurationError("Too many patches.");
72
88
  const list = r.spectralWeights;
73
89
  if (!Array.isArray(list) || list.length < 1 || list.length > LENS_PSF_CONVOLUTION_KERNELS_MAXIMUM_WAVELENGTHS) {
74
- throw new InvalidConfigurationError("spectralWeights must list 1 to 64 wavelengths.");
90
+ throw new InvalidConfigurationError("spectralWeights must list 1 to " + LENS_PSF_CONVOLUTION_KERNELS_MAXIMUM_WAVELENGTHS + " wavelengths.");
75
91
  }
76
92
  const spectral = list.map((entry) => {
77
93
  const e = requireAllowlistedRecord(entry, ["wavelengthNm", "weight"], "Invalid spectral weight.");
@@ -83,9 +99,10 @@ export function resolveLensPsfConvolutionKernels(input) {
83
99
  if (!(totalWeight > 0 && totalWeight <= Number.MAX_VALUE))
84
100
  throw new InvalidConfigurationError("At least one spectral weight must be positive.");
85
101
  const psf = requireAllowlistedRecord(r.psf, ["profile", "focalLengthMm", "focus", "apertureFNumber", "signedDefocusImagePlaneMicrometers"], "Invalid PSF state.");
86
- // One private parse of the profile for every patch and wavelength.
87
- const profile = structuredClone(psf.profile);
88
- markEngineOwnedLensSampledPsfProfile(profile);
102
+ // One private parse of the profile for every patch and wavelength (and, with an owned profile, for every call).
103
+ const profile = ownedProfile ?? structuredClone(psf.profile);
104
+ if (!ownedProfile)
105
+ markEngineOwnedLensSampledPsfProfile(profile);
89
106
  const state = { ...psf, profile };
90
107
  // Resolve every patch and wavelength, splatting straight into one scratch displacement map sized for the largest
91
108
  // allowed radius; each patch keeps a copy cropped to its own reach. The common radius is known only at the end.
@@ -1 +1 @@
1
- {"version":3,"file":"lens-psf-kernels.js","sourceRoot":"","sources":["../../src/optics/lens-psf-kernels.ts"],"names":[],"mappings":"AAAA,sCAAsC;AAEtC;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AAEH,OAAO,EAAE,mBAAmB,EAA0B,MAAM,+BAA+B,CAAC;AAC5F,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAC3E,OAAO,EAAE,wBAAwB,EAAE,MAAM,8BAA8B,CAAC;AACxE,OAAO,EAAE,6BAA6B,EAAE,MAAM,6BAA6B,CAAC;AAC5E,OAAO,EAAE,oCAAoC,EAAE,qBAAqB,EAAmC,MAAM,uBAAuB,CAAC;AAErI,MAAM,CAAC,MAAM,2CAA2C,GAAG,OAAgB,CAAC;AAC5E,8CAA8C;AAC9C,MAAM,CAAC,MAAM,gDAAgD,GAAG,EAAE,CAAC;AAiCnE,SAAS,QAAQ,CAAC,KAAc,EAAE,OAAe;IAC/C,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,CAAC,KAAK,GAAG,CAAC,IAAI,KAAK,IAAI,MAAM,CAAC,SAAS,CAAC;QAAE,MAAM,IAAI,yBAAyB,CAAC,OAAO,CAAC,CAAC;IACzH,OAAO,KAAK,CAAC;AACf,CAAC;AACD,SAAS,OAAO,CAAC,KAAc,EAAE,OAAe,EAAE,OAAe,EAAE,OAAe;IAChF,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,KAAK,CAAC,IAAI,KAAK,GAAG,OAAO,IAAI,KAAK,GAAG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AC,CAAC,CAAC;IACH,IAAI,gBAAgB,GAAG,CAAC,CAAC,gBAAgB;QAAE,MAAM,IAAI,yBAAyB,CAAC,qCAAqC,CAAC,CAAC;IACtH,OAAO,mBAAmB,CAAC,EAAE,aAAa,EAAE,2CAA2C,EAAE,YAAY,EAAE,MAAM,EAAE,UAAU,EAAE,WAAW;QACpI,YAAY,EAAE,OAAO,EAAE,SAAS,EAAE,IAAI,EAAE,OAAO,EAAE,iBAAiB,EAAE,KAAK,EAAE,gBAAgB,EAAE,OAAO,EAAE,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,EAAE,EAChI,8BAA8B,EAAE,2CAA2C,EAAE;QAC3E,8IAA8I;QAC9I,KAAK,CAAC,CAAC,CAAC,4EAA4E,CAAC,CAAC;YACpF,uIAAuI;QACzI,6FAA6F;KAC9F,CAAC,CAAC;AACL,CAAC","sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Samples the engine's lens PSFs (`LensSampledPsfProfile`, resolved with `resolveLensSampledPsf`) into\n * the per-patch kernels of the isoplanatic convolution (`calculateIrradianceConvolution`, #277).\n *\n * For each patch, the PSF is resolved at the patch centre's field point, in the per-site engine's own\n * coordinates: native sensor millimetres from the optical axis (+Y down), field point (x, −y). Every\n * PSF tap then maps to a site displacement with the per-site quadrature's inverse support\n * (`sensorPsfSourcePoint`): tap (kx, ky) is the source at native offset (−(kx − cx)·pₓ, +(ky − cy)·p_y)\n * from the destination, so its weight lands at displacement u = (kx − cx)·pₓ/sₓ, v = −(ky − cy)·p_y/s_y\n * sites (p: PSF sample pitch, s: site pitch). When p equals s the displacement is taken as the tap offset itself\n * (kx − cx, −(ky − cy)): the rounded quotient (n·p)/p misses the integer n by one unit in the last place for some\n * pitches (for example 3 · 1.6 / 1.6), which split the tap bilinearly or reached one site past the window (2.2.1).\n *\n * - **Exact site sampling.** When every displacement is an integer (equal pitches, integer centre), each\n * tap's weight goes to one kernel cell. For a destination whose PSF equals its patch's, the\n * convolution then equals the per-site PSF quadrature at site-centre sources term by term.\n * - **Otherwise (labelled approximation): bilinear splatting.** Each weight is split over the four\n * surrounding integer displacements with bilinear weights. This is the exact adjoint of bilinear\n * interpolation, so the convolution equals the per-site quadrature applied to the bilinear interpolant of\n * the site-centre samples (tested). Weights are conserved.\n *\n * With several wavelengths the kernel is the weight-normalized sum of the per-wavelength kernels. For a\n * spectrally neutral scene that is exactly the per-site engine's spectral sum when the weights are its\n * spectral quadrature weights times the scene spectrum (see docs/WEBGPU.md).\n *\n * The patch approximation (one PSF per patch, indexed by source site) is the caller's choice of patch\n * size; its method error is measured, not bounded (docs/WEBGPU.md, \"Per-fixture rollout\"). Relative\n * pupil throughput stays a separate factor and is reported, never folded into the unit-energy kernels.\n */\n\nimport { approximationResult, type CalculationResult } from \"../core/calculation-result.js\";\nimport { InvalidConfigurationError } from \"../core/configuration-error.js\";\nimport { requireAllowlistedRecord } from \"../core/record-validation.js\";\nimport { IRRADIANCE_CONVOLUTION_LIMITS } from \"./irradiance-convolution.js\";\nimport { markEngineOwnedLensSampledPsfProfile, resolveLensSampledPsf, type ResolveLensSampledPsfInput } from \"./lens-psf-profile.js\";\n\nexport const LENS_PSF_CONVOLUTION_KERNELS_SCHEMA_VERSION = \"0.1.0\" as const;\n/** At most this many wavelengths per call. */\nexport const LENS_PSF_CONVOLUTION_KERNELS_MAXIMUM_WAVELENGTHS = 64;\n\nexport interface LensPsfConvolutionKernelsInput {\n schemaVersion: typeof LENS_PSF_CONVOLUTION_KERNELS_SCHEMA_VERSION;\n /** The optical state, as for `resolveLensSampledPsf`, without the field point and wavelength. */\n psf: Omit<ResolveLensSampledPsfInput, \"fieldPointMm\" | \"wavelengthNm\">;\n /** One or more wavelengths with non-negative weights (at least one positive). */\n spectralWeights: readonly { wavelengthNm: number; weight: number }[];\n /** The convolution grid: sites, their pitch, and the optical axis in site units (site centres at i + 0.5). */\n grid: { width: number; height: number; sitePitchMicrometers: { x: number; y: number }; opticalAxisSite: { x: number; y: number } };\n /** Patch size in sites; the last row and column of patches may be partial. */\n patchWidth: number;\n patchHeight: number;\n /** Kernel radius to use; omitted, the smallest radius that holds every tap. A radius too small to hold the PSF is rejected. */\n kernelRadius?: number;\n}\n\nexport interface LensPsfConvolutionKernels {\n schemaVersion: typeof LENS_PSF_CONVOLUTION_KERNELS_SCHEMA_VERSION;\n kernelRadius: number;\n patchWidth: number;\n patchHeight: number;\n patchColumns: number;\n patchRows: number;\n /** `[patchRow][patchColumn][v + r][u + r]`, ready for `IrradianceConvolutionInput.kernels`. */\n kernels: Float64Array;\n /** True when every tap landed on one integer displacement (no bilinear splatting). */\n exactSiteSampling: boolean;\n maximumKernelSum: number;\n /** Per patch, row-major: the field point used and the weight-averaged relative pupil throughput (not applied). */\n patches: readonly { fieldPointMm: { x: number; y: number }; relativePupilThroughputFactor: number; interpolated: boolean }[];\n}\n\nfunction positive(value: unknown, message: string): number {\n if (typeof value !== \"number\" || !(value > 0 && value <= Number.MAX_VALUE)) throw new InvalidConfigurationError(message);\n return value;\n}\nfunction integer(value: unknown, minimum: number, maximum: number, message: string): number {\n if (typeof value !== \"number\" || !Number.isSafeInteger(value) || value < minimum || value > maximum) throw new InvalidConfigurationError(message);\n return value;\n}\n\n/**\n * Builds the per-patch convolution kernels from a sampled lens PSF profile.\n * @param input - See `LensPsfConvolutionKernelsInput`.\n * @returns The kernels and per-patch field points. Success does not imply calibration.\n * @see docs/WEBGPU.md, \"Kernels from a lens PSF profile\".\n */\nexport function resolveLensPsfConvolutionKernels(input: LensPsfConvolutionKernelsInput): CalculationResult<LensPsfConvolutionKernels> {\n const r = requireAllowlistedRecord(input, [\"schemaVersion\", \"psf\", \"spectralWeights\", \"grid\", \"patchWidth\", \"patchHeight\", \"kernelRadius\"],\n \"Invalid lens PSF convolution kernel input.\");\n if (r.schemaVersion !== LENS_PSF_CONVOLUTION_KERNELS_SCHEMA_VERSION) throw new InvalidConfigurationError(\"Unsupported lens PSF convolution kernel schema.\");\n const L = IRRADIANCE_CONVOLUTION_LIMITS;\n const g = requireAllowlistedRecord(r.grid, [\"width\", \"height\", \"sitePitchMicrometers\", \"opticalAxisSite\"], \"Invalid convolution grid.\");\n const width = integer(g.width, 1, L.maximumDimension, \"Invalid convolution grid size.\"), height = integer(g.height, 1, L.maximumDimension, \"Invalid convolution grid size.\");\n const pitch = requireAllowlistedRecord(g.sitePitchMicrometers, [\"x\", \"y\"], \"Invalid site pitch.\");\n const sx = positive(pitch.x, \"Site pitch must be positive.\"), sy = positive(pitch.y, \"Site pitch must be positive.\");\n const axis = requireAllowlistedRecord(g.opticalAxisSite, [\"x\", \"y\"], \"Invalid optical axis.\");\n if (typeof axis.x !== \"number\" || typeof axis.y !== \"number\" || !Number.isFinite(axis.x) || !Number.isFinite(axis.y)) {\n throw new InvalidConfigurationError(\"The optical axis must be finite site coordinates.\");\n }\n const patchWidth = integer(r.patchWidth, 1, width, \"Invalid patch size.\"), patchHeight = integer(r.patchHeight, 1, height, \"Invalid patch size.\");\n const columns = Math.ceil(width / patchWidth), rows = Math.ceil(height / patchHeight);\n if (columns * rows > L.maximumPatchCount) throw new InvalidConfigurationError(\"Too many patches.\");\n const list = r.spectralWeights;\n if (!Array.isArray(list) || list.length < 1 || list.length > LENS_PSF_CONVOLUTION_KERNELS_MAXIMUM_WAVELENGTHS) {\n throw new InvalidConfigurationError(\"spectralWeights must list 1 to 64 wavelengths.\");\n }\n const spectral = list.map((entry: unknown) => {\n const e = requireAllowlistedRecord(entry, [\"wavelengthNm\", \"weight\"], \"Invalid spectral weight.\");\n if (typeof e.weight !== \"number\" || !(e.weight >= 0 && e.weight <= Number.MAX_VALUE)) throw new InvalidConfigurationError(\"Spectral weights must be finite and non-negative.\");\n return { wavelengthNm: positive(e.wavelengthNm, \"Wavelengths must be positive.\"), weight: e.weight };\n });\n const totalWeight = spectral.reduce((s, e) => s + e.weight, 0);\n if (!(totalWeight > 0 && totalWeight <= Number.MAX_VALUE)) throw new InvalidConfigurationError(\"At least one spectral weight must be positive.\");\n const psf = requireAllowlistedRecord(r.psf, [\"profile\", \"focalLengthMm\", \"focus\", \"apertureFNumber\", \"signedDefocusImagePlaneMicrometers\"], \"Invalid PSF state.\");\n // One private parse of the profile for every patch and wavelength.\n const profile = structuredClone(psf.profile);\n markEngineOwnedLensSampledPsfProfile(profile);\n const state = { ...(psf as unknown as Omit<ResolveLensSampledPsfInput, \"fieldPointMm\" | \"wavelengthNm\">), profile } as Omit<ResolveLensSampledPsfInput, \"fieldPointMm\" | \"wavelengthNm\">;\n\n // Resolve every patch and wavelength, splatting straight into one scratch displacement map sized for the largest\n // allowed radius; each patch keeps a copy cropped to its own reach. The common radius is known only at the end.\n // Every cell receives its weights in the same order as a direct sum (taps in kernel order, then the four\n // bilinear corners), so the kernels do not depend on the scratch layout.\n const M = L.maximumKernelRadius, scratchSize = 2 * M + 1, scratch = new Float64Array(scratchSize * scratchSize);\n const cropped: { reach: number; values: Float64Array }[] = [], patches: LensPsfConvolutionKernels[\"patches\"][number][] = [];\n let reach = 0, exact = true, overflow = false;\n for (let pr = 0; pr < rows; pr++) for (let pc = 0; pc < columns; pc++) {\n const x0 = pc * patchWidth, y0 = pr * patchHeight, x1 = Math.min(width, x0 + patchWidth), y1 = Math.min(height, y0 + patchHeight);\n const nativeX = ((x0 + x1) / 2 - axis.x) * sx / 1000, nativeY = ((y0 + y1) / 2 - axis.y) * sy / 1000;\n const fieldPointMm = { x: nativeX, y: -nativeY };\n let throughput = 0, interpolated = false, patchReach = 0;\n for (const { wavelengthNm, weight } of spectral) {\n if (weight === 0) continue;\n const resolved = resolveLensSampledPsf({ ...state, fieldPointMm, wavelengthNm }).value, k = resolved.kernel, share = weight / totalWeight;\n throughput += share * resolved.relativePupilThroughputFactor;\n if (resolved.resolutionStatus !== \"exact-grid-sample\") interpolated = true;\n const equalX = k.samplePitchMicrometersX === sx, equalY = k.samplePitchMicrometersY === sy;\n for (let ky = 0; ky < k.heightSamples; ky++) for (let kx = 0; kx < k.widthSamples; kx++) {\n const intensity = k.normalizedIntensity[ky * k.widthSamples + kx]!;\n if (intensity === 0) continue;\n // With equal pitches the displacement is the tap offset itself: (n·p)/p can miss n by one unit in the last place.\n const u = equalX ? kx - k.centerSampleX : (kx - k.centerSampleX) * k.samplePitchMicrometersX / sx;\n const v = equalY ? -(ky - k.centerSampleY) : -(ky - k.centerSampleY) * k.samplePitchMicrometersY / sy;\n const u0 = Math.floor(u), v0 = Math.floor(v), fu = u - u0, fv = v - v0, w = share * intensity;\n if (fu !== 0 || fv !== 0) exact = false;\n for (let corner = 0; corner < 4; corner++) {\n const du = corner & 1, dv = corner >> 1;\n const b = du === 0 ? (dv === 0 ? (1 - fu) * (1 - fv) : (1 - fu) * fv) : (dv === 0 ? fu * (1 - fv) : fu * fv);\n if (b === 0) continue;\n const cu = u0 + du, cv = v0 + dv;\n patchReach = Math.max(patchReach, Math.abs(cu), Math.abs(cv));\n // Past the largest radius the call is rejected below; resolving continues so errors keep their order.\n if (patchReach > M) { overflow = true; continue; }\n if (!overflow) scratch[(cv + M) * scratchSize + cu + M]! += w * b;\n }\n }\n }\n reach = Math.max(reach, patchReach);\n if (!overflow) {\n const n = 2 * patchReach + 1, values = new Float64Array(n * n);\n for (let v = -patchReach; v <= patchReach; v++) {\n const row = (v + M) * scratchSize + M;\n values.set(scratch.subarray(row - patchReach, row + patchReach + 1), (v + patchReach) * n);\n scratch.fill(0, row - patchReach, row + patchReach + 1);\n }\n cropped.push({ reach: patchReach, values });\n }\n patches.push(Object.freeze({ fieldPointMm: Object.freeze(fieldPointMm), relativePupilThroughputFactor: throughput, interpolated }));\n }\n const radius = r.kernelRadius === undefined ? reach : integer(r.kernelRadius, 0, L.maximumKernelRadius, \"Invalid kernel radius.\");\n if (reach > radius) throw new InvalidConfigurationError(\"The kernel radius is too small for the PSF support; no tap is dropped.\");\n if (radius > L.maximumKernelRadius) throw new InvalidConfigurationError(\"The PSF support needs a kernel radius above 32 sites.\");\n const size = 2 * radius + 1, taps = size * size;\n if (columns * rows * taps > L.maximumKernelWeights) throw new InvalidConfigurationError(\"Too many kernel weights.\");\n const kernels = new Float64Array(columns * rows * taps);\n let maximumKernelSum = 0;\n cropped.forEach(({ reach: q, values }, p) => {\n const n = 2 * q + 1;\n let sum = 0;\n for (let v = 0; v < n; v++) kernels.set(values.subarray(v * n, (v + 1) * n), p * taps + (v - q + radius) * size + radius - q);\n for (let t = 0; t < taps; t++) sum += kernels[p * taps + t]!;\n maximumKernelSum = Math.max(maximumKernelSum, sum);\n });\n if (maximumKernelSum > L.maximumKernelSum) throw new InvalidConfigurationError(\"Sampled kernels exceed unit energy.\");\n return approximationResult({ schemaVersion: LENS_PSF_CONVOLUTION_KERNELS_SCHEMA_VERSION, kernelRadius: radius, patchWidth, patchHeight,\n patchColumns: columns, patchRows: rows, kernels, exactSiteSampling: exact, maximumKernelSum, patches: Object.freeze(patches) },\n \"lens-psf-convolution-kernels\", LENS_PSF_CONVOLUTION_KERNELS_SCHEMA_VERSION, [\n \"One PSF per patch, resolved at the patch centre with resolveLensSampledPsf; indexed by source site in the convolution (isoplanatic patches).\",\n exact ? \"Every PSF tap maps to one integer site displacement (exact site sampling).\" :\n \"PSF taps between sites are split bilinearly (the adjoint of bilinear interpolation of site-centre samples); a labelled approximation.\",\n \"Relative pupil throughput is reported per patch and not applied to the unit-energy kernels.\"\n ]);\n}\n"]}
1
+ {"version":3,"file":"lens-psf-kernels.js","sourceRoot":"","sources":["../../src/optics/lens-psf-kernels.ts"],"names":[],"mappings":"AAAA,sCAAsC;AAEtC;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AAEH,OAAO,EAAE,mBAAmB,EAA0B,MAAM,+BAA+B,CAAC;AAC5F,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAC3E,OAAO,EAAE,wBAAwB,EAAE,MAAM,8BAA8B,CAAC;AACxE,OAAO,EAAE,6BAA6B,EAAE,MAAM,6BAA6B,CAAC;AAC5E,OAAO,EAAE,oCAAoC,EAAE,qBAAqB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AAM,CAAC,MAAM,CAAC,OAAO,CAAC,EAAE,EAChI,8BAA8B,EAAE,2CAA2C,EAAE;QAC3E,8IAA8I;QAC9I,KAAK,CAAC,CAAC,CAAC,4EAA4E,CAAC,CAAC;YACpF,uIAAuI;QACzI,6FAA6F;KAC9F,CAAC,CAAC;AACL,CAAC","sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Samples the engine's lens PSFs (`LensSampledPsfProfile`, resolved with `resolveLensSampledPsf`) into\n * the per-patch kernels of the isoplanatic convolution (`calculateIrradianceConvolution`, #277).\n *\n * For each patch, the PSF is resolved at the patch centre's field point, in the per-site engine's own\n * coordinates: native sensor millimetres from the optical axis (+Y down), field point (x, −y). Every\n * PSF tap then maps to a site displacement with the per-site quadrature's inverse support\n * (`sensorPsfSourcePoint`): tap (kx, ky) is the source at native offset (−(kx − cx)·pₓ, +(ky − cy)·p_y)\n * from the destination, so its weight lands at displacement u = (kx − cx)·pₓ/sₓ, v = −(ky − cy)·p_y/s_y\n * sites (p: PSF sample pitch, s: site pitch). When p equals s the displacement is taken as the tap offset itself\n * (kx − cx, −(ky − cy)): the rounded quotient (n·p)/p misses the integer n by one unit in the last place for some\n * pitches (for example 3 · 1.6 / 1.6), which split the tap bilinearly or reached one site past the window (2.2.1).\n *\n * - **Exact site sampling.** When every displacement is an integer (equal pitches, integer centre), each\n * tap's weight goes to one kernel cell. For a destination whose PSF equals its patch's, the\n * convolution then equals the per-site PSF quadrature at site-centre sources term by term.\n * - **Otherwise (labelled approximation): bilinear splatting.** Each weight is split over the four\n * surrounding integer displacements with bilinear weights. This is the exact adjoint of bilinear\n * interpolation, so the convolution equals the per-site quadrature applied to the bilinear interpolant of\n * the site-centre samples (tested). Weights are conserved.\n *\n * With several wavelengths the kernel is the weight-normalized sum of the per-wavelength kernels. For a\n * spectrally neutral scene that is exactly the per-site engine's spectral sum when the weights are its\n * spectral quadrature weights times the scene spectrum (see docs/WEBGPU.md).\n *\n * The patch approximation (one PSF per patch, indexed by source site) is the caller's choice of patch\n * size; its method error is measured, not bounded (docs/WEBGPU.md, \"Per-fixture rollout\"). Relative\n * pupil throughput stays a separate factor and is reported, never folded into the unit-energy kernels.\n */\n\nimport { approximationResult, type CalculationResult } from \"../core/calculation-result.js\";\nimport { InvalidConfigurationError } from \"../core/configuration-error.js\";\nimport { requireAllowlistedRecord } from \"../core/record-validation.js\";\nimport { IRRADIANCE_CONVOLUTION_LIMITS } from \"./irradiance-convolution.js\";\nimport { markEngineOwnedLensSampledPsfProfile, resolveLensSampledPsf, type ResolveLensSampledPsfInput } from \"./lens-psf-profile.js\";\n\nexport const LENS_PSF_CONVOLUTION_KERNELS_SCHEMA_VERSION = \"0.1.0\" as const;\n/**\n * At most this many wavelengths per call: 400, the finest spectral sampling of `simulateCapture` (1 nm over 380–780 nm),\n * as `DIFFRACTION_LIMITED_PSF_PROFILE_LIMITS.maximumWavelengths` (64 before 2.15.0). The work is linear in the count.\n */\nexport const LENS_PSF_CONVOLUTION_KERNELS_MAXIMUM_WAVELENGTHS = 400;\n\nexport interface LensPsfConvolutionKernelsInput {\n schemaVersion: typeof LENS_PSF_CONVOLUTION_KERNELS_SCHEMA_VERSION;\n /** The optical state, as for `resolveLensSampledPsf`, without the field point and wavelength. */\n psf: Omit<ResolveLensSampledPsfInput, \"fieldPointMm\" | \"wavelengthNm\">;\n /** One or more wavelengths with non-negative weights (at least one positive). */\n spectralWeights: readonly { wavelengthNm: number; weight: number }[];\n /** The convolution grid: sites, their pitch, and the optical axis in site units (site centres at i + 0.5). */\n grid: { width: number; height: number; sitePitchMicrometers: { x: number; y: number }; opticalAxisSite: { x: number; y: number } };\n /** Patch size in sites; the last row and column of patches may be partial. */\n patchWidth: number;\n patchHeight: number;\n /** Kernel radius to use; omitted, the smallest radius that holds every tap. A radius too small to hold the PSF is rejected. */\n kernelRadius?: number;\n}\n\nexport interface LensPsfConvolutionKernels {\n schemaVersion: typeof LENS_PSF_CONVOLUTION_KERNELS_SCHEMA_VERSION;\n kernelRadius: number;\n patchWidth: number;\n patchHeight: number;\n patchColumns: number;\n patchRows: number;\n /** `[patchRow][patchColumn][v + r][u + r]`, ready for `IrradianceConvolutionInput.kernels`. */\n kernels: Float64Array;\n /** True when every tap landed on one integer displacement (no bilinear splatting). */\n exactSiteSampling: boolean;\n maximumKernelSum: number;\n /** Per patch, row-major: the field point used and the weight-averaged relative pupil throughput (not applied). */\n patches: readonly { fieldPointMm: { x: number; y: number }; relativePupilThroughputFactor: number; interpolated: boolean }[];\n}\n\nfunction positive(value: unknown, message: string): number {\n if (typeof value !== \"number\" || !(value > 0 && value <= Number.MAX_VALUE)) throw new InvalidConfigurationError(message);\n return value;\n}\nfunction integer(value: unknown, minimum: number, maximum: number, message: string): number {\n if (typeof value !== \"number\" || !Number.isSafeInteger(value) || value < minimum || value > maximum) throw new InvalidConfigurationError(message);\n return value;\n}\n\n/**\n * Builds the per-patch convolution kernels from a sampled lens PSF profile.\n * @param input - See `LensPsfConvolutionKernelsInput`.\n * @returns The kernels and per-patch field points. Success does not imply calibration.\n * @see docs/WEBGPU.md, \"Kernels from a lens PSF profile\".\n */\nexport function resolveLensPsfConvolutionKernels(input: LensPsfConvolutionKernelsInput): CalculationResult<LensPsfConvolutionKernels> {\n return resolveKernels(input, undefined);\n}\n\n/**\n * Internal (not exported from the package): `resolveLensPsfConvolutionKernels` with `ownedProfile` used in place of a fresh\n * private clone of `input.psf.profile`. `ownedProfile` must be a structured clone of that profile that no caller code can\n * reach, already passed to `markEngineOwnedLensSampledPsfProfile`; repeated calls then share one parse (the clone is frozen\n * and its parse cached on the first resolve), so N one-wavelength calls cost O(N) instead of O(N²) (2.15.0).\n * The values are the same: the public function parses its own clone the same way.\n */\nexport function resolveLensPsfConvolutionKernelsWithOwnedProfile(input: LensPsfConvolutionKernelsInput, ownedProfile: object): CalculationResult<LensPsfConvolutionKernels> {\n return resolveKernels(input, ownedProfile);\n}\n\nfunction resolveKernels(input: LensPsfConvolutionKernelsInput, ownedProfile: object | undefined): CalculationResult<LensPsfConvolutionKernels> {\n const r = requireAllowlistedRecord(input, [\"schemaVersion\", \"psf\", \"spectralWeights\", \"grid\", \"patchWidth\", \"patchHeight\", \"kernelRadius\"],\n \"Invalid lens PSF convolution kernel input.\");\n if (r.schemaVersion !== LENS_PSF_CONVOLUTION_KERNELS_SCHEMA_VERSION) throw new InvalidConfigurationError(\"Unsupported lens PSF convolution kernel schema.\");\n const L = IRRADIANCE_CONVOLUTION_LIMITS;\n const g = requireAllowlistedRecord(r.grid, [\"width\", \"height\", \"sitePitchMicrometers\", \"opticalAxisSite\"], \"Invalid convolution grid.\");\n const width = integer(g.width, 1, L.maximumDimension, \"Invalid convolution grid size.\"), height = integer(g.height, 1, L.maximumDimension, \"Invalid convolution grid size.\");\n const pitch = requireAllowlistedRecord(g.sitePitchMicrometers, [\"x\", \"y\"], \"Invalid site pitch.\");\n const sx = positive(pitch.x, \"Site pitch must be positive.\"), sy = positive(pitch.y, \"Site pitch must be positive.\");\n const axis = requireAllowlistedRecord(g.opticalAxisSite, [\"x\", \"y\"], \"Invalid optical axis.\");\n if (typeof axis.x !== \"number\" || typeof axis.y !== \"number\" || !Number.isFinite(axis.x) || !Number.isFinite(axis.y)) {\n throw new InvalidConfigurationError(\"The optical axis must be finite site coordinates.\");\n }\n const patchWidth = integer(r.patchWidth, 1, width, \"Invalid patch size.\"), patchHeight = integer(r.patchHeight, 1, height, \"Invalid patch size.\");\n const columns = Math.ceil(width / patchWidth), rows = Math.ceil(height / patchHeight);\n if (columns * rows > L.maximumPatchCount) throw new InvalidConfigurationError(\"Too many patches.\");\n const list = r.spectralWeights;\n if (!Array.isArray(list) || list.length < 1 || list.length > LENS_PSF_CONVOLUTION_KERNELS_MAXIMUM_WAVELENGTHS) {\n throw new InvalidConfigurationError(\"spectralWeights must list 1 to \" + LENS_PSF_CONVOLUTION_KERNELS_MAXIMUM_WAVELENGTHS + \" wavelengths.\");\n }\n const spectral = list.map((entry: unknown) => {\n const e = requireAllowlistedRecord(entry, [\"wavelengthNm\", \"weight\"], \"Invalid spectral weight.\");\n if (typeof e.weight !== \"number\" || !(e.weight >= 0 && e.weight <= Number.MAX_VALUE)) throw new InvalidConfigurationError(\"Spectral weights must be finite and non-negative.\");\n return { wavelengthNm: positive(e.wavelengthNm, \"Wavelengths must be positive.\"), weight: e.weight };\n });\n const totalWeight = spectral.reduce((s, e) => s + e.weight, 0);\n if (!(totalWeight > 0 && totalWeight <= Number.MAX_VALUE)) throw new InvalidConfigurationError(\"At least one spectral weight must be positive.\");\n const psf = requireAllowlistedRecord(r.psf, [\"profile\", \"focalLengthMm\", \"focus\", \"apertureFNumber\", \"signedDefocusImagePlaneMicrometers\"], \"Invalid PSF state.\");\n // One private parse of the profile for every patch and wavelength (and, with an owned profile, for every call).\n const profile = ownedProfile ?? structuredClone(psf.profile);\n if (!ownedProfile) markEngineOwnedLensSampledPsfProfile(profile);\n const state = { ...(psf as unknown as Omit<ResolveLensSampledPsfInput, \"fieldPointMm\" | \"wavelengthNm\">), profile } as Omit<ResolveLensSampledPsfInput, \"fieldPointMm\" | \"wavelengthNm\">;\n\n // Resolve every patch and wavelength, splatting straight into one scratch displacement map sized for the largest\n // allowed radius; each patch keeps a copy cropped to its own reach. The common radius is known only at the end.\n // Every cell receives its weights in the same order as a direct sum (taps in kernel order, then the four\n // bilinear corners), so the kernels do not depend on the scratch layout.\n const M = L.maximumKernelRadius, scratchSize = 2 * M + 1, scratch = new Float64Array(scratchSize * scratchSize);\n const cropped: { reach: number; values: Float64Array }[] = [], patches: LensPsfConvolutionKernels[\"patches\"][number][] = [];\n let reach = 0, exact = true, overflow = false;\n for (let pr = 0; pr < rows; pr++) for (let pc = 0; pc < columns; pc++) {\n const x0 = pc * patchWidth, y0 = pr * patchHeight, x1 = Math.min(width, x0 + patchWidth), y1 = Math.min(height, y0 + patchHeight);\n const nativeX = ((x0 + x1) / 2 - axis.x) * sx / 1000, nativeY = ((y0 + y1) / 2 - axis.y) * sy / 1000;\n const fieldPointMm = { x: nativeX, y: -nativeY };\n let throughput = 0, interpolated = false, patchReach = 0;\n for (const { wavelengthNm, weight } of spectral) {\n if (weight === 0) continue;\n const resolved = resolveLensSampledPsf({ ...state, fieldPointMm, wavelengthNm }).value, k = resolved.kernel, share = weight / totalWeight;\n throughput += share * resolved.relativePupilThroughputFactor;\n if (resolved.resolutionStatus !== \"exact-grid-sample\") interpolated = true;\n const equalX = k.samplePitchMicrometersX === sx, equalY = k.samplePitchMicrometersY === sy;\n for (let ky = 0; ky < k.heightSamples; ky++) for (let kx = 0; kx < k.widthSamples; kx++) {\n const intensity = k.normalizedIntensity[ky * k.widthSamples + kx]!;\n if (intensity === 0) continue;\n // With equal pitches the displacement is the tap offset itself: (n·p)/p can miss n by one unit in the last place.\n const u = equalX ? kx - k.centerSampleX : (kx - k.centerSampleX) * k.samplePitchMicrometersX / sx;\n const v = equalY ? -(ky - k.centerSampleY) : -(ky - k.centerSampleY) * k.samplePitchMicrometersY / sy;\n const u0 = Math.floor(u), v0 = Math.floor(v), fu = u - u0, fv = v - v0, w = share * intensity;\n if (fu !== 0 || fv !== 0) exact = false;\n for (let corner = 0; corner < 4; corner++) {\n const du = corner & 1, dv = corner >> 1;\n const b = du === 0 ? (dv === 0 ? (1 - fu) * (1 - fv) : (1 - fu) * fv) : (dv === 0 ? fu * (1 - fv) : fu * fv);\n if (b === 0) continue;\n const cu = u0 + du, cv = v0 + dv;\n patchReach = Math.max(patchReach, Math.abs(cu), Math.abs(cv));\n // Past the largest radius the call is rejected below; resolving continues so errors keep their order.\n if (patchReach > M) { overflow = true; continue; }\n if (!overflow) scratch[(cv + M) * scratchSize + cu + M]! += w * b;\n }\n }\n }\n reach = Math.max(reach, patchReach);\n if (!overflow) {\n const n = 2 * patchReach + 1, values = new Float64Array(n * n);\n for (let v = -patchReach; v <= patchReach; v++) {\n const row = (v + M) * scratchSize + M;\n values.set(scratch.subarray(row - patchReach, row + patchReach + 1), (v + patchReach) * n);\n scratch.fill(0, row - patchReach, row + patchReach + 1);\n }\n cropped.push({ reach: patchReach, values });\n }\n patches.push(Object.freeze({ fieldPointMm: Object.freeze(fieldPointMm), relativePupilThroughputFactor: throughput, interpolated }));\n }\n const radius = r.kernelRadius === undefined ? reach : integer(r.kernelRadius, 0, L.maximumKernelRadius, \"Invalid kernel radius.\");\n if (reach > radius) throw new InvalidConfigurationError(\"The kernel radius is too small for the PSF support; no tap is dropped.\");\n if (radius > L.maximumKernelRadius) throw new InvalidConfigurationError(\"The PSF support needs a kernel radius above 32 sites.\");\n const size = 2 * radius + 1, taps = size * size;\n if (columns * rows * taps > L.maximumKernelWeights) throw new InvalidConfigurationError(\"Too many kernel weights.\");\n const kernels = new Float64Array(columns * rows * taps);\n let maximumKernelSum = 0;\n cropped.forEach(({ reach: q, values }, p) => {\n const n = 2 * q + 1;\n let sum = 0;\n for (let v = 0; v < n; v++) kernels.set(values.subarray(v * n, (v + 1) * n), p * taps + (v - q + radius) * size + radius - q);\n for (let t = 0; t < taps; t++) sum += kernels[p * taps + t]!;\n maximumKernelSum = Math.max(maximumKernelSum, sum);\n });\n if (maximumKernelSum > L.maximumKernelSum) throw new InvalidConfigurationError(\"Sampled kernels exceed unit energy.\");\n return approximationResult({ schemaVersion: LENS_PSF_CONVOLUTION_KERNELS_SCHEMA_VERSION, kernelRadius: radius, patchWidth, patchHeight,\n patchColumns: columns, patchRows: rows, kernels, exactSiteSampling: exact, maximumKernelSum, patches: Object.freeze(patches) },\n \"lens-psf-convolution-kernels\", LENS_PSF_CONVOLUTION_KERNELS_SCHEMA_VERSION, [\n \"One PSF per patch, resolved at the patch centre with resolveLensSampledPsf; indexed by source site in the convolution (isoplanatic patches).\",\n exact ? \"Every PSF tap maps to one integer site displacement (exact site sampling).\" :\n \"PSF taps between sites are split bilinearly (the adjoint of bilinear interpolation of site-centre samples); a labelled approximation.\",\n \"Relative pupil throughput is reported per patch and not applied to the unit-energy kernels.\"\n ]);\n}\n"]}
@@ -118,6 +118,37 @@ export interface SensorEnvironmentRadianceQuery {
118
118
  * computes radiance or renders.
119
119
  */
120
120
  export declare function calculateSensorEnvironmentRadianceQuery(input: CalculateSensorEnvironmentRadianceQueryInput): CalculationResult<SensorEnvironmentRadianceQuery>;
121
+ /**
122
+ * @internal The ideal (undistorted) image point of a physical sensor point (+X right, +Y up, mm) and the distortion area
123
+ * factor 1 / det(d distorted / d ideal) there; the ideal point is the sensor point itself without distortion. Shared by
124
+ * the mapped query below and the image-space defocus of `simulateCapture` (#548), so both use one arithmetic.
125
+ */
126
+ export declare function undistortedImagePoint(prepared: PreparedEnvironmentLensFieldMapping, imagePointMm: {
127
+ x: number;
128
+ y: number;
129
+ }): {
130
+ ideal: {
131
+ x: number;
132
+ y: number;
133
+ };
134
+ distortionAreaFactor: number;
135
+ };
136
+ /**
137
+ * @internal The forward distortion of an ideal image point (+X right, +Y up, mm) to the physical sensor point, with the
138
+ * singular values of d distorted / d ideal there (the largest and smallest local scale of the map; 1 and 1 without
139
+ * distortion). The inverse of {@link undistortedImagePoint} up to its solver's rounding (#548).
140
+ */
141
+ export declare function distortedImagePoint(prepared: PreparedEnvironmentLensFieldMapping, ideal: {
142
+ x: number;
143
+ y: number;
144
+ }): {
145
+ pointMm: {
146
+ x: number;
147
+ y: number;
148
+ };
149
+ largestScale: number;
150
+ smallestScale: number;
151
+ };
121
152
  /**
122
153
  * @internal Query with a lens field mapping that is already validated. The environment photo-signal
123
154
  * planner shares it, so profiles are validated once per plan.
@@ -106,21 +106,15 @@ export function calculateSensorEnvironmentRadianceQuery(input) {
106
106
  ]);
107
107
  }
108
108
  /**
109
- * @internal Query with a lens field mapping that is already validated. The environment photo-signal
110
- * planner shares it, so profiles are validated once per plan.
109
+ * @internal The ideal (undistorted) image point of a physical sensor point (+X right, +Y up, mm) and the distortion area
110
+ * factor 1 / det(d distorted / d ideal) there; the ideal point is the sensor point itself without distortion. Shared by
111
+ * the mapped query below and the image-space defocus of `simulateCapture` (#548), so both use one arithmetic.
111
112
  */
112
- export function calculateMappedSensorEnvironmentRadianceQuery(input, prepared) {
113
- if (input.timeReference !== "first-opening-boundary-phase" ||
114
- input.environmentDirectionConvention !== "outgoing-radiance-toward-camera") {
115
- throw new InvalidScientificInputError("Environment projection requires explicit opening-boundary time and outgoing-toward-camera direction conventions.");
116
- }
117
- const focus = parseFocusPlane(input.focus);
118
- const sourcePointImagePlaneMm = { x: input.sourcePointNativeSensorMm.x, y: -input.sourcePointNativeSensorMm.y };
119
- const mapping = prepared.mapping;
120
- let ideal = sourcePointImagePlaneMm;
113
+ export function undistortedImagePoint(prepared, imagePointMm) {
114
+ let ideal = imagePointMm;
121
115
  let distortionAreaFactor = 1;
122
116
  if (prepared.radial !== undefined) {
123
- ideal = calculateInverseRadialSourcePointValue(sourcePointImagePlaneMm, prepared.radial, "sourcePointNativeSensorMm").sourceImagePointMm;
117
+ ideal = calculateInverseRadialSourcePointValue(imagePointMm, prepared.radial, "sourcePointNativeSensorMm").sourceImagePointMm;
124
118
  // Radial map p -> s(r) p: det = s (s + r ds/dr) with r ds/dr = 2 r^2 s'(r^2).
125
119
  const { k1, k2, k3 } = prepared.radial.coefficients;
126
120
  const r2 = (ideal.x * ideal.x + ideal.y * ideal.y) / prepared.radial.normalizationRadiusMm ** 2;
@@ -129,13 +123,51 @@ export function calculateMappedSensorEnvironmentRadianceQuery(input, prepared) {
129
123
  distortionAreaFactor = 1 / (scale * radialDerivative);
130
124
  }
131
125
  else if (prepared.brownConrady !== undefined) {
132
- ideal = brownConradyInverseValue(prepared.brownConrady, sourcePointImagePlaneMm);
126
+ ideal = brownConradyInverseValue(prepared.brownConrady, imagePointMm);
133
127
  const j = brownConradyForwardValue(prepared.brownConrady, ideal).jacobian;
134
128
  distortionAreaFactor = 1 / (j[0] * j[3] - j[1] * j[2]);
135
129
  }
136
130
  if (!(distortionAreaFactor > 0) || !Number.isFinite(distortionAreaFactor)) {
137
131
  throw new InvalidScientificInputError("Distortion area factor must remain finite and positive.");
138
132
  }
133
+ return { ideal, distortionAreaFactor };
134
+ }
135
+ /**
136
+ * @internal The forward distortion of an ideal image point (+X right, +Y up, mm) to the physical sensor point, with the
137
+ * singular values of d distorted / d ideal there (the largest and smallest local scale of the map; 1 and 1 without
138
+ * distortion). The inverse of {@link undistortedImagePoint} up to its solver's rounding (#548).
139
+ */
140
+ export function distortedImagePoint(prepared, ideal) {
141
+ if (prepared.radial !== undefined) {
142
+ const { k1, k2, k3 } = prepared.radial.coefficients;
143
+ const r2 = (ideal.x * ideal.x + ideal.y * ideal.y) / prepared.radial.normalizationRadiusMm ** 2;
144
+ const scale = 1 + k1 * r2 + k2 * r2 * r2 + k3 * r2 * r2 * r2;
145
+ // Tangential scale s, radial scale s + r ds/dr (the two eigenvalues of the symmetric Jacobian of p -> s(r) p).
146
+ const radialDerivative = 1 + 3 * k1 * r2 + 5 * k2 * r2 * r2 + 7 * k3 * r2 * r2 * r2;
147
+ return { pointMm: { x: ideal.x * scale, y: ideal.y * scale }, largestScale: Math.max(scale, radialDerivative), smallestScale: Math.min(scale, radialDerivative) };
148
+ }
149
+ if (prepared.brownConrady !== undefined) {
150
+ const forward = brownConradyForwardValue(prepared.brownConrady, ideal), [a, b, c, d] = forward.jacobian;
151
+ // Singular values of [[a, b], [c, d]]: sqrt of the eigenvalues of J^T J.
152
+ const p = a * a + b * b + c * c + d * d, q = Math.abs(a * d - b * c), root = Math.sqrt(Math.max(0, p * p - 4 * q * q));
153
+ const largest = Math.sqrt((p + root) / 2);
154
+ return { pointMm: forward.mappedImagePointMm, largestScale: largest, smallestScale: largest > 0 ? q / largest : 0 };
155
+ }
156
+ return { pointMm: { ...ideal }, largestScale: 1, smallestScale: 1 };
157
+ }
158
+ /**
159
+ * @internal Query with a lens field mapping that is already validated. The environment photo-signal
160
+ * planner shares it, so profiles are validated once per plan.
161
+ */
162
+ export function calculateMappedSensorEnvironmentRadianceQuery(input, prepared) {
163
+ if (input.timeReference !== "first-opening-boundary-phase" ||
164
+ input.environmentDirectionConvention !== "outgoing-radiance-toward-camera") {
165
+ throw new InvalidScientificInputError("Environment projection requires explicit opening-boundary time and outgoing-toward-camera direction conventions.");
166
+ }
167
+ const focus = parseFocusPlane(input.focus);
168
+ const sourcePointImagePlaneMm = { x: input.sourcePointNativeSensorMm.x, y: -input.sourcePointNativeSensorMm.y };
169
+ const mapping = prepared.mapping;
170
+ const { ideal, distortionAreaFactor } = undistortedImagePoint(prepared, sourcePointImagePlaneMm);
139
171
  let projection = null;
140
172
  let look;
141
173
  let projectionScaleMm;
@@ -1 +1 @@
1
- {"version":3,"file":"sensor-environment-query.js","sourceRoot":"","sources":["../../src/optics/sensor-environment-query.ts"],"names":[],"mappings":"AAAA,sCAAsC;AAEtC;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,EAAE,mBAAmB,EAA0B,MAAM,+BAA+B,CAAC;AAC5F,OAAO,EAAE,2BAA2B,EAAE,MAAM,uBAAuB,CAAC;AACpE,OAAO,EAAE,2BAA2B,EAAE,0CAA0C,EACzC,MAAM,8BAA8B,CAAC;AAC5E,OAAO,EAAE,4BAA4B,EAAE,wBAAwB,EAA4B,MAAM,8BAA8B,CAAC;AAChI,OAAO,EACL,sCAAsC,EAAE,+BAA+B,EACxE,MAAM,wBAAwB,CAAC;AAChC,OAAO,EACL,wBAAwB,EAAE,wBAAwB,EAAE,qCAAqC,EAE1F,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,8BAA8B,EAAE,MAAM,gBAAgB,CAAC;AAChE,OAAO,EAAE,mCAAmC,EAAuC,MAAM,6BAA6B,CAAC;AACvH,OAAO,EAAE,eAAe,EAAmB,MAAM,kBAAkB,CAAC;AACpE,OAAO,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AAChE,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAC3E,OAAO,EAAE,MAAM,EAAE,MAAM,0BAA0B,CAAC;AAwBlD,kGAAkG;AAClG,MAAM,UAAU,kCAAkC,CAAC,KAAc;IAC/D,IAAI,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AC,EAAE,CAAC,IAAI,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;IACpH,OAAO,mBAAmB,CAAC,EAAE,OAAO,EAAE,yBAAyB,EAAE,EAAE,GAAG,KAAK,CAAC,yBAAyB,EAAE;QACrG,uBAAuB,EAAE,gCAAgC,EAAE,IAAI,EAAE,UAAU;QAC3E,gBAAgB,EAAE,EAAE,eAAe,EAAE,OAAO,CAAC,eAAe,EAAE,cAAc,EAAE,OAAO,CAAC,UAAU,CAAC,IAAI;YACnG,iBAAiB,EAAE,EAAE,GAAG,KAAK,EAAE,EAAE,iBAAiB,EAAE,oBAAoB,EAAE;QAC5E,aAAa,EAAE,qDAAqD,EAAE,mBAAmB,EAAE,iCAAiC;QAC5H,gCAAgC,EAAE,IAAI,EAAE,2BAA2B,EAAE,KAAK,EAAE,oBAAoB,EAAE,KAAK,EAAE,gBAAgB,EAAE,KAAK;KACjI,EAAE,+CAA+C,EAAE,OAAO,EAAE;QAC3D,qLAAqL;QACrL,iLAAiL;QACjL,qLAAqL;QACrL,mGAAmG;KACpG,CAAC,CAAC;AACL,CAAC","sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Builds an environment radiance request from points on the physical sensor. It uses the existing\n * focus-aware ideal projection and the analytic inverse camera rotation.\n *\n * Native Y (+Y down) is inverted explicitly. The direction sent to the provider points opposite the\n * look ray at exposure start, because radiance travels toward the camera. This module does not\n * intersect the scene, compute radiance or render anything.\n *\n * Optional lens field mapping (2.0):\n * 1. The physical sensor point is inverse-distorted (radial or Brown-Conrady) to the ideal image\n * point.\n * 2. That point is unprojected with the declared ideal projection (rectilinear, fisheye or\n * equirectangular), at the same focus-aware projection scale.\n * 3. The ray is rotated to the camera axes at exposure start.\n * The local area factor 1 / det(d distorted / d ideal) is reported. The caller applies it to\n * irradiance exactly once. Without the mapping, the existing rectilinear computation is unchanged.\n * @see docs/PHYSICS_FOUNDATION.md for the equations, units, coordinate conventions, known blockers\n * and support limits.\n */\n\nimport { approximationResult, type CalculationResult } from \"../core/calculation-result.js\";\nimport { InvalidScientificInputError } from \"../core/validation.js\";\nimport { applyPhysicalCameraRotation, calculateInverseCameraRotationImageMapping,\n type CameraAngularVelocityRadPerSec } from \"../motion/camera-rotation.js\";\nimport { lensProjectionDirectionValue, parseLensProjectionModel, type LensProjectionModel } from \"../camera/lens-projection.js\";\nimport {\n calculateInverseRadialSourcePointValue, validateRadialDistortionProfile, type RadialDistortionProfile, type ValidatedRadialProfile\n} from \"./radial-distortion.js\";\nimport {\n brownConradyForwardValue, brownConradyInverseValue, validateBrownConradyDistortionProfile,\n type BrownConradyDistortionProfile, type ValidatedBrownConradyDistortionProfile\n} from \"./brown-conrady-distortion.js\";\nimport { calculateThinLensImageDistance } from \"./thin-lens.js\";\nimport { parseSceneRadianceEvaluationRequest, type SceneRadianceEvaluationRequest } from \"../schema/scene-radiance.js\";\nimport { parseFocusPlane, type FocusPlane } from \"./focus-state.js\";\nimport { requireInputKeys } from \"../core/record-validation.js\";\nimport { InvalidConfigurationError } from \"../core/configuration-error.js\";\nimport { hypot3 } from \"../core/portable-math.js\";\n\n/**\n * Lens field mapping between the physical (distorted) sensor point and the scene ray (2.0).\n * `radiometricAreaCorrection` states who applies the distortion area factor. The environment\n * photo signal multiplies irradiance by 1 / det(d distorted / d ideal) exactly once. A supplied\n * field-throughput profile must therefore not include it as well.\n */\nexport interface EnvironmentLensFieldMapping {\n projectionModel: LensProjectionModel;\n distortion:\n | { kind: \"none\" }\n | { kind: \"radial\"; profile: RadialDistortionProfile }\n | { kind: \"brown-conrady\"; profile: BrownConradyDistortionProfile };\n radiometricAreaCorrection: \"inverse-distortion-jacobian\";\n}\n\n/** @internal Parsed mapping with validated profiles, reused across one plan's queries. */\nexport interface PreparedEnvironmentLensFieldMapping {\n mapping: EnvironmentLensFieldMapping;\n radial?: ValidatedRadialProfile;\n brownConrady?: ValidatedBrownConradyDistortionProfile;\n}\n\n/** @internal Strict parse and validation of a lens field mapping. Unknown fields are rejected. */\nexport function prepareEnvironmentLensFieldMapping(value: unknown): PreparedEnvironmentLensFieldMapping {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new InvalidConfigurationError(\"lensFieldMapping must be an object.\");\n }\n const record = value as Record<string, unknown>;\n for (const key of Object.keys(record)) {\n if (![\"projectionModel\", \"distortion\", \"radiometricAreaCorrection\"].includes(key)) {\n throw new InvalidConfigurationError(`lensFieldMapping has unknown field ${JSON.stringify(key)}.`);\n }\n }\n if (record.radiometricAreaCorrection !== \"inverse-distortion-jacobian\") {\n throw new InvalidConfigurationError(\"lensFieldMapping.radiometricAreaCorrection must be \\\"inverse-distortion-jacobian\\\".\");\n }\n const projectionModel = parseLensProjectionModel(record.projectionModel);\n const distortion = record.distortion as EnvironmentLensFieldMapping[\"distortion\"] | undefined;\n if (typeof distortion !== \"object\" || distortion === null) {\n throw new InvalidConfigurationError(\"lensFieldMapping.distortion must be an object.\");\n }\n if (distortion.kind === \"none\") {\n return { mapping: { projectionModel, distortion: { kind: \"none\" }, radiometricAreaCorrection: \"inverse-distortion-jacobian\" } };\n }\n if (distortion.kind === \"radial\") {\n const radial = validateRadialDistortionProfile(distortion.profile);\n return { mapping: { projectionModel, distortion: { kind: \"radial\", profile: distortion.profile },\n radiometricAreaCorrection: \"inverse-distortion-jacobian\" }, radial };\n }\n if (distortion.kind === \"brown-conrady\") {\n const brownConrady = validateBrownConradyDistortionProfile(distortion.profile);\n return { mapping: { projectionModel, distortion: { kind: \"brown-conrady\", profile: distortion.profile },\n radiometricAreaCorrection: \"inverse-distortion-jacobian\" }, brownConrady };\n }\n throw new InvalidConfigurationError(\"lensFieldMapping.distortion.kind must be none, radial or brown-conrady.\");\n}\n\nexport interface CalculateSensorEnvironmentRadianceQueryInput {\n /** Optical sample point before the anti-aliasing filter or PSF. Native +X right, +Y down, in mm from the optical axis. */\n sourcePointNativeSensorMm: { x: number; y: number };\n focalLengthMm: number;\n focus: FocusPlane;\n angularVelocityRadPerSec: CameraAngularVelocityRadPerSec;\n /** States that the moment the shutter opens is t=0 in the rotation model. */\n timeReference: \"first-opening-boundary-phase\";\n timeSecondsFromOpeningReference: number;\n /** The request uses the direction radiance travels: toward the camera, opposite the look ray. */\n environmentDirectionConvention: \"outgoing-radiance-toward-camera\";\n request: Omit<SceneRadianceEvaluationRequest, \"target\" | \"timeSecondsFromExposureStart\">;\n /** Optional 2.0 lens field mapping. Omit it for the ideal rectilinear, distortion-free query. */\n lensFieldMapping?: EnvironmentLensFieldMapping;\n}\n\nexport interface SensorEnvironmentLensFieldMappingResult {\n projectionModel: LensProjectionModel;\n distortionKind: \"none\" | \"radial\" | \"brown-conrady\";\n /** Ideal (undistorted) image-plane point, +X right / +Y up, mm. */\n idealImagePointMm: { x: number; y: number };\n /** Projection scale: thin-lens image distance at finite focus, focal length at infinity, mm. */\n projectionScaleMm: number;\n /** 1 / det(d distorted / d ideal) at this point; 1 without distortion. */\n distortionAreaFactor: number;\n}\n\nexport interface SensorEnvironmentRadianceQuery {\n request: SceneRadianceEvaluationRequest;\n sourcePointNativeSensorMm: { x: number; y: number };\n sourcePointImagePlaneMm: { x: number; y: number };\n referenceLookDirectionUnitVector: { x: number; y: number; z: number };\n /** Rectilinear rotation mapping. Null when a non-rectilinear lens field mapping is used. */\n projection: ReturnType<typeof calculateInverseCameraRotationImageMapping> | null;\n /** Present only when the input declared a lens field mapping. */\n lensFieldMapping?: SensorEnvironmentLensFieldMappingResult;\n targetMeaning: \"environment-direction-in-exposure-start-camera-axes\";\n directionConvention: \"outgoing-radiance-toward-camera\";\n geometricRayProjectionCalculated: true;\n sceneIntersectionCalculated: false;\n visibilityCalculated: false;\n providerExecuted: false;\n}\n\n/**\n * Builds an environment radiance request from points on the physical sensor,\n * using the existing focus-aware ideal projection and the analytic inverse\n * camera rotation.\n *\n * Native Y (+Y down) is inverted explicitly. The provider direction points\n * opposite the look ray at exposure start. Nothing intersects the scene,\n * computes radiance or renders.\n */\nexport function calculateSensorEnvironmentRadianceQuery(\n input: CalculateSensorEnvironmentRadianceQueryInput\n): CalculationResult<SensorEnvironmentRadianceQuery> {\n requireInputKeys(input, \"calculateSensorEnvironmentRadianceQuery\", [\"sourcePointNativeSensorMm\", \"focalLengthMm\", \"focus\", \"angularVelocityRadPerSec\", \"timeReference\", \"timeSecondsFromOpeningReference\", \"environmentDirectionConvention\", \"request\", \"lensFieldMapping\"]);\n if (input.lensFieldMapping !== undefined) {\n return calculateMappedSensorEnvironmentRadianceQuery(input, prepareEnvironmentLensFieldMapping(input.lensFieldMapping));\n }\n if (input.timeReference !== \"first-opening-boundary-phase\" ||\n input.environmentDirectionConvention !== \"outgoing-radiance-toward-camera\") {\n throw new InvalidScientificInputError(\"Environment projection requires explicit opening-boundary time and outgoing-toward-camera direction conventions.\");\n }\n const focus = parseFocusPlane(input.focus);\n const sourcePointImagePlaneMm = { x: input.sourcePointNativeSensorMm.x, y: -input.sourcePointNativeSensorMm.y };\n const projection = calculateInverseCameraRotationImageMapping({ focalLengthMm: input.focalLengthMm,\n imagePointMm: sourcePointImagePlaneMm, angularVelocityRadPerSec: input.angularVelocityRadPerSec,\n timeSecondsFromExposureStart: input.timeSecondsFromOpeningReference,\n ...(focus.kind === \"finite\" ? { focusDistanceM: focus.distanceM } : {}) });\n const point = projection.value.referenceImagePointMm, z = projection.value.projectionDistanceMm;\n const length = hypot3(point.x, point.y, z);\n const referenceLookDirectionUnitVector = { x: point.x/length, y: point.y/length, z: z/length };\n const ray = referenceLookDirectionUnitVector;\n const request = parseSceneRadianceEvaluationRequest({ ...input.request,\n timeSecondsFromExposureStart: input.timeSecondsFromOpeningReference,\n target: { kind: \"environment-direction\", outgoingDirectionUnitVector: { x: -ray.x, y: -ray.y, z: -ray.z } } });\n return approximationResult({ request, sourcePointNativeSensorMm: { ...input.sourcePointNativeSensorMm },\n sourcePointImagePlaneMm, referenceLookDirectionUnitVector, projection,\n targetMeaning: \"environment-direction-in-exposure-start-camera-axes\", directionConvention: \"outgoing-radiance-toward-camera\",\n geometricRayProjectionCalculated: true, sceneIntersectionCalculated: false, visibilityCalculated: false, providerExecuted: false\n }, \"sensor-environment-radiance-query\", \"0.1.0\", [\n \"Ideal focus-aware rectilinear projection and constant-axis pure camera rotation; reference ray must stay in the forward hemisphere.\",\n \"The environment and rotation reference axes coincide with camera axes at the first opening boundary by explicit convention.\",\n \"Lens distortion, breathing, chromatic field mapping, translation/parallax and scene intersections remain separate.\"\n ]);\n}\n\n/**\n * @internal Query with a lens field mapping that is already validated. The environment photo-signal\n * planner shares it, so profiles are validated once per plan.\n */\nexport function calculateMappedSensorEnvironmentRadianceQuery(\n input: CalculateSensorEnvironmentRadianceQueryInput,\n prepared: PreparedEnvironmentLensFieldMapping\n): CalculationResult<SensorEnvironmentRadianceQuery> {\n if (input.timeReference !== \"first-opening-boundary-phase\" ||\n input.environmentDirectionConvention !== \"outgoing-radiance-toward-camera\") {\n throw new InvalidScientificInputError(\"Environment projection requires explicit opening-boundary time and outgoing-toward-camera direction conventions.\");\n }\n const focus = parseFocusPlane(input.focus);\n const sourcePointImagePlaneMm = { x: input.sourcePointNativeSensorMm.x, y: -input.sourcePointNativeSensorMm.y };\n const mapping = prepared.mapping;\n let ideal = sourcePointImagePlaneMm;\n let distortionAreaFactor = 1;\n if (prepared.radial !== undefined) {\n ideal = calculateInverseRadialSourcePointValue(sourcePointImagePlaneMm, prepared.radial, \"sourcePointNativeSensorMm\").sourceImagePointMm;\n // Radial map p -> s(r) p: det = s (s + r ds/dr) with r ds/dr = 2 r^2 s'(r^2).\n const { k1, k2, k3 } = prepared.radial.coefficients;\n const r2 = (ideal.x*ideal.x+ideal.y*ideal.y)/prepared.radial.normalizationRadiusMm**2;\n const scale = 1+k1*r2+k2*r2*r2+k3*r2*r2*r2;\n const radialDerivative = 1+3*k1*r2+5*k2*r2*r2+7*k3*r2*r2*r2;\n distortionAreaFactor = 1/(scale*radialDerivative);\n } else if (prepared.brownConrady !== undefined) {\n ideal = brownConradyInverseValue(prepared.brownConrady, sourcePointImagePlaneMm);\n const j = brownConradyForwardValue(prepared.brownConrady, ideal).jacobian;\n distortionAreaFactor = 1/(j[0]*j[3]-j[1]*j[2]);\n }\n if (!(distortionAreaFactor > 0) || !Number.isFinite(distortionAreaFactor)) {\n throw new InvalidScientificInputError(\"Distortion area factor must remain finite and positive.\");\n }\n let projection: ReturnType<typeof calculateInverseCameraRotationImageMapping> | null = null;\n let look: { x: number; y: number; z: number };\n let projectionScaleMm: number;\n if (mapping.projectionModel === \"rectilinear\") {\n projection = calculateInverseCameraRotationImageMapping({ focalLengthMm: input.focalLengthMm,\n imagePointMm: ideal, angularVelocityRadPerSec: input.angularVelocityRadPerSec,\n timeSecondsFromExposureStart: input.timeSecondsFromOpeningReference,\n ...(focus.kind === \"finite\" ? { focusDistanceM: focus.distanceM } : {}) });\n const point = projection.value.referenceImagePointMm, z = projection.value.projectionDistanceMm;\n const length = hypot3(point.x, point.y, z);\n look = { x: point.x/length, y: point.y/length, z: z/length };\n projectionScaleMm = z;\n } else {\n projectionScaleMm = focus.kind === \"finite\"\n ? calculateThinLensImageDistance({ focalLengthMm: input.focalLengthMm, objectDistanceM: focus.distanceM }).value.imageDistanceMm\n : input.focalLengthMm;\n const velocity = input.angularVelocityRadPerSec;\n const t = input.timeSecondsFromOpeningReference;\n if (typeof t !== \"number\" || !Number.isFinite(t) || t < 0) {\n throw new InvalidScientificInputError(\"timeSecondsFromOpeningReference must be finite and non-negative.\");\n }\n const captured = lensProjectionDirectionValue(mapping.projectionModel, projectionScaleMm, ideal.x, ideal.y);\n const reference = applyPhysicalCameraRotation(captured,\n { pitch: velocity.pitch*t, yaw: velocity.yaw*t, roll: velocity.roll*t }, \"camera-to-reference\");\n const length = hypot3(reference.x, reference.y, reference.z);\n if (!(length > 0) || !Number.isFinite(length)) throw new InvalidScientificInputError(\"Mapped reference ray must be finite.\");\n look = { x: reference.x/length, y: reference.y/length, z: reference.z/length };\n }\n const request = parseSceneRadianceEvaluationRequest({ ...input.request,\n timeSecondsFromExposureStart: input.timeSecondsFromOpeningReference,\n target: { kind: \"environment-direction\", outgoingDirectionUnitVector: { x: -look.x, y: -look.y, z: -look.z } } });\n return approximationResult({ request, sourcePointNativeSensorMm: { ...input.sourcePointNativeSensorMm },\n sourcePointImagePlaneMm, referenceLookDirectionUnitVector: look, projection,\n lensFieldMapping: { projectionModel: mapping.projectionModel, distortionKind: mapping.distortion.kind,\n idealImagePointMm: { ...ideal }, projectionScaleMm, distortionAreaFactor },\n targetMeaning: \"environment-direction-in-exposure-start-camera-axes\", directionConvention: \"outgoing-radiance-toward-camera\",\n geometricRayProjectionCalculated: true, sceneIntersectionCalculated: false, visibilityCalculated: false, providerExecuted: false\n }, \"lens-mapped-sensor-environment-radiance-query\", \"0.1.0\", [\n \"The physical sensor point is inverse-distorted to the ideal image point, then unprojected with the declared ideal projection and rotated by the constant-axis pure camera rotation.\",\n \"Projection scale is the thin-lens image distance at finite focus (focal length at infinity) for every projection model; a calibrated finite-focus fisheye scale is not modeled.\",\n \"The distortion area factor 1/det(d distorted/d ideal) is reported for exactly-once application to irradiance; field throughput, PSF and pupil models are not changed by this query.\",\n \"Breathing, chromatic field mapping, translation/parallax and scene intersections remain separate.\"\n ]);\n}\n"]}
1
+ {"version":3,"file":"sensor-environment-query.js","sourceRoot":"","sources":["../../src/optics/sensor-environment-query.ts"],"names":[],"mappings":"AAAA,sCAAsC;AAEtC;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,EAAE,mBAAmB,EAA0B,MAAM,+BAA+B,CAAC;AAC5F,OAAO,EAAE,2BAA2B,EAAE,MAAM,uBAAuB,CAAC;AACpE,OAAO,EAAE,2BAA2B,EAAE,0CAA0C,EACzC,MAAM,8BAA8B,CAAC;AAC5E,OAAO,EAAE,4BAA4B,EAAE,wBAAwB,EAA4B,MAAM,8BAA8B,CAAC;AAChI,OAAO,EACL,sCAAsC,EAAE,+BAA+B,EACxE,MAAM,wBAA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E,CAAC,EAAE,SAAS,CAAC,CAAC,GAAC,MAAM,EAAE,CAAC;IACjF,CAAC;IACD,MAAM,OAAO,GAAG,mCAAmC,CAAC,EAAE,GAAG,KAAK,CAAC,OAAO;QACpE,4BAA4B,EAAE,KAAK,CAAC,+BAA+B;QACnE,MAAM,EAAE,EAAE,IAAI,EAAE,uBAAuB,EAAE,2BAA2B,EAAE,EAAE,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;IACpH,OAAO,mBAAmB,CAAC,EAAE,OAAO,EAAE,yBAAyB,EAAE,EAAE,GAAG,KAAK,CAAC,yBAAyB,EAAE;QACrG,uBAAuB,EAAE,gCAAgC,EAAE,IAAI,EAAE,UAAU;QAC3E,gBAAgB,EAAE,EAAE,eAAe,EAAE,OAAO,CAAC,eAAe,EAAE,cAAc,EAAE,OAAO,CAAC,UAAU,CAAC,IAAI;YACnG,iBAAiB,EAAE,EAAE,GAAG,KAAK,EAAE,EAAE,iBAAiB,EAAE,oBAAoB,EAAE;QAC5E,aAAa,EAAE,qDAAqD,EAAE,mBAAmB,EAAE,iCAAiC;QAC5H,gCAAgC,EAAE,IAAI,EAAE,2BAA2B,EAAE,KAAK,EAAE,oBAAoB,EAAE,KAAK,EAAE,gBAAgB,EAAE,KAAK;KACjI,EAAE,+CAA+C,EAAE,OAAO,EAAE;QAC3D,qLAAqL;QACrL,iLAAiL;QACjL,qLAAqL;QACrL,mGAAmG;KACpG,CAAC,CAAC;AACL,CAAC","sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Builds an environment radiance request from points on the physical sensor. It uses the existing\n * focus-aware ideal projection and the analytic inverse camera rotation.\n *\n * Native Y (+Y down) is inverted explicitly. The direction sent to the provider points opposite the\n * look ray at exposure start, because radiance travels toward the camera. This module does not\n * intersect the scene, compute radiance or render anything.\n *\n * Optional lens field mapping (2.0):\n * 1. The physical sensor point is inverse-distorted (radial or Brown-Conrady) to the ideal image\n * point.\n * 2. That point is unprojected with the declared ideal projection (rectilinear, fisheye or\n * equirectangular), at the same focus-aware projection scale.\n * 3. The ray is rotated to the camera axes at exposure start.\n * The local area factor 1 / det(d distorted / d ideal) is reported. The caller applies it to\n * irradiance exactly once. Without the mapping, the existing rectilinear computation is unchanged.\n * @see docs/PHYSICS_FOUNDATION.md for the equations, units, coordinate conventions, known blockers\n * and support limits.\n */\n\nimport { approximationResult, type CalculationResult } from \"../core/calculation-result.js\";\nimport { InvalidScientificInputError } from \"../core/validation.js\";\nimport { applyPhysicalCameraRotation, calculateInverseCameraRotationImageMapping,\n type CameraAngularVelocityRadPerSec } from \"../motion/camera-rotation.js\";\nimport { lensProjectionDirectionValue, parseLensProjectionModel, type LensProjectionModel } from \"../camera/lens-projection.js\";\nimport {\n calculateInverseRadialSourcePointValue, validateRadialDistortionProfile, type RadialDistortionProfile, type ValidatedRadialProfile\n} from \"./radial-distortion.js\";\nimport {\n brownConradyForwardValue, brownConradyInverseValue, validateBrownConradyDistortionProfile,\n type BrownConradyDistortionProfile, type ValidatedBrownConradyDistortionProfile\n} from \"./brown-conrady-distortion.js\";\nimport { calculateThinLensImageDistance } from \"./thin-lens.js\";\nimport { parseSceneRadianceEvaluationRequest, type SceneRadianceEvaluationRequest } from \"../schema/scene-radiance.js\";\nimport { parseFocusPlane, type FocusPlane } from \"./focus-state.js\";\nimport { requireInputKeys } from \"../core/record-validation.js\";\nimport { InvalidConfigurationError } from \"../core/configuration-error.js\";\nimport { hypot3 } from \"../core/portable-math.js\";\n\n/**\n * Lens field mapping between the physical (distorted) sensor point and the scene ray (2.0).\n * `radiometricAreaCorrection` states who applies the distortion area factor. The environment\n * photo signal multiplies irradiance by 1 / det(d distorted / d ideal) exactly once. A supplied\n * field-throughput profile must therefore not include it as well.\n */\nexport interface EnvironmentLensFieldMapping {\n projectionModel: LensProjectionModel;\n distortion:\n | { kind: \"none\" }\n | { kind: \"radial\"; profile: RadialDistortionProfile }\n | { kind: \"brown-conrady\"; profile: BrownConradyDistortionProfile };\n radiometricAreaCorrection: \"inverse-distortion-jacobian\";\n}\n\n/** @internal Parsed mapping with validated profiles, reused across one plan's queries. */\nexport interface PreparedEnvironmentLensFieldMapping {\n mapping: EnvironmentLensFieldMapping;\n radial?: ValidatedRadialProfile;\n brownConrady?: ValidatedBrownConradyDistortionProfile;\n}\n\n/** @internal Strict parse and validation of a lens field mapping. Unknown fields are rejected. */\nexport function prepareEnvironmentLensFieldMapping(value: unknown): PreparedEnvironmentLensFieldMapping {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new InvalidConfigurationError(\"lensFieldMapping must be an object.\");\n }\n const record = value as Record<string, unknown>;\n for (const key of Object.keys(record)) {\n if (![\"projectionModel\", \"distortion\", \"radiometricAreaCorrection\"].includes(key)) {\n throw new InvalidConfigurationError(`lensFieldMapping has unknown field ${JSON.stringify(key)}.`);\n }\n }\n if (record.radiometricAreaCorrection !== \"inverse-distortion-jacobian\") {\n throw new InvalidConfigurationError(\"lensFieldMapping.radiometricAreaCorrection must be \\\"inverse-distortion-jacobian\\\".\");\n }\n const projectionModel = parseLensProjectionModel(record.projectionModel);\n const distortion = record.distortion as EnvironmentLensFieldMapping[\"distortion\"] | undefined;\n if (typeof distortion !== \"object\" || distortion === null) {\n throw new InvalidConfigurationError(\"lensFieldMapping.distortion must be an object.\");\n }\n if (distortion.kind === \"none\") {\n return { mapping: { projectionModel, distortion: { kind: \"none\" }, radiometricAreaCorrection: \"inverse-distortion-jacobian\" } };\n }\n if (distortion.kind === \"radial\") {\n const radial = validateRadialDistortionProfile(distortion.profile);\n return { mapping: { projectionModel, distortion: { kind: \"radial\", profile: distortion.profile },\n radiometricAreaCorrection: \"inverse-distortion-jacobian\" }, radial };\n }\n if (distortion.kind === \"brown-conrady\") {\n const brownConrady = validateBrownConradyDistortionProfile(distortion.profile);\n return { mapping: { projectionModel, distortion: { kind: \"brown-conrady\", profile: distortion.profile },\n radiometricAreaCorrection: \"inverse-distortion-jacobian\" }, brownConrady };\n }\n throw new InvalidConfigurationError(\"lensFieldMapping.distortion.kind must be none, radial or brown-conrady.\");\n}\n\nexport interface CalculateSensorEnvironmentRadianceQueryInput {\n /** Optical sample point before the anti-aliasing filter or PSF. Native +X right, +Y down, in mm from the optical axis. */\n sourcePointNativeSensorMm: { x: number; y: number };\n focalLengthMm: number;\n focus: FocusPlane;\n angularVelocityRadPerSec: CameraAngularVelocityRadPerSec;\n /** States that the moment the shutter opens is t=0 in the rotation model. */\n timeReference: \"first-opening-boundary-phase\";\n timeSecondsFromOpeningReference: number;\n /** The request uses the direction radiance travels: toward the camera, opposite the look ray. */\n environmentDirectionConvention: \"outgoing-radiance-toward-camera\";\n request: Omit<SceneRadianceEvaluationRequest, \"target\" | \"timeSecondsFromExposureStart\">;\n /** Optional 2.0 lens field mapping. Omit it for the ideal rectilinear, distortion-free query. */\n lensFieldMapping?: EnvironmentLensFieldMapping;\n}\n\nexport interface SensorEnvironmentLensFieldMappingResult {\n projectionModel: LensProjectionModel;\n distortionKind: \"none\" | \"radial\" | \"brown-conrady\";\n /** Ideal (undistorted) image-plane point, +X right / +Y up, mm. */\n idealImagePointMm: { x: number; y: number };\n /** Projection scale: thin-lens image distance at finite focus, focal length at infinity, mm. */\n projectionScaleMm: number;\n /** 1 / det(d distorted / d ideal) at this point; 1 without distortion. */\n distortionAreaFactor: number;\n}\n\nexport interface SensorEnvironmentRadianceQuery {\n request: SceneRadianceEvaluationRequest;\n sourcePointNativeSensorMm: { x: number; y: number };\n sourcePointImagePlaneMm: { x: number; y: number };\n referenceLookDirectionUnitVector: { x: number; y: number; z: number };\n /** Rectilinear rotation mapping. Null when a non-rectilinear lens field mapping is used. */\n projection: ReturnType<typeof calculateInverseCameraRotationImageMapping> | null;\n /** Present only when the input declared a lens field mapping. */\n lensFieldMapping?: SensorEnvironmentLensFieldMappingResult;\n targetMeaning: \"environment-direction-in-exposure-start-camera-axes\";\n directionConvention: \"outgoing-radiance-toward-camera\";\n geometricRayProjectionCalculated: true;\n sceneIntersectionCalculated: false;\n visibilityCalculated: false;\n providerExecuted: false;\n}\n\n/**\n * Builds an environment radiance request from points on the physical sensor,\n * using the existing focus-aware ideal projection and the analytic inverse\n * camera rotation.\n *\n * Native Y (+Y down) is inverted explicitly. The provider direction points\n * opposite the look ray at exposure start. Nothing intersects the scene,\n * computes radiance or renders.\n */\nexport function calculateSensorEnvironmentRadianceQuery(\n input: CalculateSensorEnvironmentRadianceQueryInput\n): CalculationResult<SensorEnvironmentRadianceQuery> {\n requireInputKeys(input, \"calculateSensorEnvironmentRadianceQuery\", [\"sourcePointNativeSensorMm\", \"focalLengthMm\", \"focus\", \"angularVelocityRadPerSec\", \"timeReference\", \"timeSecondsFromOpeningReference\", \"environmentDirectionConvention\", \"request\", \"lensFieldMapping\"]);\n if (input.lensFieldMapping !== undefined) {\n return calculateMappedSensorEnvironmentRadianceQuery(input, prepareEnvironmentLensFieldMapping(input.lensFieldMapping));\n }\n if (input.timeReference !== \"first-opening-boundary-phase\" ||\n input.environmentDirectionConvention !== \"outgoing-radiance-toward-camera\") {\n throw new InvalidScientificInputError(\"Environment projection requires explicit opening-boundary time and outgoing-toward-camera direction conventions.\");\n }\n const focus = parseFocusPlane(input.focus);\n const sourcePointImagePlaneMm = { x: input.sourcePointNativeSensorMm.x, y: -input.sourcePointNativeSensorMm.y };\n const projection = calculateInverseCameraRotationImageMapping({ focalLengthMm: input.focalLengthMm,\n imagePointMm: sourcePointImagePlaneMm, angularVelocityRadPerSec: input.angularVelocityRadPerSec,\n timeSecondsFromExposureStart: input.timeSecondsFromOpeningReference,\n ...(focus.kind === \"finite\" ? { focusDistanceM: focus.distanceM } : {}) });\n const point = projection.value.referenceImagePointMm, z = projection.value.projectionDistanceMm;\n const length = hypot3(point.x, point.y, z);\n const referenceLookDirectionUnitVector = { x: point.x/length, y: point.y/length, z: z/length };\n const ray = referenceLookDirectionUnitVector;\n const request = parseSceneRadianceEvaluationRequest({ ...input.request,\n timeSecondsFromExposureStart: input.timeSecondsFromOpeningReference,\n target: { kind: \"environment-direction\", outgoingDirectionUnitVector: { x: -ray.x, y: -ray.y, z: -ray.z } } });\n return approximationResult({ request, sourcePointNativeSensorMm: { ...input.sourcePointNativeSensorMm },\n sourcePointImagePlaneMm, referenceLookDirectionUnitVector, projection,\n targetMeaning: \"environment-direction-in-exposure-start-camera-axes\", directionConvention: \"outgoing-radiance-toward-camera\",\n geometricRayProjectionCalculated: true, sceneIntersectionCalculated: false, visibilityCalculated: false, providerExecuted: false\n }, \"sensor-environment-radiance-query\", \"0.1.0\", [\n \"Ideal focus-aware rectilinear projection and constant-axis pure camera rotation; reference ray must stay in the forward hemisphere.\",\n \"The environment and rotation reference axes coincide with camera axes at the first opening boundary by explicit convention.\",\n \"Lens distortion, breathing, chromatic field mapping, translation/parallax and scene intersections remain separate.\"\n ]);\n}\n\n/**\n * @internal The ideal (undistorted) image point of a physical sensor point (+X right, +Y up, mm) and the distortion area\n * factor 1 / det(d distorted / d ideal) there; the ideal point is the sensor point itself without distortion. Shared by\n * the mapped query below and the image-space defocus of `simulateCapture` (#548), so both use one arithmetic.\n */\nexport function undistortedImagePoint(prepared: PreparedEnvironmentLensFieldMapping, imagePointMm: { x: number; y: number }):\n { ideal: { x: number; y: number }; distortionAreaFactor: number } {\n let ideal = imagePointMm;\n let distortionAreaFactor = 1;\n if (prepared.radial !== undefined) {\n ideal = calculateInverseRadialSourcePointValue(imagePointMm, prepared.radial, \"sourcePointNativeSensorMm\").sourceImagePointMm;\n // Radial map p -> s(r) p: det = s (s + r ds/dr) with r ds/dr = 2 r^2 s'(r^2).\n const { k1, k2, k3 } = prepared.radial.coefficients;\n const r2 = (ideal.x*ideal.x+ideal.y*ideal.y)/prepared.radial.normalizationRadiusMm**2;\n const scale = 1+k1*r2+k2*r2*r2+k3*r2*r2*r2;\n const radialDerivative = 1+3*k1*r2+5*k2*r2*r2+7*k3*r2*r2*r2;\n distortionAreaFactor = 1/(scale*radialDerivative);\n } else if (prepared.brownConrady !== undefined) {\n ideal = brownConradyInverseValue(prepared.brownConrady, imagePointMm);\n const j = brownConradyForwardValue(prepared.brownConrady, ideal).jacobian;\n distortionAreaFactor = 1/(j[0]*j[3]-j[1]*j[2]);\n }\n if (!(distortionAreaFactor > 0) || !Number.isFinite(distortionAreaFactor)) {\n throw new InvalidScientificInputError(\"Distortion area factor must remain finite and positive.\");\n }\n return { ideal, distortionAreaFactor };\n}\n\n/**\n * @internal The forward distortion of an ideal image point (+X right, +Y up, mm) to the physical sensor point, with the\n * singular values of d distorted / d ideal there (the largest and smallest local scale of the map; 1 and 1 without\n * distortion). The inverse of {@link undistortedImagePoint} up to its solver's rounding (#548).\n */\nexport function distortedImagePoint(prepared: PreparedEnvironmentLensFieldMapping, ideal: { x: number; y: number }):\n { pointMm: { x: number; y: number }; largestScale: number; smallestScale: number } {\n if (prepared.radial !== undefined) {\n const { k1, k2, k3 } = prepared.radial.coefficients;\n const r2 = (ideal.x*ideal.x+ideal.y*ideal.y)/prepared.radial.normalizationRadiusMm**2;\n const scale = 1+k1*r2+k2*r2*r2+k3*r2*r2*r2;\n // Tangential scale s, radial scale s + r ds/dr (the two eigenvalues of the symmetric Jacobian of p -> s(r) p).\n const radialDerivative = 1+3*k1*r2+5*k2*r2*r2+7*k3*r2*r2*r2;\n return { pointMm: { x: ideal.x*scale, y: ideal.y*scale }, largestScale: Math.max(scale, radialDerivative), smallestScale: Math.min(scale, radialDerivative) };\n }\n if (prepared.brownConrady !== undefined) {\n const forward = brownConradyForwardValue(prepared.brownConrady, ideal), [a, b, c, d] = forward.jacobian;\n // Singular values of [[a, b], [c, d]]: sqrt of the eigenvalues of J^T J.\n const p = a*a+b*b+c*c+d*d, q = Math.abs(a*d-b*c), root = Math.sqrt(Math.max(0, p*p-4*q*q));\n const largest = Math.sqrt((p+root)/2);\n return { pointMm: forward.mappedImagePointMm, largestScale: largest, smallestScale: largest > 0 ? q/largest : 0 };\n }\n return { pointMm: { ...ideal }, largestScale: 1, smallestScale: 1 };\n}\n\n/**\n * @internal Query with a lens field mapping that is already validated. The environment photo-signal\n * planner shares it, so profiles are validated once per plan.\n */\nexport function calculateMappedSensorEnvironmentRadianceQuery(\n input: CalculateSensorEnvironmentRadianceQueryInput,\n prepared: PreparedEnvironmentLensFieldMapping\n): CalculationResult<SensorEnvironmentRadianceQuery> {\n if (input.timeReference !== \"first-opening-boundary-phase\" ||\n input.environmentDirectionConvention !== \"outgoing-radiance-toward-camera\") {\n throw new InvalidScientificInputError(\"Environment projection requires explicit opening-boundary time and outgoing-toward-camera direction conventions.\");\n }\n const focus = parseFocusPlane(input.focus);\n const sourcePointImagePlaneMm = { x: input.sourcePointNativeSensorMm.x, y: -input.sourcePointNativeSensorMm.y };\n const mapping = prepared.mapping;\n const { ideal, distortionAreaFactor } = undistortedImagePoint(prepared, sourcePointImagePlaneMm);\n let projection: ReturnType<typeof calculateInverseCameraRotationImageMapping> | null = null;\n let look: { x: number; y: number; z: number };\n let projectionScaleMm: number;\n if (mapping.projectionModel === \"rectilinear\") {\n projection = calculateInverseCameraRotationImageMapping({ focalLengthMm: input.focalLengthMm,\n imagePointMm: ideal, angularVelocityRadPerSec: input.angularVelocityRadPerSec,\n timeSecondsFromExposureStart: input.timeSecondsFromOpeningReference,\n ...(focus.kind === \"finite\" ? { focusDistanceM: focus.distanceM } : {}) });\n const point = projection.value.referenceImagePointMm, z = projection.value.projectionDistanceMm;\n const length = hypot3(point.x, point.y, z);\n look = { x: point.x/length, y: point.y/length, z: z/length };\n projectionScaleMm = z;\n } else {\n projectionScaleMm = focus.kind === \"finite\"\n ? calculateThinLensImageDistance({ focalLengthMm: input.focalLengthMm, objectDistanceM: focus.distanceM }).value.imageDistanceMm\n : input.focalLengthMm;\n const velocity = input.angularVelocityRadPerSec;\n const t = input.timeSecondsFromOpeningReference;\n if (typeof t !== \"number\" || !Number.isFinite(t) || t < 0) {\n throw new InvalidScientificInputError(\"timeSecondsFromOpeningReference must be finite and non-negative.\");\n }\n const captured = lensProjectionDirectionValue(mapping.projectionModel, projectionScaleMm, ideal.x, ideal.y);\n const reference = applyPhysicalCameraRotation(captured,\n { pitch: velocity.pitch*t, yaw: velocity.yaw*t, roll: velocity.roll*t }, \"camera-to-reference\");\n const length = hypot3(reference.x, reference.y, reference.z);\n if (!(length > 0) || !Number.isFinite(length)) throw new InvalidScientificInputError(\"Mapped reference ray must be finite.\");\n look = { x: reference.x/length, y: reference.y/length, z: reference.z/length };\n }\n const request = parseSceneRadianceEvaluationRequest({ ...input.request,\n timeSecondsFromExposureStart: input.timeSecondsFromOpeningReference,\n target: { kind: \"environment-direction\", outgoingDirectionUnitVector: { x: -look.x, y: -look.y, z: -look.z } } });\n return approximationResult({ request, sourcePointNativeSensorMm: { ...input.sourcePointNativeSensorMm },\n sourcePointImagePlaneMm, referenceLookDirectionUnitVector: look, projection,\n lensFieldMapping: { projectionModel: mapping.projectionModel, distortionKind: mapping.distortion.kind,\n idealImagePointMm: { ...ideal }, projectionScaleMm, distortionAreaFactor },\n targetMeaning: \"environment-direction-in-exposure-start-camera-axes\", directionConvention: \"outgoing-radiance-toward-camera\",\n geometricRayProjectionCalculated: true, sceneIntersectionCalculated: false, visibilityCalculated: false, providerExecuted: false\n }, \"lens-mapped-sensor-environment-radiance-query\", \"0.1.0\", [\n \"The physical sensor point is inverse-distorted to the ideal image point, then unprojected with the declared ideal projection and rotated by the constant-axis pure camera rotation.\",\n \"Projection scale is the thin-lens image distance at finite focus (focal length at infinity) for every projection model; a calibrated finite-focus fisheye scale is not modeled.\",\n \"The distortion area factor 1/det(d distorted/d ideal) is reported for exactly-once application to irradiance; field throughput, PSF and pupil models are not changed by this query.\",\n \"Breathing, chromatic field mapping, translation/parallax and scene intersections remain separate.\"\n ]);\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { resolveLensPsfConvolutionKernels } from "./lens-psf-kernels.js";
1
+ import { type resolveLensPsfConvolutionKernels } from "./lens-psf-kernels.js";
2
2
  type Psf = Parameters<typeof resolveLensPsfConvolutionKernels>[0]["psf"];
3
3
  /** PSF records kept by value: at most 20 kernels of (2·32 + 1)² doubles each (676 KB) per record at the default spectral sampling. */
4
4
  export declare const SITE_DIFFRACTION_KERNEL_CACHE_SIZE = 4;
@@ -11,17 +11,27 @@
11
11
  * own fields (everything the kernel is a function of besides the wavelength, pitch and radius of the query). Records with an equal
12
12
  * string share their kernels, in a least-recently-used cache of `SITE_DIFFRACTION_KERNEL_CACHE_SIZE` records. A record that was not
13
13
  * registered (a caller's own profile) keeps its kernels while it lives, by identity, as before.
14
+ *
15
+ * 2.15.0: the most recently used entry also keeps one private, engine-owned clone of the profile, taken on its first resolve,
16
+ * and every later wavelength resolves from it (`resolveLensPsfConvolutionKernelsWithOwnedProfile`), so a request's profile is
17
+ * cloned and parsed once rather than once per wavelength; only one clone is held at a time. Before, N wavelengths cost N clones
18
+ * and parses of an N-wavelength profile, O(N²): at radius 32, 124 s for the 400 nodes of a 1 nm spectral step and 5.1 s for 80
19
+ * nodes, against 1.4 s and 0.12 s now (one machine, docs/PSF_FOUNDATION.md "Spectral nodes (2.15.0)"). The kernels are the same
20
+ * numbers (test/diffraction-spectral-grid.test.ts): both paths parse a structured clone of the same profile, and the clone is never changed.
14
21
  */
15
22
  import { InvalidConfigurationError } from "../core/configuration-error.js";
16
- import { resolveLensPsfConvolutionKernels } from "./lens-psf-kernels.js";
23
+ import { resolveLensPsfConvolutionKernelsWithOwnedProfile } from "./lens-psf-kernels.js";
24
+ import { markEngineOwnedLensSampledPsfProfile } from "./lens-psf-profile.js";
17
25
  /** PSF records kept by value: at most 20 kernels of (2·32 + 1)² doubles each (676 KB) per record at the default spectral sampling. */
18
26
  export const SITE_DIFFRACTION_KERNEL_CACHE_SIZE = 4;
19
27
  /** Canonical value key of each registered PSF record. */
20
28
  const keys = new WeakMap();
21
- /** Kernels per registered value key (least recently used first), then per wavelength, pitch and radius. */
29
+ /** Entries per registered value key (least recently used first). */
22
30
  const byValue = new Map();
23
- /** Kernels per unregistered PSF record (by identity: the record is large, so it is not serialized), then per wavelength, pitch and radius. */
31
+ /** Entries per unregistered PSF record (by identity: the record is large, so it is not serialized). */
24
32
  const byIdentity = new WeakMap();
33
+ /** The one entry that holds its private clone of the profile. */
34
+ let lastOwner;
25
35
  /** Kernels resolved so far (test hook). */
26
36
  let resolves = 0;
27
37
  /** JSON with every number spelled exactly: shortest round-trip digits, and -0, NaN and ±Infinity kept apart from 0 and null. */
@@ -37,34 +47,43 @@ export function registerDiffractionPsfKey(psf, profileInput) {
37
47
  const fields = Object.entries(psf).filter(([name]) => name !== "profile").sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
38
48
  keys.set(psf, canonical(["createDiffractionLimitedPsfProfile", profileInput, fields]));
39
49
  }
40
- /** The kernels kept for `psf`, made the most recently used. */
41
- function kernelsOf(psf) {
50
+ /** The entry kept for `psf`, made the most recently used. */
51
+ function entryOf(psf) {
42
52
  const key = keys.get(psf);
43
53
  if (key === undefined) {
44
- let kernels = byIdentity.get(psf);
45
- if (!kernels)
46
- byIdentity.set(psf, (kernels = new Map()));
47
- return kernels;
54
+ let entry = byIdentity.get(psf);
55
+ if (!entry)
56
+ byIdentity.set(psf, (entry = { kernels: new Map() }));
57
+ return entry;
48
58
  }
49
- let kernels = byValue.get(key);
50
- if (kernels)
59
+ let entry = byValue.get(key);
60
+ if (entry)
51
61
  byValue.delete(key);
52
62
  else
53
- kernels = new Map();
54
- byValue.set(key, kernels);
63
+ entry = { kernels: new Map() };
64
+ byValue.set(key, entry);
55
65
  while (byValue.size > SITE_DIFFRACTION_KERNEL_CACHE_SIZE)
56
66
  byValue.delete(byValue.keys().next().value);
57
- return kernels;
67
+ return entry;
58
68
  }
59
69
  /** The (2·radius + 1)² kernel of `psf` at `wavelengthNm` on a square site grid of `pitchMicrometers`; `failure` is the error message when the kernel cannot sample the pitch exactly. */
60
70
  export function siteDiffractionKernel(psf, wavelengthNm, pitchMicrometers, radius, failure) {
61
- const kernels = kernelsOf(psf);
71
+ const entry = entryOf(psf), kernels = entry.kernels;
62
72
  const key = canonical([wavelengthNm, pitchMicrometers, radius]);
63
73
  let kernel = kernels.get(key);
64
74
  if (!kernel) {
65
- const k = resolveLensPsfConvolutionKernels({ schemaVersion: "0.1.0", psf, spectralWeights: [{ wavelengthNm, weight: 1 }],
75
+ if (!entry.ownedProfile) {
76
+ const owned = structuredClone(psf.profile);
77
+ markEngineOwnedLensSampledPsfProfile(owned);
78
+ // Only the most recent entry keeps its clone (a request resolves its wavelengths in one run), so at most one is held.
79
+ if (lastOwner)
80
+ delete lastOwner.ownedProfile;
81
+ entry.ownedProfile = owned;
82
+ lastOwner = entry;
83
+ }
84
+ const k = resolveLensPsfConvolutionKernelsWithOwnedProfile({ schemaVersion: "0.1.0", psf, spectralWeights: [{ wavelengthNm, weight: 1 }],
66
85
  grid: { width: 1, height: 1, sitePitchMicrometers: { x: pitchMicrometers, y: pitchMicrometers }, opticalAxisSite: { x: 0.5, y: 0.5 } }, patchWidth: 1, patchHeight: 1,
67
- kernelRadius: radius }).value;
86
+ kernelRadius: radius }, entry.ownedProfile).value;
68
87
  if (!k.exactSiteSampling || k.kernelRadius !== radius)
69
88
  throw new InvalidConfigurationError(failure);
70
89
  kernel = Float64Array.from(k.kernels);
@@ -80,5 +99,6 @@ export function siteDiffractionKernelCacheState(psf) {
80
99
  /** Test hook: forgets every kernel kept by value. */
81
100
  export function clearSiteDiffractionKernelCache() {
82
101
  byValue.clear();
102
+ lastOwner = undefined;
83
103
  }
84
104
  //# sourceMappingURL=site-diffraction-kernel.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"site-diffraction-kernel.js","sourceRoot":"","sources":["../../src/optics/site-diffraction-kernel.ts"],"names":[],"mappings":"AAAA,sCAAsC;AAEtC;;;;;;;;;;;;GAYG;AAEH,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAC3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C,OAAO,CAAC,KAAK,EAAE,CAAC;AAClB,CAAC","sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Internal (not exported from the package): one wavelength's diffraction kernel sampled on the site pitch, as the object-space\n * convolution (facade/diffraction-provider.ts) and the tabulated expected signal (facade/expected-signal-setup.ts) use it.\n *\n * `resolveLensPsfConvolutionKernels` parses and samples the PSF profile on every call (about 10 ms per wavelength), and both users\n * ask for the same kernels. The kernel is a function of its inputs alone; each caller gets its own copy.\n *\n * The facade builds a new PSF record for every request, so kernels are kept by value: `registerDiffractionPsfKey` records, for a\n * record whose profile `createDiffractionLimitedPsfProfile` built, a canonical string of that call's whole input and of the record's\n * own fields (everything the kernel is a function of besides the wavelength, pitch and radius of the query). Records with an equal\n * string share their kernels, in a least-recently-used cache of `SITE_DIFFRACTION_KERNEL_CACHE_SIZE` records. A record that was not\n * registered (a caller's own profile) keeps its kernels while it lives, by identity, as before.\n */\n\nimport { InvalidConfigurationError } from \"../core/configuration-error.js\";\nimport { resolveLensPsfConvolutionKernels } from \"./lens-psf-kernels.js\";\n\ntype Psf = Parameters<typeof resolveLensPsfConvolutionKernels>[0][\"psf\"];\n\n/** PSF records kept by value: at most 20 kernels of (2·32 + 1)² doubles each (676 KB) per record at the default spectral sampling. */\nexport const SITE_DIFFRACTION_KERNEL_CACHE_SIZE = 4;\n\n/** Canonical value key of each registered PSF record. */\nconst keys = new WeakMap<object, string>();\n/** Kernels per registered value key (least recently used first), then per wavelength, pitch and radius. */\nconst byValue = new Map<string, Map<string, Float64Array>>();\n/** Kernels per unregistered PSF record (by identity: the record is large, so it is not serialized), then per wavelength, pitch and radius. */\nconst byIdentity = new WeakMap<object, Map<string, Float64Array>>();\n/** Kernels resolved so far (test hook). */\nlet resolves = 0;\n\n/** JSON with every number spelled exactly: shortest round-trip digits, and -0, NaN and ±Infinity kept apart from 0 and null. */\nfunction canonical(value: unknown): string {\n return JSON.stringify(value, (_key, v: unknown) => (typeof v === \"number\" && (Object.is(v, -0) || !Number.isFinite(v)) ? \"number:\" + (Object.is(v, -0) ? \"-0\" : String(v)) : v));\n}\n\n/**\n * Records that `psf.profile` is the profile `createDiffractionLimitedPsfProfile(profileInput)` returned, unmodified, so that the\n * kernels of `psf` are those of any record with the same `profileInput` and the same other fields. Call it right after building the\n * record; neither the record nor `profileInput` may change afterwards.\n */\nexport function registerDiffractionPsfKey(psf: Psf, profileInput: object): void {\n const fields = Object.entries(psf as object).filter(([name]) => name !== \"profile\").sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));\n keys.set(psf as object, canonical([\"createDiffractionLimitedPsfProfile\", profileInput, fields]));\n}\n\n/** The kernels kept for `psf`, made the most recently used. */\nfunction kernelsOf(psf: Psf): Map<string, Float64Array> {\n const key = keys.get(psf as object);\n if (key === undefined) {\n let kernels = byIdentity.get(psf as object);\n if (!kernels) byIdentity.set(psf as object, (kernels = new Map()));\n return kernels;\n }\n let kernels = byValue.get(key);\n if (kernels) byValue.delete(key);\n else kernels = new Map();\n byValue.set(key, kernels);\n while (byValue.size > SITE_DIFFRACTION_KERNEL_CACHE_SIZE) byValue.delete(byValue.keys().next().value!);\n return kernels;\n}\n\n/** The (2·radius + 1)² kernel of `psf` at `wavelengthNm` on a square site grid of `pitchMicrometers`; `failure` is the error message when the kernel cannot sample the pitch exactly. */\nexport function siteDiffractionKernel(psf: Psf, wavelengthNm: number, pitchMicrometers: number, radius: number, failure: string): Float64Array {\n const kernels = kernelsOf(psf);\n const key = canonical([wavelengthNm, pitchMicrometers, radius]);\n let kernel = kernels.get(key);\n if (!kernel) {\n const k = resolveLensPsfConvolutionKernels({ schemaVersion: \"0.1.0\", psf, spectralWeights: [{ wavelengthNm, weight: 1 }],\n grid: { width: 1, height: 1, sitePitchMicrometers: { x: pitchMicrometers, y: pitchMicrometers }, opticalAxisSite: { x: 0.5, y: 0.5 } }, patchWidth: 1, patchHeight: 1,\n kernelRadius: radius }).value;\n if (!k.exactSiteSampling || k.kernelRadius !== radius) throw new InvalidConfigurationError(failure);\n kernel = Float64Array.from(k.kernels);\n resolves++;\n kernels.set(key, kernel);\n }\n return Float64Array.from(kernel);\n}\n\n/** Test hook: the number of PSF records kept by value, the kernels resolved so far, and whether `psf` is registered. */\nexport function siteDiffractionKernelCacheState(psf?: Psf): { valueEntries: number; resolves: number; registered: boolean } {\n return { valueEntries: byValue.size, resolves, registered: psf !== undefined && keys.has(psf as object) };\n}\n\n/** Test hook: forgets every kernel kept by value. */\nexport function clearSiteDiffractionKernelCache(): void {\n byValue.clear();\n}\n"]}
1
+ {"version":3,"file":"site-diffraction-kernel.js","sourceRoot":"","sources":["../../src/optics/site-diffraction-kernel.ts"],"names":[],"mappings":"AAAA,sCAAsC;AAEtC;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAC3E,OAAO,EAAE,gDAAgD,EAAyC,MAAM,uBAAuB,CAAC;AAChI,OAAO,EAAE,oCAAoC,EAAE,MAAM,uBAAuB,CAAC;AAI7E,sIAAsI;AACtI,MAAM,CAAC,MAAM,kCAAkC,GAAG,CAAC,CAAC;AAEpD,yDAAyD;AACzD,MAAM,IAAI,GAAG,IAAI,OAAO,EAAkB,CAAC;AAG3C,oEAAoE;AACpE,MAAM,OAAO,GAAG,IAAI,GAAG,EAAiB,CAAC;AACzC,uGAAuG;AACvG,MAAM,UAAU,GAAG,IAAI,OAAO,EAAiB,CAAC;AAChD,iEAAiE;AACjE,IAAI,SAA4B,CAAC;AACjC,2CAA2C;AAC3C,IAAI,QAAQ,GAAG,CAAC,CAAC;AAEjB,gIAAgI;AAChI,SAAS,SAAS,CAAC,KAAc;IAC/B,OAAO,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,CAAC,IAAI,EAAE,CAAU,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,KAAK,QAAQ,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,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AAE,eAAe,EAAE,CAAC,EAAE,YAAY,EAAE,MAAM,EAAE,CAAC,EAAE,CAAC;YACtI,IAAI,EAAE,EAAE,KAAK,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,oBAAoB,EAAE,EAAE,CAAC,EAAE,gBAAgB,EAAE,CAAC,EAAE,gBAAgB,EAAE,EAAE,eAAe,EAAE,EAAE,CAAC,EAAE,GAAG,EAAE,CAAC,EAAE,GAAG,EAAE,EAAE,EAAE,UAAU,EAAE,CAAC,EAAE,WAAW,EAAE,CAAC;YACrK,YAAY,EAAE,MAAM,EAAE,EAAE,KAAK,CAAC,YAAY,CAAC,CAAC,KAAK,CAAC;QACpD,IAAI,CAAC,CAAC,CAAC,iBAAiB,IAAI,CAAC,CAAC,YAAY,KAAK,MAAM;YAAE,MAAM,IAAI,yBAAyB,CAAC,OAAO,CAAC,CAAC;QACpG,MAAM,GAAG,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC;QACtC,QAAQ,EAAE,CAAC;QACX,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;IAC3B,CAAC;IACD,OAAO,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;AACnC,CAAC;AAED,wHAAwH;AACxH,MAAM,UAAU,+BAA+B,CAAC,GAAS;IACvD,OAAO,EAAE,YAAY,EAAE,OAAO,CAAC,IAAI,EAAE,QAAQ,EAAE,UAAU,EAAE,GAAG,KAAK,SAAS,IAAI,IAAI,CAAC,GAAG,CAAC,GAAa,CAAC,EAAE,CAAC;AAC5G,CAAC;AAED,qDAAqD;AACrD,MAAM,UAAU,+BAA+B;IAC7C,OAAO,CAAC,KAAK,EAAE,CAAC;IAChB,SAAS,GAAG,SAAS,CAAC;AACxB,CAAC","sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Internal (not exported from the package): one wavelength's diffraction kernel sampled on the site pitch, as the object-space\n * convolution (facade/diffraction-provider.ts) and the tabulated expected signal (facade/expected-signal-setup.ts) use it.\n *\n * `resolveLensPsfConvolutionKernels` parses and samples the PSF profile on every call (about 10 ms per wavelength), and both users\n * ask for the same kernels. The kernel is a function of its inputs alone; each caller gets its own copy.\n *\n * The facade builds a new PSF record for every request, so kernels are kept by value: `registerDiffractionPsfKey` records, for a\n * record whose profile `createDiffractionLimitedPsfProfile` built, a canonical string of that call's whole input and of the record's\n * own fields (everything the kernel is a function of besides the wavelength, pitch and radius of the query). Records with an equal\n * string share their kernels, in a least-recently-used cache of `SITE_DIFFRACTION_KERNEL_CACHE_SIZE` records. A record that was not\n * registered (a caller's own profile) keeps its kernels while it lives, by identity, as before.\n *\n * 2.15.0: the most recently used entry also keeps one private, engine-owned clone of the profile, taken on its first resolve,\n * and every later wavelength resolves from it (`resolveLensPsfConvolutionKernelsWithOwnedProfile`), so a request's profile is\n * cloned and parsed once rather than once per wavelength; only one clone is held at a time. Before, N wavelengths cost N clones\n * and parses of an N-wavelength profile, O(N²): at radius 32, 124 s for the 400 nodes of a 1 nm spectral step and 5.1 s for 80\n * nodes, against 1.4 s and 0.12 s now (one machine, docs/PSF_FOUNDATION.md \"Spectral nodes (2.15.0)\"). The kernels are the same\n * numbers (test/diffraction-spectral-grid.test.ts): both paths parse a structured clone of the same profile, and the clone is never changed.\n */\n\nimport { InvalidConfigurationError } from \"../core/configuration-error.js\";\nimport { resolveLensPsfConvolutionKernelsWithOwnedProfile, type resolveLensPsfConvolutionKernels } from \"./lens-psf-kernels.js\";\nimport { markEngineOwnedLensSampledPsfProfile } from \"./lens-psf-profile.js\";\n\ntype Psf = Parameters<typeof resolveLensPsfConvolutionKernels>[0][\"psf\"];\n\n/** PSF records kept by value: at most 20 kernels of (2·32 + 1)² doubles each (676 KB) per record at the default spectral sampling. */\nexport const SITE_DIFFRACTION_KERNEL_CACHE_SIZE = 4;\n\n/** Canonical value key of each registered PSF record. */\nconst keys = new WeakMap<object, string>();\n/** One entry's kernels per wavelength, pitch and radius, and its private clone of the profile (taken on the first resolve). */\ninterface Entry { kernels: Map<string, Float64Array>; ownedProfile?: object }\n/** Entries per registered value key (least recently used first). */\nconst byValue = new Map<string, Entry>();\n/** Entries per unregistered PSF record (by identity: the record is large, so it is not serialized). */\nconst byIdentity = new WeakMap<object, Entry>();\n/** The one entry that holds its private clone of the profile. */\nlet lastOwner: Entry | undefined;\n/** Kernels resolved so far (test hook). */\nlet resolves = 0;\n\n/** JSON with every number spelled exactly: shortest round-trip digits, and -0, NaN and ±Infinity kept apart from 0 and null. */\nfunction canonical(value: unknown): string {\n return JSON.stringify(value, (_key, v: unknown) => (typeof v === \"number\" && (Object.is(v, -0) || !Number.isFinite(v)) ? \"number:\" + (Object.is(v, -0) ? \"-0\" : String(v)) : v));\n}\n\n/**\n * Records that `psf.profile` is the profile `createDiffractionLimitedPsfProfile(profileInput)` returned, unmodified, so that the\n * kernels of `psf` are those of any record with the same `profileInput` and the same other fields. Call it right after building the\n * record; neither the record nor `profileInput` may change afterwards.\n */\nexport function registerDiffractionPsfKey(psf: Psf, profileInput: object): void {\n const fields = Object.entries(psf as object).filter(([name]) => name !== \"profile\").sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));\n keys.set(psf as object, canonical([\"createDiffractionLimitedPsfProfile\", profileInput, fields]));\n}\n\n/** The entry kept for `psf`, made the most recently used. */\nfunction entryOf(psf: Psf): Entry {\n const key = keys.get(psf as object);\n if (key === undefined) {\n let entry = byIdentity.get(psf as object);\n if (!entry) byIdentity.set(psf as object, (entry = { kernels: new Map() }));\n return entry;\n }\n let entry = byValue.get(key);\n if (entry) byValue.delete(key);\n else entry = { kernels: new Map() };\n byValue.set(key, entry);\n while (byValue.size > SITE_DIFFRACTION_KERNEL_CACHE_SIZE) byValue.delete(byValue.keys().next().value!);\n return entry;\n}\n\n/** The (2·radius + 1)² kernel of `psf` at `wavelengthNm` on a square site grid of `pitchMicrometers`; `failure` is the error message when the kernel cannot sample the pitch exactly. */\nexport function siteDiffractionKernel(psf: Psf, wavelengthNm: number, pitchMicrometers: number, radius: number, failure: string): Float64Array {\n const entry = entryOf(psf), kernels = entry.kernels;\n const key = canonical([wavelengthNm, pitchMicrometers, radius]);\n let kernel = kernels.get(key);\n if (!kernel) {\n if (!entry.ownedProfile) {\n const owned = structuredClone((psf as { profile: unknown }).profile) as object;\n markEngineOwnedLensSampledPsfProfile(owned);\n // Only the most recent entry keeps its clone (a request resolves its wavelengths in one run), so at most one is held.\n if (lastOwner) delete lastOwner.ownedProfile;\n entry.ownedProfile = owned;\n lastOwner = entry;\n }\n const k = resolveLensPsfConvolutionKernelsWithOwnedProfile({ schemaVersion: \"0.1.0\", psf, spectralWeights: [{ wavelengthNm, weight: 1 }],\n grid: { width: 1, height: 1, sitePitchMicrometers: { x: pitchMicrometers, y: pitchMicrometers }, opticalAxisSite: { x: 0.5, y: 0.5 } }, patchWidth: 1, patchHeight: 1,\n kernelRadius: radius }, entry.ownedProfile).value;\n if (!k.exactSiteSampling || k.kernelRadius !== radius) throw new InvalidConfigurationError(failure);\n kernel = Float64Array.from(k.kernels);\n resolves++;\n kernels.set(key, kernel);\n }\n return Float64Array.from(kernel);\n}\n\n/** Test hook: the number of PSF records kept by value, the kernels resolved so far, and whether `psf` is registered. */\nexport function siteDiffractionKernelCacheState(psf?: Psf): { valueEntries: number; resolves: number; registered: boolean } {\n return { valueEntries: byValue.size, resolves, registered: psf !== undefined && keys.has(psf as object) };\n}\n\n/** Test hook: forgets every kernel kept by value. */\nexport function clearSiteDiffractionKernelCache(): void {\n byValue.clear();\n lastOwner = undefined;\n}\n"]}