@photivra/engine 2.11.1 → 2.13.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 (55) hide show
  1. package/CHANGELOG.md +94 -1
  2. package/CITATION.cff +1 -1
  3. package/NODE_SUPPORT.md +2 -4
  4. package/README.md +6 -6
  5. package/SECURITY.md +1 -1
  6. package/THIRD_PARTY.md +1 -0
  7. package/dist/capture/export-jpeg.d.ts +1 -1
  8. package/dist/capture/export-jpeg.js +6 -4
  9. package/dist/capture/export-jpeg.js.map +1 -1
  10. package/dist/core/version.d.ts +1 -1
  11. package/dist/core/version.js +1 -1
  12. package/dist/core/version.js.map +1 -1
  13. package/dist/exposure/auto-iso-slowest-shutter.d.ts +120 -0
  14. package/dist/exposure/auto-iso-slowest-shutter.js +216 -0
  15. package/dist/exposure/auto-iso-slowest-shutter.js.map +1 -0
  16. package/dist/exposure/exposure-mode-resolver.d.ts +57 -1
  17. package/dist/exposure/exposure-mode-resolver.js +238 -33
  18. package/dist/exposure/exposure-mode-resolver.js.map +1 -1
  19. package/dist/facade/diffraction-provider.js +12 -13
  20. package/dist/facade/diffraction-provider.js.map +1 -1
  21. package/dist/facade/display-view.d.ts +27 -0
  22. package/dist/facade/display-view.js +234 -65
  23. package/dist/facade/display-view.js.map +1 -1
  24. package/dist/facade/simulate-capture.d.ts +159 -3
  25. package/dist/facade/simulate-capture.js +203 -10
  26. package/dist/facade/simulate-capture.js.map +1 -1
  27. package/dist/facade/simulate-display-view.js +2 -2
  28. package/dist/facade/simulate-display-view.js.map +1 -1
  29. package/dist/gpu/display-view-quality-gpu.d.ts +2 -1
  30. package/dist/gpu/display-view-quality-gpu.js +24 -14
  31. package/dist/gpu/display-view-quality-gpu.js.map +1 -1
  32. package/dist/gpu/wgsl-display-view-quality-kernel.d.ts +13 -1
  33. package/dist/gpu/wgsl-display-view-quality-kernel.js +36 -2
  34. package/dist/gpu/wgsl-display-view-quality-kernel.js.map +1 -1
  35. package/dist/index.d.ts +4 -3
  36. package/dist/index.js +2 -1
  37. package/dist/index.js.map +1 -1
  38. package/dist/optics/irradiance-convolution.d.ts +10 -0
  39. package/dist/optics/irradiance-convolution.js +48 -13
  40. package/dist/optics/irradiance-convolution.js.map +1 -1
  41. package/dist/output/print-jpeg.js +12 -9
  42. package/dist/output/print-jpeg.js.map +1 -1
  43. package/dist/output/text-metadata.d.ts +22 -2
  44. package/dist/output/text-metadata.js +58 -9
  45. package/dist/output/text-metadata.js.map +1 -1
  46. package/docs/API_REFERENCE.md +23 -1
  47. package/docs/QUICK_START.md +109 -3
  48. package/docs/USAGE.md +234 -1
  49. package/docs/api/core-version.md +1 -1
  50. package/docs/api/exports.json +77 -2
  51. package/docs/api/exposure-auto-iso-slowest-shutter.md +139 -0
  52. package/docs/api/exposure-exposure-mode-resolver.md +68 -0
  53. package/docs/api/facade-simulate-capture.md +153 -5
  54. package/docs/api/output-text-metadata.md +34 -0
  55. package/package.json +1 -1
@@ -16,7 +16,9 @@
16
16
  * So E(q, λ) = T·B(q, λ) with B = K_λ ⊛ L sampled on that lattice: the same sum, in a different floating-point
17
17
  * order. B is computed once per spectral node with the engine's isoplanatic convolution
18
18
  * (`calculateIrradianceConvolution`, kernels from `resolveLensPsfConvolutionKernels`, exact site sampling) over a
19
- * grid that holds every source (the native raster plus the kernel radius on each side), in row bands. The
19
+ * grid that holds every source (the native raster plus the kernel radius on each side), in row bands; each band gathers only
20
+ * its own values, the grid's interior (#419, `createIrradianceConvolutionInteriorRunner`: each value bit-identical to
21
+ * `calculateIrradianceConvolution`'s there, without the 2R rows and columns of the band's grid that no query reads). The
20
22
  * provider then answers each site-centre query with B instead of L, and the environment request declares no
21
23
  * PSF. Incoherent imaging is a linear superposition of intensity PSFs, so convolving radiance on the object
22
24
  * plane and convolving irradiance on the image plane agree for a planar object and a space-invariant PSF
@@ -33,7 +35,7 @@
33
35
  * plus the largest offset on each side) are convolved, over a grid that adds the kernel radius on each side. Every
34
36
  * output value is the same gather as in the whole render: the grid always holds every tap of every value it keeps
35
37
  * (real scene radiance out to the kernel radius, never a truncated edge), the single kernel patch does not depend on
36
- * the grid's origin, and `convolveIrradianceRows` sums each value in a fixed tap order (v outer, u inner). Narrowing
38
+ * the grid's origin, and the gather (`convolveIrradianceRows`, and its interior form) sums each value in a fixed tap order (v outer, u inner). Narrowing
37
39
  * the grid therefore removes only values that no query reads, and the kept values are bit-identical.
38
40
  *
39
41
  * A query that does not land on one of the lattices (within 1e-6 site) is refused rather than approximated: the
