@photivra/engine 2.15.0 → 2.17.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 (119) hide show
  1. package/CHANGELOG.md +102 -1
  2. package/CITATION.cff +1 -1
  3. package/README.md +6 -6
  4. package/SECURITY.md +1 -1
  5. package/THIRD_PARTY.md +38 -0
  6. package/dist/camera/lens-projection.d.ts +5 -0
  7. package/dist/camera/lens-projection.js +10 -0
  8. package/dist/camera/lens-projection.js.map +1 -1
  9. package/dist/capture/native-environment-lean.js +1 -1
  10. package/dist/capture/native-environment-lean.js.map +1 -1
  11. package/dist/capture/native-raw-development.d.ts +15 -0
  12. package/dist/capture/native-raw-development.js +12 -6
  13. package/dist/capture/native-raw-development.js.map +1 -1
  14. package/dist/capture/raw-development-kernel.d.ts +10 -3
  15. package/dist/capture/raw-development-kernel.js +25 -6
  16. package/dist/capture/raw-development-kernel.js.map +1 -1
  17. package/dist/core/internal-radiance-evaluator.d.ts +5 -2
  18. package/dist/core/internal-radiance-evaluator.js.map +1 -1
  19. package/dist/core/version.d.ts +1 -1
  20. package/dist/core/version.js +1 -1
  21. package/dist/core/version.js.map +1 -1
  22. package/dist/equipment/generic-lens-catalogue.d.ts +227 -0
  23. package/dist/equipment/generic-lens-catalogue.js +243 -0
  24. package/dist/equipment/generic-lens-catalogue.js.map +1 -0
  25. package/dist/facade/defocus-bokeh-zones.d.ts +33 -0
  26. package/dist/facade/defocus-bokeh-zones.js +53 -0
  27. package/dist/facade/defocus-bokeh-zones.js.map +1 -0
  28. package/dist/facade/defocus-image-space-provider.d.ts +118 -0
  29. package/dist/facade/defocus-image-space-provider.js +448 -0
  30. package/dist/facade/defocus-image-space-provider.js.map +1 -0
  31. package/dist/facade/diffraction-provider.d.ts +45 -0
  32. package/dist/facade/diffraction-provider.js +120 -14
  33. package/dist/facade/diffraction-provider.js.map +1 -1
  34. package/dist/facade/display-view-gpu-session.js +4 -0
  35. package/dist/facade/display-view-gpu-session.js.map +1 -1
  36. package/dist/facade/display-view-gpu.d.ts +10 -0
  37. package/dist/facade/display-view-gpu.js.map +1 -1
  38. package/dist/facade/display-view-lens-signal.d.ts +30 -0
  39. package/dist/facade/display-view-lens-signal.js +427 -0
  40. package/dist/facade/display-view-lens-signal.js.map +1 -0
  41. package/dist/facade/display-view.d.ts +21 -0
  42. package/dist/facade/display-view.js +66 -8
  43. package/dist/facade/display-view.js.map +1 -1
  44. package/dist/facade/expected-signal-setup.d.ts +7 -0
  45. package/dist/facade/expected-signal-setup.js +12 -2
  46. package/dist/facade/expected-signal-setup.js.map +1 -1
  47. package/dist/facade/expected-signal.d.ts +8 -0
  48. package/dist/facade/expected-signal.js +150 -0
  49. package/dist/facade/expected-signal.js.map +1 -1
  50. package/dist/facade/generic-lens-capture.d.ts +6 -0
  51. package/dist/facade/generic-lens-capture.js +8 -0
  52. package/dist/facade/generic-lens-capture.js.map +1 -0
  53. package/dist/facade/large-defocus-lattice.d.ts +39 -0
  54. package/dist/facade/large-defocus-lattice.js +64 -0
  55. package/dist/facade/large-defocus-lattice.js.map +1 -0
  56. package/dist/facade/scene-radiance.d.ts +5 -0
  57. package/dist/facade/scene-radiance.js +5 -2
  58. package/dist/facade/scene-radiance.js.map +1 -1
  59. package/dist/facade/simulate-capture.d.ts +148 -6
  60. package/dist/facade/simulate-capture.js +521 -88
  61. package/dist/facade/simulate-capture.js.map +1 -1
  62. package/dist/facade/simulate-display-view.js +29 -19
  63. package/dist/facade/simulate-display-view.js.map +1 -1
  64. package/dist/gpu/display-view-quality-gpu.d.ts +2 -9
  65. package/dist/gpu/display-view-quality-gpu.js +63 -13
  66. package/dist/gpu/display-view-quality-gpu.js.map +1 -1
  67. package/dist/gpu/display-view-speed-gpu.d.ts +2 -0
  68. package/dist/gpu/display-view-speed-gpu.js +47 -16
  69. package/dist/gpu/display-view-speed-gpu.js.map +1 -1
  70. package/dist/gpu/image-kernel-accelerator.js +3 -0
  71. package/dist/gpu/image-kernel-accelerator.js.map +1 -1
  72. package/dist/gpu/wgsl-display-view-quality-kernel.d.ts +4 -0
  73. package/dist/gpu/wgsl-display-view-quality-kernel.js +53 -2
  74. package/dist/gpu/wgsl-display-view-quality-kernel.js.map +1 -1
  75. package/dist/gpu/wgsl-display-view-speed-kernel.d.ts +15 -0
  76. package/dist/gpu/wgsl-display-view-speed-kernel.js +42 -1
  77. package/dist/gpu/wgsl-display-view-speed-kernel.js.map +1 -1
  78. package/dist/index.d.ts +5 -2
  79. package/dist/index.js +4 -1
  80. package/dist/index.js.map +1 -1
  81. package/dist/optics/defocus-bokeh-kernel.d.ts +207 -0
  82. package/dist/optics/defocus-bokeh-kernel.js +380 -0
  83. package/dist/optics/defocus-bokeh-kernel.js.map +1 -0
  84. package/dist/optics/defocus-disc-kernel.d.ts +44 -21
  85. package/dist/optics/defocus-disc-kernel.js +47 -25
  86. package/dist/optics/defocus-disc-kernel.js.map +1 -1
  87. package/dist/optics/generic-lens-psf.d.ts +68 -0
  88. package/dist/optics/generic-lens-psf.js +337 -0
  89. package/dist/optics/generic-lens-psf.js.map +1 -0
  90. package/dist/optics/illumination-vignetting.d.ts +6 -0
  91. package/dist/optics/illumination-vignetting.js +24 -7
  92. package/dist/optics/illumination-vignetting.js.map +1 -1
  93. package/dist/optics/sensor-environment-query.d.ts +37 -0
  94. package/dist/optics/sensor-environment-query.js +58 -19
  95. package/dist/optics/sensor-environment-query.js.map +1 -1
  96. package/dist/optics/site-kernel-runs.d.ts +77 -0
  97. package/dist/optics/site-kernel-runs.js +200 -0
  98. package/dist/optics/site-kernel-runs.js.map +1 -0
  99. package/dist/output/generic-lens-corrections.d.ts +24 -0
  100. package/dist/output/generic-lens-corrections.js +51 -0
  101. package/dist/output/generic-lens-corrections.js.map +1 -0
  102. package/dist/processing/development-detail.d.ts +132 -0
  103. package/dist/processing/development-detail.js +325 -0
  104. package/dist/processing/development-detail.js.map +1 -0
  105. package/docs/AGENT_GUIDE.md +1 -0
  106. package/docs/API_REFERENCE.md +54 -1
  107. package/docs/QUICK_START.md +444 -26
  108. package/docs/USAGE.md +71 -8
  109. package/docs/api/capture-native-raw-development.md +16 -0
  110. package/docs/api/core-version.md +1 -1
  111. package/docs/api/equipment-generic-lens-catalogue.md +281 -0
  112. package/docs/api/exports.json +162 -2
  113. package/docs/api/facade-simulate-capture.md +151 -5
  114. package/docs/api/optics-defocus-bokeh-kernel.md +145 -0
  115. package/docs/api/optics-defocus-disc-kernel.md +25 -17
  116. package/docs/api/optics-sensor-environment-query.md +6 -0
  117. package/docs/api/output-generic-lens-corrections.md +39 -0
  118. package/llms.txt +1 -0
  119. package/package.json +1 -1
@@ -47,11 +47,16 @@
47
47
  * samples and the kernel sums as that function does and gathers only the band's own values (`gatherInterior`), each summed
48
48
  * over the taps in the same fixed order (v outer, u inner, ascending; zero taps skipped, which adds exact zeros only). Like
