@photivra/engine 2.9.0 → 2.11.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +223 -1
- package/CITATION.cff +1 -1
- package/NODE_SUPPORT.md +21 -3
- package/README.md +6 -6
- package/SECURITY.md +1 -1
- package/THIRD_PARTY.md +2 -0
- package/dist/capture/native-environment-lean.js +89 -5
- package/dist/capture/native-environment-lean.js.map +1 -1
- package/dist/capture/native-environment-tabulated.d.ts +37 -0
- package/dist/capture/native-environment-tabulated.js +42 -6
- package/dist/capture/native-environment-tabulated.js.map +1 -1
- package/dist/core/portable-math.d.ts +19 -0
- package/dist/core/portable-math.js +82 -0
- package/dist/core/portable-math.js.map +1 -1
- package/dist/core/version.d.ts +1 -1
- package/dist/core/version.js +1 -1
- package/dist/core/version.js.map +1 -1
- package/dist/facade/channel-response.d.ts +15 -0
- package/dist/facade/channel-response.js +33 -0
- package/dist/facade/channel-response.js.map +1 -0
- package/dist/facade/chart-material-layers.d.ts +115 -0
- package/dist/facade/chart-material-layers.js +224 -0
- package/dist/facade/chart-material-layers.js.map +1 -0
- package/dist/facade/chart-radiance-batch.d.ts +8 -2
- package/dist/facade/chart-radiance-batch.js +11 -4
- package/dist/facade/chart-radiance-batch.js.map +1 -1
- package/dist/facade/chart-scenes.d.ts +134 -0
- package/dist/facade/chart-scenes.js +32 -22
- package/dist/facade/chart-scenes.js.map +1 -1
- package/dist/facade/diffraction-provider.d.ts +8 -2
- package/dist/facade/diffraction-provider.js +120 -16
- package/dist/facade/diffraction-provider.js.map +1 -1
- package/dist/facade/display-view-gpu-session.d.ts +18 -0
- package/dist/facade/display-view-gpu-session.js +280 -0
- package/dist/facade/display-view-gpu-session.js.map +1 -0
- package/dist/facade/display-view-gpu.d.ts +146 -0
- package/dist/facade/display-view-gpu.js +59 -0
- package/dist/facade/display-view-gpu.js.map +1 -0
- package/dist/facade/display-view.d.ts +123 -1
- package/dist/facade/display-view.js +478 -116
- package/dist/facade/display-view.js.map +1 -1
- package/dist/facade/expected-signal-setup.d.ts +5 -0
- package/dist/facade/expected-signal-setup.js +18 -1
- package/dist/facade/expected-signal-setup.js.map +1 -1
- package/dist/facade/expected-signal.d.ts +80 -6
- package/dist/facade/expected-signal.js +200 -24
- package/dist/facade/expected-signal.js.map +1 -1
- package/dist/facade/scene-radiance.d.ts +4 -2
- package/dist/facade/scene-radiance.js +7 -4
- package/dist/facade/scene-radiance.js.map +1 -1
- package/dist/facade/simulate-capture.d.ts +81 -7
- package/dist/facade/simulate-capture.js +276 -53
- package/dist/facade/simulate-capture.js.map +1 -1
- package/dist/facade/simulate-display-view.d.ts +54 -3
- package/dist/facade/simulate-display-view.js +120 -27
- package/dist/facade/simulate-display-view.js.map +1 -1
- package/dist/gpu/chart-composite-gpu.d.ts +119 -0
- package/dist/gpu/chart-composite-gpu.js +572 -0
- package/dist/gpu/chart-composite-gpu.js.map +1 -0
- package/dist/gpu/chart-radiance-gpu.d.ts +6 -6
- package/dist/gpu/chart-radiance-gpu.js +9 -11
- package/dist/gpu/chart-radiance-gpu.js.map +1 -1
- package/dist/gpu/display-view-chart-material-module.d.ts +10 -0
- package/dist/gpu/display-view-chart-material-module.js +58 -0
- package/dist/gpu/display-view-chart-material-module.js.map +1 -0
- package/dist/gpu/display-view-composite-material-module.d.ts +68 -0
- package/dist/gpu/display-view-composite-material-module.js +248 -0
- package/dist/gpu/display-view-composite-material-module.js.map +1 -0
- package/dist/gpu/display-view-quality-gpu.d.ts +185 -0
- package/dist/gpu/display-view-quality-gpu.js +1000 -0
- package/dist/gpu/display-view-quality-gpu.js.map +1 -0
- package/dist/gpu/display-view-speed-gpu.d.ts +156 -0
- package/dist/gpu/display-view-speed-gpu.js +524 -0
- package/dist/gpu/display-view-speed-gpu.js.map +1 -0
- package/dist/gpu/image-kernel-accelerator.d.ts +23 -4
- package/dist/gpu/image-kernel-accelerator.js +58 -10
- package/dist/gpu/image-kernel-accelerator.js.map +1 -1
- package/dist/gpu/image-kernel-execution.d.ts +60 -3
- package/dist/gpu/image-kernel-execution.js +2 -2
- package/dist/gpu/image-kernel-execution.js.map +1 -1
- package/dist/gpu/sensor-stage-gpu.d.ts +11 -0
- package/dist/gpu/sensor-stage-gpu.js +42 -13
- package/dist/gpu/sensor-stage-gpu.js.map +1 -1
- package/dist/gpu/webgpu-runtime.d.ts +4 -2
- package/dist/gpu/webgpu-runtime.js +13 -4
- package/dist/gpu/webgpu-runtime.js.map +1 -1
- package/dist/gpu/webgpu-switch.d.ts +4 -0
- package/dist/gpu/webgpu-switch.js +29 -0
- package/dist/gpu/webgpu-switch.js.map +1 -0
- package/dist/gpu/wgsl-chart-composite-kernel.d.ts +52 -0
- package/dist/gpu/wgsl-chart-composite-kernel.js +515 -0
- package/dist/gpu/wgsl-chart-composite-kernel.js.map +1 -0
- package/dist/gpu/wgsl-chart-kernel.d.ts +11 -9
- package/dist/gpu/wgsl-chart-kernel.js +33 -27
- package/dist/gpu/wgsl-chart-kernel.js.map +1 -1
- package/dist/gpu/wgsl-display-view-quality-kernel.d.ts +95 -0
- package/dist/gpu/wgsl-display-view-quality-kernel.js +769 -0
- package/dist/gpu/wgsl-display-view-quality-kernel.js.map +1 -0
- package/dist/gpu/wgsl-display-view-speed-kernel.d.ts +75 -0
- package/dist/gpu/wgsl-display-view-speed-kernel.js +386 -0
- package/dist/gpu/wgsl-display-view-speed-kernel.js.map +1 -0
- package/dist/gpu/wgsl-sensor-kernel.d.ts +28 -9
- package/dist/gpu/wgsl-sensor-kernel.js +94 -50
- package/dist/gpu/wgsl-sensor-kernel.js.map +1 -1
- package/dist/index.d.ts +6 -3
- package/dist/index.js +4 -2
- package/dist/index.js.map +1 -1
- package/dist/optics/defocus-disc-kernel.d.ts +61 -0
- package/dist/optics/defocus-disc-kernel.js +191 -0
- package/dist/optics/defocus-disc-kernel.js.map +1 -0
- package/dist/optics/irradiance-convolution.d.ts +11 -0
- package/dist/optics/irradiance-convolution.js +64 -24
- package/dist/optics/irradiance-convolution.js.map +1 -1
- package/dist/optics/scene-to-sensor-irradiance.d.ts +13 -0
- package/dist/optics/scene-to-sensor-irradiance.js +58 -24
- package/dist/optics/scene-to-sensor-irradiance.js.map +1 -1
- package/dist/optics/sensor-aperture-rays.js +2 -1
- package/dist/optics/sensor-aperture-rays.js.map +1 -1
- package/dist/optics/sensor-environment-query.js +4 -3
- package/dist/optics/sensor-environment-query.js.map +1 -1
- package/dist/optics/site-diffraction-kernel.d.ts +16 -0
- package/dist/optics/site-diffraction-kernel.js +60 -8
- package/dist/optics/site-diffraction-kernel.js.map +1 -1
- package/dist/processing/demosaic.js +114 -37
- package/dist/processing/demosaic.js.map +1 -1
- package/dist/schema/scene-radiance.d.ts +8 -0
- package/dist/schema/scene-radiance.js +28 -17
- package/dist/schema/scene-radiance.js.map +1 -1
- package/dist/sensor/environment-photo-signal.d.ts +21 -0
- package/dist/sensor/environment-photo-signal.js +68 -2
- package/dist/sensor/environment-photo-signal.js.map +1 -1
- package/docs/API_REFERENCE.md +60 -1
- package/docs/QUICK_START.md +120 -11
- package/docs/USAGE.md +82 -2
- package/docs/api/core-version.md +1 -1
- package/docs/api/exports.json +157 -2
- package/docs/api/facade-chart-material-layers.md +137 -0
- package/docs/api/facade-chart-radiance-batch.md +7 -2
- package/docs/api/facade-display-view-gpu.md +94 -0
- package/docs/api/facade-display-view.md +50 -0
- package/docs/api/facade-scene-radiance.md +3 -2
- package/docs/api/facade-simulate-capture.md +81 -12
- package/docs/api/facade-simulate-display-view.md +39 -2
- package/docs/api/gpu-image-kernel-accelerator.md +10 -3
- package/docs/api/gpu-image-kernel-execution.md +76 -4
- package/docs/api/gpu-webgpu-switch.md +23 -0
- package/package.json +3 -1
|
@@ -38,10 +38,17 @@
|
|
|
38
38
|
*
|
|
39
39
|
* A query that does not land on one of the lattices (within 1e-6 site) is refused rather than approximated: the
|
|
40
40
|
* facade uses this path only when the lattice argument above holds. A query outside the window is refused too.
|
|
41
|
+
*
|
|
42
|
+
* Defocus (#492, `lens.defocus`): the same argument holds for any space-invariant kernel on the site lattice, so the facade
|
|
43
|
+
* passes `siteKernels` instead (the geometric defocus disc, or each node's diffraction kernel convolved with it). Their radius
|
|
44
|
+
* may exceed the public 32-site convolution limit, so this path does not call `calculateIrradianceConvolution`: it checks the
|
|
45
|
+
* samples and the kernel sums as that function does and gathers only the band's own values (`gatherInterior`), each summed
|
|
46
|
+
* over the taps in the same fixed order (v outer, u inner, ascending; zero taps skipped, which adds exact zeros only). It
|
|
47
|
+
* does not compute the 2R grid rows above and below a band that `calculateIrradianceConvolution` would also return (#419).
|
|
41
48
|
*/
|
|
42
49
|
import { InvalidConfigurationError } from "../core/configuration-error.js";
|
|
43
50
|
import { isInternalSceneRadianceEvaluator, markInternalSceneRadianceEvaluator, registerInternalRadianceAccess } from "../core/internal-radiance-evaluator.js";
|
|
44
|
-
import {
|
|
51
|
+
import { createIrradianceConvolutionRunner } from "../optics/irradiance-convolution.js";
|
|
45
52
|
import { siteDiffractionKernel } from "../optics/site-diffraction-kernel.js";
|
|
46
53
|
/** Rows of native sites per convolution band, and the bands kept. Banding changes memory only, never values. */
|
|
47
54
|
const BAND_ROWS = 32;
|
|
@@ -72,10 +79,17 @@ export function createDiffractedPlanarProvider(input) {
|
|
|
72
79
|
throw new InvalidConfigurationError("Diffraction window must overlap the native raster.");
|
|
73
80
|
const NW = lx1 - lx0;
|
|
74
81
|
// One kernel per wavelength, on the site grid, from the engine's own tap-to-site mapping (field point 0, 0); kept across calls.
|
|
75
|
-
const
|
|
82
|
+
const siteKernels = input.siteKernels;
|
|
83
|
+
if (!siteKernels && !input.psf)
|
|
84
|
+
throw new InvalidConfigurationError("The object-space convolution needs a PSF or site kernels.");
|
|
85
|
+
const kernels = wavelengthsNm.map((wavelengthNm) => siteKernels ? checkedSiteKernel(siteKernels(wavelengthNm), R) :
|
|
86
|
+
siteDiffractionKernel(input.psf, wavelengthNm, pitch, R, "Diffraction kernels must sample the site pitch exactly."));
|
|
87
|
+
// #492: each site kernel's non-zero taps as grid offsets, in the gather's order.
|
|
88
|
+
const taps = siteKernels ? kernels.map((kernel) => kernelTaps(kernel, R, NW + 2 * R)) : [];
|
|
76
89
|
const gridWidth = NW + 2 * R;
|
|
77
90
|
const now = () => globalThis.performance?.now() ?? Date.now();
|
|
78
91
|
const bands = new Map();
|
|
92
|
+
const materialAt = base.chartMaterialAt?.bind(base), materialRadiance = base.materialRadiance?.bind(base);
|
|
79
93
|
function band(b) {
|
|
80
94
|
const cached = bands.get(b);
|
|
81
95
|
if (cached) {
|
|
@@ -84,21 +98,57 @@ export function createDiffractedPlanarProvider(input) {
|
|
|
84
98
|
return cached;
|
|
85
99
|
}
|
|
86
100
|
const started = input.onConvolution ? now() : 0;
|
|
87
|
-
const y0 = ly0 + b * BAND_ROWS, rows = Math.min(BAND_ROWS, ly1 - y0), gridHeight = rows + 2 * R;
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
101
|
+
const y0 = ly0 + b * BAND_ROWS, rows = Math.min(BAND_ROWS, ly1 - y0), gridHeight = rows + 2 * R, size = gridWidth * gridHeight;
|
|
102
|
+
// #453: the band's shifts × spectral nodes convolutions share one geometry, validated once (the first runs the full
|
|
103
|
+
// calculateIrradianceConvolution; every later one still checks its samples and kernel).
|
|
104
|
+
const convolve = siteKernels ? undefined : createIrradianceConvolutionRunner({ schemaVersion: "0.1.0", width: gridWidth, height: gridHeight, kernelRadius: R,
|
|
105
|
+
patchWidth: gridWidth, patchHeight: gridHeight, boundary: "zero-outside-grid" });
|
|
106
|
+
const values = shifts.map((shift) => {
|
|
107
|
+
// The plane point of lattice grid sample (gx, gy) of this shift, the same expressions for both fills below.
|
|
108
|
+
const vOf = (gy) => shift.y === 0 ? -(y0 + gy - R - M + 0.5 - H / 2) * g : -(y0 + gy - R - M + 0.5 + shift.y - H / 2) * g;
|
|
109
|
+
const uOf = (x) => shift.x === 0 ? (x - R - M + 0.5 - W / 2) * g : (x - R - M + 0.5 + shift.x - W / 2) * g;
|
|
110
|
+
// #453, material scenes (chart presets and caller material scenes): radianceAt(u, v, nm) is materialRadiance(chartMaterialAt(u, v), nm)
|
|
111
|
+
// (scene-radiance.ts), so the material is looked up once per lattice point and each node's samples come from one
|
|
112
|
+
// materialRadiance per material present, the same numbers as one radianceAt per point and node.
|
|
113
|
+
let materialOf;
|
|
114
|
+
if (materialAt && materialRadiance) {
|
|
115
|
+
materialOf = new Int32Array(size);
|
|
116
|
+
for (let gy = 0; gy < gridHeight; gy++) {
|
|
117
|
+
const v = vOf(gy);
|
|
118
|
+
for (let gx = 0, x = lx0; gx < gridWidth; gx++, x++)
|
|
119
|
+
materialOf[gy * gridWidth + gx] = materialAt(uOf(x), v);
|
|
120
|
+
}
|
|
94
121
|
}
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
122
|
+
return wavelengthsNm.map((nm, w) => {
|
|
123
|
+
const samples = new Float64Array(size);
|
|
124
|
+
if (materialOf) {
|
|
125
|
+
const radiance = new Map();
|
|
126
|
+
for (let i = 0; i < size; i++) {
|
|
127
|
+
const m = materialOf[i];
|
|
128
|
+
let value = radiance.get(m);
|
|
129
|
+
if (value === undefined) {
|
|
130
|
+
value = materialRadiance(m, nm);
|
|
131
|
+
radiance.set(m, value);
|
|
132
|
+
}
|
|
133
|
+
samples[i] = value;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
else {
|
|
137
|
+
for (let gy = 0; gy < gridHeight; gy++) {
|
|
138
|
+
const v = vOf(gy);
|
|
139
|
+
for (let gx = 0, x = lx0; gx < gridWidth; gx++, x++)
|
|
140
|
+
samples[gy * gridWidth + gx] = base.radianceAt(uOf(x), v, nm);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
if (!convolve)
|
|
144
|
+
return gatherInterior(samples, taps[w], gridWidth, NW, rows, R);
|
|
145
|
+
const blurred = convolve(samples, kernels[w]);
|
|
146
|
+
const out = new Float64Array(NW * rows);
|
|
147
|
+
for (let y = 0; y < rows; y++)
|
|
148
|
+
out.set(blurred.subarray((y + R) * gridWidth + R, (y + R) * gridWidth + R + NW), y * NW);
|
|
149
|
+
return out;
|
|
150
|
+
});
|
|
151
|
+
});
|
|
102
152
|
bands.set(b, values);
|
|
103
153
|
if (bands.size > CACHED_BANDS)
|
|
104
154
|
bands.delete(bands.keys().next().value);
|
|
@@ -166,4 +216,58 @@ export function createDiffractedPlanarProvider(input) {
|
|
|
166
216
|
}
|
|
167
217
|
};
|
|
168
218
|
}
|
|
219
|
+
/** Largest kernel sum, and largest sample, the object-space convolution accepts (as `IRRADIANCE_CONVOLUTION_LIMITS`). */
|
|
220
|
+
const MAXIMUM_KERNEL_SUM = 1 + 2 ** -20, MAXIMUM_SAMPLE = 2 ** 100;
|
|
221
|
+
/** #492: a site kernel of radius R, checked as `calculateIrradianceConvolution` checks its kernels. */
|
|
222
|
+
function checkedSiteKernel(kernel, R) {
|
|
223
|
+
if (!(kernel instanceof Float64Array) || kernel.length !== (2 * R + 1) ** 2)
|
|
224
|
+
throw new InvalidConfigurationError("Site kernels must be (2R + 1)² taps.");
|
|
225
|
+
let sum = 0;
|
|
226
|
+
for (let k = 0; k < kernel.length; k++) {
|
|
227
|
+
const w = kernel[k];
|
|
228
|
+
if (!(w >= 0 && w <= 1))
|
|
229
|
+
throw new InvalidConfigurationError("Site kernel weights must be finite numbers in [0, 1].");
|
|
230
|
+
sum += w;
|
|
231
|
+
}
|
|
232
|
+
if (sum > MAXIMUM_KERNEL_SUM)
|
|
233
|
+
throw new InvalidConfigurationError("A PSF kernel may not create energy (sum exceeds 1).");
|
|
234
|
+
return kernel;
|
|
235
|
+
}
|
|
236
|
+
/** #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. */
|
|
237
|
+
function kernelTaps(kernel, R, gridWidth) {
|
|
238
|
+
const offsets = [], weights = [];
|
|
239
|
+
for (let v = -R, t = 0; v <= R; v++)
|
|
240
|
+
for (let u = -R; u <= R; u++, t++) {
|
|
241
|
+
const w = kernel[t];
|
|
242
|
+
if (w !== 0) {
|
|
243
|
+
offsets.push(-v * gridWidth - u);
|
|
244
|
+
weights.push(w);
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
return { offsets: Int32Array.from(offsets), weights: Float64Array.from(weights) };
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* #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
|
|
251
|
+
* these lies inside the grid (it holds R extra samples on each side), so no boundary rule applies. Samples are checked as
|
|
252
|
+
* `calculateIrradianceConvolution` checks them.
|
|
253
|
+
*/
|
|
254
|
+
function gatherInterior(samples, taps, gridWidth, width, rows, R) {
|
|
255
|
+
for (let k = 0; k < samples.length; k++) {
|
|
256
|
+
const v = samples[k];
|
|
257
|
+
if (!(v >= 0 && v <= MAXIMUM_SAMPLE))
|
|
258
|
+
throw new InvalidConfigurationError("Irradiance samples must be finite, non-negative and within the declared magnitude.");
|
|
259
|
+
}
|
|
260
|
+
const { offsets, weights } = taps, count = weights.length, out = new Float64Array(width * rows);
|
|
261
|
+
for (let y = 0; y < rows; y++) {
|
|
262
|
+
const rowBase = (y + R) * gridWidth + R;
|
|
263
|
+
for (let x = 0; x < width; x++) {
|
|
264
|
+
const base = rowBase + x;
|
|
265
|
+
let sum = 0;
|
|
266
|
+
for (let k = 0; k < count; k++)
|
|
267
|
+
sum += samples[base + offsets[k]] * weights[k];
|
|
268
|
+
out[y * width + x] = sum;
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
return out;
|
|
272
|
+
}
|
|
169
273
|
//# sourceMappingURL=diffraction-provider.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"diffraction-provider.js","sourceRoot":"","sources":["../../src/facade/diffraction-prov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EAAE,EAAE;gBACnB,MAAM,CAAC,GAAG,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;gBACxB,IAAI,CAAC,KAAK,SAAS;oBAAE,MAAM,IAAI,yBAAyB,CAAC,yFAAyF,CAAC,CAAC;gBACpJ,MAAM,EAAE,GAAG,GAAG,GAAG,EAAE,EAAE,IAAI,GAAG,CAAC,GAAG,GAAG,EAAE,CAAC,GAAG,EAAE,EAAE,EAAE,GAAG,IAAI,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,IAAI,GAAG,EAAE,CAAC,GAAG,EAAE,CAAC;gBAClF,OAAO,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,GAAG,CAAC,GAAG,SAAS,CAAC,CAAC,CAAC,CAAC,CAAE,CAAC,CAAC,CAAE,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,CAAC,GAAG,SAAS,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,GAAG,CAAE,CAAC;YACrG,CAAC;SACF,CAAC,CAAC;IACL,CAAC;IACD,OAAO;QACL,OAAO,EAAE,IAAI,CAAC,OAAO,EAAE,iBAAiB,EAAE,IAAI,CAAC,iBAAiB,EAAE,UAAU,EAAE,IAAI,CAAC,UAAU;QAC7F,gBAAgB;QAChB,wBAAwB;YACtB,MAAM,IAAI,yBAAyB,CAAC,mEAAmE,CAAC,CAAC;QAC3G,CAAC;KACF,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. The\n * provider then answers each site-centre query with B instead of L, and the environment request declares no\n * PSF. Incoherent imaging is a linear superposition of intensity PSFs, so convolving radiance on the object\n * plane and convolving irradiance on the image plane agree for a planar object and a space-invariant PSF\n * (MIT OpenCourseWare 2.71, lecture 22, free; also see: Goodman, Introduction to Fourier Optics, 4th ed., §7.1).\n *\n * With an anti-aliasing point-splitting filter (2.1, `sensor.antiAliasing`) the environment queries the PSF taps\n * around each pre-filter source point q − a (a = a split offset) instead of around q. Those taps lie on the site\n * lattice shifted by a, so the same argument holds on each shifted lattice: B is computed once per distinct\n * fractional shift (offsets that differ by whole sites share one lattice; the centred four-spot filter with a\n * one-site separation needs a single half-site-shifted lattice) over the native raster widened by the largest\n * offset, and the environment's spatial quadrature still forms the weighted split sum.\n *\n * Region renders (2.6, `window`): only the lattice rows and columns that the region's sites can query (the window\n * plus the largest offset on each side) are convolved, over a grid that adds the kernel radius on each side. Every\n * output value is the same gather as in the whole render: the grid always holds every tap of every value it keeps\n * (real scene radiance out to the kernel radius, never a truncated edge), the single kernel patch does not depend on\n * the grid's origin, and `convolveIrradianceRows` sums each value in a fixed tap order (v outer, u inner). Narrowing\n * the grid therefore removes only values that no query reads, and the kept values are bit-identical.\n *\n * A query that does not land on one of the lattices (within 1e-6 site) is refused rather than approximated: the\n * facade uses this path only when the lattice argument above holds. A query outside the window is refused too.\n */\n\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 { calculateIrradianceConvolution } 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. */\n psf: Omit<ResolveLensSampledPsfInput, \"fieldPointMm\" | \"wavelengthNm\">;\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 kernels = wavelengthsNm.map((wavelengthNm) => siteDiffractionKernel(input.psf, wavelengthNm, pitch, R, \"Diffraction kernels must sample the site pitch exactly.\"));\n const gridWidth = NW + 2 * R;\n const now = (): number => globalThis.performance?.now() ?? Date.now();\n const bands = new Map<number, Float64Array[][]>();\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;\n const values = shifts.map((shift) => wavelengthsNm.map((nm, w) => {\n const samples = new Float64Array(gridWidth * gridHeight);\n for (let gy = 0; gy < gridHeight; gy++) {\n const v = shift.y === 0 ? -(y0 + gy - R - M + 0.5 - H / 2) * g : -(y0 + gy - R - M + 0.5 + shift.y - H / 2) * g;\n for (let gx = 0, x = lx0; gx < gridWidth; gx++, x++) samples[gy * gridWidth + gx] = base.radianceAt(shift.x === 0 ? (x - R - M + 0.5 - W / 2) * g : (x - R - M + 0.5 + shift.x - W / 2) * g, v, nm);\n }\n const blurred = calculateIrradianceConvolution({ schemaVersion: \"0.1.0\", width: gridWidth, height: gridHeight, samples, kernelRadius: R,\n patchWidth: gridWidth, patchHeight: gridHeight, kernels: kernels[w]!, boundary: \"zero-outside-grid\" }).values;\n const out = new Float64Array(NW * rows);\n for (let y = 0; y < rows; y++) out.set(blurred.subarray((y + R) * gridWidth + R, (y + R) * gridWidth + R + NW), y * NW);\n return out;\n }));\n 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"]}
|
|
1
|
+
{"version":3,"file":"diffraction-provider.js","sourceRoot":"","sources":["../../src/facade/diffraction-provider.ts"],"names":[],"mappings":"AAAA,sCAAsC;AAEtC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8CG;AAEH,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAC3E,OAAO,EAAE,gCAAgC,EAAE,kCAAkC,EAAE,8BAA8B,EAAE,MAAM,wCAAwC,CAAC;AAE9J,OAAO,EAAE,iCAAiC,EAAE,MAAM,qCAAqC,CAAC;AACxF,OAAO,EAAE,qBAAqB,EAAE,MAAM,sCAAsC,CAAC;AAI7E,gHAAgH;AAChH,MAAM,SAAS,GAAG,EAAE,CAAC;AACrB,MAAM,YAAY,GAAG,CAAC,CAAC;AACvB,MAAM,uBAAuB,GAAG,IAAI,CAAC;AAqCrC,2HAA2H;AAC3H,MAAM,UAAU,8BAA8B,CAAC,KAAoC;IACjF,MAAM,EAAE,IAAI,EAAE,aAAa,EAAE,WAAW,EAAE,CAAC,EAAE,YAAY,EAAE,CAAC,EAAE,YAAY,EAAE,CAAC,EAAE,GAAG,KAAK,CAAC;IACxF,MAAM,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC,WAAW,EAAE,KAAK,GAAG,KAAK,CAAC,oBAAoB,CAAC;IACpE,MAAM,KAAK,GAAG,IAAI,GA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CAAC,EAAE,CAAC,GAAG,KAAK,EAAE,CAAC,EAAE;gBAAE,GAAG,IAAI,OAAO,CAAC,IAAI,GAAG,OAAO,CAAC,CAAC,CAAE,CAAE,GAAG,OAAO,CAAC,CAAC,CAAE,CAAC;YAClF,GAAG,CAAC,CAAC,GAAG,KAAK,GAAG,CAAC,CAAC,GAAG,GAAG,CAAC;QAC3B,CAAC;IACH,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Fast execution of `simulateCapture`'s `lens.diffraction` (2.1): an object-space convolution in the scene\n * provider, instead of one scene query per PSF tap in the environment PSF quadrature.\n *\n * The environment quadrature computes, at each site centre q and spectral node λ,\n * E(q, λ) = Σ_k K_λ(k)·T·L(s_k(q), λ),\n * where s_k(q) is the tap's source point (`sensorPsfSourcePoint`), L the scene radiance at the plane point\n * that source point sees, and T the radiance-to-irradiance factor. For the facade's planar scene seen\n * through the ideal rectilinear projection with a still camera and no lens field mapping, field throughput or\n * pupil rays:\n * - T is the same at every sensor point (paraxial π/(4·N_w²), no cos⁴ term), and\n * - with the kernel sampled on the site pitch, every source point is the centre of another site, so the plane\n * points form one regular lattice: u = (i + ½ − W/2)·2/w, v = −(j + ½ − H/2)·2/w (frame units, native\n * site (i, j), W×H native sites, w output width).\n * So E(q, λ) = T·B(q, λ) with B = K_λ ⊛ L sampled on that lattice: the same sum, in a different floating-point\n * order. B is computed once per spectral node with the engine's isoplanatic convolution\n * (`calculateIrradianceConvolution`, kernels from `resolveLensPsfConvolutionKernels`, exact site sampling) over a\n * grid that holds every source (the native raster plus the kernel radius on each side), in row bands. The\n * provider then answers each site-centre query with B instead of L, and the environment request declares no\n * PSF. Incoherent imaging is a linear superposition of intensity PSFs, so convolving radiance on the object\n * plane and convolving irradiance on the image plane agree for a planar object and a space-invariant PSF\n * (MIT OpenCourseWare 2.71, lecture 22, free; also see: Goodman, Introduction to Fourier Optics, 4th ed., §7.1).\n *\n * With an anti-aliasing point-splitting filter (2.1, `sensor.antiAliasing`) the environment queries the PSF taps\n * around each pre-filter source point q − a (a = a split offset) instead of around q. Those taps lie on the site\n * lattice shifted by a, so the same argument holds on each shifted lattice: B is computed once per distinct\n * fractional shift (offsets that differ by whole sites share one lattice; the centred four-spot filter with a\n * one-site separation needs a single half-site-shifted lattice) over the native raster widened by the largest\n * offset, and the environment's spatial quadrature still forms the weighted split sum.\n *\n * Region renders (2.6, `window`): only the lattice rows and columns that the region's sites can query (the window\n * plus the largest offset on each side) are convolved, over a grid that adds the kernel radius on each side. Every\n * output value is the same gather as in the whole render: the grid always holds every tap of every value it keeps\n * (real scene radiance out to the kernel radius, never a truncated edge), the single kernel patch does not depend on\n * the grid's origin, and `convolveIrradianceRows` sums each value in a fixed tap order (v outer, u inner). Narrowing\n * the grid therefore removes only values that no query reads, and the kept values are bit-identical.\n *\n * A query that does not land on one of the lattices (within 1e-6 site) is refused rather than approximated: the\n * facade uses this path only when the lattice argument above holds. A query outside the window is refused too.\n *\n * Defocus (#492, `lens.defocus`): the same argument holds for any space-invariant kernel on the site lattice, so the facade\n * passes `siteKernels` instead (the geometric defocus disc, or each node's diffraction kernel convolved with it). Their radius\n * may exceed the public 32-site convolution limit, so this path does not call `calculateIrradianceConvolution`: it checks the\n * samples and the kernel sums as that function does and gathers only the band's own values (`gatherInterior`), each summed\n * over the taps in the same fixed order (v outer, u inner, ascending; zero taps skipped, which adds exact zeros only). It\n * does not compute the 2R grid rows above and below a band that `calculateIrradianceConvolution` would also return (#419).\n */\n\nimport { InvalidConfigurationError } from \"../core/configuration-error.js\";\nimport { isInternalSceneRadianceEvaluator, markInternalSceneRadianceEvaluator, registerInternalRadianceAccess } from \"../core/internal-radiance-evaluator.js\";\nimport type { SceneRadianceEvaluationRequest, SceneRadianceEvaluationResult } from \"../schema/scene-radiance.js\";\nimport { createIrradianceConvolutionRunner } from \"../optics/irradiance-convolution.js\";\nimport { siteDiffractionKernel } from \"../optics/site-diffraction-kernel.js\";\nimport type { ResolveLensSampledPsfInput } from \"../optics/lens-psf-profile.js\";\nimport type { PlanarSceneRadianceProvider } from \"./scene-radiance.js\";\n\n/** Rows of native sites per convolution band, and the bands kept. Banding changes memory only, never values. */\nconst BAND_ROWS = 32;\nconst CACHED_BANDS = 4;\nconst LATTICE_TOLERANCE_SITES = 1e-6;\n\nexport interface DiffractedPlanarProviderInput {\n base: PlanarSceneRadianceProvider;\n /** The optical state of the sampled PSF, as for `resolveLensSampledPsf`, without field point and wavelength. Unused with `siteKernels`. */\n psf?: Omit<ResolveLensSampledPsfInput, \"fieldPointMm\" | \"wavelengthNm\">;\n /**\n * #492: the kernel of each spectral node on the site lattice, (2·kernelRadius + 1)² taps in row-major order, applied\n * instead of the diffraction kernels of `psf` (the defocus disc, or each node's diffraction kernel convolved with it).\n * Any radius; each kernel's sum may not exceed 1 + 2^-20.\n */\n siteKernels?: (wavelengthNm: number) => Float64Array;\n /** Spectral nodes the environment queries (the profile's wavelength nodes). */\n wavelengthsNm: readonly number[];\n kernelRadius: number;\n nativeWidth: number;\n nativeHeight: number;\n /** Output (active) width in sites: frame units are 2/outputWidth per site. */\n outputWidth: number;\n sitePitchMicrometers: number;\n /** Planar geometry of the base provider, to map query directions to plane points exactly as it does. */\n distanceM: number;\n metresPerFrameUnit: number;\n /**\n * Offsets of the query points from the site centres, in sites (+x right, +y down): the anti-aliasing split\n * offsets with their sign reversed (the environment queries q − a). Default: one zero offset.\n */\n queryOffsetsSites?: readonly { x: number; y: number }[];\n /**\n * Region renders (2.6): the native sites that will be queried (x, y, width, height in the native raster). Only the\n * lattice they can reach is convolved; values are bit-identical to the whole render's. Default: the whole raster.\n */\n window?: { x: number; y: number; width: number; height: number };\n /** Called with the duration in ms of each band convolution (diagnostics only; never changes values). */\n onConvolution?: (milliseconds: number) => void;\n}\n\n/** Internal (not exported from the package): the base provider with diffraction applied as an object-space convolution. */\nexport function createDiffractedPlanarProvider(input: DiffractedPlanarProviderInput): PlanarSceneRadianceProvider {\n const { base, wavelengthsNm, nativeWidth: W, nativeHeight: H, kernelRadius: R } = input;\n const g = 2 / input.outputWidth, pitch = input.sitePitchMicrometers;\n const index = new Map(wavelengthsNm.map((nm, i) => [nm, i]));\n // One lattice per distinct fractional query offset; M extra sites per side hold the offset queries.\n const offsets = input.queryOffsetsSites ?? [{ x: 0, y: 0 }];\n const fraction = (value: number): number => { const f = value - Math.floor(value); return f > 1 - LATTICE_TOLERANCE_SITES ? 0 : f < LATTICE_TOLERANCE_SITES ? 0 : f; };\n const shifts: { x: number; y: number }[] = [];\n for (const o of offsets) {\n const f = { x: fraction(o.x), y: fraction(o.y) };\n if (!shifts.some((s) => Math.abs(s.x - f.x) <= LATTICE_TOLERANCE_SITES && Math.abs(s.y - f.y) <= LATTICE_TOLERANCE_SITES)) shifts.push(f);\n }\n const M = Math.max(0, ...offsets.map((o) => Math.ceil(Math.max(Math.abs(o.x), Math.abs(o.y)) - LATTICE_TOLERANCE_SITES)));\n const LW = W + 2 * M, LH = H + 2 * M;\n // Lattice window (indices i + M, j + M): the sites the region queries plus the largest offset on each side, clipped\n // to the lattice. A site i queries i + floor(offset), and floor(offset) lies in [-M, M].\n const win = input.window ?? { x: 0, y: 0, width: W, height: H };\n const lx0 = Math.max(0, win.x), lx1 = Math.min(LW, win.x + win.width + 2 * M);\n const ly0 = Math.max(0, win.y), ly1 = Math.min(LH, win.y + win.height + 2 * M);\n if (!(lx0 < lx1 && ly0 < ly1)) throw new InvalidConfigurationError(\"Diffraction window must overlap the native raster.\");\n const NW = lx1 - lx0;\n // One kernel per wavelength, on the site grid, from the engine's own tap-to-site mapping (field point 0, 0); kept across calls.\n const siteKernels = input.siteKernels;\n if (!siteKernels && !input.psf) throw new InvalidConfigurationError(\"The object-space convolution needs a PSF or site kernels.\");\n const kernels = wavelengthsNm.map((wavelengthNm) => siteKernels ? checkedSiteKernel(siteKernels(wavelengthNm), R) :\n siteDiffractionKernel(input.psf!, wavelengthNm, pitch, R, \"Diffraction kernels must sample the site pitch exactly.\"));\n // #492: each site kernel's non-zero taps as grid offsets, in the gather's order.\n const taps = siteKernels ? kernels.map((kernel) => kernelTaps(kernel, R, NW + 2 * R)) : [];\n const gridWidth = NW + 2 * R;\n const now = (): number => globalThis.performance?.now() ?? Date.now();\n const bands = new Map<number, Float64Array[][]>();\n const materialAt = base.chartMaterialAt?.bind(base), materialRadiance = base.materialRadiance?.bind(base);\n function band(b: number): Float64Array[][] {\n const cached = bands.get(b);\n if (cached) { bands.delete(b); bands.set(b, cached); return cached; }\n const started = input.onConvolution ? now() : 0;\n const y0 = ly0 + b * BAND_ROWS, rows = Math.min(BAND_ROWS, ly1 - y0), gridHeight = rows + 2 * R, size = gridWidth * gridHeight;\n // #453: the band's shifts × spectral nodes convolutions share one geometry, validated once (the first runs the full\n // calculateIrradianceConvolution; every later one still checks its samples and kernel).\n const convolve = siteKernels ? undefined : createIrradianceConvolutionRunner({ schemaVersion: \"0.1.0\", width: gridWidth, height: gridHeight, kernelRadius: R,\n patchWidth: gridWidth, patchHeight: gridHeight, boundary: \"zero-outside-grid\" });\n const values = shifts.map((shift) => {\n // The plane point of lattice grid sample (gx, gy) of this shift, the same expressions for both fills below.\n const vOf = (gy: number): number => shift.y === 0 ? -(y0 + gy - R - M + 0.5 - H / 2) * g : -(y0 + gy - R - M + 0.5 + shift.y - H / 2) * g;\n const uOf = (x: number): number => shift.x === 0 ? (x - R - M + 0.5 - W / 2) * g : (x - R - M + 0.5 + shift.x - W / 2) * g;\n // #453, material scenes (chart presets and caller material scenes): radianceAt(u, v, nm) is materialRadiance(chartMaterialAt(u, v), nm)\n // (scene-radiance.ts), so the material is looked up once per lattice point and each node's samples come from one\n // materialRadiance per material present, the same numbers as one radianceAt per point and node.\n let materialOf: Int32Array | undefined;\n if (materialAt && materialRadiance) {\n materialOf = new Int32Array(size);\n for (let gy = 0; gy < gridHeight; gy++) {\n const v = vOf(gy);\n for (let gx = 0, x = lx0; gx < gridWidth; gx++, x++) materialOf[gy * gridWidth + gx] = materialAt(uOf(x), v);\n }\n }\n return wavelengthsNm.map((nm, w) => {\n const samples = new Float64Array(size);\n if (materialOf) {\n const radiance = new Map<number, number>();\n for (let i = 0; i < size; i++) {\n const m = materialOf[i]!;\n let value = radiance.get(m);\n if (value === undefined) { value = materialRadiance!(m, nm); radiance.set(m, value); }\n samples[i] = value;\n }\n } else {\n for (let gy = 0; gy < gridHeight; gy++) {\n const v = vOf(gy);\n for (let gx = 0, x = lx0; gx < gridWidth; gx++, x++) samples[gy * gridWidth + gx] = base.radianceAt(uOf(x), v, nm);\n }\n }\n if (!convolve) return gatherInterior(samples, taps[w]!, gridWidth, NW, rows, R);\n const blurred = convolve(samples, kernels[w]!);\n const out = new Float64Array(NW * rows);\n for (let y = 0; y < rows; y++) out.set(blurred.subarray((y + R) * gridWidth + R, (y + R) * gridWidth + R + NW), y * NW);\n return out;\n });\n });\n bands.set(b, values);\n if (bands.size > CACHED_BANDS) bands.delete(bands.keys().next().value!);\n if (input.onConvolution) input.onConvolution(now() - started);\n return values;\n }\n function blurredAt(u: number, v: number, nm: number): number {\n const w = index.get(nm), fi = u / g - 0.5 + W / 2, fj = -v / g - 0.5 + H / 2;\n if (w !== undefined) for (let s = 0; s < shifts.length; s++) {\n const shift = shifts[s]!, i = Math.round(fi - shift.x), j = Math.round(fj - shift.y);\n if (Math.abs(fi - shift.x - i) > LATTICE_TOLERANCE_SITES || Math.abs(fj - shift.y - j) > LATTICE_TOLERANCE_SITES) continue;\n const li = i + M, lj = j + M;\n if (li < lx0 || lj < ly0 || li >= lx1 || lj >= ly1) break;\n return band(Math.floor((lj - ly0) / BAND_ROWS))[s]![w]![((lj - ly0) % BAND_ROWS) * NW + li - lx0]!;\n }\n throw new InvalidConfigurationError(\"Diffraction query is off the site lattice; the object-space convolution does not apply.\");\n }\n const scale = input.metresPerFrameUnit, distance = input.distanceM, baseEvaluate = base.evaluateRadiance;\n const evaluateRadiance = (request: Readonly<SceneRadianceEvaluationRequest>): SceneRadianceEvaluationResult => {\n const result = baseEvaluate.call(base, request), o = (request.target as { outgoingDirectionUnitVector: { x: number; y: number; z: number } }).outgoingDirectionUnitVector;\n const t = distance / -o.z;\n return { ...result, spectralRadianceWattsPerSquareMeterSteradianNanometer: blurredAt(-o.x * t / scale, -o.y * t / scale, request.wavelengthNanometers) };\n };\n // 2.6: the result is the base result with only its radiance replaced (same keys and records), so an engine-built base\n // evaluator keeps its mark (see core/internal-radiance-evaluator.ts).\n if (isInternalSceneRadianceEvaluator(baseEvaluate)) {\n markInternalSceneRadianceEvaluator(evaluateRadiance);\n // #394: its radiance is the convolved value at one lattice site (shift s, lattice column li, row lj) per wavelength, so\n // the lean executor may read it by that key: the same plane point, lattice choice and band value as evaluateRadiance.\n registerInternalRadianceAccess(evaluateRadiance, {\n tabulated: false,\n keyOfDirection(o): number | undefined {\n if (!(-o.z > 0)) return undefined;\n const t = distance / -o.z, u = -o.x * t / scale, v = -o.y * t / scale, fi = u / g - 0.5 + W / 2, fj = -v / g - 0.5 + H / 2;\n for (let s = 0; s < shifts.length; s++) {\n const shift = shifts[s]!, i = Math.round(fi - shift.x), j = Math.round(fj - shift.y);\n if (Math.abs(fi - shift.x - i) > LATTICE_TOLERANCE_SITES || Math.abs(fj - shift.y - j) > LATTICE_TOLERANCE_SITES) continue;\n const li = i + M, lj = j + M;\n if (li < lx0 || lj < ly0 || li >= lx1 || lj >= ly1) return undefined;\n return (s * LH + lj) * LW + li;\n }\n return undefined;\n },\n radianceOfKey(key, nm): number {\n const w = index.get(nm);\n if (w === undefined) throw new InvalidConfigurationError(\"Diffraction query is off the site lattice; the object-space convolution does not apply.\");\n const li = key % LW, rest = (key - li) / LW, lj = rest % LH, s = (rest - lj) / LH;\n return band(Math.floor((lj - ly0) / BAND_ROWS))[s]![w]![((lj - ly0) % BAND_ROWS) * NW + li - lx0]!;\n }\n });\n }\n return {\n sceneId: base.sceneId, providerProfileId: base.providerProfileId, radianceAt: base.radianceAt,\n evaluateRadiance,\n evaluateApertureRadiance(): SceneRadianceEvaluationResult {\n throw new InvalidConfigurationError(\"Diffraction by object-space convolution does not take pupil rays.\");\n }\n };\n}\n\n/** Largest kernel sum, and largest sample, the object-space convolution accepts (as `IRRADIANCE_CONVOLUTION_LIMITS`). */\nconst MAXIMUM_KERNEL_SUM = 1 + 2 ** -20, MAXIMUM_SAMPLE = 2 ** 100;\n\n/** #492: a site kernel of radius R, checked as `calculateIrradianceConvolution` checks its kernels. */\nfunction checkedSiteKernel(kernel: Float64Array, R: number): Float64Array {\n if (!(kernel instanceof Float64Array) || kernel.length !== (2 * R + 1) ** 2) throw new InvalidConfigurationError(\"Site kernels must be (2R + 1)² taps.\");\n let sum = 0;\n for (let k = 0; k < kernel.length; k++) {\n const w = kernel[k]!;\n if (!(w >= 0 && w <= 1)) throw new InvalidConfigurationError(\"Site kernel weights must be finite numbers in [0, 1].\");\n sum += w;\n }\n if (sum > MAXIMUM_KERNEL_SUM) throw new InvalidConfigurationError(\"A PSF kernel may not create energy (sum exceeds 1).\");\n return kernel;\n}\n\n/** #492: the non-zero taps of a kernel as offsets into a grid of `gridWidth` columns (−v·gridWidth − u) and weights, v outer, u inner, ascending. */\nfunction kernelTaps(kernel: Float64Array, R: number, gridWidth: number): { offsets: Int32Array; weights: Float64Array } {\n const offsets: number[] = [], weights: number[] = [];\n for (let v = -R, t = 0; v <= R; v++) for (let u = -R; u <= R; u++, t++) {\n const w = kernel[t]!;\n if (w !== 0) { offsets.push(-v * gridWidth - u); weights.push(w); }\n }\n return { offsets: Int32Array.from(offsets), weights: Float64Array.from(weights) };\n}\n\n/**\n * #492: out(x, y) = Σ_t K(t)·samples(x + R − t_u, y + R − t_v) for the band's own values only (x < width, y < rows): every tap of\n * these lies inside the grid (it holds R extra samples on each side), so no boundary rule applies. Samples are checked as\n * `calculateIrradianceConvolution` checks them.\n */\nfunction gatherInterior(samples: Float64Array, taps: { offsets: Int32Array; weights: Float64Array }, gridWidth: number, width: number, rows: number, R: number): Float64Array {\n for (let k = 0; k < samples.length; k++) {\n const v = samples[k]!;\n if (!(v >= 0 && v <= MAXIMUM_SAMPLE)) throw new InvalidConfigurationError(\"Irradiance samples must be finite, non-negative and within the declared magnitude.\");\n }\n const { offsets, weights } = taps, count = weights.length, out = new Float64Array(width * rows);\n for (let y = 0; y < rows; y++) {\n const rowBase = (y + R) * gridWidth + R;\n for (let x = 0; x < width; x++) {\n const base = rowBase + x;\n let sum = 0;\n for (let k = 0; k < count; k++) sum += samples[base + offsets[k]!]! * weights[k]!;\n out[y * width + x] = sum;\n }\n }\n return out;\n}\n"]}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { DisplayViewRenderResult, DisplayViewSetup } from "./display-view.js";
|
|
2
|
+
import { type DisplayViewExecution, type DisplayViewGpuConformanceCase, type DisplayViewGpuRequest, type ParsedPrepareDisplayViewOptions } from "./display-view-gpu.js";
|
|
3
|
+
/** Internal: the GPU side of one prepared view. */
|
|
4
|
+
export interface DisplayViewGpuSession {
|
|
5
|
+
/** Renders `setup` on the GPU when the session can, else through `cpu`; the label says which ran. */
|
|
6
|
+
render(setup: DisplayViewSetup, signal: AbortSignal | undefined, cpu: () => Promise<DisplayViewRenderResult>): Promise<{
|
|
7
|
+
rendered: DisplayViewRenderResult;
|
|
8
|
+
execution: DisplayViewExecution;
|
|
9
|
+
}>;
|
|
10
|
+
dispose(): void;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Internal (#481): opens the GPU session of a prepared view, or throws (`"require"`) when the GPU cannot be used. Called only
|
|
14
|
+
* for `gpu: "auto" | "require"`.
|
|
15
|
+
*/
|
|
16
|
+
export declare function openDisplayViewGpuSession(options: ParsedPrepareDisplayViewOptions, request: DisplayViewGpuRequest, signal: AbortSignal | undefined): Promise<DisplayViewGpuSession>;
|
|
17
|
+
/** The built-in cases, run on every device before its first display-view render: the existing convolution kernel on two small images. */
|
|
18
|
+
export declare const DISPLAY_VIEW_GPU_BUILT_IN_CASES: readonly DisplayViewGpuConformanceCase[];
|
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
/**
|
|
3
|
+
* #481: the device handling behind `prepareDisplayView(request, { gpu: "auto" | "require", gpuDevice })`. Loaded on demand by
|
|
4
|
+
* `simulate-display-view.ts`, so the GPU code stays out of bundles that never ask for it. One session per prepared view:
|
|
5
|
+
*
|
|
6
|
+
* - the realm's switch (`setWebGpuEnabled(false)`) vetoes before anything else: `"auto"` falls back with `webgpu-disabled`,
|
|
7
|
+
* `"require"` throws it;
|
|
8
|
+
* - with no renderer registered (the engine registers its renderer, the Speed and Quality kernels of #478 and #479, when this module
|
|
9
|
+
* loads; a caller may replace it or set null) no device is requested: `unsupported-on-backend`;
|
|
10
|
+
* - the device is the handle's (`gpuDevice`: an `ImageKernelAccelerator`'s device, shared and left to its owner, or a WebGPU
|
|
11
|
+
* entry point to acquire from), or acquired from `navigator.gpu` and owned by the session; the accelerator's acquisition
|
|
12
|
+
* reasons apply, and the request's `signal` aborts the acquisition;
|
|
13
|
+
* - the renderer must support the request, else `unsupported-on-backend`; a render the renderer refuses only when rendering
|
|
14
|
+
* (`unsupported-on-backend` thrown by `render`: a coarse view, a device that fails the composite chart probe, #491) runs the
|
|
15
|
+
* CPU reference for that render with the same label, and so does a render whose tables or bands exceed the device's limits
|
|
16
|
+
* (`insufficient-limits` thrown by `render`: #492, a large defocus kernel's table on a scene of many materials);
|
|
17
|
+
* - before the first GPU render on the device a short conformance self-check runs once (single-flight): the built-in cases run
|
|
18
|
+
* the existing `webgpu-f32` convolution kernel against the float64 reference within its a-priori bound, then the renderer's own
|
|
19
|
+
* cases; a failure keeps the whole view on the CPU, labelled `conformance-failed`, with the adapter recorded;
|
|
20
|
+
* - GPU renders of one session run one at a time on the device (the accelerator's single flight; later renders wait);
|
|
21
|
+
* - a lost device falls back to the CPU for that render and every later one, labelled `device-lost`; `dispose()` releases an
|
|
22
|
+
* owned device, and later renders run on the CPU labelled `disposed`.
|
|
23
|
+
*/
|
|
24
|
+
import { InvalidConfigurationError } from "../core/configuration-error.js";
|
|
25
|
+
import { getWebGpuEnabled } from "../gpu/webgpu-switch.js";
|
|
26
|
+
import { acquireWebGpuRuntime } from "../gpu/webgpu-runtime.js";
|
|
27
|
+
import { ImageKernelExecutionError, WEBGPU_F32_LIMITATIONS } from "../gpu/image-kernel-execution.js";
|
|
28
|
+
import { acceleratorRuntime, convolveIrradianceOnRuntime } from "../gpu/image-kernel-accelerator.js";
|
|
29
|
+
import { calculateIrradianceConvolutionPlan, convolveIrradianceRows } from "../optics/irradiance-convolution.js";
|
|
30
|
+
import { displayViewGpuRendererFactory as engineDisplayViewGpuRendererFactory } from "../gpu/display-view-quality-gpu.js";
|
|
31
|
+
import { cpuDisplayViewExecution, displayViewGpuRendererFactory, setDisplayViewGpuRendererFactory } from "./display-view-gpu.js";
|
|
32
|
+
// #478, #479: the engine's own renderer, the display view's Speed and Quality kernels behind one renderer
|
|
33
|
+
// (`src/gpu/display-view-quality-gpu.ts`), is registered when this module loads (that is, when a prepared view first asks for the
|
|
34
|
+
// GPU) unless a caller registered a renderer before; a test that needs "no renderer" sets the factory to null.
|
|
35
|
+
if (displayViewGpuRendererFactory() === null)
|
|
36
|
+
setDisplayViewGpuRendererFactory(engineDisplayViewGpuRendererFactory);
|
|
37
|
+
/** A session that renders every view on the CPU with one fixed reason. */
|
|
38
|
+
function cpuSession(options, reason, detail, adapter, conformance) {
|
|
39
|
+
const execution = cpuDisplayViewExecution(options.gpu, reason, adapter, conformance, detail);
|
|
40
|
+
return { async render(_setup, _signal, cpu) { return { rendered: await cpu(), execution }; },
|
|
41
|
+
dispose() { } };
|
|
42
|
+
}
|
|
43
|
+
/** `"require"` throws the reason; `"auto"` gets a CPU session labelled with it. */
|
|
44
|
+
function fallBack(options, reason, detail, adapter = null, conformance = null) {
|
|
45
|
+
if (options.gpu === "require")
|
|
46
|
+
throw requireError(reason, detail);
|
|
47
|
+
return cpuSession(options, reason, detail, adapter, conformance);
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* The error `"require"` throws instead of falling back. Every display-view fallback reason is also a failure reason of the accelerator's
|
|
51
|
+
* error. A refusal by the composite chart probe carries its record as `probe` (the structured detail of the message).
|
|
52
|
+
*/
|
|
53
|
+
function requireError(reason, detail, probe = null) {
|
|
54
|
+
const error = new ImageKernelExecutionError(reason, "prepareDisplayView with gpu \"require\": " + detail);
|
|
55
|
+
if (probe)
|
|
56
|
+
Object.defineProperty(error, "probe", { value: probe, enumerable: true });
|
|
57
|
+
return error;
|
|
58
|
+
}
|
|
59
|
+
/** The composite chart probe's record on a refusal (`ChartCompositeProbeError.probe`), or null. */
|
|
60
|
+
function probeOf(error) {
|
|
61
|
+
const probe = error.probe;
|
|
62
|
+
return typeof probe === "object" && probe !== null ? probe : null;
|
|
63
|
+
}
|
|
64
|
+
/** True for an object shaped like an `ImageKernelAccelerator` (the handle form that shares a device). */
|
|
65
|
+
function isAccelerator(value) {
|
|
66
|
+
return typeof value === "object" && value !== null && typeof value.convolveIrradiance === "function" &&
|
|
67
|
+
typeof value.backend === "string";
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Internal (#481): opens the GPU session of a prepared view, or throws (`"require"`) when the GPU cannot be used. Called only
|
|
71
|
+
* for `gpu: "auto" | "require"`.
|
|
72
|
+
*/
|
|
73
|
+
export async function openDisplayViewGpuSession(options, request, signal) {
|
|
74
|
+
if (!getWebGpuEnabled())
|
|
75
|
+
return fallBack(options, "webgpu-disabled", "WebGPU is switched off in this realm (setWebGpuEnabled(false)).");
|
|
76
|
+
const factory = displayViewGpuRendererFactory();
|
|
77
|
+
if (!factory)
|
|
78
|
+
return fallBack(options, "unsupported-on-backend", "this version of the engine has no GPU display-view renderer (#478); no device was requested.");
|
|
79
|
+
let runtime, owned = false;
|
|
80
|
+
if (isAccelerator(options.gpuDevice)) {
|
|
81
|
+
const shared = acceleratorRuntime(options.gpuDevice);
|
|
82
|
+
if (shared === undefined)
|
|
83
|
+
throw new InvalidConfigurationError("prepareDisplayView options.gpuDevice must be an accelerator created by createImageKernelAccelerator.");
|
|
84
|
+
const accelerator = options.gpuDevice;
|
|
85
|
+
if (accelerator.state === "disposed")
|
|
86
|
+
throw new InvalidConfigurationError("prepareDisplayView options.gpuDevice is a disposed accelerator.");
|
|
87
|
+
if (shared === null)
|
|
88
|
+
return fallBack(options, accelerator.fallbackReason ?? "webgpu-unavailable", "the given accelerator runs the CPU reference and has no device.");
|
|
89
|
+
if (shared.isLost())
|
|
90
|
+
return fallBack(options, "device-lost", "the given accelerator's device was lost.", shared.adapter);
|
|
91
|
+
runtime = shared;
|
|
92
|
+
}
|
|
93
|
+
else {
|
|
94
|
+
const gpu = options.gpuDevice !== undefined ? options.gpuDevice : globalThis.navigator?.gpu;
|
|
95
|
+
let acquired;
|
|
96
|
+
try {
|
|
97
|
+
acquired = await acquireWebGpuRuntime(gpu, undefined, signal);
|
|
98
|
+
}
|
|
99
|
+
catch (error) {
|
|
100
|
+
if (error instanceof ImageKernelExecutionError && error.reason === "aborted")
|
|
101
|
+
throw new InvalidConfigurationError("prepareDisplayView aborted.");
|
|
102
|
+
throw error;
|
|
103
|
+
}
|
|
104
|
+
if ("failure" in acquired)
|
|
105
|
+
return fallBack(options, acquired.failure, acquired.message);
|
|
106
|
+
runtime = acquired.runtime;
|
|
107
|
+
owned = true;
|
|
108
|
+
}
|
|
109
|
+
const renderer = factory(runtime), supported = renderer.supports(request);
|
|
110
|
+
if (supported !== true) {
|
|
111
|
+
if (owned)
|
|
112
|
+
runtime.destroy();
|
|
113
|
+
return fallBack(options, "unsupported-on-backend", "the GPU display-view renderer \"" + renderer.id + "\" does not support this request: " + supported, runtime.adapter);
|
|
114
|
+
}
|
|
115
|
+
return createSession(options, runtime, owned, renderer);
|
|
116
|
+
}
|
|
117
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
118
|
+
// Run-time conformance self-check.
|
|
119
|
+
/** A fixed, seeded test image (mulberry32) for the built-in cases. */
|
|
120
|
+
function seededSamples(count, seed) {
|
|
121
|
+
let a = seed >>> 0;
|
|
122
|
+
const out = new Float64Array(count);
|
|
123
|
+
for (let i = 0; i < count; i++) {
|
|
124
|
+
a = (a + 0x6d2b79f5) >>> 0;
|
|
125
|
+
let t = Math.imul(a ^ (a >>> 15), 1 | a);
|
|
126
|
+
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
|
127
|
+
const u = ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
|
128
|
+
out[i] = u < 0.05 ? 0 : 10 ** (u * 6 - 3);
|
|
129
|
+
}
|
|
130
|
+
return out;
|
|
131
|
+
}
|
|
132
|
+
/** One convolution case: normalized Gaussian kernels of width `sigma` per patch, compared with the float64 reference within the a-priori bound. */
|
|
133
|
+
function convolutionCase(id, width, height, radius, patchWidth, patchHeight, seed) {
|
|
134
|
+
return { id, async run(runtime, signal) {
|
|
135
|
+
const size = 2 * radius + 1, taps = size * size, columns = Math.ceil(width / patchWidth), rows = Math.ceil(height / patchHeight);
|
|
136
|
+
const kernels = new Float64Array(columns * rows * taps);
|
|
137
|
+
for (let p = 0; p < columns * rows; p++) {
|
|
138
|
+
const sigma = 0.6 + 0.4 * (p % 3), scale = 0.8 + 0.05 * p;
|
|
139
|
+
let sum = 0;
|
|
140
|
+
for (let v = -radius; v <= radius; v++)
|
|
141
|
+
for (let u = -radius; u <= radius; u++) {
|
|
142
|
+
const w = Math.exp(-0.5 * (u * u + v * v) / (sigma * sigma));
|
|
143
|
+
kernels[p * taps + (v + radius) * size + u + radius] = w;
|
|
144
|
+
sum += w;
|
|
145
|
+
}
|
|
146
|
+
for (let t = 0; t < taps; t++)
|
|
147
|
+
kernels[p * taps + t] = kernels[p * taps + t] / sum * Math.min(1, scale);
|
|
148
|
+
}
|
|
149
|
+
const input = { schemaVersion: "0.1.0", width, height, kernelRadius: radius, patchWidth, patchHeight, boundary: "zero-outside-grid",
|
|
150
|
+
samples: seededSamples(width * height, seed), kernels };
|
|
151
|
+
const plan = calculateIrradianceConvolutionPlan(input), reference = new Float64Array(width * height);
|
|
152
|
+
convolveIrradianceRows(plan, input.samples, input.kernels, 0, height, reference);
|
|
153
|
+
{
|
|
154
|
+
const result = await convolveIrradianceOnRuntime(runtime, input, signal);
|
|
155
|
+
const bound = result.execution.errorBound;
|
|
156
|
+
if (!bound || bound.kind !== "relative-to-reference")
|
|
157
|
+
return "the convolution reported no relative bound.";
|
|
158
|
+
let worst = 0, worstIndex = -1;
|
|
159
|
+
for (let i = 0; i < reference.length; i++) {
|
|
160
|
+
const allowed = bound.relative * reference[i] + bound.absolute, excess = Math.abs(result.values[i] - reference[i]) - allowed;
|
|
161
|
+
if (excess > worst) {
|
|
162
|
+
worst = excess;
|
|
163
|
+
worstIndex = i;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
return worstIndex < 0 ? true : "sample " + worstIndex + " differs from the reference by " + Math.abs(result.values[worstIndex] - reference[worstIndex]) +
|
|
167
|
+
", more than the a-priori bound " + (bound.relative * reference[worstIndex] + bound.absolute) + ".";
|
|
168
|
+
}
|
|
169
|
+
} };
|
|
170
|
+
}
|
|
171
|
+
/** The built-in cases, run on every device before its first display-view render: the existing convolution kernel on two small images. */
|
|
172
|
+
export const DISPLAY_VIEW_GPU_BUILT_IN_CASES = Object.freeze([
|
|
173
|
+
convolutionCase("image-kernel:convolution:16x12-r1", 16, 12, 1, 16, 12, 481),
|
|
174
|
+
convolutionCase("image-kernel:convolution:32x24-r3-patches", 32, 24, 3, 16, 12, 4781)
|
|
175
|
+
]);
|
|
176
|
+
async function runConformance(runtime, renderer, signal) {
|
|
177
|
+
const cases = [...DISPLAY_VIEW_GPU_BUILT_IN_CASES, ...(renderer.conformanceCases ?? [])], ids = Object.freeze(cases.map((c) => c.id));
|
|
178
|
+
for (const c of cases) {
|
|
179
|
+
let outcome;
|
|
180
|
+
try {
|
|
181
|
+
outcome = await c.run(runtime, signal);
|
|
182
|
+
}
|
|
183
|
+
catch (error) {
|
|
184
|
+
// An abort is the caller's, not the device's; everything else the device did wrong is a failed case.
|
|
185
|
+
if (error instanceof ImageKernelExecutionError && error.reason === "aborted")
|
|
186
|
+
throw error;
|
|
187
|
+
outcome = "the case threw " + (error instanceof ImageKernelExecutionError ? error.reason + ": " : "") + (error instanceof Error ? error.message : String(error));
|
|
188
|
+
}
|
|
189
|
+
if (outcome !== true)
|
|
190
|
+
return Object.freeze({ cases: ids, passed: false, failedCase: c.id, detail: outcome });
|
|
191
|
+
}
|
|
192
|
+
return Object.freeze({ cases: ids, passed: true, failedCase: null, detail: null });
|
|
193
|
+
}
|
|
194
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
195
|
+
function createSession(options, runtime, owned, renderer) {
|
|
196
|
+
const adapter = runtime.adapter;
|
|
197
|
+
let disposed = false, lost = false, conformance = null, checking = null;
|
|
198
|
+
/** The last GPU turn: renders queue behind it, so one dispatch runs at a time on the device. */
|
|
199
|
+
let tail = Promise.resolve();
|
|
200
|
+
/** A CPU fallback label for `"auto"`; with `"require"` the same event is an error. */
|
|
201
|
+
const fallback = async (reason, detail, cpu, compositeProbe = null) => {
|
|
202
|
+
if (options.gpu === "require")
|
|
203
|
+
throw requireError(reason, detail, compositeProbe);
|
|
204
|
+
return { rendered: await cpu(), execution: cpuDisplayViewExecution(options.gpu, reason, adapter, conformance, detail, compositeProbe) };
|
|
205
|
+
};
|
|
206
|
+
/** The self-check, run once per session (single flight); a failing check is remembered and never repeated. */
|
|
207
|
+
function selfCheck(signal) {
|
|
208
|
+
if (conformance)
|
|
209
|
+
return Promise.resolve(conformance);
|
|
210
|
+
if (!checking) {
|
|
211
|
+
checking = runConformance(runtime, renderer, signal).then((result) => { conformance = result; return result; }, (error) => { checking = null; throw error; });
|
|
212
|
+
}
|
|
213
|
+
return checking;
|
|
214
|
+
}
|
|
215
|
+
function lostError(error) { return (error instanceof ImageKernelExecutionError && error.reason === "device-lost") || runtime.isLost(); }
|
|
216
|
+
return {
|
|
217
|
+
async render(setup, signal, cpu) {
|
|
218
|
+
if (disposed)
|
|
219
|
+
return fallback("disposed", "the prepared view was disposed.", cpu);
|
|
220
|
+
if (lost || runtime.isLost()) {
|
|
221
|
+
lost = true;
|
|
222
|
+
return fallback("device-lost", "the WebGPU device was lost; the rest of the view runs on the CPU.", cpu);
|
|
223
|
+
}
|
|
224
|
+
let check;
|
|
225
|
+
try {
|
|
226
|
+
check = await selfCheck(signal);
|
|
227
|
+
}
|
|
228
|
+
catch (error) {
|
|
229
|
+
if (lostError(error)) {
|
|
230
|
+
lost = true;
|
|
231
|
+
return fallback("device-lost", "the WebGPU device was lost during its conformance check.", cpu);
|
|
232
|
+
}
|
|
233
|
+
setup.checkAbort();
|
|
234
|
+
throw error;
|
|
235
|
+
}
|
|
236
|
+
if (!check.passed)
|
|
237
|
+
return fallback("conformance-failed", "the device failed conformance case \"" + check.failedCase + "\": " + check.detail, cpu);
|
|
238
|
+
const turn = tail.then(async () => {
|
|
239
|
+
if (disposed || lost || runtime.isLost())
|
|
240
|
+
return null;
|
|
241
|
+
setup.checkAbort();
|
|
242
|
+
return renderer.render({ setup, signal });
|
|
243
|
+
});
|
|
244
|
+
tail = turn.catch(() => undefined);
|
|
245
|
+
let output;
|
|
246
|
+
try {
|
|
247
|
+
output = await turn;
|
|
248
|
+
}
|
|
249
|
+
catch (error) {
|
|
250
|
+
if (lostError(error)) {
|
|
251
|
+
lost = true;
|
|
252
|
+
return fallback("device-lost", "the WebGPU device was lost during a render; the rest of the view runs on the CPU.", cpu);
|
|
253
|
+
}
|
|
254
|
+
setup.checkAbort();
|
|
255
|
+
if (error instanceof ImageKernelExecutionError && error.reason === "unsupported-on-backend")
|
|
256
|
+
return fallback("unsupported-on-backend", "the GPU display-view renderer \"" + renderer.id + "\" does not cover this render: " + error.message, cpu, probeOf(error));
|
|
257
|
+
// #492: a render past the device's limits (a kernel table or band above its storage binding limit) runs the CPU reference too.
|
|
258
|
+
if (error instanceof ImageKernelExecutionError && error.reason === "insufficient-limits")
|
|
259
|
+
return fallback("insufficient-limits", "the device's limits do not hold this render on the GPU: " + error.message, cpu);
|
|
260
|
+
throw error;
|
|
261
|
+
}
|
|
262
|
+
if (output === null)
|
|
263
|
+
return this.render(setup, signal, cpu);
|
|
264
|
+
const { errorBound, diagnosticUncertaintySampleCount: uncertainty = 0, compositeProbe = null, ...rendered } = output;
|
|
265
|
+
const execution = Object.freeze({ gpu: options.gpu, backend: "webgpu-f32", requestedBackend: "webgpu-f32", fallbackReason: null, arithmetic: "float32",
|
|
266
|
+
assurance: "approximation-with-a-priori-bound", fast: true, bitIdenticalToReference: false, errorBound, diagnosticsExact: uncertainty === 0,
|
|
267
|
+
diagnosticUncertaintySampleCount: uncertainty, limitations: WEBGPU_F32_LIMITATIONS, adapter, conformance: check, compositeProbe });
|
|
268
|
+
return { rendered, execution };
|
|
269
|
+
},
|
|
270
|
+
dispose() {
|
|
271
|
+
if (disposed)
|
|
272
|
+
return;
|
|
273
|
+
disposed = true;
|
|
274
|
+
renderer.dispose?.();
|
|
275
|
+
if (owned)
|
|
276
|
+
runtime.destroy();
|
|
277
|
+
}
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
//# sourceMappingURL=display-view-gpu-session.js.map
|