@@ -43,12 +45,12 @@
43
45
  * passes `siteKernels` instead (the geometric defocus disc, or each node's diffraction kernel convolved with it). Their radius
44
46
  * may exceed the public 32-site convolution limit, so this path does not call `calculateIrradianceConvolution`: it checks the
45
47
  * samples and the kernel sums as that function does and gathers only the band's own values (`gatherInterior`), each summed
46
- * over the taps in the same fixed order (v outer, u inner, ascending; zero taps skipped, which adds exact zeros only). It
47
- * does not compute the 2R grid rows above and below a band that `calculateIrradianceConvolution` would also return (#419).
48
+ * over the taps in the same fixed order (v outer, u inner, ascending; zero taps skipped, which adds exact zeros only). Like
49
+ * the diffraction path (#419), it does not compute the 2R grid rows and columns around a band.
48
50
  */
49
51
  import { InvalidConfigurationError } from "../core/configuration-error.js";
50
52
  import { isInternalSceneRadianceEvaluator, markInternalSceneRadianceEvaluator, registerInternalRadianceAccess } from "../core/internal-radiance-evaluator.js";
51
- import { createIrradianceConvolutionRunner } from "../optics/irradiance-convolution.js";
53
+ import { createIrradianceConvolutionInteriorRunner } from "../optics/irradiance-convolution.js";
52
54
  import { siteDiffractionKernel } from "../optics/site-diffraction-kernel.js";
53
55
  /** Rows of native sites per convolution band, and the bands kept. Banding changes memory only, never values. */
54
56
  const BAND_ROWS = 32;
@@ -99,9 +101,10 @@ export function createDiffractedPlanarProvider(input) {
99
101
  }
100
102
  const started = input.onConvolution ? now() : 0;
101
103
  const y0 = ly0 + b * BAND_ROWS, rows = Math.min(BAND_ROWS, ly1 - y0), gridHeight = rows + 2 * R, size = gridWidth * gridHeight;
102
- // #453: the band's shifts × spectral nodes convolutions share one geometry, validated once (the first runs the full
103
- // calculateIrradianceConvolution; every later one still checks its samples and kernel).
104
- const convolve = siteKernels ? undefined : createIrradianceConvolutionRunner({ schemaVersion: "0.1.0", width: gridWidth, height: gridHeight, kernelRadius: R,
104
+ // #453: the band's shifts × spectral nodes convolutions share one geometry, validated once (the first with every check of
105
+ // calculateIrradianceConvolution; every later one still checks its samples and kernel). #419: only the band's own rows × NW
106
+ // values are gathered (the grid's interior), each bit-identical to calculateIrradianceConvolution's value there.
107
+ const convolve = siteKernels ? undefined : createIrradianceConvolutionInteriorRunner({ schemaVersion: "0.1.0", width: gridWidth, height: gridHeight, kernelRadius: R,
105
108
  patchWidth: gridWidth, patchHeight: gridHeight, boundary: "zero-outside-grid" });
106
109
  const values = shifts.map((shift) => {
107
110
  // The plane point of lattice grid sample (gx, gy) of this shift, the same expressions for both fills below.
@@ -142,11 +145,7 @@ export function createDiffractedPlanarProvider(input) {
142
145
  }
143
146
  if (!convolve)
144
147
  return gatherInterior(samples, taps[w], gridWidth, NW, rows, R);
145
- const blurred = convolve(samples, kernels[w]);
146
- const out = new Float64Array(NW * rows);
147
- for (let y = 0; y < rows; y++)
148
- out.set(blurred.subarray((y + R) * gridWidth + R, (y + R) * gridWidth + R + NW), y * NW);
149
- return out;
148
+ return convolve(samples, kernels[w]);
150
149
  });
151
150
  });
152
151
  bands.set(b, values);
@@ -1 +1 @@
1
- {"version":3,"file":"diffraction-provider.js","sourceRoot":"","sources":["../../src/facade/diffraction-provider.ts"],"names":[],"mappings":"AAAA,sCAAsC;AAEtC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8CG;AAEH,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAC3E,OAAO,EAAE,gCAAgC,EAAE,kCAAkC,EAAE,8BAA8B,EAAE,MAAM,wCAAwC,CAAC;AAE9J,OAAO,EAAE,iCA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MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,GAAG,IAAI,EAAE,KAAK,GAAG,OAAO,CAAC,MAAM,EAAE,GAAG,GAAG,IAAI,YAAY,CAAC,KAAK,GAAG,IAAI,CAAC,CAAC;IAChG,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,EAAE,CAAC,EAAE,EAAE,CAAC;QAC9B,MAAM,OAAO,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,SAAS,GAAG,CAAC,CAAC;QACxC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,EAAE,CAAC,EAAE,EAAE,CAAC;YAC/B,MAAM,IAAI,GAAG,OAAO,GAAG,CAAC,CAAC;YACzB,IAAI,GAAG,GAAG,CAAC,CAAC;YACZ,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,EAAE,CAAC,EAAE;gBAAE,GAAG,IAAI,OAAO,CAAC,IAAI,GAAG,OAAO,CAAC,CAAC,CAAE,CAAE,GAAG,OAAO,CAAC,CAAC,CAAE,CAAC;YAClF,GAAG,CAAC,CAAC,GAAG,KAAK,GAAG,CAAC,CAAC,GAAG,GAAG,CAAC;QAC3B,CAAC;IACH,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Fast execution of `simulateCapture`'s `lens.diffraction` (2.1): an object-space convolution in the scene\n * provider, instead of one scene query per PSF tap in the environment PSF quadrature.\n *\n * The environment quadrature computes, at each site centre q and spectral node λ,\n * E(q, λ) = Σ_k K_λ(k)·T·L(s_k(q), λ),\n * where s_k(q) is the tap's source point (`sensorPsfSourcePoint`), L the scene radiance at the plane point\n * that source point sees, and T the radiance-to-irradiance factor. For the facade's planar scene seen\n * through the ideal rectilinear projection with a still camera and no lens field mapping, field throughput or\n * pupil rays:\n * - T is the same at every sensor point (paraxial π/(4·N_w²), no cos⁴ term), and\n * - with the kernel sampled on the site pitch, every source point is the centre of another site, so the plane\n * points form one regular lattice: u = (i + ½ − W/2)·2/w, v = −(j + ½ − H/2)·2/w (frame units, native\n * site (i, j), W×H native sites, w output width).\n * So E(q, λ) = T·B(q, λ) with B = K_λ ⊛ L sampled on that lattice: the same sum, in a different floating-point\n * order. B is computed once per spectral node with the engine's isoplanatic convolution\n * (`calculateIrradianceConvolution`, kernels from `resolveLensPsfConvolutionKernels`, exact site sampling) over a\n * grid that holds every source (the native raster plus the kernel radius on each side), in row bands. The\n * provider then answers each site-centre query with B instead of L, and the environment request declares no\n * PSF. Incoherent imaging is a linear superposition of intensity PSFs, so convolving radiance on the object\n * plane and convolving irradiance on the image plane agree for a planar object and a space-invariant PSF\n * (MIT OpenCourseWare 2.71, lecture 22, free; also see: Goodman, Introduction to Fourier Optics, 4th ed., §7.1).\n *\n * With an anti-aliasing point-splitting filter (2.1, `sensor.antiAliasing`) the environment queries the PSF taps\n * around each pre-filter source point q − a (a = a split offset) instead of around q. Those taps lie on the site\n * lattice shifted by a, so the same argument holds on each shifted lattice: B is computed once per distinct\n * fractional shift (offsets that differ by whole sites share one lattice; the centred four-spot filter with a\n * one-site separation needs a single half-site-shifted lattice) over the native raster widened by the largest\n * offset, and the environment's spatial quadrature still forms the weighted split sum.\n *\n * Region renders (2.6, `window`): only the lattice rows and columns that the region's sites can query (the window\n * plus the largest offset on each side) are convolved, over a grid that adds the kernel radius on each side. Every\n * output value is the same gather as in the whole render: the grid always holds every tap of every value it keeps\n * (real scene radiance out to the kernel radius, never a truncated edge), the single kernel patch does not depend on\n * the grid's origin, and `convolveIrradianceRows` sums each value in a fixed tap order (v outer, u inner). Narrowing\n * the grid therefore removes only values that no query reads, and the kept values are bit-identical.\n *\n * A query that does not land on one of the lattices (within 1e-6 site) is refused rather than approximated: the\n * facade uses this path only when the lattice argument above holds. A query outside the window is refused too.\n *\n * Defocus (#492, `lens.defocus`): the same argument holds for any space-invariant kernel on the site lattice, so the facade\n * passes `siteKernels` instead (the geometric defocus disc, or each node's diffraction kernel convolved with it). Their radius\n * may exceed the public 32-site convolution limit, so this path does not call `calculateIrradianceConvolution`: it checks the\n * samples and the kernel sums as that function does and gathers only the band's own values (`gatherInterior`), each summed\n * over the taps in the same fixed order (v outer, u inner, ascending; zero taps skipped, which adds exact zeros only). It\n * does not compute the 2R grid rows above and below a band that `calculateIrradianceConvolution` would also return (#419).\n */\n\nimport { InvalidConfigurationError } from \"../core/configuration-error.js\";\nimport { isInternalSceneRadianceEvaluator, markInternalSceneRadianceEvaluator, registerInternalRadianceAccess } from \"../core/internal-radiance-evaluator.js\";\nimport type { SceneRadianceEvaluationRequest, SceneRadianceEvaluationResult } from \"../schema/scene-radiance.js\";\nimport { createIrradianceConvolutionRunner } from \"../optics/irradiance-convolution.js\";\nimport { siteDiffractionKernel } from \"../optics/site-diffraction-kernel.js\";\nimport type { ResolveLensSampledPsfInput } from \"../optics/lens-psf-profile.js\";\nimport type { PlanarSceneRadianceProvider } from \"./scene-radiance.js\";\n\n/** Rows of native sites per convolution band, and the bands kept. Banding changes memory only, never values. */\nconst BAND_ROWS = 32;\nconst CACHED_BANDS = 4;\nconst LATTICE_TOLERANCE_SITES = 1e-6;\n\nexport interface DiffractedPlanarProviderInput {\n base: PlanarSceneRadianceProvider;\n /** The optical state of the sampled PSF, as for `resolveLensSampledPsf`, without field point and wavelength. Unused with `siteKernels`. */\n psf?: Omit<ResolveLensSampledPsfInput, \"fieldPointMm\" | \"wavelengthNm\">;\n /**\n * #492: the kernel of each spectral node on the site lattice, (2·kernelRadius + 1)² taps in row-major order, applied\n * instead of the diffraction kernels of `psf` (the defocus disc, or each node's diffraction kernel convolved with it).\n * Any radius; each kernel's sum may not exceed 1 + 2^-20.\n */\n siteKernels?: (wavelengthNm: number) => Float64Array;\n /** Spectral nodes the environment queries (the profile's wavelength nodes). */\n wavelengthsNm: readonly number[];\n kernelRadius: number;\n nativeWidth: number;\n nativeHeight: number;\n /** Output (active) width in sites: frame units are 2/outputWidth per site. */\n outputWidth: number;\n sitePitchMicrometers: number;\n /** Planar geometry of the base provider, to map query directions to plane points exactly as it does. */\n distanceM: number;\n metresPerFrameUnit: number;\n /**\n * Offsets of the query points from the site centres, in sites (+x right, +y down): the anti-aliasing split\n * offsets with their sign reversed (the environment queries q − a). Default: one zero offset.\n */\n queryOffsetsSites?: readonly { x: number; y: number }[];\n /**\n * Region renders (2.6): the native sites that will be queried (x, y, width, height in the native raster). Only the\n * lattice they can reach is convolved; values are bit-identical to the whole render's. Default: the whole raster.\n */\n window?: { x: number; y: number; width: number; height: number };\n /** Called with the duration in ms of each band convolution (diagnostics only; never changes values). */\n onConvolution?: (milliseconds: number) => void;\n}\n\n/** Internal (not exported from the package): the base provider with diffraction applied as an object-space convolution. */\nexport function createDiffractedPlanarProvider(input: DiffractedPlanarProviderInput): PlanarSceneRadianceProvider {\n const { base, wavelengthsNm, nativeWidth: W, nativeHeight: H, kernelRadius: R } = input;\n const g = 2 / input.outputWidth, pitch = input.sitePitchMicrometers;\n const index = new Map(wavelengthsNm.map((nm, i) => [nm, i]));\n // One lattice per distinct fractional query offset; M extra sites per side hold the offset queries.\n const offsets = input.queryOffsetsSites ?? [{ x: 0, y: 0 }];\n const fraction = (value: number): number => { const f = value - Math.floor(value); return f > 1 - LATTICE_TOLERANCE_SITES ? 0 : f < LATTICE_TOLERANCE_SITES ? 0 : f; };\n const shifts: { x: number; y: number }[] = [];\n for (const o of offsets) {\n const f = { x: fraction(o.x), y: fraction(o.y) };\n if (!shifts.some((s) => Math.abs(s.x - f.x) <= LATTICE_TOLERANCE_SITES && Math.abs(s.y - f.y) <= LATTICE_TOLERANCE_SITES)) shifts.push(f);\n }\n const M = Math.max(0, ...offsets.map((o) => Math.ceil(Math.max(Math.abs(o.x), Math.abs(o.y)) - LATTICE_TOLERANCE_SITES)));\n const LW = W + 2 * M, LH = H + 2 * M;\n // Lattice window (indices i + M, j + M): the sites the region queries plus the largest offset on each side, clipped\n // to the lattice. A site i queries i + floor(offset), and floor(offset) lies in [-M, M].\n const win = input.window ?? { x: 0, y: 0, width: W, height: H };\n const lx0 = Math.max(0, win.x), lx1 = Math.min(LW, win.x + win.width + 2 * M);\n const ly0 = Math.max(0, win.y), ly1 = Math.min(LH, win.y + win.height + 2 * M);\n if (!(lx0 < lx1 && ly0 < ly1)) throw new InvalidConfigurationError(\"Diffraction window must overlap the native raster.\");\n const NW = lx1 - lx0;\n // One kernel per wavelength, on the site grid, from the engine's own tap-to-site mapping (field point 0, 0); kept across calls.\n const siteKernels = input.siteKernels;\n if (!siteKernels && !input.psf) throw new InvalidConfigurationError(\"The object-space convolution needs a PSF or site kernels.\");\n const kernels = wavelengthsNm.map((wavelengthNm) => siteKernels ? checkedSiteKernel(siteKernels(wavelengthNm), R) :\n siteDiffractionKernel(input.psf!, wavelengthNm, pitch, R, \"Diffraction kernels must sample the site pitch exactly.\"));\n // #492: each site kernel's non-zero taps as grid offsets, in the gather's order.\n const taps = siteKernels ? kernels.map((kernel) => kernelTaps(kernel, R, NW + 2 * R)) : [];\n const gridWidth = NW + 2 * R;\n const now = (): number => globalThis.performance?.now() ?? Date.now();\n const bands = new Map<number, Float64Array[][]>();\n const materialAt = base.chartMaterialAt?.bind(base), materialRadiance = base.materialRadiance?.bind(base);\n function band(b: number): Float64Array[][] {\n const cached = bands.get(b);\n if (cached) { bands.delete(b); bands.set(b, cached); return cached; }\n const started = input.onConvolution ? now() : 0;\n const y0 = ly0 + b * BAND_ROWS, rows = Math.min(BAND_ROWS, ly1 - y0), gridHeight = rows + 2 * R, size = gridWidth * gridHeight;\n // #453: the band's shifts × spectral nodes convolutions share one geometry, validated once (the first runs the full\n // calculateIrradianceConvolution; every later one still checks its samples and kernel).\n const convolve = siteKernels ? undefined : createIrradianceConvolutionRunner({ schemaVersion: \"0.1.0\", width: gridWidth, height: gridHeight, kernelRadius: R,\n patchWidth: gridWidth, patchHeight: gridHeight, boundary: \"zero-outside-grid\" });\n const values = shifts.map((shift) => {\n // The plane point of lattice grid sample (gx, gy) of this shift, the same expressions for both fills below.\n const vOf = (gy: number): number => shift.y === 0 ? -(y0 + gy - R - M + 0.5 - H / 2) * g : -(y0 + gy - R - M + 0.5 + shift.y - H / 2) * g;\n const uOf = (x: number): number => shift.x === 0 ? (x - R - M + 0.5 - W / 2) * g : (x - R - M + 0.5 + shift.x - W / 2) * g;\n // #453, material scenes (chart presets and caller material scenes): radianceAt(u, v, nm) is materialRadiance(chartMaterialAt(u, v), nm)\n // (scene-radiance.ts), so the material is looked up once per lattice point and each node's samples come from one\n // materialRadiance per material present, the same numbers as one radianceAt per point and node.\n let materialOf: Int32Array | undefined;\n if (materialAt && materialRadiance) {\n materialOf = new Int32Array(size);\n for (let gy = 0; gy < gridHeight; gy++) {\n const v = vOf(gy);\n for (let gx = 0, x = lx0; gx < gridWidth; gx++, x++) materialOf[gy * gridWidth + gx] = materialAt(uOf(x), v);\n }\n }\n return wavelengthsNm.map((nm, w) => {\n const samples = new Float64Array(size);\n if (materialOf) {\n const radiance = new Map<number, number>();\n for (let i = 0; i < size; i++) {\n const m = materialOf[i]!;\n let value = radiance.get(m);\n if (value === undefined) { value = materialRadiance!(m, nm); radiance.set(m, value); }\n samples[i] = value;\n }\n } else {\n for (let gy = 0; gy < gridHeight; gy++) {\n const v = vOf(gy);\n for (let gx = 0, x = lx0; gx < gridWidth; gx++, x++) samples[gy * gridWidth + gx] = base.radianceAt(uOf(x), v, nm);\n }\n }\n if (!convolve) return gatherInterior(samples, taps[w]!, gridWidth, NW, rows, R);\n const blurred = convolve(samples, kernels[w]!);\n const out = new Float64Array(NW * rows);\n for (let y = 0; y < rows; y++) out.set(blurred.subarray((y + R) * gridWidth + R, (y + R) * gridWidth + R + NW), y * NW);\n return out;\n });\n });\n bands.set(b, values);\n if (bands.size > CACHED_BANDS) bands.delete(bands.keys().next().value!);\n if (input.onConvolution) input.onConvolution(now() - started);\n return values;\n }\n function blurredAt(u: number, v: number, nm: number): number {\n const w = index.get(nm), fi = u / g - 0.5 + W / 2, fj = -v / g - 0.5 + H / 2;\n if (w !== undefined) for (let s = 0; s < shifts.length; s++) {\n const shift = shifts[s]!, i = Math.round(fi - shift.x), j = Math.round(fj - shift.y);\n if (Math.abs(fi - shift.x - i) > LATTICE_TOLERANCE_SITES || Math.abs(fj - shift.y - j) > LATTICE_TOLERANCE_SITES) continue;\n const li = i + M, lj = j + M;\n if (li < lx0 || lj < ly0 || li >= lx1 || lj >= ly1) break;\n return band(Math.floor((lj - ly0) / BAND_ROWS))[s]![w]![((lj - ly0) % BAND_ROWS) * NW + li - lx0]!;\n }\n throw new InvalidConfigurationError(\"Diffraction query is off the site lattice; the object-space convolution does not apply.\");\n }\n const scale = input.metresPerFrameUnit, distance = input.distanceM, baseEvaluate = base.evaluateRadiance;\n const evaluateRadiance = (request: Readonly<SceneRadianceEvaluationRequest>): SceneRadianceEvaluationResult => {\n const result = baseEvaluate.call(base, request), o = (request.target as { outgoingDirectionUnitVector: { x: number; y: number; z: number } }).outgoingDirectionUnitVector;\n const t = distance / -o.z;\n return { ...result, spectralRadianceWattsPerSquareMeterSteradianNanometer: blurredAt(-o.x * t / scale, -o.y * t / scale, request.wavelengthNanometers) };\n };\n // 2.6: the result is the base result with only its radiance replaced (same keys and records), so an engine-built base\n // evaluator keeps its mark (see core/internal-radiance-evaluator.ts).\n if (isInternalSceneRadianceEvaluator(baseEvaluate)) {\n markInternalSceneRadianceEvaluator(evaluateRadiance);\n // #394: its radiance is the convolved value at one lattice site (shift s, lattice column li, row lj) per wavelength, so\n // the lean executor may read it by that key: the same plane point, lattice choice and band value as evaluateRadiance.\n registerInternalRadianceAccess(evaluateRadiance, {\n tabulated: false,\n keyOfDirection(o): number | undefined {\n if (!(-o.z > 0)) return undefined;\n const t = distance / -o.z, u = -o.x * t / scale, v = -o.y * t / scale, fi = u / g - 0.5 + W / 2, fj = -v / g - 0.5 + H / 2;\n for (let s = 0; s < shifts.length; s++) {\n const shift = shifts[s]!, i = Math.round(fi - shift.x), j = Math.round(fj - shift.y);\n if (Math.abs(fi - shift.x - i) > LATTICE_TOLERANCE_SITES || Math.abs(fj - shift.y - j) > LATTICE_TOLERANCE_SITES) continue;\n const li = i + M, lj = j + M;\n if (li < lx0 || lj < ly0 || li >= lx1 || lj >= ly1) return undefined;\n return (s * LH + lj) * LW + li;\n }\n return undefined;\n },\n radianceOfKey(key, nm): number {\n const w = index.get(nm);\n if (w === undefined) throw new InvalidConfigurationError(\"Diffraction query is off the site lattice; the object-space convolution does not apply.\");\n const li = key % LW, rest = (key - li) / LW, lj = rest % LH, s = (rest - lj) / LH;\n return band(Math.floor((lj - ly0) / BAND_ROWS))[s]![w]![((lj - ly0) % BAND_ROWS) * NW + li - lx0]!;\n }\n });\n }\n return {\n sceneId: base.sceneId, providerProfileId: base.providerProfileId, radianceAt: base.radianceAt,\n evaluateRadiance,\n evaluateApertureRadiance(): SceneRadianceEvaluationResult {\n throw new InvalidConfigurationError(\"Diffraction by object-space convolution does not take pupil rays.\");\n }\n };\n}\n\n/** Largest kernel sum, and largest sample, the object-space convolution accepts (as `IRRADIANCE_CONVOLUTION_LIMITS`). */\nconst MAXIMUM_KERNEL_SUM = 1 + 2 ** -20, MAXIMUM_SAMPLE = 2 ** 100;\n\n/** #492: a site kernel of radius R, checked as `calculateIrradianceConvolution` checks its kernels. */\nfunction checkedSiteKernel(kernel: Float64Array, R: number): Float64Array {\n if (!(kernel instanceof Float64Array) || kernel.length !== (2 * R + 1) ** 2) throw new InvalidConfigurationError(\"Site kernels must be (2R + 1)² taps.\");\n let sum = 0;\n for (let k = 0; k < kernel.length; k++) {\n const w = kernel[k]!;\n if (!(w >= 0 && w <= 1)) throw new InvalidConfigurationError(\"Site kernel weights must be finite numbers in [0, 1].\");\n sum += w;\n }\n if (sum > MAXIMUM_KERNEL_SUM) throw new InvalidConfigurationError(\"A PSF kernel may not create energy (sum exceeds 1).\");\n return kernel;\n}\n\n/** #492: the non-zero taps of a kernel as offsets into a grid of `gridWidth` columns (−v·gridWidth − u) and weights, v outer, u inner, ascending. */\nfunction kernelTaps(kernel: Float64Array, R: number, gridWidth: number): { offsets: Int32Array; weights: Float64Array } {\n const offsets: number[] = [], weights: number[] = [];\n for (let v = -R, t = 0; v <= R; v++) for (let u = -R; u <= R; u++, t++) {\n const w = kernel[t]!;\n if (w !== 0) { offsets.push(-v * gridWidth - u); weights.push(w); }\n }\n return { offsets: Int32Array.from(offsets), weights: Float64Array.from(weights) };\n}\n\n/**\n * #492: out(x, y) = Σ_t K(t)·samples(x + R − t_u, y + R − t_v) for the band's own values only (x < width, y < rows): every tap of\n * these lies inside the grid (it holds R extra samples on each side), so no boundary rule applies. Samples are checked as\n * `calculateIrradianceConvolution` checks them.\n */\nfunction gatherInterior(samples: Float64Array, taps: { offsets: Int32Array; weights: Float64Array }, gridWidth: number, width: number, rows: number, R: number): Float64Array {\n for (let k = 0; k < samples.length; k++) {\n const v = samples[k]!;\n if (!(v >= 0 && v <= MAXIMUM_SAMPLE)) throw new InvalidConfigurationError(\"Irradiance samples must be finite, non-negative and within the declared magnitude.\");\n }\n const { offsets, weights } = taps, count = weights.length, out = new Float64Array(width * rows);\n for (let y = 0; y < rows; y++) {\n const rowBase = (y + R) * gridWidth + R;\n for (let x = 0; x < width; x++) {\n const base = rowBase + x;\n let sum = 0;\n for (let k = 0; k < count; k++) sum += samples[base + offsets[k]!]! * weights[k]!;\n out[y * width + x] = sum;\n }\n }\n return out;\n}\n"]}
1
+ {"version":3,"file":"diffraction-provider.js","sourceRoot":"","sources":["../../src/facade/diffraction-provider.ts"],"names":[],"mappings":"AAAA,sCAAsC;AAEtC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgDG;AAEH,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAC3E,OAAO,EAAE,gCAAgC,EAAE,kCAAkC,EAAE,8BAA8B,EAAE,MAAM,wCAAwC,CAAC;AAE9J,OAAO,EAAE,yCAAyC,EAAE,MAAM,q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AC/B,MAAM,IAAI,GAAG,OAAO,GAAG,CAAC,CAAC;YACzB,IAAI,GAAG,GAAG,CAAC,CAAC;YACZ,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,EAAE,CAAC,EAAE;gBAAE,GAAG,IAAI,OAAO,CAAC,IAAI,GAAG,OAAO,CAAC,CAAC,CAAE,CAAE,GAAG,OAAO,CAAC,CAAC,CAAE,CAAC;YAClF,GAAG,CAAC,CAAC,GAAG,KAAK,GAAG,CAAC,CAAC,GAAG,GAAG,CAAC;QAC3B,CAAC;IACH,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Fast execution of `simulateCapture`'s `lens.diffraction` (2.1): an object-space convolution in the scene\n * provider, instead of one scene query per PSF tap in the environment PSF quadrature.\n *\n * The environment quadrature computes, at each site centre q and spectral node λ,\n * E(q, λ) = Σ_k K_λ(k)·T·L(s_k(q), λ),\n * where s_k(q) is the tap's source point (`sensorPsfSourcePoint`), L the scene radiance at the plane point\n * that source point sees, and T the radiance-to-irradiance factor. For the facade's planar scene seen\n * through the ideal rectilinear projection with a still camera and no lens field mapping, field throughput or\n * pupil rays:\n * - T is the same at every sensor point (paraxial π/(4·N_w²), no cos⁴ term), and\n * - with the kernel sampled on the site pitch, every source point is the centre of another site, so the plane\n * points form one regular lattice: u = (i + ½ − W/2)·2/w, v = −(j + ½ − H/2)·2/w (frame units, native\n * site (i, j), W×H native sites, w output width).\n * So E(q, λ) = T·B(q, λ) with B = K_λ ⊛ L sampled on that lattice: the same sum, in a different floating-point\n * order. B is computed once per spectral node with the engine's isoplanatic convolution\n * (`calculateIrradianceConvolution`, kernels from `resolveLensPsfConvolutionKernels`, exact site sampling) over a\n * grid that holds every source (the native raster plus the kernel radius on each side), in row bands; each band gathers only\n * its own values, the grid's interior (#419, `createIrradianceConvolutionInteriorRunner`: each value bit-identical to\n * `calculateIrradianceConvolution`'s there, without the 2R rows and columns of the band's grid that no query reads). The\n * provider then answers each site-centre query with B instead of L, and the environment request declares no\n * PSF. Incoherent imaging is a linear superposition of intensity PSFs, so convolving radiance on the object\n * plane and convolving irradiance on the image plane agree for a planar object and a space-invariant PSF\n * (MIT OpenCourseWare 2.71, lecture 22, free; also see: Goodman, Introduction to Fourier Optics, 4th ed., §7.1).\n *\n * With an anti-aliasing point-splitting filter (2.1, `sensor.antiAliasing`) the environment queries the PSF taps\n * around each pre-filter source point q − a (a = a split offset) instead of around q. Those taps lie on the site\n * lattice shifted by a, so the same argument holds on each shifted lattice: B is computed once per distinct\n * fractional shift (offsets that differ by whole sites share one lattice; the centred four-spot filter with a\n * one-site separation needs a single half-site-shifted lattice) over the native raster widened by the largest\n * offset, and the environment's spatial quadrature still forms the weighted split sum.\n *\n * Region renders (2.6, `window`): only the lattice rows and columns that the region's sites can query (the window\n * plus the largest offset on each side) are convolved, over a grid that adds the kernel radius on each side. Every\n * output value is the same gather as in the whole render: the grid always holds every tap of every value it keeps\n * (real scene radiance out to the kernel radius, never a truncated edge), the single kernel patch does not depend on\n * the grid's origin, and the gather (`convolveIrradianceRows`, and its interior form) sums each value in a fixed tap order (v outer, u inner). Narrowing\n * the grid therefore removes only values that no query reads, and the kept values are bit-identical.\n *\n * A query that does not land on one of the lattices (within 1e-6 site) is refused rather than approximated: the\n * facade uses this path only when the lattice argument above holds. A query outside the window is refused too.\n *\n * Defocus (#492, `lens.defocus`): the same argument holds for any space-invariant kernel on the site lattice, so the facade\n * passes `siteKernels` instead (the geometric defocus disc, or each node's diffraction kernel convolved with it). Their radius\n * may exceed the public 32-site convolution limit, so this path does not call `calculateIrradianceConvolution`: it checks the\n * samples and the kernel sums as that function does and gathers only the band's own values (`gatherInterior`), each summed\n * over the taps in the same fixed order (v outer, u inner, ascending; zero taps skipped, which adds exact zeros only). Like\n * the diffraction path (#419), it does not compute the 2R grid rows and columns around a band.\n */\n\nimport { InvalidConfigurationError } from \"../core/configuration-error.js\";\nimport { isInternalSceneRadianceEvaluator, markInternalSceneRadianceEvaluator, registerInternalRadianceAccess } from \"../core/internal-radiance-evaluator.js\";\nimport type { SceneRadianceEvaluationRequest, SceneRadianceEvaluationResult } from \"../schema/scene-radiance.js\";\nimport { createIrradianceConvolutionInteriorRunner } from \"../optics/irradiance-convolution.js\";\nimport { siteDiffractionKernel } from \"../optics/site-diffraction-kernel.js\";\nimport type { ResolveLensSampledPsfInput } from \"../optics/lens-psf-profile.js\";\nimport type { PlanarSceneRadianceProvider } from \"./scene-radiance.js\";\n\n/** Rows of native sites per convolution band, and the bands kept. Banding changes memory only, never values. */\nconst BAND_ROWS = 32;\nconst CACHED_BANDS = 4;\nconst LATTICE_TOLERANCE_SITES = 1e-6;\n\nexport interface DiffractedPlanarProviderInput {\n base: PlanarSceneRadianceProvider;\n /** The optical state of the sampled PSF, as for `resolveLensSampledPsf`, without field point and wavelength. Unused with `siteKernels`. */\n psf?: Omit<ResolveLensSampledPsfInput, \"fieldPointMm\" | \"wavelengthNm\">;\n /**\n * #492: the kernel of each spectral node on the site lattice, (2·kernelRadius + 1)² taps in row-major order, applied\n * instead of the diffraction kernels of `psf` (the defocus disc, or each node's diffraction kernel convolved with it).\n * Any radius; each kernel's sum may not exceed 1 + 2^-20.\n */\n siteKernels?: (wavelengthNm: number) => Float64Array;\n /** Spectral nodes the environment queries (the profile's wavelength nodes). */\n wavelengthsNm: readonly number[];\n kernelRadius: number;\n nativeWidth: number;\n nativeHeight: number;\n /** Output (active) width in sites: frame units are 2/outputWidth per site. */\n outputWidth: number;\n sitePitchMicrometers: number;\n /** Planar geometry of the base provider, to map query directions to plane points exactly as it does. */\n distanceM: number;\n metresPerFrameUnit: number;\n /**\n * Offsets of the query points from the site centres, in sites (+x right, +y down): the anti-aliasing split\n * offsets with their sign reversed (the environment queries q − a). Default: one zero offset.\n */\n queryOffsetsSites?: readonly { x: number; y: number }[];\n /**\n * Region renders (2.6): the native sites that will be queried (x, y, width, height in the native raster). Only the\n * lattice they can reach is convolved; values are bit-identical to the whole render's. Default: the whole raster.\n */\n window?: { x: number; y: number; width: number; height: number };\n /** Called with the duration in ms of each band convolution (diagnostics only; never changes values). */\n onConvolution?: (milliseconds: number) => void;\n}\n\n/** Internal (not exported from the package): the base provider with diffraction applied as an object-space convolution. */\nexport function createDiffractedPlanarProvider(input: DiffractedPlanarProviderInput): PlanarSceneRadianceProvider {\n const { base, wavelengthsNm, nativeWidth: W, nativeHeight: H, kernelRadius: R } = input;\n const g = 2 / input.outputWidth, pitch = input.sitePitchMicrometers;\n const index = new Map(wavelengthsNm.map((nm, i) => [nm, i]));\n // One lattice per distinct fractional query offset; M extra sites per side hold the offset queries.\n const offsets = input.queryOffsetsSites ?? [{ x: 0, y: 0 }];\n const fraction = (value: number): number => { const f = value - Math.floor(value); return f > 1 - LATTICE_TOLERANCE_SITES ? 0 : f < LATTICE_TOLERANCE_SITES ? 0 : f; };\n const shifts: { x: number; y: number }[] = [];\n for (const o of offsets) {\n const f = { x: fraction(o.x), y: fraction(o.y) };\n if (!shifts.some((s) => Math.abs(s.x - f.x) <= LATTICE_TOLERANCE_SITES && Math.abs(s.y - f.y) <= LATTICE_TOLERANCE_SITES)) shifts.push(f);\n }\n const M = Math.max(0, ...offsets.map((o) => Math.ceil(Math.max(Math.abs(o.x), Math.abs(o.y)) - LATTICE_TOLERANCE_SITES)));\n const LW = W + 2 * M, LH = H + 2 * M;\n // Lattice window (indices i + M, j + M): the sites the region queries plus the largest offset on each side, clipped\n // to the lattice. A site i queries i + floor(offset), and floor(offset) lies in [-M, M].\n const win = input.window ?? { x: 0, y: 0, width: W, height: H };\n const lx0 = Math.max(0, win.x), lx1 = Math.min(LW, win.x + win.width + 2 * M);\n const ly0 = Math.max(0, win.y), ly1 = Math.min(LH, win.y + win.height + 2 * M);\n if (!(lx0 < lx1 && ly0 < ly1)) throw new InvalidConfigurationError(\"Diffraction window must overlap the native raster.\");\n const NW = lx1 - lx0;\n // One kernel per wavelength, on the site grid, from the engine's own tap-to-site mapping (field point 0, 0); kept across calls.\n const siteKernels = input.siteKernels;\n if (!siteKernels && !input.psf) throw new InvalidConfigurationError(\"The object-space convolution needs a PSF or site kernels.\");\n const kernels = wavelengthsNm.map((wavelengthNm) => siteKernels ? checkedSiteKernel(siteKernels(wavelengthNm), R) :\n siteDiffractionKernel(input.psf!, wavelengthNm, pitch, R, \"Diffraction kernels must sample the site pitch exactly.\"));\n // #492: each site kernel's non-zero taps as grid offsets, in the gather's order.\n const taps = siteKernels ? kernels.map((kernel) => kernelTaps(kernel, R, NW + 2 * R)) : [];\n const gridWidth = NW + 2 * R;\n const now = (): number => globalThis.performance?.now() ?? Date.now();\n const bands = new Map<number, Float64Array[][]>();\n const materialAt = base.chartMaterialAt?.bind(base), materialRadiance = base.materialRadiance?.bind(base);\n function band(b: number): Float64Array[][] {\n const cached = bands.get(b);\n if (cached) { bands.delete(b); bands.set(b, cached); return cached; }\n const started = input.onConvolution ? now() : 0;\n const y0 = ly0 + b * BAND_ROWS, rows = Math.min(BAND_ROWS, ly1 - y0), gridHeight = rows + 2 * R, size = gridWidth * gridHeight;\n // #453: the band's shifts × spectral nodes convolutions share one geometry, validated once (the first with every check of\n // calculateIrradianceConvolution; every later one still checks its samples and kernel). #419: only the band's own rows × NW\n // values are gathered (the grid's interior), each bit-identical to calculateIrradianceConvolution's value there.\n const convolve = siteKernels ? undefined : createIrradianceConvolutionInteriorRunner({ schemaVersion: \"0.1.0\", width: gridWidth, height: gridHeight, kernelRadius: R,\n patchWidth: gridWidth, patchHeight: gridHeight, boundary: \"zero-outside-grid\" });\n const values = shifts.map((shift) => {\n // The plane point of lattice grid sample (gx, gy) of this shift, the same expressions for both fills below.\n const vOf = (gy: number): number => shift.y === 0 ? -(y0 + gy - R - M + 0.5 - H / 2) * g : -(y0 + gy - R - M + 0.5 + shift.y - H / 2) * g;\n const uOf = (x: number): number => shift.x === 0 ? (x - R - M + 0.5 - W / 2) * g : (x - R - M + 0.5 + shift.x - W / 2) * g;\n // #453, material scenes (chart presets and caller material scenes): radianceAt(u, v, nm) is materialRadiance(chartMaterialAt(u, v), nm)\n // (scene-radiance.ts), so the material is looked up once per lattice point and each node's samples come from one\n // materialRadiance per material present, the same numbers as one radianceAt per point and node.\n let materialOf: Int32Array | undefined;\n if (materialAt && materialRadiance) {\n materialOf = new Int32Array(size);\n for (let gy = 0; gy < gridHeight; gy++) {\n const v = vOf(gy);\n for (let gx = 0, x = lx0; gx < gridWidth; gx++, x++) materialOf[gy * gridWidth + gx] = materialAt(uOf(x), v);\n }\n }\n return wavelengthsNm.map((nm, w) => {\n const samples = new Float64Array(size);\n if (materialOf) {\n const radiance = new Map<number, number>();\n for (let i = 0; i < size; i++) {\n const m = materialOf[i]!;\n let value = radiance.get(m);\n if (value === undefined) { value = materialRadiance!(m, nm); radiance.set(m, value); }\n samples[i] = value;\n }\n } else {\n for (let gy = 0; gy < gridHeight; gy++) {\n const v = vOf(gy);\n for (let gx = 0, x = lx0; gx < gridWidth; gx++, x++) samples[gy * gridWidth + gx] = base.radianceAt(uOf(x), v, nm);\n }\n }\n if (!convolve) return gatherInterior(samples, taps[w]!, gridWidth, NW, rows, R);\n return convolve(samples, kernels[w]!);\n });\n });\n bands.set(b, values);\n if (bands.size > CACHED_BANDS) bands.delete(bands.keys().next().value!);\n if (input.onConvolution) input.onConvolution(now() - started);\n return values;\n }\n function blurredAt(u: number, v: number, nm: number): number {\n const w = index.get(nm), fi = u / g - 0.5 + W / 2, fj = -v / g - 0.5 + H / 2;\n if (w !== undefined) for (let s = 0; s < shifts.length; s++) {\n const shift = shifts[s]!, i = Math.round(fi - shift.x), j = Math.round(fj - shift.y);\n if (Math.abs(fi - shift.x - i) > LATTICE_TOLERANCE_SITES || Math.abs(fj - shift.y - j) > LATTICE_TOLERANCE_SITES) continue;\n const li = i + M, lj = j + M;\n if (li < lx0 || lj < ly0 || li >= lx1 || lj >= ly1) break;\n return band(Math.floor((lj - ly0) / BAND_ROWS))[s]![w]![((lj - ly0) % BAND_ROWS) * NW + li - lx0]!;\n }\n throw new InvalidConfigurationError(\"Diffraction query is off the site lattice; the object-space convolution does not apply.\");\n }\n const scale = input.metresPerFrameUnit, distance = input.distanceM, baseEvaluate = base.evaluateRadiance;\n const evaluateRadiance = (request: Readonly<SceneRadianceEvaluationRequest>): SceneRadianceEvaluationResult => {\n const result = baseEvaluate.call(base, request), o = (request.target as { outgoingDirectionUnitVector: { x: number; y: number; z: number } }).outgoingDirectionUnitVector;\n const t = distance / -o.z;\n return { ...result, spectralRadianceWattsPerSquareMeterSteradianNanometer: blurredAt(-o.x * t / scale, -o.y * t / scale, request.wavelengthNanometers) };\n };\n // 2.6: the result is the base result with only its radiance replaced (same keys and records), so an engine-built base\n // evaluator keeps its mark (see core/internal-radiance-evaluator.ts).\n if (isInternalSceneRadianceEvaluator(baseEvaluate)) {\n markInternalSceneRadianceEvaluator(evaluateRadiance);\n // #394: its radiance is the convolved value at one lattice site (shift s, lattice column li, row lj) per wavelength, so\n // the lean executor may read it by that key: the same plane point, lattice choice and band value as evaluateRadiance.\n registerInternalRadianceAccess(evaluateRadiance, {\n tabulated: false,\n keyOfDirection(o): number | undefined {\n if (!(-o.z > 0)) return undefined;\n const t = distance / -o.z, u = -o.x * t / scale, v = -o.y * t / scale, fi = u / g - 0.5 + W / 2, fj = -v / g - 0.5 + H / 2;\n for (let s = 0; s < shifts.length; s++) {\n const shift = shifts[s]!, i = Math.round(fi - shift.x), j = Math.round(fj - shift.y);\n if (Math.abs(fi - shift.x - i) > LATTICE_TOLERANCE_SITES || Math.abs(fj - shift.y - j) > LATTICE_TOLERANCE_SITES) continue;\n const li = i + M, lj = j + M;\n if (li < lx0 || lj < ly0 || li >= lx1 || lj >= ly1) return undefined;\n return (s * LH + lj) * LW + li;\n }\n return undefined;\n },\n radianceOfKey(key, nm): number {\n const w = index.get(nm);\n if (w === undefined) throw new InvalidConfigurationError(\"Diffraction query is off the site lattice; the object-space convolution does not apply.\");\n const li = key % LW, rest = (key - li) / LW, lj = rest % LH, s = (rest - lj) / LH;\n return band(Math.floor((lj - ly0) / BAND_ROWS))[s]![w]![((lj - ly0) % BAND_ROWS) * NW + li - lx0]!;\n }\n });\n }\n return {\n sceneId: base.sceneId, providerProfileId: base.providerProfileId, radianceAt: base.radianceAt,\n evaluateRadiance,\n evaluateApertureRadiance(): SceneRadianceEvaluationResult {\n throw new InvalidConfigurationError(\"Diffraction by object-space convolution does not take pupil rays.\");\n }\n };\n}\n\n/** Largest kernel sum, and largest sample, the object-space convolution accepts (as `IRRADIANCE_CONVOLUTION_LIMITS`). */\nconst MAXIMUM_KERNEL_SUM = 1 + 2 ** -20, MAXIMUM_SAMPLE = 2 ** 100;\n\n/** #492: a site kernel of radius R, checked as `calculateIrradianceConvolution` checks its kernels. */\nfunction checkedSiteKernel(kernel: Float64Array, R: number): Float64Array {\n if (!(kernel instanceof Float64Array) || kernel.length !== (2 * R + 1) ** 2) throw new InvalidConfigurationError(\"Site kernels must be (2R + 1)² taps.\");\n let sum = 0;\n for (let k = 0; k < kernel.length; k++) {\n const w = kernel[k]!;\n if (!(w >= 0 && w <= 1)) throw new InvalidConfigurationError(\"Site kernel weights must be finite numbers in [0, 1].\");\n sum += w;\n }\n if (sum > MAXIMUM_KERNEL_SUM) throw new InvalidConfigurationError(\"A PSF kernel may not create energy (sum exceeds 1).\");\n return kernel;\n}\n\n/** #492: the non-zero taps of a kernel as offsets into a grid of `gridWidth` columns (−v·gridWidth − u) and weights, v outer, u inner, ascending. */\nfunction kernelTaps(kernel: Float64Array, R: number, gridWidth: number): { offsets: Int32Array; weights: Float64Array } {\n const offsets: number[] = [], weights: number[] = [];\n for (let v = -R, t = 0; v <= R; v++) for (let u = -R; u <= R; u++, t++) {\n const w = kernel[t]!;\n if (w !== 0) { offsets.push(-v * gridWidth - u); weights.push(w); }\n }\n return { offsets: Int32Array.from(offsets), weights: Float64Array.from(weights) };\n}\n\n/**\n * #492: out(x, y) = Σ_t K(t)·samples(x + R − t_u, y + R − t_v) for the band's own values only (x < width, y < rows): every tap of\n * these lies inside the grid (it holds R extra samples on each side), so no boundary rule applies. Samples are checked as\n * `calculateIrradianceConvolution` checks them.\n */\nfunction gatherInterior(samples: Float64Array, taps: { offsets: Int32Array; weights: Float64Array }, gridWidth: number, width: number, rows: number, R: number): Float64Array {\n for (let k = 0; k < samples.length; k++) {\n const v = samples[k]!;\n if (!(v >= 0 && v <= MAXIMUM_SAMPLE)) throw new InvalidConfigurationError(\"Irradiance samples must be finite, non-negative and within the declared magnitude.\");\n }\n const { offsets, weights } = taps, count = weights.length, out = new Float64Array(width * rows);\n for (let y = 0; y < rows; y++) {\n const rowBase = (y + R) * gridWidth + R;\n for (let x = 0; x < width; x++) {\n const base = rowBase + x;\n let sum = 0;\n for (let k = 0; k < count; k++) sum += samples[base + offsets[k]!]! * weights[k]!;\n out[y * width + x] = sum;\n }\n }\n return out;\n}\n"]}
@@ -255,6 +255,33 @@ export declare function computeDisplayViewCorrectionStates(setup: DisplayViewCor
255
255
  * evaluated while the stratified estimator takes a quarter of its samples per axis where the pilot finds no detail.
256
256
  */
257
257
  export declare const EXACT_AREA_MEAN_MAX_PIXELS = 25;
258
+ /**
259
+ * createAhdDemosaicTask's steps at the centre pixel of an 11 × 11 patch (patch (dy + 5)·11 + dx + 5, normalized site values):
260
+ * `choose(phase)` fills the two candidates within 2 sites (`horizontal`, `vertical`: (dy + 2)·5 + dx + 2, three channels) and
261
+ * returns the centre's direction, 0 horizontal, 1 vertical, 2 equal homogeneity (both averaged). Greens are read by flat
262
+ * index (dy + 3)·7 + dx + 3; every value is formed with the same operations in the same order as the steps themselves,
263
+ * except that CIELAB's cube root is `portableCbrt` (within 1 ulp of Math.cbrt) and squares are products, so the result has
264
+ * the same bits in every JavaScript engine. (The task keeps its intermediate planes in float32; these are binary64.)
265
+ */
266
+ export declare function createAhdCentreSteps(labMatrix: readonly (readonly number[])[], patch: Float64Array): {
267
+ horizontal: Float64Array;
268
+ vertical: Float64Array;
269
+ choose(phase: number): number;
270
+ };
271
+ /**
272
+ * #457: AHD's direction at real pixels of the noise-free mosaic, as `createAhdDemosaicTask` computes it on the whole raster
273
+ * (every neighbour read at its reflect-101 position, so a position's greens, candidates, CIELAB and homogeneity are those of
274
+ * the task's planes), with each per-position quantity computed once and kept in rings of native rows. `direction(x, y)` is 0
275
+ * horizontal, 1 vertical, 2 equal homogeneity; `site(x, y)` gives the normalized expected value of an in-raster site, clipped
276
+ * at white. The kept columns are [x0, x0 + columns), set by `origin(x0)` (which also forgets every kept value); they must hold
277
+ * every real pixel asked about and 5 sites around it, clipped to the raster. `rows` is a power of two at least the native rows
278
+ * the real pixels asked about between two `origin` calls span plus 10. The arithmetic is the task's, in binary64 (the task
279
+ * stores its planes in float32), with `portableCbrt` and products for squares, as `createAhdCentreSteps`.
280
+ */
281
+ export declare function createAhdDirectionPlane(labMatrix: readonly (readonly number[])[], nativeWidth: number, nativeHeight: number, columns: number, rows: number, site: (x: number, y: number) => number): {
282
+ origin(x0: number): void;
283
+ direction(x: number, y: number): number;
284
+ };
258
285
  /** Renders the display view (docs/DISPLAY_VIEW.md). */
259
286
  export declare function renderDisplayView(setup: DisplayViewSetup): Promise<DisplayViewRenderResult>;
260
287
  /**
@@ -499,73 +499,19 @@ const SITE_RING_LIMIT = 1 << 18;
499
499
  /** Pilot points per axis: about one per two sites of the footprint plus its reach, 4 to 16. */
500
500
  function pilotCount(span) { return Math.max(4, Math.min(16, Math.ceil(span / 2))); }
501
501
  /**
502
- * The state computer of one setup's AHD correction (#447: shared by the render and `computeDisplayViewCorrectionStates`):
503
- * gridCorrection(i0, i1, i2) returns the offset of the grid state's three values in `states.values`, computing and storing
504
- * the state on first use. The code and its operations are those the render ran in place before.
502
+ * createAhdDemosaicTask's steps at the centre pixel of an 11 × 11 patch (patch (dy + 5)·11 + dx + 5, normalized site values):
503
+ * `choose(phase)` fills the two candidates within 2 sites (`horizontal`, `vertical`: (dy + 2)·5 + dx + 2, three channels) and
504
+ * returns the centre's direction, 0 horizontal, 1 vertical, 2 equal homogeneity (both averaged). Greens are read by flat
505
+ * index (dy + 3)·7 + dx + 3; every value is formed with the same operations in the same order as the steps themselves,
506
+ * except that CIELAB's cube root is `portableCbrt` (within 1 ulp of Math.cbrt) and squares are products, so the result has
507
+ * the same bits in every JavaScript engine. (The task keeps its intermediate planes in float32; these are binary64.)
505
508
  */
506
- function createGridCorrection(setup, states) {
507
- const { seed, ahdCorrection } = setup;
508
- const k = Float64Array.from(setup.readout, (r) => r.perElectron), c0 = Float64Array.from(setup.readout, (r) => r.constantVariance);
509
- const M = setup.matrix, m00 = M[0][0], m01 = M[0][1], m02 = M[0][2], m10 = M[1][0], m11 = M[1][1], m12 = M[1][2], m20 = M[2][0], m21 = M[2][1], m22 = M[2][2];
510
- const g0 = setup.gains[0], g1 = setup.gains[1], g2 = setup.gains[2], L = setup.clipLevel, reinhard = setup.toneCurve === "positive-reinhard-per-channel";
511
- const correction = new Float64Array(3), patch = new Float64Array(AHD_SIDE * AHD_SIDE);
512
- const readStd = Float64Array.from(c0, (v) => Math.sqrt(v));
513
- /** The offset of a grid state's three values in states.values (computed and stored on first use). */
514
- function gridCorrection(i0, i1, i2) {
515
- const key = (i0 * AHD_KEY_LEVELS + i1) * AHD_KEY_LEVELS + i2, cached = states.index.get(key);
516
- if (cached !== undefined)
517
- return 3 * cached;
518
- const electrons = [i0, i1, i2].map((i, c) => portableExp2(i / AHD_KEY_STEPS - AHD_KEY_OCTAVES) / k[c]);
519
- const random = createDeterministicUniformStream(deriveNativeSiteStreamSeedUint32(seed, fmixKey(i0, i1, i2), DISPLAY_VIEW_AHD_STREAM_ID));
520
- const sum = new Float64Array(3), draws = ahdCorrection.drawsPerState, poisson = electrons.map((e) => createPoissonSampler(e, true));
521
- const normal = createPortableStandardNormalPairs(random);
522
- for (let draw = 0; draw < draws; draw++) {
523
- const phase = draw & 3, roles = AHD_ROLES[phase];
524
- for (let p = 0; p < AHD_SIDE * AHD_SIDE; p++) {
525
- // The 16 sites the AHD steps never read are not drawn.
526
- if (AHD_READ[p] === 0)
527
- continue;
528
- const c = roles[p], value = k[c] * poisson[c](random) + readStd[c] * normal();
529
- patch[p] = value < 1 ? value : 1;
530
- }
531
- ahdDifference(phase, correction);
532
- for (let comp = 0; comp < 3; comp++)
533
- sum[comp] = sum[comp] + correction[comp] / draws;
534
- }
535
- if (states.index.size >= AHD_STATE_LIMIT)
536
- states.index.clear();
537
- const n = states.index.size;
538
- if (states.values.length < 3 * (n + 1)) {
539
- const grown = new Float64Array(2 * states.values.length);
540
- grown.set(states.values);
541
- states.values = grown;
542
- }
543
- states.values.set(sum, 3 * n);
544
- states.index.set(key, n);
545
- return 3 * n;
546
- }
547
- const lab = ahdCorrection.labMatrix, labWhite = Float64Array.from(lab, (row) => row[0] + row[1] + row[2]);
509
+ export function createAhdCentreSteps(labMatrix, patch) {
510
+ const lab = labMatrix, labWhite = Float64Array.from(lab, (row) => row[0] + row[1] + row[2]);
548
511
  const l00 = lab[0][0], l01 = lab[0][1], l02 = lab[0][2], l10 = lab[1][0], l11 = lab[1][1], l12 = lab[1][2], l20 = lab[2][0], l21 = lab[2][1], l22 = lab[2][2];
549
512
  const lw0 = labWhite[0], lw1 = labWhite[1], lw2 = labWhite[2];
550
513
  const gh = new Float64Array(49), gv = new Float64Array(49), cand = [new Float64Array(75), new Float64Array(75)], labs = [new Float64Array(75), new Float64Array(75)];
551
- const rgb = new Float64Array(3), rendered = new Float64Array(3), linear = new Float64Array(3);
552
- /** Develops one deterministic camera pixel and renders it: WB, highlight clip, colour matrix, tone curve, clip to [0, 1]. */
553
- function renderPixel(r, gr, b, out) {
554
- const u0 = Math.min(L, g0 * r), u1 = Math.min(L, g1 * gr), u2 = Math.min(L, g2 * b);
555
- for (let comp = 0; comp < 3; comp++) {
556
- let v = comp === 0 ? m00 * u0 + m01 * u1 + m02 * u2 : comp === 1 ? m10 * u0 + m11 * u1 + m12 * u2 : m20 * u0 + m21 * u1 + m22 * u2;
557
- if (reinhard)
558
- v = v > 0 ? v / (1 + v) : v;
559
- out[comp] = v < 0 ? 0 : v > 1 ? 1 : v;
560
- }
561
- }
562
- /**
563
- * h(AHD) − ½(h(H) + h(V)) at the centre of the drawn neighbourhood (createAhdDemosaicTask's steps, centre pixel only). The
564
- * patch and the greens are read by flat index (patch (dy + 5)·11 + dx + 5, greens (dy + 3)·7 + dx + 3); every value is formed
565
- * with the same operations in the same order as the steps themselves, except that CIELAB's cube root is `portableCbrt`
566
- * (within 1 ulp of Math.cbrt) and squares are products, so the result has the same bits in every JavaScript engine.
567
- */
568
- function ahdDifference(phase, out) {
514
+ function choose(phase) {
569
515
  const roles = AHD_ROLES[phase];
570
516
  // 1. Directional greens within 3 sites.
571
517
  for (let dy = -3; dy <= 3; dy++)
@@ -625,9 +571,195 @@ function createGridCorrection(setup, states) {
625
571
  sh += (hL0 <= epsL && hC0 <= epsC ? 1 : 0) + (hL1 <= epsL && hC1 <= epsC ? 1 : 0) + (hL2 <= epsL && hC2 <= epsC ? 1 : 0) + (hL3 <= epsL && hC3 <= epsC ? 1 : 0);
626
572
  sv += (vL0 <= epsL && vC0 <= epsC ? 1 : 0) + (vL1 <= epsL && vC1 <= epsC ? 1 : 0) + (vL2 <= epsL && vC2 <= epsC ? 1 : 0) + (vL3 <= epsL && vC3 <= epsC ? 1 : 0);
627
573
  }
628
- const centre = 12, a = cand[0], b = cand[1];
574
+ return sh > sv ? 0 : sv > sh ? 1 : 2;
575
+ }
576
+ return { horizontal: cand[0], vertical: cand[1], choose };
577
+ }
578
+ /**
579
+ * #457: AHD's direction at real pixels of the noise-free mosaic, as `createAhdDemosaicTask` computes it on the whole raster
580
+ * (every neighbour read at its reflect-101 position, so a position's greens, candidates, CIELAB and homogeneity are those of
581
+ * the task's planes), with each per-position quantity computed once and kept in rings of native rows. `direction(x, y)` is 0
582
+ * horizontal, 1 vertical, 2 equal homogeneity; `site(x, y)` gives the normalized expected value of an in-raster site, clipped
583
+ * at white. The kept columns are [x0, x0 + columns), set by `origin(x0)` (which also forgets every kept value); they must hold
584
+ * every real pixel asked about and 5 sites around it, clipped to the raster. `rows` is a power of two at least the native rows
585
+ * the real pixels asked about between two `origin` calls span plus 10. The arithmetic is the task's, in binary64 (the task
586
+ * stores its planes in float32), with `portableCbrt` and products for squares, as `createAhdCentreSteps`.
587
+ */
588
+ export function createAhdDirectionPlane(labMatrix, nativeWidth, nativeHeight, columns, rows, site) {
589
+ const lab = labMatrix, labWhite = Float64Array.from(lab, (row) => row[0] + row[1] + row[2]);
590
+ const l00 = lab[0][0], l01 = lab[0][1], l02 = lab[0][2], l10 = lab[1][0], l11 = lab[1][1], l12 = lab[1][2], l20 = lab[2][0], l21 = lab[2][1], l22 = lab[2][2];
591
+ const lw0 = labWhite[0], lw1 = labWhite[1], lw2 = labWhite[2];
592
+ const W = columns, mask = rows - 1, n = rows * W;
593
+ // Per position (slot (y & mask)·W + x − x0): the site value, the two greens, the two candidates' RGB and CIELAB and the two
594
+ // homogeneity counts, each valid while its stamp is epoch·2^24 + the position's row + 1 (exact in binary64; rows < 2^24).
595
+ const siteV = new Float64Array(n), siteS = new Float64Array(n), gH = new Float64Array(n), gV = new Float64Array(n), gS = new Float64Array(n);
596
+ const rgb = new Float64Array(6 * n), labs = new Float64Array(6 * n), cS = new Float64Array(n), hom = new Uint8Array(2 * n), hS = new Float64Array(n);
597
+ let x0 = 0, epoch = 0;
598
+ const rx = (x) => (x < 0 ? -x : x >= nativeWidth ? 2 * nativeWidth - 2 - x : x);
599
+ const ry = (y) => (y < 0 ? -y : y >= nativeHeight ? 2 * nativeHeight - 2 - y : y);
600
+ const role = (x, y) => ((y & 1) === 0 ? ((x & 1) === 0 ? 0 : 1) : ((x & 1) === 0 ? 1 : 2));
601
+ /** The site at (x, y) read reflect-101 (`at` of the task). */
602
+ function at(x, y) {
603
+ const X = rx(x), Y = ry(y), q = (Y & mask) * W + X - x0;
604
+ if (siteS[q] !== epoch + Y + 1) {
605
+ siteV[q] = site(X, Y);
606
+ siteS[q] = epoch + Y + 1;
607
+ }
608
+ return siteV[q];
609
+ }
610
+ /** Fills the two greens of in-raster position (x, y) (step 1) and returns its slot. */
611
+ function greens(x, y) {
612
+ const q = (y & mask) * W + x - x0;
613
+ if (gS[q] === epoch + y + 1)
614
+ return q;
615
+ const c = at(x, y);
616
+ if (role(x, y) === 1) {
617
+ gH[q] = c;
618
+ gV[q] = c;
619
+ }
620
+ else {
621
+ gH[q] = (at(x - 1, y) + at(x + 1, y)) / 2 + (2 * c - at(x - 2, y) - at(x + 2, y)) / 4;
622
+ gV[q] = (at(x, y - 1) + at(x, y + 1)) / 2 + (2 * c - at(x, y - 2) - at(x, y + 2)) / 4;
623
+ }
624
+ gS[q] = epoch + y + 1;
625
+ return q;
626
+ }
627
+ /** s − g of direction d at the reflected position of (x, y). */
628
+ function difference(x, y, d) {
629
+ const X = rx(x), Y = ry(y), q = greens(X, Y);
630
+ return at(X, Y) - (d === 0 ? gH[q] : gV[q]);
631
+ }
632
+ /** Fills the two candidates and their CIELAB at in-raster position (x, y) (steps 2 and 3) and returns its slot. */
633
+ function candidates(x, y) {
634
+ const q = (y & mask) * W + x - x0;
635
+ if (cS[q] === epoch + y + 1)
636
+ return q;
637
+ greens(x, y);
638
+ const own = role(x, y);
639
+ for (let d = 0; d < 2; d++) {
640
+ const gi = d === 0 ? gH[q] : gV[q], o = 6 * q + 3 * d;
641
+ rgb[o + 1] = gi;
642
+ if (own === 1) {
643
+ const hRole = role(x + 1, y), vRole = 2 - hRole;
644
+ const a = difference(x - 1, y, d), b = difference(x + 1, y, d);
645
+ rgb[o + hRole] = gi + (a + b) / 2;
646
+ const cc = difference(x, y - 1, d), dd = difference(x, y + 1, d);
647
+ rgb[o + vRole] = gi + (cc + dd) / 2;
648
+ }
649
+ else {
650
+ rgb[o + own] = at(x, y);
651
+ rgb[o + 2 - own] = gi + (difference(x - 1, y - 1, d) + difference(x + 1, y - 1, d) + difference(x - 1, y + 1, d) + difference(x + 1, y + 1, d)) / 4;
652
+ }
653
+ const R = rgb[o], G = rgb[o + 1], Bc = rgb[o + 2];
654
+ let tx = (l00 * R + l01 * G + l02 * Bc) / lw0, ty = (l10 * R + l11 * G + l12 * Bc) / lw1, tz = (l20 * R + l21 * G + l22 * Bc) / lw2;
655
+ tx = tx > LAB_EPSILON ? portableCbrt(tx) : (LAB_KAPPA * tx + 16) / 116;
656
+ ty = ty > LAB_EPSILON ? portableCbrt(ty) : (LAB_KAPPA * ty + 16) / 116;
657
+ tz = tz > LAB_EPSILON ? portableCbrt(tz) : (LAB_KAPPA * tz + 16) / 116;
658
+ labs[o] = 116 * ty - 16;
659
+ labs[o + 1] = 500 * (tx - ty);
660
+ labs[o + 2] = 200 * (ty - tz);
661
+ }
662
+ cS[q] = epoch + y + 1;
663
+ return q;
664
+ }
665
+ /** The two homogeneity counts of in-raster position (x, y) (step 4), at hom[2·slot] and hom[2·slot + 1]. */
666
+ function homogeneity(x, y) {
667
+ const q = (y & mask) * W + x - x0;
668
+ if (hS[q] === epoch + y + 1)
669
+ return q;
670
+ const i = 6 * candidates(x, y), jl = 6 * candidates(rx(x - 1), y), jr = 6 * candidates(rx(x + 1), y), ju = 6 * candidates(x, ry(y - 1)), jd = 6 * candidates(x, ry(y + 1));
671
+ const h = labs;
672
+ // Direction 0 at offsets +0, direction 1 at +3; neighbours left, right, up, down.
673
+ const hL0 = Math.abs(h[i] - h[jl]), hL1 = Math.abs(h[i] - h[jr]), hL2 = Math.abs(h[i] - h[ju]), hL3 = Math.abs(h[i] - h[jd]);
674
+ const vL0 = Math.abs(h[i + 3] - h[jl + 3]), vL1 = Math.abs(h[i + 3] - h[jr + 3]), vL2 = Math.abs(h[i + 3] - h[ju + 3]), vL3 = Math.abs(h[i + 3] - h[jd + 3]);
675
+ const hC0 = square(h[i + 1] - h[jl + 1]) + square(h[i + 2] - h[jl + 2]), hC1 = square(h[i + 1] - h[jr + 1]) + square(h[i + 2] - h[jr + 2]);
676
+ const hC2 = square(h[i + 1] - h[ju + 1]) + square(h[i + 2] - h[ju + 2]), hC3 = square(h[i + 1] - h[jd + 1]) + square(h[i + 2] - h[jd + 2]);
677
+ const vC0 = square(h[i + 4] - h[jl + 4]) + square(h[i + 5] - h[jl + 5]), vC1 = square(h[i + 4] - h[jr + 4]) + square(h[i + 5] - h[jr + 5]);
678
+ const vC2 = square(h[i + 4] - h[ju + 4]) + square(h[i + 5] - h[ju + 5]), vC3 = square(h[i + 4] - h[jd + 4]) + square(h[i + 5] - h[jd + 5]);
679
+ const epsL = Math.min(Math.max(hL0, hL1), Math.max(vL2, vL3)), epsC = Math.min(Math.max(hC0, hC1), Math.max(vC2, vC3));
680
+ hom[2 * q] = (hL0 <= epsL && hC0 <= epsC ? 1 : 0) + (hL1 <= epsL && hC1 <= epsC ? 1 : 0) + (hL2 <= epsL && hC2 <= epsC ? 1 : 0) + (hL3 <= epsL && hC3 <= epsC ? 1 : 0);
681
+ hom[2 * q + 1] = (vL0 <= epsL && vC0 <= epsC ? 1 : 0) + (vL1 <= epsL && vC1 <= epsC ? 1 : 0) + (vL2 <= epsL && vC2 <= epsC ? 1 : 0) + (vL3 <= epsL && vC3 <= epsC ? 1 : 0);
682
+ hS[q] = epoch + y + 1;
683
+ return q;
684
+ }
685
+ return {
686
+ origin(first) { x0 = first; epoch += 16777216; },
687
+ /** Step 5: the 3 × 3 sums of homogeneity (reflected) select the direction. */
688
+ direction(x, y) {
689
+ let sh = 0, sv = 0;
690
+ for (let dy = -1; dy <= 1; dy++)
691
+ for (let dx = -1; dx <= 1; dx++) {
692
+ const q = homogeneity(rx(x + dx), ry(y + dy));
693
+ sh += hom[2 * q];
694
+ sv += hom[2 * q + 1];
695
+ }
696
+ return sh > sv ? 0 : sv > sh ? 1 : 2;
697
+ }
698
+ };
699
+ }
700
+ /**
701
+ * The state computer of one setup's AHD correction (#447: shared by the render and `computeDisplayViewCorrectionStates`):
702
+ * gridCorrection(i0, i1, i2) returns the offset of the grid state's three values in `states.values`, computing and storing
703
+ * the state on first use. The code and its operations are those the render ran in place before.
704
+ */
705
+ function createGridCorrection(setup, states) {
706
+ const { seed, ahdCorrection } = setup;
707
+ const k = Float64Array.from(setup.readout, (r) => r.perElectron), c0 = Float64Array.from(setup.readout, (r) => r.constantVariance);
708
+ const M = setup.matrix, m00 = M[0][0], m01 = M[0][1], m02 = M[0][2], m10 = M[1][0], m11 = M[1][1], m12 = M[1][2], m20 = M[2][0], m21 = M[2][1], m22 = M[2][2];
709
+ const g0 = setup.gains[0], g1 = setup.gains[1], g2 = setup.gains[2], L = setup.clipLevel, reinhard = setup.toneCurve === "positive-reinhard-per-channel";
710
+ const correction = new Float64Array(3), patch = new Float64Array(AHD_SIDE * AHD_SIDE);
711
+ const readStd = Float64Array.from(c0, (v) => Math.sqrt(v));
712
+ /** The offset of a grid state's three values in states.values (computed and stored on first use). */
713
+ function gridCorrection(i0, i1, i2) {
714
+ const key = (i0 * AHD_KEY_LEVELS + i1) * AHD_KEY_LEVELS + i2, cached = states.index.get(key);
715
+ if (cached !== undefined)
716
+ return 3 * cached;
717
+ const electrons = [i0, i1, i2].map((i, c) => portableExp2(i / AHD_KEY_STEPS - AHD_KEY_OCTAVES) / k[c]);
718
+ const random = createDeterministicUniformStream(deriveNativeSiteStreamSeedUint32(seed, fmixKey(i0, i1, i2), DISPLAY_VIEW_AHD_STREAM_ID));
719
+ const sum = new Float64Array(3), draws = ahdCorrection.drawsPerState, poisson = electrons.map((e) => createPoissonSampler(e, true));
720
+ const normal = createPortableStandardNormalPairs(random);
721
+ for (let draw = 0; draw < draws; draw++) {
722
+ const phase = draw & 3, roles = AHD_ROLES[phase];
723
+ for (let p = 0; p < AHD_SIDE * AHD_SIDE; p++) {
724
+ // The 16 sites the AHD steps never read are not drawn.
725
+ if (AHD_READ[p] === 0)
726
+ continue;
727
+ const c = roles[p], value = k[c] * poisson[c](random) + readStd[c] * normal();
728
+ patch[p] = value < 1 ? value : 1;
729
+ }
730
+ ahdDifference(phase, correction);
731
+ for (let comp = 0; comp < 3; comp++)
732
+ sum[comp] = sum[comp] + correction[comp] / draws;
733
+ }
734
+ if (states.index.size >= AHD_STATE_LIMIT)
735
+ states.index.clear();
736
+ const n = states.index.size;
737
+ if (states.values.length < 3 * (n + 1)) {
738
+ const grown = new Float64Array(2 * states.values.length);
739
+ grown.set(states.values);
740
+ states.values = grown;
741
+ }
742
+ states.values.set(sum, 3 * n);
743
+ states.index.set(key, n);
744
+ return 3 * n;
745
+ }
746
+ const steps = createAhdCentreSteps(ahdCorrection.labMatrix, patch);
747
+ const rgb = new Float64Array(3), rendered = new Float64Array(3), linear = new Float64Array(3);
748
+ /** Develops one deterministic camera pixel and renders it: WB, highlight clip, colour matrix, tone curve, clip to [0, 1]. */
749
+ function renderPixel(r, gr, b, out) {
750
+ const u0 = Math.min(L, g0 * r), u1 = Math.min(L, g1 * gr), u2 = Math.min(L, g2 * b);
751
+ for (let comp = 0; comp < 3; comp++) {
752
+ let v = comp === 0 ? m00 * u0 + m01 * u1 + m02 * u2 : comp === 1 ? m10 * u0 + m11 * u1 + m12 * u2 : m20 * u0 + m21 * u1 + m22 * u2;
753
+ if (reinhard)
754
+ v = v > 0 ? v / (1 + v) : v;
755
+ out[comp] = v < 0 ? 0 : v > 1 ? 1 : v;
756
+ }
757
+ }
758
+ /** h(AHD) − ½(h(H) + h(V)) at the centre of the drawn neighbourhood (`createAhdCentreSteps`). */
759
+ function ahdDifference(phase, out) {
760
+ const dir = steps.choose(phase), a = steps.horizontal, b = steps.vertical, centre = 12;
629
761
  for (let c = 0; c < 3; c++)
630
- rgb[c] = sh > sv ? a[3 * centre + c] : sv > sh ? b[3 * centre + c] : (a[3 * centre + c] + b[3 * centre + c]) / 2;
762
+ rgb[c] = dir === 0 ? a[3 * centre + c] : dir === 1 ? b[3 * centre + c] : (a[3 * centre + c] + b[3 * centre + c]) / 2;
631
763
  renderPixel(rgb[0], rgb[1], rgb[2], rendered);
632
764
  renderPixel(a[3 * centre], a[3 * centre + 1], a[3 * centre + 2], linear);
633
765
  for (let c = 0; c < 3; c++)
@@ -720,6 +852,19 @@ export async function renderDisplayView(setup) {
720
852
  // AHD low-signal correction: an 11 × 11 noisy neighbourhood (AHD reads up to 5 sites away) and the local AHD steps.
721
853
  const ahdCorrection = setup.ahdCorrection, windowReach = ahdCorrection ? Math.max(reach, AHD_REACH) : reach;
722
854
  const cmAverage = new Float64Array(3);
855
+ // #457: AHD's choice on the noise-free mosaic. Per candidate the rendered mean and the camera-channel means of the sample.
856
+ const candidateRendered = new Float64Array(6), candidateChannels = new Float64Array(6);
857
+ /** The normalized expected value of an in-raster site, clipped at white (the noise-free mosaic AHD's choice reads). */
858
+ const noiseFreeSite = (x, y) => { const c = (y & 1) === 0 ? ((x & 1) === 0 ? 0 : 1) : ((x & 1) === 0 ? 1 : 2), v = k[c] * (setup.signal.site(x, y) + dark[c]); return v < 1 ? v : 1; };
859
+ // The exact path keeps the region's columns for the whole render; the stratified estimator keeps one display pixel's
860
+ // footprint at a time (its samples are scattered over it), so its plane is set to each display pixel's columns.
861
+ let choiceRows = 1;
862
+ while (choiceRows < Math.ceil(sy) + 2 + 2 * AHD_REACH)
863
+ choiceRows *= 2;
864
+ const choiceX0 = Math.max(0, exactX0 - AHD_REACH), choiceColumns = exactView ? Math.min(nativeWidth - 1, exactX0 + exactWidth - 1 + AHD_REACH) - choiceX0 + 1 : Math.ceil(sx) + 2 + 2 * AHD_REACH;
865
+ const choicePlane = ahdCorrection ? createAhdDirectionPlane(ahdCorrection.labMatrix, nativeWidth, nativeHeight, choiceColumns, exactView ? 2 * choiceRows : choiceRows, noiseFreeSite) : undefined;
866
+ if (choicePlane && exactView)
867
+ choicePlane.origin(choiceX0);
723
868
  let correctedPixels = 0;
724
869
  // The correction of a flat neighbourhood whose sites of channel c have normalized mean μ_c, on a logarithmic grid of states
725
870
  // (AHD_KEY_STEPS per octave from 2^-AHD_KEY_OCTAVES of white); each grid state is computed once with draws seeded by the state
@@ -866,6 +1011,8 @@ export async function renderDisplayView(setup) {
866
1011
  markM = new Int32Array(slotsCount);
867
1012
  }
868
1013
  const mx0 = Math.floor(vx * sx) + margin, my0 = Math.floor(vy * sy) + margin;
1014
+ if (choicePlane && !exactView)
1015
+ choicePlane.origin(Math.max(0, mx0 - AHD_REACH));
869
1016
  const mw = Math.min(frameWidth - 1, Math.ceil((vx + 1) * sx)) + margin - mx0 + 1, mh = Math.min(frameHeight - 1, Math.ceil((vy + 1) * sy)) + margin - my0 + 1;
870
1017
  const pixelMemo = !exactView && setup.signal.cachesSites && mw * mh <= PIXEL_MEMO_LIMIT;
871
1018
  if (pixelMemo) {
@@ -1220,6 +1367,12 @@ export async function renderDisplayView(setup) {
1220
1367
  e0 += share * hm[0];
1221
1368
  e1 += share * hm[1];
1222
1369
  e2 += share * hm[2];
1370
+ candidateRendered[3 * d] = hm[0];
1371
+ candidateRendered[3 * d + 1] = hm[1];
1372
+ candidateRendered[3 * d + 2] = hm[2];
1373
+ candidateChannels[3 * d] = cm[0];
1374
+ candidateChannels[3 * d + 1] = cm[1];
1375
+ candidateChannels[3 * d + 2] = cm[2];
1223
1376
  // Linear (Stein) part: a_c = J ∘ M[:, c]·Γ_c, accumulated with B_c·σ_c² (site variance of channel c); the pixel's own
1224
1377
  // linear variance (aᵀ·C·a, full channel covariance) for the residual.
1225
1378
  let l0 = 0, l1 = 0, l2 = 0;
@@ -1261,6 +1414,22 @@ export async function renderDisplayView(setup) {
1261
1414
  // Two-argument maxima (inlined; the same value as one four-argument Math.max, which V8 calls with boxed arguments).
1262
1415
  pixelVariance = Math.max(Math.max(pixelVariance, hv[0]), Math.max(hv[1], hv[2]));
1263
1416
  }
1417
+ // #457: AHD chooses one candidate per pixel by homogeneity. Where the scene decides that choice (structure finer than a
1418
+ // few sites, such as a Siemens star's centre), the expected value is the chosen candidate's, not the candidates' average:
1419
+ // the steps run on the noise-free mosaic (the expected normalized site values, clipped at white, mirrored at the raster
1420
+ // edges as the capture's AHD reads them), and a decided direction takes that candidate's rendered mean. A tie (every flat
1421
+ // neighbourhood, where the noise decides) keeps the average, and the low-signal correction below stays the noise's
1422
+ // bias of a flat neighbourhood. Skipped where the two candidates' channel means are equal (the choice cannot change the
1423
+ // value) and for one-material samples (equal up to rounding; their memo is keyed by material and phase, not by the
1424
+ // patch). The noise terms are unchanged.
1425
+ if (choicePlane && count === 2 && memoKey < 0 && (candidateChannels[0] !== candidateChannels[3] || candidateChannels[1] !== candidateChannels[4] || candidateChannels[2] !== candidateChannels[5])) {
1426
+ const direction = choicePlane.direction(x, y);
1427
+ if (direction !== 2) {
1428
+ e0 = candidateRendered[3 * direction];
1429
+ e1 = candidateRendered[3 * direction + 1];
1430
+ e2 = candidateRendered[3 * direction + 2];
1431
+ }
1432
+ }
1264
1433
  s0 += wE * e0;
1265
1434
  s1 += wE * e1;
1266
1435
  s2 += wE * e2;