49
49
  * the diffraction path (#419), it does not compute the 2R grid rows and columns around a band.
50
+ *
51
+ * Large defocus kernels (#564, `largeKernel`): above 64 sites the disc is convolved by runs in fixed tiles instead of bands
52
+ * (`large-defocus-lattice.ts`, `site-kernel-runs.ts`), each node's diffraction kernel after it; the plane points and the
53
+ * material lookup are the bands' own, and values stay independent of the window.
50
54
  */
51
55
  import { InvalidConfigurationError } from "../core/configuration-error.js";
52
56
  import { isInternalSceneRadianceEvaluator, markInternalSceneRadianceEvaluator, registerInternalRadianceAccess } from "../core/internal-radiance-evaluator.js";
53
57
  import { createIrradianceConvolutionInteriorRunner } from "../optics/irradiance-convolution.js";
54
58
  import { siteDiffractionKernel } from "../optics/site-diffraction-kernel.js";
59
+ import { LARGE_DEFOCUS_CACHE_BYTES, createLargeDefocusNodeLattice } from "./large-defocus-lattice.js";
55
60
  /** Rows of native sites per convolution band, and the bands kept. Banding changes memory only, never values. */
56
61
  const BAND_ROWS = 32;
57
62
  const CACHED_BANDS = 4;
@@ -81,14 +86,15 @@ export function createDiffractedPlanarProvider(input) {
81
86
  throw new InvalidConfigurationError("Diffraction window must overlap the native raster.");
82
87
  const NW = lx1 - lx0;
83
88
  // One kernel per wavelength, on the site grid, from the engine's own tap-to-site mapping (field point 0, 0); kept across calls.
84
- const siteKernels = input.siteKernels;
85
- if (!siteKernels && !input.psf)
89
+ const siteKernels = input.siteKernels, large = input.largeKernel;
90
+ if (!siteKernels && !input.psf && !large)
86
91
  throw new InvalidConfigurationError("The object-space convolution needs a PSF or site kernels.");
87
- const kernels = wavelengthsNm.map((wavelengthNm) => siteKernels ? checkedSiteKernel(siteKernels(wavelengthNm), R) :
92
+ const kernels = large ? [] : wavelengthsNm.map((wavelengthNm) => siteKernels ? checkedSiteKernel(siteKernels(wavelengthNm), R) :
88
93
  siteDiffractionKernel(input.psf, wavelengthNm, pitch, R, "Diffraction kernels must sample the site pitch exactly."));
89
94
  // #492: each site kernel's non-zero taps as grid offsets, in the gather's order.
90
- const taps = siteKernels ? kernels.map((kernel) => kernelTaps(kernel, R, NW + 2 * R)) : [];
95
+ const taps = siteKernels && !large ? kernels.map((kernel) => kernelTaps(kernel, R, NW + 2 * R)) : [];
91
96
  const gridWidth = NW + 2 * R;
97
+ const zonedGather = input.fieldZones && siteKernels ? createZonedGather(input.fieldZones, R, gridWidth, W, H, M) : undefined;
92
98
  const now = () => globalThis.performance?.now() ?? Date.now();
93
99
  const bands = new Map();
94
100
  const materialAt = base.chartMaterialAt?.bind(base), materialRadiance = base.materialRadiance?.bind(base);
@@ -143,6 +149,8 @@ export function createDiffractedPlanarProvider(input) {
143
149
  samples[gy * gridWidth + gx] = base.radianceAt(uOf(x), v, nm);
144
150
  }
145
151
  }
152
+ if (zonedGather)
153
+ return zonedGather(samples, lx0, y0, NW, rows);
146
154
  if (!convolve)
147
155
  return gatherInterior(samples, taps[w], gridWidth, NW, rows, R);
148
156
  return convolve(samples, kernels[w]);
@@ -155,6 +163,56 @@ export function createDiffractedPlanarProvider(input) {
155
163
  input.onConvolution(now() - started);
156
164
  return values;
157
165
  }
166
+ // #564: one run lattice per shift (lattice points li, lj), its samples the base radiance at the same plane points as the bands'.
167
+ const largeLattices = [];
168
+ function largeLattice(s) {
169
+ let lattice = largeLattices[s];
170
+ if (!lattice) {
171
+ const shift = shifts[s];
172
+ const vOf = (lj) => shift.y === 0 ? -(lj - M + 0.5 - H / 2) * g : -(lj - M + 0.5 + shift.y - H / 2) * g;
173
+ const uOf = (li) => shift.x === 0 ? (li - M + 0.5 - W / 2) * g : (li - M + 0.5 + shift.x - W / 2) * g;
174
+ lattice = largeLattices[s] = createLargeDefocusNodeLattice({ kernel: large, wavelengthsNm, capacityBytes: LARGE_DEFOCUS_CACHE_BYTES / shifts.length, ...(input.onConvolution ? { onTile: input.onConvolution } : {}),
175
+ source: (x0, y0, width, height) => {
176
+ const size = width * height;
177
+ let materialOf;
178
+ if (materialAt && materialRadiance) {
179
+ materialOf = new Int32Array(size);
180
+ for (let y = 0; y < height; y++) {
181
+ const v = vOf(y0 + y);
182
+ for (let x = 0; x < width; x++)
183
+ materialOf[y * width + x] = materialAt(uOf(x0 + x), v);
184
+ }
185
+ }
186
+ return (node) => {
187
+ const nm = wavelengthsNm[node], samples = new Float64Array(size);
188
+ if (materialOf) {
189
+ const radiance = new Map();
190
+ for (let k = 0; k < size; k++) {
191
+ const m = materialOf[k];
192
+ let value = radiance.get(m);
193
+ if (value === undefined) {
194
+ value = materialRadiance(m, nm);
195
+ radiance.set(m, value);
196
+ }
197
+ samples[k] = value;
198
+ }
199
+ }
200
+ else
201
+ for (let y = 0; y < height; y++) {
202
+ const v = vOf(y0 + y);
203
+ for (let x = 0; x < width; x++)
204
+ samples[y * width + x] = base.radianceAt(uOf(x0 + x), v, nm);
205
+ }
206
+ return samples;
207
+ };
208
+ } });
209
+ }
210
+ return lattice;
211
+ }
212
+ /** The convolved value of shift s, node index w, at lattice point (li, lj) inside the window. */
213
+ function valueAt(s, w, li, lj) {
214
+ return large ? largeLattice(s).valueAt(w, li, lj) : band(Math.floor((lj - ly0) / BAND_ROWS))[s][w][((lj - ly0) % BAND_ROWS) * NW + li - lx0];
215
+ }
158
216
  function blurredAt(u, v, nm) {
159
217
  const w = index.get(nm), fi = u / g - 0.5 + W / 2, fj = -v / g - 0.5 + H / 2;
160
218
  if (w !== undefined)
@@ -165,7 +223,7 @@ export function createDiffractedPlanarProvider(input) {
165
223
  const li = i + M, lj = j + M;
166
224
  if (li < lx0 || lj < ly0 || li >= lx1 || lj >= ly1)
167
225
  break;
168
- return band(Math.floor((lj - ly0) / BAND_ROWS))[s][w][((lj - ly0) % BAND_ROWS) * NW + li - lx0];
226
+ return valueAt(s, w, li, lj);
169
227
  }
170
228
  throw new InvalidConfigurationError("Diffraction query is off the site lattice; the object-space convolution does not apply.");
171
229
  }
@@ -203,7 +261,7 @@ export function createDiffractedPlanarProvider(input) {
203
261
  if (w === undefined)
204
262
  throw new InvalidConfigurationError("Diffraction query is off the site lattice; the object-space convolution does not apply.");
205
263
  const li = key % LW, rest = (key - li) / LW, lj = rest % LH, s = (rest - lj) / LH;
206
- return band(Math.floor((lj - ly0) / BAND_ROWS))[s][w][((lj - ly0) % BAND_ROWS) * NW + li - lx0];
264
+ return valueAt(s, w, li, lj);
207
265
  }
208
266
  });
209
267
  }
@@ -218,7 +276,7 @@ export function createDiffractedPlanarProvider(input) {
218
276
  /** Largest kernel sum, and largest sample, the object-space convolution accepts (as `IRRADIANCE_CONVOLUTION_LIMITS`). */
219
277
  const MAXIMUM_KERNEL_SUM = 1 + 2 ** -20, MAXIMUM_SAMPLE = 2 ** 100;
220
278
  /** #492: a site kernel of radius R, checked as `calculateIrradianceConvolution` checks its kernels. */
221
- function checkedSiteKernel(kernel, R) {
279
+ export function checkedSiteKernel(kernel, R) {
222
280
  if (!(kernel instanceof Float64Array) || kernel.length !== (2 * R + 1) ** 2)
223
281
  throw new InvalidConfigurationError("Site kernels must be (2R + 1)² taps.");
224
282
  let sum = 0;
@@ -233,7 +291,7 @@ function checkedSiteKernel(kernel, R) {
233
291
  return kernel;
234
292
  }
235
293
  /** #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. */
236
- function kernelTaps(kernel, R, gridWidth) {
294
+ export function kernelTaps(kernel, R, gridWidth) {
237
295
  const offsets = [], weights = [];
238
296
  for (let v = -R, t = 0; v <= R; v++)
239
297
  for (let u = -R; u <= R; u++, t++) {
@@ -250,12 +308,8 @@ function kernelTaps(kernel, R, gridWidth) {
250
308
  * these lies inside the grid (it holds R extra samples on each side), so no boundary rule applies. Samples are checked as
251
309
  * `calculateIrradianceConvolution` checks them.
252
310
  */
253
- function gatherInterior(samples, taps, gridWidth, width, rows, R) {
254
- for (let k = 0; k < samples.length; k++) {
255
- const v = samples[k];
256
- if (!(v >= 0 && v <= MAXIMUM_SAMPLE))
257
- throw new InvalidConfigurationError("Irradiance samples must be finite, non-negative and within the declared magnitude.");
258
- }
311
+ export function gatherInterior(samples, taps, gridWidth, width, rows, R) {
312
+ checkSamples(samples);
259
313
  const { offsets, weights } = taps, count = weights.length, out = new Float64Array(width * rows);
260
314
  for (let y = 0; y < rows; y++) {
261
315
  const rowBase = (y + R) * gridWidth + R;
@@ -269,4 +323,56 @@ function gatherInterior(samples, taps, gridWidth, width, rows, R) {
269
323
  }
270
324
  return out;
271
325
  }
326
+ /** Samples are checked as `calculateIrradianceConvolution` checks them. */
327
+ function checkSamples(samples) {
328
+ for (let k = 0; k < samples.length; k++) {
329
+ const v = samples[k];
330
+ if (!(v >= 0 && v <= MAXIMUM_SAMPLE))
331
+ throw new InvalidConfigurationError("Irradiance samples must be finite, non-negative and within the declared magnitude.");
332
+ }
333
+ }
334
+ /**
335
+ * #553: the band gather with {@link SiteKernelFieldZones}: out(x) = Σ_t K_z(t)·samples(x − t), z the zone of output site x
336
+ * (its native site, clamped to the raster for the margins of offset lattices). Each value is summed over its zone's taps in
337
+ * the order of {@link gatherInterior} (v outer, u inner, ascending), so a zoned gather whose zones all hold one kernel gives
338
+ * gatherInterior's bits. The zones' taps are built on first use and the last 3 rows of zones kept.
339
+ */
340
+ export function createZonedGather(zones, R, gridWidth, nativeWidth, nativeHeight, margin) {
341
+ const cache = new Map(), capacity = 3 * zones.columns;
342
+ const tapsOf = (zone) => {
343
+ let taps = cache.get(zone);
344
+ if (taps) {
345
+ cache.delete(zone);
346
+ cache.set(zone, taps);
347
+ return taps;
348
+ }
349
+ taps = kernelTaps(checkedSiteKernel(zones.kernelOf(zone), R), R, gridWidth);
350
+ cache.set(zone, taps);
351
+ if (cache.size > capacity)
352
+ cache.delete(cache.keys().next().value);
353
+ return taps;
354
+ };
355
+ const zoneOf = (lattice, extent, count) => Math.min(count - 1, Math.floor(Math.min(extent - 1, Math.max(0, lattice - margin)) / zones.size));
356
+ return (samples, latticeX0, latticeY0, width, rows) => {
357
+ checkSamples(samples);
358
+ const out = new Float64Array(width * rows), columnZone = new Int32Array(width);
359
+ for (let x = 0; x < width; x++)
360
+ columnZone[x] = zoneOf(latticeX0 + x, nativeWidth, zones.columns);
361
+ for (let y = 0; y < rows; y++) {
362
+ const rowBase = (y + R) * gridWidth + R, zoneRow = zoneOf(latticeY0 + y, nativeHeight, zones.rows) * zones.columns;
363
+ let x = 0;
364
+ while (x < width) {
365
+ const zx = columnZone[x], { offsets, weights } = tapsOf(zoneRow + zx), count = weights.length;
366
+ for (; x < width && columnZone[x] === zx; x++) {
367
+ const base = rowBase + x;
368
+ let sum = 0;
369
+ for (let k = 0; k < count; k++)
370
+ sum += samples[base + offsets[k]] * weights[k];
371
+ out[y * width + x] = sum;
372
+ }
373
+ }
374
+ }
375
+ return out;
376
+ };
377
+ }
272
378
  //# sourceMappingURL=diffraction-provider.js.map
@@ -1 +1 @@
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;AAC3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AG,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; 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"]}
1
+ {"version":3,"file":"diffraction-provider.js","sourceRoot":"","sources":["../../src/facade/diffraction-provider.ts"],"names":[],"mappings":"AAAA,sCAAsC;AAEtC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoDG;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,qCAAqC,CAAC;AAChG,OAAO,EAAE,qBAAqB,EAAE,MAAM,sCAAsC,CAAC;AAG7E,OAAO,EAAE,yBAAyB,EAAE,6BAA6B,EAAyD,MAAM,4BAA4B,CAAC;AAE7J,gHAAgH;AAChH,MAAM,SAAS,GAAG,EAAE,CAAC;AACrB,MAAM,YAAY,GAAG,CA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,CAAC,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC;oBAC9C,MAAM,IAAI,GAAG,OAAO,GAAG,CAAC,CAAC;oBACzB,IAAI,GAAG,GAAG,CAAC,CAAC;oBACZ,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,EAAE,CAAC,EAAE;wBAAE,GAAG,IAAI,OAAO,CAAC,IAAI,GAAG,OAAO,CAAC,CAAC,CAAE,CAAE,GAAG,OAAO,CAAC,CAAC,CAAE,CAAC;oBAClF,GAAG,CAAC,CAAC,GAAG,KAAK,GAAG,CAAC,CAAC,GAAG,GAAG,CAAC;gBAC3B,CAAC;YACH,CAAC;QACH,CAAC;QACD,OAAO,GAAG,CAAC;IACb,CAAC,CAAC;AACJ,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 * Large defocus kernels (#564, `largeKernel`): above 64 sites the disc is convolved by runs in fixed tiles instead of bands\n * (`large-defocus-lattice.ts`, `site-kernel-runs.ts`), each node's diffraction kernel after it; the plane points and the\n * material lookup are the bands' own, and values stay independent of the window.\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\";\nimport { LARGE_DEFOCUS_CACHE_BYTES, createLargeDefocusNodeLattice, type LargeDefocusKernel, type LargeDefocusNodeLattice } from \"./large-defocus-lattice.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 * #564: a defocus kernel above the direct radius, convolved by runs in fixed tiles (`large-defocus-lattice.ts`), with each\n * node's diffraction kernel after it; used instead of `siteKernels` and `psf` (`kernelRadius` is then unused).\n */\n largeKernel?: LargeDefocusKernel;\n /** #553: a field-varying kernel by zones (the cat's eye), used instead of `siteKernels` in the gather; needs `siteKernels`. */\n fieldZones?: SiteKernelFieldZones;\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, large = input.largeKernel;\n if (!siteKernels && !input.psf && !large) throw new InvalidConfigurationError(\"The object-space convolution needs a PSF or site kernels.\");\n const kernels = large ? [] : 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 && !large ? kernels.map((kernel) => kernelTaps(kernel, R, NW + 2 * R)) : [];\n const gridWidth = NW + 2 * R;\n const zonedGather = input.fieldZones && siteKernels ? createZonedGather(input.fieldZones, R, gridWidth, W, H, M) : undefined;\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 (zonedGather) return zonedGather(samples, lx0, y0, NW, rows);\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 // #564: one run lattice per shift (lattice points li, lj), its samples the base radiance at the same plane points as the bands'.\n const largeLattices: (LargeDefocusNodeLattice | undefined)[] = [];\n function largeLattice(s: number): LargeDefocusNodeLattice {\n let lattice = largeLattices[s];\n if (!lattice) {\n const shift = shifts[s]!;\n const vOf = (lj: number): number => shift.y === 0 ? -(lj - M + 0.5 - H / 2) * g : -(lj - M + 0.5 + shift.y - H / 2) * g;\n const uOf = (li: number): number => shift.x === 0 ? (li - M + 0.5 - W / 2) * g : (li - M + 0.5 + shift.x - W / 2) * g;\n lattice = largeLattices[s] = createLargeDefocusNodeLattice({ kernel: large!, wavelengthsNm, capacityBytes: LARGE_DEFOCUS_CACHE_BYTES / shifts.length, ...(input.onConvolution ? { onTile: input.onConvolution } : {}),\n source: (x0, y0, width, height) => {\n const size = width * height;\n let materialOf: Int32Array | undefined;\n if (materialAt && materialRadiance) {\n materialOf = new Int32Array(size);\n for (let y = 0; y < height; y++) { const v = vOf(y0 + y); for (let x = 0; x < width; x++) materialOf[y * width + x] = materialAt(uOf(x0 + x), v); }\n }\n return (node: number): Float64Array => {\n const nm = wavelengthsNm[node]!, samples = new Float64Array(size);\n if (materialOf) {\n const radiance = new Map<number, number>();\n for (let k = 0; k < size; k++) {\n const m = materialOf[k]!;\n let value = radiance.get(m);\n if (value === undefined) { value = materialRadiance!(m, nm); radiance.set(m, value); }\n samples[k] = value;\n }\n } else for (let y = 0; y < height; y++) { const v = vOf(y0 + y); for (let x = 0; x < width; x++) samples[y * width + x] = base.radianceAt(uOf(x0 + x), v, nm); }\n return samples;\n };\n } });\n }\n return lattice;\n }\n /** The convolved value of shift s, node index w, at lattice point (li, lj) inside the window. */\n function valueAt(s: number, w: number, li: number, lj: number): number {\n return large ? largeLattice(s).valueAt(w, li, lj) : band(Math.floor((lj - ly0) / BAND_ROWS))[s]![w]![((lj - ly0) % BAND_ROWS) * NW + li - lx0]!;\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 valueAt(s, w, li, lj);\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 valueAt(s, w, li, lj);\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. */\nexport function 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. */\nexport function 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 */\nexport function gatherInterior(samples: Float64Array, taps: { offsets: Int32Array; weights: Float64Array }, gridWidth: number, width: number, rows: number, R: number): Float64Array {\n checkSamples(samples);\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\n/** Samples are checked as `calculateIrradianceConvolution` checks them. */\nfunction checkSamples(samples: Float64Array): void {\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}\n\n/**\n * #553: a field-varying site kernel (the cat's eye of `lens.defocus`) as square zones of the native raster, each zone with\n * the kernel of its centre's field point, the same at every spectral node. A piecewise-constant (sectioned) approximation\n * of a space-variant PSF (Denis, Thiébaut, Soulez, Becker and Mourya 2015, \"Fast approximations of shift-variant blur\",\n * International Journal of Computer Vision 115:253–278, §3.1, open preprint arXiv:1502.03305).\n */\nexport interface SiteKernelFieldZones {\n /** Zone side in native sites: zone (zx, zy) holds the native sites [zx·size, (zx + 1)·size) × [zy·size, (zy + 1)·size). */\n size: number;\n columns: number;\n rows: number;\n /** The kernel of zone zy·columns + zx, (2R + 1)² row-major taps with R the provider's `kernelRadius`. */\n kernelOf(zone: number): Float64Array;\n}\n\n/**\n * #553: the band gather with {@link SiteKernelFieldZones}: out(x) = Σ_t K_z(t)·samples(x − t), z the zone of output site x\n * (its native site, clamped to the raster for the margins of offset lattices). Each value is summed over its zone's taps in\n * the order of {@link gatherInterior} (v outer, u inner, ascending), so a zoned gather whose zones all hold one kernel gives\n * gatherInterior's bits. The zones' taps are built on first use and the last 3 rows of zones kept.\n */\nexport function createZonedGather(zones: SiteKernelFieldZones, R: number, gridWidth: number, nativeWidth: number, nativeHeight: number, margin: number):\n (samples: Float64Array, latticeX0: number, latticeY0: number, width: number, rows: number) => Float64Array {\n const cache = new Map<number, { offsets: Int32Array; weights: Float64Array }>(), capacity = 3 * zones.columns;\n const tapsOf = (zone: number): { offsets: Int32Array; weights: Float64Array } => {\n let taps = cache.get(zone);\n if (taps) { cache.delete(zone); cache.set(zone, taps); return taps; }\n taps = kernelTaps(checkedSiteKernel(zones.kernelOf(zone), R), R, gridWidth);\n cache.set(zone, taps);\n if (cache.size > capacity) cache.delete(cache.keys().next().value!);\n return taps;\n };\n const zoneOf = (lattice: number, extent: number, count: number): number => Math.min(count - 1, Math.floor(Math.min(extent - 1, Math.max(0, lattice - margin)) / zones.size));\n return (samples, latticeX0, latticeY0, width, rows) => {\n checkSamples(samples);\n const out = new Float64Array(width * rows), columnZone = new Int32Array(width);\n for (let x = 0; x < width; x++) columnZone[x] = zoneOf(latticeX0 + x, nativeWidth, zones.columns);\n for (let y = 0; y < rows; y++) {\n const rowBase = (y + R) * gridWidth + R, zoneRow = zoneOf(latticeY0 + y, nativeHeight, zones.rows) * zones.columns;\n let x = 0;\n while (x < width) {\n const zx = columnZone[x]!, { offsets, weights } = tapsOf(zoneRow + zx), count = weights.length;\n for (; x < width && columnZone[x] === zx; 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 }\n return out;\n };\n}\n"]}
@@ -76,6 +76,10 @@ export async function openDisplayViewGpuSession(options, request, signal) {
76
76
  const factory = displayViewGpuRendererFactory();
77
77
  if (!factory)
78
78
  return fallBack(options, "unsupported-on-backend", "this version of the engine has no GPU display-view renderer (#478); no device was requested.");
79
+ // #563: the lens signal (projection, distortion, vignetting, rotation) runs on the CPU reference only; no device is requested for it.
80
+ if (request.lens)
81
+ return fallBack(options, "unsupported-on-backend", "the GPU display-view renderers do not render lens.projection, lens.distortion, lens.vignetting or " +
82
+ "camera rotation (#563); the CPU reference renders them. No device was requested.");
79
83
  let runtime, owned = false;
80
84
  if (isAccelerator(options.gpuDevice)) {
81
85
  const shared = acceleratorRuntime(options.gpuDevice);
@@ -1 +1 @@
1
- {"version":3,"file":"display-view-gpu-session.js","sourceRoot":"","sources":["../../src/facade/display-view-gpu-session.ts"],"names":[],"mappings":"AAAA,sCAAsC;AAEtC;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAC3E,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAC3D,OAAO,EAAE,oBAAoB,EAAsB,MAAM,0BAA0B,CAAC;AACpF,OAAO,EAAE,yBAAyB,EAAE,sBAAsB,EAAsE,MAAM,kCAAkC,CAAC;AACzK,OAAO,EAAE,kBAAkB,EAAE,2BAA2B,EAAE,MAAM,o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CAAC,EAAE,GAAG,EAAE,OAAO,CAAC,GAAG,EAAE,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,YAAY,EAAE,cAAc,EAAE,IAAI,EAAE,UAAU,EAAE,SAAS;gBAC1K,SAAS,EAAE,mCAAmC,EAAE,IAAI,EAAE,IAAI,EAAE,uBAAuB,EAAE,KAAK,EAAE,UAAU,EAAE,gBAAgB,EAAE,WAAW,KAAK,CAAC;gBAC3I,gCAAgC,EAAE,WAAW,EAAE,WAAW,EAAE,sBAAsB,EAAE,OAAO,EAAE,WAAW,EAAE,KAAK,EAAE,cAAc,EAAE,CAAC,CAAC;YACrI,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,CAAC;QACjC,CAAC;QACD,OAAO;YACL,IAAI,QAAQ;gBAAE,OAAO;YACrB,QAAQ,GAAG,IAAI,CAAC;YAChB,QAAQ,CAAC,OAAO,EAAE,EAAE,CAAC;YACrB,IAAI,KAAK;gBAAE,OAAO,CAAC,OAAO,EAAE,CAAC;QAC/B,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\n/**\n * #481: the device handling behind `prepareDisplayView(request, { gpu: \"auto\" | \"require\", gpuDevice })`. Loaded on demand by\n * `simulate-display-view.ts`, so the GPU code stays out of bundles that never ask for it. One session per prepared view:\n *\n * - the realm's switch (`setWebGpuEnabled(false)`) vetoes before anything else: `\"auto\"` falls back with `webgpu-disabled`,\n * `\"require\"` throws it;\n * - with no renderer registered (the engine registers its renderer, the Speed and Quality kernels of #478 and #479, when this module\n * loads; a caller may replace it or set null) no device is requested: `unsupported-on-backend`;\n * - the device is the handle's (`gpuDevice`: an `ImageKernelAccelerator`'s device, shared and left to its owner, or a WebGPU\n * entry point to acquire from), or acquired from `navigator.gpu` and owned by the session; the accelerator's acquisition\n * reasons apply, and the request's `signal` aborts the acquisition;\n * - the renderer must support the request, else `unsupported-on-backend`; a render the renderer refuses only when rendering\n * (`unsupported-on-backend` thrown by `render`: a coarse view, a device that fails the composite chart probe, #491) runs the\n * CPU reference for that render with the same label, and so does a render whose tables or bands exceed the device's limits\n * (`insufficient-limits` thrown by `render`: #492, a large defocus kernel's table on a scene of many materials);\n * - before the first GPU render on the device a short conformance self-check runs once (single-flight): the built-in cases run\n * the existing `webgpu-f32` convolution kernel against the float64 reference within its a-priori bound, then the renderer's own\n * cases; a failure keeps the whole view on the CPU, labelled `conformance-failed`, with the adapter recorded;\n * - GPU renders of one session run one at a time on the device (the accelerator's single flight; later renders wait);\n * - a lost device falls back to the CPU for that render and every later one, labelled `device-lost`; `dispose()` releases an\n * owned device, and later renders run on the CPU labelled `disposed`.\n */\n\nimport { InvalidConfigurationError } from \"../core/configuration-error.js\";\nimport { getWebGpuEnabled } from \"../gpu/webgpu-switch.js\";\nimport { acquireWebGpuRuntime, type WebGpuRuntime } from \"../gpu/webgpu-runtime.js\";\nimport { ImageKernelExecutionError, WEBGPU_F32_LIMITATIONS, type ChartCompositeProbeRecord, type ImageKernelAdapterDescription } from \"../gpu/image-kernel-execution.js\";\nimport { acceleratorRuntime, convolveIrradianceOnRuntime } from \"../gpu/image-kernel-accelerator.js\";\nimport { calculateIrradianceConvolutionPlan, convolveIrradianceRows, type IrradianceConvolutionInput } from \"../optics/irradiance-convolution.js\";\nimport type { DisplayViewRenderResult, DisplayViewSetup } from \"./display-view.js\";\nimport { displayViewGpuRendererFactory as engineDisplayViewGpuRendererFactory } from \"../gpu/display-view-quality-gpu.js\";\nimport { cpuDisplayViewExecution, displayViewGpuRendererFactory, setDisplayViewGpuRendererFactory, type DisplayViewExecution, type DisplayViewGpuConformance, type DisplayViewGpuConformanceCase,\n type DisplayViewGpuFallbackReason, type DisplayViewGpuRenderer, type DisplayViewGpuRequest, type ParsedPrepareDisplayViewOptions } from \"./display-view-gpu.js\";\n\n// #478, #479: the engine's own renderer, the display view's Speed and Quality kernels behind one renderer\n// (`src/gpu/display-view-quality-gpu.ts`), is registered when this module loads (that is, when a prepared view first asks for the\n// GPU) unless a caller registered a renderer before; a test that needs \"no renderer\" sets the factory to null.\nif (displayViewGpuRendererFactory() === null) setDisplayViewGpuRendererFactory(engineDisplayViewGpuRendererFactory);\n\n/** Internal: the GPU side of one prepared view. */\nexport interface DisplayViewGpuSession {\n /** Renders `setup` on the GPU when the session can, else through `cpu`; the label says which ran. */\n render(setup: DisplayViewSetup, signal: AbortSignal | undefined, cpu: () => Promise<DisplayViewRenderResult>): Promise<{ rendered: DisplayViewRenderResult; execution: DisplayViewExecution }>;\n dispose(): void;\n}\n\n/** A session that renders every view on the CPU with one fixed reason. */\nfunction cpuSession(options: ParsedPrepareDisplayViewOptions, reason: DisplayViewGpuFallbackReason, detail: string, adapter: ImageKernelAdapterDescription | null,\n conformance: DisplayViewGpuConformance | null): DisplayViewGpuSession {\n const execution = cpuDisplayViewExecution(options.gpu, reason, adapter, conformance, detail);\n return { async render(_setup, _signal, cpu): Promise<{ rendered: DisplayViewRenderResult; execution: DisplayViewExecution }> { return { rendered: await cpu(), execution }; },\n dispose(): void { /* nothing acquired */ } };\n}\n\n/** `\"require\"` throws the reason; `\"auto\"` gets a CPU session labelled with it. */\nfunction fallBack(options: ParsedPrepareDisplayViewOptions, reason: DisplayViewGpuFallbackReason, detail: string, adapter: ImageKernelAdapterDescription | null = null,\n conformance: DisplayViewGpuConformance | null = null): DisplayViewGpuSession {\n if (options.gpu === \"require\") throw requireError(reason, detail);\n return cpuSession(options, reason, detail, adapter, conformance);\n}\n/**\n * The error `\"require\"` throws instead of falling back. Every display-view fallback reason is also a failure reason of the accelerator's\n * error. A refusal by the composite chart probe carries its record as `probe` (the structured detail of the message).\n */\nfunction requireError(reason: DisplayViewGpuFallbackReason, detail: string, probe: ChartCompositeProbeRecord | null = null): ImageKernelExecutionError {\n const error = new ImageKernelExecutionError(reason, \"prepareDisplayView with gpu \\\"require\\\": \" + detail);\n if (probe) Object.defineProperty(error, \"probe\", { value: probe, enumerable: true });\n return error;\n}\n/** The composite chart probe's record on a refusal (`ChartCompositeProbeError.probe`), or null. */\nfunction probeOf(error: unknown): ChartCompositeProbeRecord | null {\n const probe = (error as { probe?: unknown }).probe;\n return typeof probe === \"object\" && probe !== null ? probe as ChartCompositeProbeRecord : null;\n}\n\n/** True for an object shaped like an `ImageKernelAccelerator` (the handle form that shares a device). */\nfunction isAccelerator(value: unknown): boolean {\n return typeof value === \"object\" && value !== null && typeof (value as { convolveIrradiance?: unknown }).convolveIrradiance === \"function\" &&\n typeof (value as { backend?: unknown }).backend === \"string\";\n}\n\n/**\n * Internal (#481): opens the GPU session of a prepared view, or throws (`\"require\"`) when the GPU cannot be used. Called only\n * for `gpu: \"auto\" | \"require\"`.\n */\nexport async function openDisplayViewGpuSession(options: ParsedPrepareDisplayViewOptions, request: DisplayViewGpuRequest, signal: AbortSignal | undefined): Promise<DisplayViewGpuSession> {\n if (!getWebGpuEnabled()) return fallBack(options, \"webgpu-disabled\", \"WebGPU is switched off in this realm (setWebGpuEnabled(false)).\");\n const factory = displayViewGpuRendererFactory();\n if (!factory) return fallBack(options, \"unsupported-on-backend\", \"this version of the engine has no GPU display-view renderer (#478); no device was requested.\");\n let runtime: WebGpuRuntime, owned = false;\n if (isAccelerator(options.gpuDevice)) {\n const shared = acceleratorRuntime(options.gpuDevice) as WebGpuRuntime | null | undefined;\n if (shared === undefined) throw new InvalidConfigurationError(\"prepareDisplayView options.gpuDevice must be an accelerator created by createImageKernelAccelerator.\");\n const accelerator = options.gpuDevice as { state: string; fallbackReason: DisplayViewGpuFallbackReason | null };\n if (accelerator.state === \"disposed\") throw new InvalidConfigurationError(\"prepareDisplayView options.gpuDevice is a disposed accelerator.\");\n if (shared === null) return fallBack(options, accelerator.fallbackReason ?? \"webgpu-unavailable\", \"the given accelerator runs the CPU reference and has no device.\");\n if (shared.isLost()) return fallBack(options, \"device-lost\", \"the given accelerator's device was lost.\", shared.adapter);\n runtime = shared;\n } else {\n const gpu = options.gpuDevice !== undefined ? options.gpuDevice : (globalThis as { navigator?: { gpu?: unknown } }).navigator?.gpu;\n let acquired: Awaited<ReturnType<typeof acquireWebGpuRuntime>>;\n try { acquired = await acquireWebGpuRuntime(gpu, undefined, signal); }\n catch (error) {\n if (error instanceof ImageKernelExecutionError && error.reason === \"aborted\") throw new InvalidConfigurationError(\"prepareDisplayView aborted.\");\n throw error;\n }\n if (\"failure\" in acquired) return fallBack(options, acquired.failure, acquired.message);\n runtime = acquired.runtime; owned = true;\n }\n const renderer = factory(runtime), supported = renderer.supports(request);\n if (supported !== true) {\n if (owned) runtime.destroy();\n return fallBack(options, \"unsupported-on-backend\", \"the GPU display-view renderer \\\"\" + renderer.id + \"\\\" does not support this request: \" + supported, runtime.adapter);\n }\n return createSession(options, runtime, owned, renderer);\n}\n\n// ---------------------------------------------------------------------------------------------------------------\n// Run-time conformance self-check.\n\n/** A fixed, seeded test image (mulberry32) for the built-in cases. */\nfunction seededSamples(count: number, seed: number): Float64Array {\n let a = seed >>> 0;\n const out = new Float64Array(count);\n for (let i = 0; i < count; i++) {\n a = (a + 0x6d2b79f5) >>> 0;\n let t = Math.imul(a ^ (a >>> 15), 1 | a);\n t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;\n const u = ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n out[i] = u < 0.05 ? 0 : 10 ** (u * 6 - 3);\n }\n return out;\n}\n/** One convolution case: normalized Gaussian kernels of width `sigma` per patch, compared with the float64 reference within the a-priori bound. */\nfunction convolutionCase(id: string, width: number, height: number, radius: number, patchWidth: number, patchHeight: number, seed: number): DisplayViewGpuConformanceCase {\n return { id, async run(runtime, signal): Promise<true | string> {\n const size = 2 * radius + 1, taps = size * size, columns = Math.ceil(width / patchWidth), rows = Math.ceil(height / patchHeight);\n const kernels = new Float64Array(columns * rows * taps);\n for (let p = 0; p < columns * rows; p++) {\n const sigma = 0.6 + 0.4 * (p % 3), scale = 0.8 + 0.05 * p;\n let sum = 0;\n for (let v = -radius; v <= radius; v++) for (let u = -radius; u <= radius; u++) { const w = Math.exp(-0.5 * (u * u + v * v) / (sigma * sigma)); kernels[p * taps + (v + radius) * size + u + radius] = w; sum += w; }\n for (let t = 0; t < taps; t++) kernels[p * taps + t] = kernels[p * taps + t]! / sum * Math.min(1, scale);\n }\n const input: IrradianceConvolutionInput = { schemaVersion: \"0.1.0\", width, height, kernelRadius: radius, patchWidth, patchHeight, boundary: \"zero-outside-grid\",\n samples: seededSamples(width * height, seed), kernels };\n const plan = calculateIrradianceConvolutionPlan(input), reference = new Float64Array(width * height);\n convolveIrradianceRows(plan, input.samples, input.kernels, 0, height, reference);\n {\n const result = await convolveIrradianceOnRuntime(runtime, input, signal);\n const bound = result.execution.errorBound;\n if (!bound || bound.kind !== \"relative-to-reference\") return \"the convolution reported no relative bound.\";\n let worst = 0, worstIndex = -1;\n for (let i = 0; i < reference.length; i++) {\n const allowed = bound.relative * reference[i]! + bound.absolute, excess = Math.abs(result.values[i]! - reference[i]!) - allowed;\n if (excess > worst) { worst = excess; worstIndex = i; }\n }\n return worstIndex < 0 ? true : \"sample \" + worstIndex + \" differs from the reference by \" + Math.abs(result.values[worstIndex]! - reference[worstIndex]!) +\n \", more than the a-priori bound \" + (bound.relative * reference[worstIndex]! + bound.absolute) + \".\";\n }\n } };\n}\n/** The built-in cases, run on every device before its first display-view render: the existing convolution kernel on two small images. */\nexport const DISPLAY_VIEW_GPU_BUILT_IN_CASES: readonly DisplayViewGpuConformanceCase[] = Object.freeze([\n convolutionCase(\"image-kernel:convolution:16x12-r1\", 16, 12, 1, 16, 12, 481),\n convolutionCase(\"image-kernel:convolution:32x24-r3-patches\", 32, 24, 3, 16, 12, 4781)\n]);\n\nasync function runConformance(runtime: WebGpuRuntime, renderer: DisplayViewGpuRenderer, signal: AbortSignal | undefined): Promise<DisplayViewGpuConformance> {\n const cases = [...DISPLAY_VIEW_GPU_BUILT_IN_CASES, ...(renderer.conformanceCases ?? [])], ids = Object.freeze(cases.map((c) => c.id));\n for (const c of cases) {\n let outcome: true | string;\n try { outcome = await c.run(runtime, signal); }\n catch (error) {\n // An abort is the caller's, not the device's; everything else the device did wrong is a failed case.\n if (error instanceof ImageKernelExecutionError && error.reason === \"aborted\") throw error;\n outcome = \"the case threw \" + (error instanceof ImageKernelExecutionError ? error.reason + \": \" : \"\") + (error instanceof Error ? error.message : String(error));\n }\n if (outcome !== true) return Object.freeze({ cases: ids, passed: false, failedCase: c.id, detail: outcome });\n }\n return Object.freeze({ cases: ids, passed: true, failedCase: null, detail: null });\n}\n\n// ---------------------------------------------------------------------------------------------------------------\n\nfunction createSession(options: ParsedPrepareDisplayViewOptions, runtime: WebGpuRuntime, owned: boolean, renderer: DisplayViewGpuRenderer): DisplayViewGpuSession {\n const adapter = runtime.adapter;\n let disposed = false, lost = false, conformance: DisplayViewGpuConformance | null = null, checking: Promise<DisplayViewGpuConformance> | null = null;\n /** The last GPU turn: renders queue behind it, so one dispatch runs at a time on the device. */\n let tail: Promise<unknown> = Promise.resolve();\n /** A CPU fallback label for `\"auto\"`; with `\"require\"` the same event is an error. */\n const fallback = async (reason: DisplayViewGpuFallbackReason, detail: string, cpu: () => Promise<DisplayViewRenderResult>, compositeProbe: ChartCompositeProbeRecord | null = null):\n Promise<{ rendered: DisplayViewRenderResult; execution: DisplayViewExecution }> => {\n if (options.gpu === \"require\") throw requireError(reason, detail, compositeProbe);\n return { rendered: await cpu(), execution: cpuDisplayViewExecution(options.gpu, reason, adapter, conformance, detail, compositeProbe) };\n };\n /** The self-check, run once per session (single flight); a failing check is remembered and never repeated. */\n function selfCheck(signal: AbortSignal | undefined): Promise<DisplayViewGpuConformance> {\n if (conformance) return Promise.resolve(conformance);\n if (!checking) {\n checking = runConformance(runtime, renderer, signal).then((result) => { conformance = result; return result; }, (error: unknown) => { checking = null; throw error; });\n }\n return checking;\n }\n function lostError(error: unknown): boolean { return (error instanceof ImageKernelExecutionError && error.reason === \"device-lost\") || runtime.isLost(); }\n return {\n async render(setup, signal, cpu): Promise<{ rendered: DisplayViewRenderResult; execution: DisplayViewExecution }> {\n if (disposed) return fallback(\"disposed\", \"the prepared view was disposed.\", cpu);\n if (lost || runtime.isLost()) { lost = true; return fallback(\"device-lost\", \"the WebGPU device was lost; the rest of the view runs on the CPU.\", cpu); }\n let check: DisplayViewGpuConformance;\n try { check = await selfCheck(signal); }\n catch (error) {\n if (lostError(error)) { lost = true; return fallback(\"device-lost\", \"the WebGPU device was lost during its conformance check.\", cpu); }\n setup.checkAbort();\n throw error;\n }\n if (!check.passed) return fallback(\"conformance-failed\", \"the device failed conformance case \\\"\" + check.failedCase + \"\\\": \" + check.detail, cpu);\n const turn = tail.then(async () => {\n if (disposed || lost || runtime.isLost()) return null;\n setup.checkAbort();\n return renderer.render({ setup, signal });\n });\n tail = turn.catch(() => undefined);\n let output: Awaited<typeof turn>;\n try { output = await turn; }\n catch (error) {\n if (lostError(error)) { lost = true; return fallback(\"device-lost\", \"the WebGPU device was lost during a render; the rest of the view runs on the CPU.\", cpu); }\n setup.checkAbort();\n if (error instanceof ImageKernelExecutionError && error.reason === \"unsupported-on-backend\")\n return fallback(\"unsupported-on-backend\", \"the GPU display-view renderer \\\"\" + renderer.id + \"\\\" does not cover this render: \" + error.message, cpu, probeOf(error));\n // #492: a render past the device's limits (a kernel table or band above its storage binding limit) runs the CPU reference too.\n if (error instanceof ImageKernelExecutionError && error.reason === \"insufficient-limits\")\n return fallback(\"insufficient-limits\", \"the device's limits do not hold this render on the GPU: \" + error.message, cpu);\n throw error;\n }\n if (output === null) return this.render(setup, signal, cpu);\n const { errorBound, diagnosticUncertaintySampleCount: uncertainty = 0, compositeProbe = null, ...rendered } = output;\n const execution: DisplayViewExecution = Object.freeze({ gpu: options.gpu, backend: \"webgpu-f32\", requestedBackend: \"webgpu-f32\", fallbackReason: null, arithmetic: \"float32\",\n assurance: \"approximation-with-a-priori-bound\", fast: true, bitIdenticalToReference: false, errorBound, diagnosticsExact: uncertainty === 0,\n diagnosticUncertaintySampleCount: uncertainty, limitations: WEBGPU_F32_LIMITATIONS, adapter, conformance: check, compositeProbe });\n return { rendered, execution };\n },\n dispose(): void {\n if (disposed) return;\n disposed = true;\n renderer.dispose?.();\n if (owned) runtime.destroy();\n }\n };\n}\n"]}
1
+ {"version":3,"file":"display-view-gpu-session.js","sourceRoot":"","sources":["../../src/facade/display-view-gpu-session.ts"],"names":[],"mappings":"AAAA,sCAAsC;AAEtC;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAC3E,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAC3D,OAAO,EAAE,oBAAoB,EAAsB,MAAM,0BAA0B,CAAC;AACpF,OAAO,EAAE,yBAAyB,EAAE,sBAAsB,EAAsE,MAAM,kCAAkC,CAAC;AACzK,OAAO,EAAE,kBAAkB,EAAE,2BAA2B,EAAE,MAAM,oCAAoC,CAAC;AACrG,OAAO,EAAE,kCAAkC,EAAE,sBAAsB,EAAmC,MAAM,qCAAqC,CAAC;AAElJ,OAAO,EAAE,6BAA6B,IAAI,mCAAmC,EAAE,MAAM,oCAAoC,CAAC;AAC1H,OAAO,EAAE,uBAAuB,EAAE,6BAA6B,EAAE,gCAAgC,EACmC,MAAM,uBAAuB,CAAC;AAElK,0GAA0G;AAC1G,kIAAkI;AAClI,+GAA+G;AAC/G,IAAI,6BAA6B,EAAE,KAAK,IAAI;IAAE,gCAAgC,CAAC,mCAAmC,CAAC,CAAC;AASpH,0EAA0E;AAC1E,SAAS,UAAU,CAAC,OAAwC,EAAE,MAAoC,EAAE,MAAc,EAAE,OAA6C,EAC/J,WAA6C;IAC7C,MAAM,SAAS,GAAG,uBAAuB,CAAC,OAAO,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,CAAC,CAAC;IAC7F,OAAO,EAAE,KAAK,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,EAAE,GAAG,IAAqF,OAAO,EAAE,QAAQ,EAAE,MAAM,GAA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AE,CAAC;YACrB,IAAI,KAAK;gBAAE,OAAO,CAAC,OAAO,EAAE,CAAC;QAC/B,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\n/**\n * #481: the device handling behind `prepareDisplayView(request, { gpu: \"auto\" | \"require\", gpuDevice })`. Loaded on demand by\n * `simulate-display-view.ts`, so the GPU code stays out of bundles that never ask for it. One session per prepared view:\n *\n * - the realm's switch (`setWebGpuEnabled(false)`) vetoes before anything else: `\"auto\"` falls back with `webgpu-disabled`,\n * `\"require\"` throws it;\n * - with no renderer registered (the engine registers its renderer, the Speed and Quality kernels of #478 and #479, when this module\n * loads; a caller may replace it or set null) no device is requested: `unsupported-on-backend`;\n * - the device is the handle's (`gpuDevice`: an `ImageKernelAccelerator`'s device, shared and left to its owner, or a WebGPU\n * entry point to acquire from), or acquired from `navigator.gpu` and owned by the session; the accelerator's acquisition\n * reasons apply, and the request's `signal` aborts the acquisition;\n * - the renderer must support the request, else `unsupported-on-backend`; a render the renderer refuses only when rendering\n * (`unsupported-on-backend` thrown by `render`: a coarse view, a device that fails the composite chart probe, #491) runs the\n * CPU reference for that render with the same label, and so does a render whose tables or bands exceed the device's limits\n * (`insufficient-limits` thrown by `render`: #492, a large defocus kernel's table on a scene of many materials);\n * - before the first GPU render on the device a short conformance self-check runs once (single-flight): the built-in cases run\n * the existing `webgpu-f32` convolution kernel against the float64 reference within its a-priori bound, then the renderer's own\n * cases; a failure keeps the whole view on the CPU, labelled `conformance-failed`, with the adapter recorded;\n * - GPU renders of one session run one at a time on the device (the accelerator's single flight; later renders wait);\n * - a lost device falls back to the CPU for that render and every later one, labelled `device-lost`; `dispose()` releases an\n * owned device, and later renders run on the CPU labelled `disposed`.\n */\n\nimport { InvalidConfigurationError } from \"../core/configuration-error.js\";\nimport { getWebGpuEnabled } from \"../gpu/webgpu-switch.js\";\nimport { acquireWebGpuRuntime, type WebGpuRuntime } from \"../gpu/webgpu-runtime.js\";\nimport { ImageKernelExecutionError, WEBGPU_F32_LIMITATIONS, type ChartCompositeProbeRecord, type ImageKernelAdapterDescription } from \"../gpu/image-kernel-execution.js\";\nimport { acceleratorRuntime, convolveIrradianceOnRuntime } from \"../gpu/image-kernel-accelerator.js\";\nimport { calculateIrradianceConvolutionPlan, convolveIrradianceRows, type IrradianceConvolutionInput } from \"../optics/irradiance-convolution.js\";\nimport type { DisplayViewRenderResult, DisplayViewSetup } from \"./display-view.js\";\nimport { displayViewGpuRendererFactory as engineDisplayViewGpuRendererFactory } from \"../gpu/display-view-quality-gpu.js\";\nimport { cpuDisplayViewExecution, displayViewGpuRendererFactory, setDisplayViewGpuRendererFactory, type DisplayViewExecution, type DisplayViewGpuConformance, type DisplayViewGpuConformanceCase,\n type DisplayViewGpuFallbackReason, type DisplayViewGpuRenderer, type DisplayViewGpuRequest, type ParsedPrepareDisplayViewOptions } from \"./display-view-gpu.js\";\n\n// #478, #479: the engine's own renderer, the display view's Speed and Quality kernels behind one renderer\n// (`src/gpu/display-view-quality-gpu.ts`), is registered when this module loads (that is, when a prepared view first asks for the\n// GPU) unless a caller registered a renderer before; a test that needs \"no renderer\" sets the factory to null.\nif (displayViewGpuRendererFactory() === null) setDisplayViewGpuRendererFactory(engineDisplayViewGpuRendererFactory);\n\n/** Internal: the GPU side of one prepared view. */\nexport interface DisplayViewGpuSession {\n /** Renders `setup` on the GPU when the session can, else through `cpu`; the label says which ran. */\n render(setup: DisplayViewSetup, signal: AbortSignal | undefined, cpu: () => Promise<DisplayViewRenderResult>): Promise<{ rendered: DisplayViewRenderResult; execution: DisplayViewExecution }>;\n dispose(): void;\n}\n\n/** A session that renders every view on the CPU with one fixed reason. */\nfunction cpuSession(options: ParsedPrepareDisplayViewOptions, reason: DisplayViewGpuFallbackReason, detail: string, adapter: ImageKernelAdapterDescription | null,\n conformance: DisplayViewGpuConformance | null): DisplayViewGpuSession {\n const execution = cpuDisplayViewExecution(options.gpu, reason, adapter, conformance, detail);\n return { async render(_setup, _signal, cpu): Promise<{ rendered: DisplayViewRenderResult; execution: DisplayViewExecution }> { return { rendered: await cpu(), execution }; },\n dispose(): void { /* nothing acquired */ } };\n}\n\n/** `\"require\"` throws the reason; `\"auto\"` gets a CPU session labelled with it. */\nfunction fallBack(options: ParsedPrepareDisplayViewOptions, reason: DisplayViewGpuFallbackReason, detail: string, adapter: ImageKernelAdapterDescription | null = null,\n conformance: DisplayViewGpuConformance | null = null): DisplayViewGpuSession {\n if (options.gpu === \"require\") throw requireError(reason, detail);\n return cpuSession(options, reason, detail, adapter, conformance);\n}\n/**\n * The error `\"require\"` throws instead of falling back. Every display-view fallback reason is also a failure reason of the accelerator's\n * error. A refusal by the composite chart probe carries its record as `probe` (the structured detail of the message).\n */\nfunction requireError(reason: DisplayViewGpuFallbackReason, detail: string, probe: ChartCompositeProbeRecord | null = null): ImageKernelExecutionError {\n const error = new ImageKernelExecutionError(reason, \"prepareDisplayView with gpu \\\"require\\\": \" + detail);\n if (probe) Object.defineProperty(error, \"probe\", { value: probe, enumerable: true });\n return error;\n}\n/** The composite chart probe's record on a refusal (`ChartCompositeProbeError.probe`), or null. */\nfunction probeOf(error: unknown): ChartCompositeProbeRecord | null {\n const probe = (error as { probe?: unknown }).probe;\n return typeof probe === \"object\" && probe !== null ? probe as ChartCompositeProbeRecord : null;\n}\n\n/** True for an object shaped like an `ImageKernelAccelerator` (the handle form that shares a device). */\nfunction isAccelerator(value: unknown): boolean {\n return typeof value === \"object\" && value !== null && typeof (value as { convolveIrradiance?: unknown }).convolveIrradiance === \"function\" &&\n typeof (value as { backend?: unknown }).backend === \"string\";\n}\n\n/**\n * Internal (#481): opens the GPU session of a prepared view, or throws (`\"require\"`) when the GPU cannot be used. Called only\n * for `gpu: \"auto\" | \"require\"`.\n */\nexport async function openDisplayViewGpuSession(options: ParsedPrepareDisplayViewOptions, request: DisplayViewGpuRequest, signal: AbortSignal | undefined): Promise<DisplayViewGpuSession> {\n if (!getWebGpuEnabled()) return fallBack(options, \"webgpu-disabled\", \"WebGPU is switched off in this realm (setWebGpuEnabled(false)).\");\n const factory = displayViewGpuRendererFactory();\n if (!factory) return fallBack(options, \"unsupported-on-backend\", \"this version of the engine has no GPU display-view renderer (#478); no device was requested.\");\n // #563: the lens signal (projection, distortion, vignetting, rotation) runs on the CPU reference only; no device is requested for it.\n if (request.lens) return fallBack(options, \"unsupported-on-backend\", \"the GPU display-view renderers do not render lens.projection, lens.distortion, lens.vignetting or \" +\n \"camera rotation (#563); the CPU reference renders them. No device was requested.\");\n let runtime: WebGpuRuntime, owned = false;\n if (isAccelerator(options.gpuDevice)) {\n const shared = acceleratorRuntime(options.gpuDevice) as WebGpuRuntime | null | undefined;\n if (shared === undefined) throw new InvalidConfigurationError(\"prepareDisplayView options.gpuDevice must be an accelerator created by createImageKernelAccelerator.\");\n const accelerator = options.gpuDevice as { state: string; fallbackReason: DisplayViewGpuFallbackReason | null };\n if (accelerator.state === \"disposed\") throw new InvalidConfigurationError(\"prepareDisplayView options.gpuDevice is a disposed accelerator.\");\n if (shared === null) return fallBack(options, accelerator.fallbackReason ?? \"webgpu-unavailable\", \"the given accelerator runs the CPU reference and has no device.\");\n if (shared.isLost()) return fallBack(options, \"device-lost\", \"the given accelerator's device was lost.\", shared.adapter);\n runtime = shared;\n } else {\n const gpu = options.gpuDevice !== undefined ? options.gpuDevice : (globalThis as { navigator?: { gpu?: unknown } }).navigator?.gpu;\n let acquired: Awaited<ReturnType<typeof acquireWebGpuRuntime>>;\n try { acquired = await acquireWebGpuRuntime(gpu, undefined, signal); }\n catch (error) {\n if (error instanceof ImageKernelExecutionError && error.reason === \"aborted\") throw new InvalidConfigurationError(\"prepareDisplayView aborted.\");\n throw error;\n }\n if (\"failure\" in acquired) return fallBack(options, acquired.failure, acquired.message);\n runtime = acquired.runtime; owned = true;\n }\n const renderer = factory(runtime), supported = renderer.supports(request);\n if (supported !== true) {\n if (owned) runtime.destroy();\n return fallBack(options, \"unsupported-on-backend\", \"the GPU display-view renderer \\\"\" + renderer.id + \"\\\" does not support this request: \" + supported, runtime.adapter);\n }\n return createSession(options, runtime, owned, renderer);\n}\n\n// ---------------------------------------------------------------------------------------------------------------\n// Run-time conformance self-check.\n\n/** A fixed, seeded test image (mulberry32) for the built-in cases. */\nfunction seededSamples(count: number, seed: number): Float64Array {\n let a = seed >>> 0;\n const out = new Float64Array(count);\n for (let i = 0; i < count; i++) {\n a = (a + 0x6d2b79f5) >>> 0;\n let t = Math.imul(a ^ (a >>> 15), 1 | a);\n t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;\n const u = ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n out[i] = u < 0.05 ? 0 : 10 ** (u * 6 - 3);\n }\n return out;\n}\n/** One convolution case: normalized Gaussian kernels of width `sigma` per patch, compared with the float64 reference within the a-priori bound. */\nfunction convolutionCase(id: string, width: number, height: number, radius: number, patchWidth: number, patchHeight: number, seed: number): DisplayViewGpuConformanceCase {\n return { id, async run(runtime, signal): Promise<true | string> {\n const size = 2 * radius + 1, taps = size * size, columns = Math.ceil(width / patchWidth), rows = Math.ceil(height / patchHeight);\n const kernels = new Float64Array(columns * rows * taps);\n for (let p = 0; p < columns * rows; p++) {\n const sigma = 0.6 + 0.4 * (p % 3), scale = 0.8 + 0.05 * p;\n let sum = 0;\n for (let v = -radius; v <= radius; v++) for (let u = -radius; u <= radius; u++) { const w = Math.exp(-0.5 * (u * u + v * v) / (sigma * sigma)); kernels[p * taps + (v + radius) * size + u + radius] = w; sum += w; }\n for (let t = 0; t < taps; t++) kernels[p * taps + t] = kernels[p * taps + t]! / sum * Math.min(1, scale);\n }\n const input: IrradianceConvolutionInput = { schemaVersion: \"0.1.0\", width, height, kernelRadius: radius, patchWidth, patchHeight, boundary: \"zero-outside-grid\",\n samples: seededSamples(width * height, seed), kernels };\n const plan = calculateIrradianceConvolutionPlan(input), reference = new Float64Array(width * height);\n convolveIrradianceRows(plan, input.samples, input.kernels, 0, height, reference);\n {\n const result = await convolveIrradianceOnRuntime(runtime, input, signal);\n const bound = result.execution.errorBound;\n if (!bound || bound.kind !== \"relative-to-reference\") return \"the convolution reported no relative bound.\";\n let worst = 0, worstIndex = -1;\n for (let i = 0; i < reference.length; i++) {\n const allowed = bound.relative * reference[i]! + bound.absolute, excess = Math.abs(result.values[i]! - reference[i]!) - allowed;\n if (excess > worst) { worst = excess; worstIndex = i; }\n }\n return worstIndex < 0 ? true : \"sample \" + worstIndex + \" differs from the reference by \" + Math.abs(result.values[worstIndex]! - reference[worstIndex]!) +\n \", more than the a-priori bound \" + (bound.relative * reference[worstIndex]! + bound.absolute) + \".\";\n }\n } };\n}\n/** The built-in cases, run on every device before its first display-view render: the existing convolution kernel on two small images. */\nexport const DISPLAY_VIEW_GPU_BUILT_IN_CASES: readonly DisplayViewGpuConformanceCase[] = Object.freeze([\n convolutionCase(\"image-kernel:convolution:16x12-r1\", 16, 12, 1, 16, 12, 481),\n convolutionCase(\"image-kernel:convolution:32x24-r3-patches\", 32, 24, 3, 16, 12, 4781)\n]);\n\nasync function runConformance(runtime: WebGpuRuntime, renderer: DisplayViewGpuRenderer, signal: AbortSignal | undefined): Promise<DisplayViewGpuConformance> {\n const cases = [...DISPLAY_VIEW_GPU_BUILT_IN_CASES, ...(renderer.conformanceCases ?? [])], ids = Object.freeze(cases.map((c) => c.id));\n for (const c of cases) {\n let outcome: true | string;\n try { outcome = await c.run(runtime, signal); }\n catch (error) {\n // An abort is the caller's, not the device's; everything else the device did wrong is a failed case.\n if (error instanceof ImageKernelExecutionError && error.reason === \"aborted\") throw error;\n outcome = \"the case threw \" + (error instanceof ImageKernelExecutionError ? error.reason + \": \" : \"\") + (error instanceof Error ? error.message : String(error));\n }\n if (outcome !== true) return Object.freeze({ cases: ids, passed: false, failedCase: c.id, detail: outcome });\n }\n return Object.freeze({ cases: ids, passed: true, failedCase: null, detail: null });\n}\n\n// ---------------------------------------------------------------------------------------------------------------\n\nfunction createSession(options: ParsedPrepareDisplayViewOptions, runtime: WebGpuRuntime, owned: boolean, renderer: DisplayViewGpuRenderer): DisplayViewGpuSession {\n const adapter = runtime.adapter;\n let disposed = false, lost = false, conformance: DisplayViewGpuConformance | null = null, checking: Promise<DisplayViewGpuConformance> | null = null;\n /** The last GPU turn: renders queue behind it, so one dispatch runs at a time on the device. */\n let tail: Promise<unknown> = Promise.resolve();\n /** A CPU fallback label for `\"auto\"`; with `\"require\"` the same event is an error. */\n const fallback = async (reason: DisplayViewGpuFallbackReason, detail: string, cpu: () => Promise<DisplayViewRenderResult>, compositeProbe: ChartCompositeProbeRecord | null = null):\n Promise<{ rendered: DisplayViewRenderResult; execution: DisplayViewExecution }> => {\n if (options.gpu === \"require\") throw requireError(reason, detail, compositeProbe);\n return { rendered: await cpu(), execution: cpuDisplayViewExecution(options.gpu, reason, adapter, conformance, detail, compositeProbe) };\n };\n /** The self-check, run once per session (single flight); a failing check is remembered and never repeated. */\n function selfCheck(signal: AbortSignal | undefined): Promise<DisplayViewGpuConformance> {\n if (conformance) return Promise.resolve(conformance);\n if (!checking) {\n checking = runConformance(runtime, renderer, signal).then((result) => { conformance = result; return result; }, (error: unknown) => { checking = null; throw error; });\n }\n return checking;\n }\n function lostError(error: unknown): boolean { return (error instanceof ImageKernelExecutionError && error.reason === \"device-lost\") || runtime.isLost(); }\n return {\n async render(setup, signal, cpu): Promise<{ rendered: DisplayViewRenderResult; execution: DisplayViewExecution }> {\n if (disposed) return fallback(\"disposed\", \"the prepared view was disposed.\", cpu);\n if (lost || runtime.isLost()) { lost = true; return fallback(\"device-lost\", \"the WebGPU device was lost; the rest of the view runs on the CPU.\", cpu); }\n let check: DisplayViewGpuConformance;\n try { check = await selfCheck(signal); }\n catch (error) {\n if (lostError(error)) { lost = true; return fallback(\"device-lost\", \"the WebGPU device was lost during its conformance check.\", cpu); }\n setup.checkAbort();\n throw error;\n }\n if (!check.passed) return fallback(\"conformance-failed\", \"the device failed conformance case \\\"\" + check.failedCase + \"\\\": \" + check.detail, cpu);\n const turn = tail.then(async () => {\n if (disposed || lost || runtime.isLost()) return null;\n setup.checkAbort();\n return renderer.render({ setup, signal });\n });\n tail = turn.catch(() => undefined);\n let output: Awaited<typeof turn>;\n try { output = await turn; }\n catch (error) {\n if (lostError(error)) { lost = true; return fallback(\"device-lost\", \"the WebGPU device was lost during a render; the rest of the view runs on the CPU.\", cpu); }\n setup.checkAbort();\n if (error instanceof ImageKernelExecutionError && error.reason === \"unsupported-on-backend\")\n return fallback(\"unsupported-on-backend\", \"the GPU display-view renderer \\\"\" + renderer.id + \"\\\" does not cover this render: \" + error.message, cpu, probeOf(error));\n // #492: a render past the device's limits (a kernel table or band above its storage binding limit) runs the CPU reference too.\n if (error instanceof ImageKernelExecutionError && error.reason === \"insufficient-limits\")\n return fallback(\"insufficient-limits\", \"the device's limits do not hold this render on the GPU: \" + error.message, cpu);\n throw error;\n }\n if (output === null) return this.render(setup, signal, cpu);\n const { errorBound, diagnosticUncertaintySampleCount: uncertainty = 0, compositeProbe = null, ...rendered } = output;\n const execution: DisplayViewExecution = Object.freeze({ gpu: options.gpu, backend: \"webgpu-f32\", requestedBackend: \"webgpu-f32\", fallbackReason: null, arithmetic: \"float32\",\n assurance: \"approximation-with-a-priori-bound\", fast: true, bitIdenticalToReference: false, errorBound, diagnosticsExact: uncertainty === 0,\n diagnosticUncertaintySampleCount: uncertainty, limitations: WEBGPU_F32_LIMITATIONS, adapter, conformance: check, compositeProbe });\n return { rendered, execution };\n },\n dispose(): void {\n if (disposed) return;\n disposed = true;\n renderer.dispose?.();\n if (owned) runtime.destroy();\n }\n };\n}\n"]}
@@ -96,6 +96,16 @@ export interface DisplayViewGpuRequest {
96
96
  * Quality site pass (step 2c). Absent or false otherwise.
97
97
  */
98
98
  defocus?: boolean;
99
+ /**
100
+ * #564: true when the defocus kernel's radius is above 64 sites, so the expected signal convolves it by runs on the CPU
101
+ * (`largeKernel`); no GPU renderer takes it. Absent or false otherwise.
102
+ */
103
+ largeDefocus?: boolean;
104
+ /**
105
+ * #563: true when the request has `lens.projection`, `lens.distortion`, `lens.vignetting` or camera rotation: the CPU reference
106
+ * renders it (display-view-lens-signal.ts) and no GPU renderer is asked or device requested (`unsupported-on-backend`).
107
+ */
108
+ lens?: boolean;
99
109
  /** The scene's form: an engine chart, a declared `material-layers` scene (#491), or a caller function. */
100
110
  scene: "chart" | "material-layers" | "material-function" | "reflectance-function" | "radiance-function";
101
111
  }