@monogrid/gainmap-js 3.6.1 → 3.7.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.
- package/CHANGELOG.md +12 -0
- package/README.md +86 -13
- package/dist/GainMapNode-CntuYSg-.js +338 -0
- package/dist/GainMapNode-DtVNqKtN.js +5 -0
- package/dist/{warn-deprecated-DtCQWGKi.js → Loader-D82gF-Rq.js} +3 -19
- package/dist/{warn-deprecated-gLZfP_DV.js → Loader-EFF6JZel.js} +2 -2
- package/dist/{QuadRenderer-DMno-Vj6.js → QuadRenderer-DD6leG7y.js} +1 -1
- package/dist/{QuadRenderer-Bhn3yOPC.js → QuadRenderer-DoK2pW5M.js} +1 -1
- package/dist/{_commonjsHelpers-DFuDJEaJ.js → _commonjsHelpers-C0JuzTK_.js} +1 -1
- package/dist/{_commonjsHelpers-C8qmDUO8.js → _commonjsHelpers-p2JmW4Hh.js} +1 -1
- package/dist/{compress-TBp7MS8D.js → compress-BTsSIi_B.js} +1 -1
- package/dist/{compress-oIjJuPa8.js → compress-PmebyFxR.js} +1 -1
- package/dist/core/webgpu/RenderTargetNode.d.ts +79 -0
- package/dist/decode/shared/utils/warn-deprecated.d.ts +1 -1
- package/dist/decode/webgl/decode.d.ts +0 -1
- package/dist/decode/webgl/index.d.ts +0 -1
- package/dist/decode/webgl/loaders/GainMapLoader.d.ts +1 -3
- package/dist/decode/webgl/loaders/HDRJPGLoader.d.ts +1 -3
- package/dist/decode/webgl/materials/GainMapDecoderMaterial.d.ts +0 -1
- package/dist/decode/webgpu/nodes/GainMapNode.d.ts +13 -19
- package/dist/decode.js +5 -18
- package/dist/decode.min.js +2 -2
- package/dist/decode.umd.cjs +1 -30
- package/dist/decode.umd.min.cjs +2 -2
- package/dist/decode.webgpu.js +27 -232
- package/dist/decode.webgpu.min.js +2 -2
- package/dist/decode.webgpu.umd.cjs +167 -61
- package/dist/decode.webgpu.umd.min.cjs +2 -2
- package/dist/encode/webgpu/GainMapEncoder.d.ts +142 -0
- package/dist/encode/webgpu/find-texture-min-max.d.ts +27 -0
- package/dist/encode/webgpu/index.d.ts +8 -0
- package/dist/encode/webgpu/nodes/GainMapEncoderNode.d.ts +92 -0
- package/dist/encode/webgpu/nodes/SDRRenditionNode.d.ts +120 -0
- package/dist/encode/webgpu/read-render-target-pixels.d.ts +11 -0
- package/dist/encode.js +5 -36
- package/dist/encode.min.js +2 -2
- package/dist/encode.umd.cjs +1 -1
- package/dist/encode.umd.min.cjs +1 -1
- package/dist/encode.webgpu.js +635 -0
- package/dist/encode.webgpu.min.js +5 -0
- package/dist/encode.webgpu.umd.cjs +1081 -0
- package/dist/encode.webgpu.umd.min.cjs +5 -0
- package/dist/get-data-texture-CkaFVcv-.js +5 -0
- package/dist/get-data-texture-DkHkbczN.js +40 -0
- package/dist/{iso-gainmap-metadata-Oi7gAKNC.js → iso-gainmap-metadata-BJxZGPtk.js} +1 -1
- package/dist/{iso-gainmap-metadata-C1io5isX.js → iso-gainmap-metadata-Bx6ha9th.js} +1 -1
- package/dist/libultrahdr.js +2 -2
- package/dist/libultrahdr.min.js +2 -2
- package/dist/libultrahdr.umd.cjs +1 -1
- package/dist/libultrahdr.umd.min.cjs +1 -1
- package/dist/worker-interface.js +2 -2
- package/dist/worker-interface.min.js +2 -2
- package/dist/worker-interface.umd.cjs +1 -1
- package/dist/worker-interface.umd.min.cjs +1 -1
- package/dist/worker.js +3 -3
- package/dist/worker.min.js +2 -2
- package/dist/worker.umd.cjs +1 -1
- package/dist/worker.umd.min.cjs +1 -1
- package/package.json +9 -1
|
@@ -0,0 +1,1081 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @monogrid/gainmap-js v3.7.0
|
|
3
|
+
* With ❤️, by MONOGRID <gainmap@monogrid.com>
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
(function (global, factory) {
|
|
7
|
+
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('three/webgpu'), require('three/tsl'), require('three')) :
|
|
8
|
+
typeof define === 'function' && define.amd ? define(['exports', 'three/webgpu', 'three/tsl', 'three'], factory) :
|
|
9
|
+
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.encode = {}, global["three/webgpu"], global["three/tsl"], global.three));
|
|
10
|
+
})(this, (function (exports, webgpu, tsl, three) { 'use strict';
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Base class for TSL texture nodes whose texture is a render target, filled by rendering a full screen quad.
|
|
14
|
+
*
|
|
15
|
+
* The quad is rendered only when something changed since the last render:
|
|
16
|
+
* subclasses list what the result depends on in {@link RenderTargetNode._getState}
|
|
17
|
+
* and the other render target nodes they read from in {@link RenderTargetNode._getDependencies}.
|
|
18
|
+
* Sampling the node costs a single texture read, like any other texture.
|
|
19
|
+
*
|
|
20
|
+
* The node renders itself before rendering whenever it is part of a rendered node graph
|
|
21
|
+
* (material, `scene.backgroundNode`, ...). When only its texture is used (`node.value`)
|
|
22
|
+
* call {@link RenderTargetNode.render} yourself.
|
|
23
|
+
*
|
|
24
|
+
* @category Nodes
|
|
25
|
+
* @group Nodes
|
|
26
|
+
*/
|
|
27
|
+
class RenderTargetNode extends webgpu.TextureNode {
|
|
28
|
+
/**
|
|
29
|
+
* The render target holding the result
|
|
30
|
+
*/
|
|
31
|
+
renderTarget;
|
|
32
|
+
/**
|
|
33
|
+
* Incremented every time the render target is rendered,
|
|
34
|
+
* nodes depending on this one use it to know when to render again
|
|
35
|
+
*/
|
|
36
|
+
revision = 0;
|
|
37
|
+
_quadMesh;
|
|
38
|
+
_material;
|
|
39
|
+
// filled by RendererUtils.resetRendererState
|
|
40
|
+
_rendererState = {};
|
|
41
|
+
_state = [];
|
|
42
|
+
/**
|
|
43
|
+
* @param material the material rendered on the full screen quad
|
|
44
|
+
* @param renderTargetOptions options of the render target, it is created with a 1x1 size
|
|
45
|
+
* and resized to {@link RenderTargetNode.width} x {@link RenderTargetNode.height} before rendering
|
|
46
|
+
*/
|
|
47
|
+
constructor(material, renderTargetOptions) {
|
|
48
|
+
const renderTarget = new webgpu.RenderTarget(1, 1, { depthBuffer: false, ...renderTargetOptions });
|
|
49
|
+
super(renderTarget.texture);
|
|
50
|
+
this.renderTarget = renderTarget;
|
|
51
|
+
this.updateBeforeType = webgpu.NodeUpdateType.RENDER;
|
|
52
|
+
this._material = material;
|
|
53
|
+
this._quadMesh = new webgpu.QuadMesh(material);
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Render target nodes read by this node, rendered (if needed) before this one
|
|
57
|
+
*/
|
|
58
|
+
_getDependencies() { return []; }
|
|
59
|
+
/**
|
|
60
|
+
* Called after the render target has been rendered
|
|
61
|
+
*/
|
|
62
|
+
_onRender() { }
|
|
63
|
+
/**
|
|
64
|
+
* Forces a render the next time {@link RenderTargetNode.render} is called,
|
|
65
|
+
* use it when something the node can't track changed (e.g. a custom input node)
|
|
66
|
+
*/
|
|
67
|
+
invalidate() {
|
|
68
|
+
this._state = [];
|
|
69
|
+
return this;
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Renders into {@link RenderTargetNode.renderTarget}, only if something changed since the last render.
|
|
73
|
+
*
|
|
74
|
+
* Called automatically when the node is part of a rendered node graph.
|
|
75
|
+
*
|
|
76
|
+
* @param renderer
|
|
77
|
+
* @returns `true` if the render target was rendered
|
|
78
|
+
*/
|
|
79
|
+
render(renderer) {
|
|
80
|
+
const dependencies = this._getDependencies();
|
|
81
|
+
for (const dependency of dependencies)
|
|
82
|
+
dependency.render(renderer);
|
|
83
|
+
const { width, height } = this;
|
|
84
|
+
// not ready yet
|
|
85
|
+
if (width === 0 || height === 0)
|
|
86
|
+
return false;
|
|
87
|
+
const state = [width, height, ...dependencies.map(d => d.revision), ...this._getState()];
|
|
88
|
+
if (state.length === this._state.length && state.every((v, i) => v === this._state[i]))
|
|
89
|
+
return false;
|
|
90
|
+
this._state = state;
|
|
91
|
+
if (this.renderTarget.width !== width || this.renderTarget.height !== height)
|
|
92
|
+
this.renderTarget.setSize(width, height);
|
|
93
|
+
webgpu.RendererUtils.resetRendererState(renderer, this._rendererState);
|
|
94
|
+
renderer.setRenderTarget(this.renderTarget);
|
|
95
|
+
this._quadMesh.render(renderer);
|
|
96
|
+
webgpu.RendererUtils.restoreRendererState(renderer, this._rendererState);
|
|
97
|
+
this.revision++;
|
|
98
|
+
this._onRender();
|
|
99
|
+
return true;
|
|
100
|
+
}
|
|
101
|
+
updateBefore(frame) {
|
|
102
|
+
if (frame.renderer)
|
|
103
|
+
this.render(frame.renderer);
|
|
104
|
+
return undefined;
|
|
105
|
+
}
|
|
106
|
+
set value(value) {
|
|
107
|
+
if (this.renderTarget && value !== this.renderTarget.texture) {
|
|
108
|
+
throw new Error(`${this.constructor.name}: the value of this node is its render target texture and can't be replaced`);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
get value() {
|
|
112
|
+
return this.renderTarget?.texture;
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Clones created by `sample()` & co. are plain TextureNodes reading this node's texture,
|
|
116
|
+
* they keep it updated before rendering as well
|
|
117
|
+
*/
|
|
118
|
+
clone() {
|
|
119
|
+
const node = new webgpu.TextureNode(this.value, this.uvNode, this.levelNode, this.biasNode);
|
|
120
|
+
node.sampler = this.sampler;
|
|
121
|
+
node.updateBeforeType = webgpu.NodeUpdateType.RENDER;
|
|
122
|
+
node.updateBefore = (frame) => this.updateBefore(frame);
|
|
123
|
+
return node;
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Disposes the render target and the material
|
|
127
|
+
*/
|
|
128
|
+
dispose() {
|
|
129
|
+
this.renderTarget.dispose();
|
|
130
|
+
this._material.dispose();
|
|
131
|
+
super.dispose();
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Used internally
|
|
137
|
+
*
|
|
138
|
+
* @internal
|
|
139
|
+
* @param canvas
|
|
140
|
+
* @param mimeType
|
|
141
|
+
* @param quality
|
|
142
|
+
* @returns
|
|
143
|
+
*/
|
|
144
|
+
const canvasToBlob = async (canvas, mimeType, quality) => {
|
|
145
|
+
if (typeof OffscreenCanvas !== 'undefined' && canvas instanceof OffscreenCanvas) {
|
|
146
|
+
return canvas.convertToBlob({ type: mimeType, quality: quality });
|
|
147
|
+
}
|
|
148
|
+
else if (canvas instanceof HTMLCanvasElement) {
|
|
149
|
+
return new Promise((resolve, reject) => {
|
|
150
|
+
canvas.toBlob((res) => {
|
|
151
|
+
if (res)
|
|
152
|
+
resolve(res);
|
|
153
|
+
else
|
|
154
|
+
reject(new Error('Failed to convert canvas to blob'));
|
|
155
|
+
}, mimeType, quality);
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
/* istanbul ignore next
|
|
159
|
+
as long as this function is not exported this is only here
|
|
160
|
+
to satisfy TS strict mode internally
|
|
161
|
+
*/
|
|
162
|
+
throw new Error('Unsupported canvas element');
|
|
163
|
+
};
|
|
164
|
+
/**
|
|
165
|
+
* Converts a RAW RGBA image buffer into the provided `mimeType` using the provided `quality`
|
|
166
|
+
*
|
|
167
|
+
* @category Compression
|
|
168
|
+
* @group Compression
|
|
169
|
+
* @param params
|
|
170
|
+
* @throws {Error} if the browser does not support [createImageBitmap](https://caniuse.com/createimagebitmap)
|
|
171
|
+
* @throws {Error} if the provided source image cannot be decoded
|
|
172
|
+
* @throws {Error} if the function fails to create a canvas context
|
|
173
|
+
*/
|
|
174
|
+
const compress = async (params) => {
|
|
175
|
+
if (typeof createImageBitmap === 'undefined')
|
|
176
|
+
throw new Error('createImageBitmap() not supported.');
|
|
177
|
+
const { source, mimeType, quality, flipY } = params;
|
|
178
|
+
let imageBitmapSource;
|
|
179
|
+
if ((source instanceof Uint8Array || source instanceof Uint8ClampedArray) && 'sourceMimeType' in params) {
|
|
180
|
+
imageBitmapSource = new Blob([source], { type: params.sourceMimeType });
|
|
181
|
+
}
|
|
182
|
+
else if (source instanceof ImageData) {
|
|
183
|
+
imageBitmapSource = source;
|
|
184
|
+
}
|
|
185
|
+
else {
|
|
186
|
+
throw new Error('Invalid source image');
|
|
187
|
+
}
|
|
188
|
+
const img = await createImageBitmap(imageBitmapSource);
|
|
189
|
+
const width = img.width;
|
|
190
|
+
const height = img.height;
|
|
191
|
+
let canvas;
|
|
192
|
+
if (typeof OffscreenCanvas !== 'undefined') {
|
|
193
|
+
canvas = new OffscreenCanvas(width, height);
|
|
194
|
+
}
|
|
195
|
+
else {
|
|
196
|
+
canvas = document.createElement('canvas');
|
|
197
|
+
canvas.width = width;
|
|
198
|
+
canvas.height = height;
|
|
199
|
+
}
|
|
200
|
+
// apparently we do need to assert the type here for npx tsc to be happy
|
|
201
|
+
const ctx = canvas.getContext('2d');
|
|
202
|
+
if (!ctx)
|
|
203
|
+
throw new Error('Failed to create canvas Context');
|
|
204
|
+
// flip Y
|
|
205
|
+
if (flipY === true) {
|
|
206
|
+
ctx.translate(0, height);
|
|
207
|
+
ctx.scale(1, -1);
|
|
208
|
+
}
|
|
209
|
+
ctx.drawImage(img, 0, 0, width, height);
|
|
210
|
+
const blob = await canvasToBlob(canvas, mimeType, quality || 0.9);
|
|
211
|
+
const data = new Uint8Array(await blob.arrayBuffer());
|
|
212
|
+
return {
|
|
213
|
+
data,
|
|
214
|
+
mimeType,
|
|
215
|
+
width,
|
|
216
|
+
height
|
|
217
|
+
};
|
|
218
|
+
};
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* Utility function to obtain a `DataTexture` from various input formats
|
|
222
|
+
*
|
|
223
|
+
* @category Utility
|
|
224
|
+
* @group Utility
|
|
225
|
+
*
|
|
226
|
+
* @param image
|
|
227
|
+
* @returns
|
|
228
|
+
*/
|
|
229
|
+
const getDataTexture = (image) => {
|
|
230
|
+
let dataTexture;
|
|
231
|
+
if (image instanceof three.DataTexture) {
|
|
232
|
+
if (!(image.image.data instanceof Uint16Array) && !(image.image.data instanceof Float32Array)) {
|
|
233
|
+
throw new Error('Provided image is not HDR');
|
|
234
|
+
}
|
|
235
|
+
dataTexture = image;
|
|
236
|
+
}
|
|
237
|
+
else {
|
|
238
|
+
if (!image.data || !image.width || !image.height) {
|
|
239
|
+
throw new Error('Provided image has no data or size');
|
|
240
|
+
}
|
|
241
|
+
dataTexture = new three.DataTexture(image.data, image.width, image.height, image.format ?? three.RGBAFormat, image.type, three.UVMapping, three.RepeatWrapping, three.RepeatWrapping, three.LinearFilter, three.LinearFilter, 1, 'colorSpace' in image && image.colorSpace === 'srgb' ? image.colorSpace : three.LinearSRGBColorSpace);
|
|
242
|
+
// TODO: This tries to detect a raw RGBE and applies flipY
|
|
243
|
+
// see if there's a better way to detect it?
|
|
244
|
+
if ('header' in image && 'gamma' in image) {
|
|
245
|
+
dataTexture.flipY = true;
|
|
246
|
+
}
|
|
247
|
+
dataTexture.needsUpdate = true;
|
|
248
|
+
}
|
|
249
|
+
return dataTexture;
|
|
250
|
+
};
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* Reads the pixels of a render target, rows are returned top to bottom
|
|
254
|
+
* (like `ImageData`, regardless of the backend) and tightly packed
|
|
255
|
+
* (WebGPU pads each row to 256 bytes).
|
|
256
|
+
*
|
|
257
|
+
* @internal
|
|
258
|
+
* @param renderer
|
|
259
|
+
* @param renderTarget
|
|
260
|
+
*/
|
|
261
|
+
const readRenderTargetPixels = async (renderer, renderTarget) => {
|
|
262
|
+
const { width, height } = renderTarget;
|
|
263
|
+
const data = await renderer.readRenderTargetPixelsAsync(renderTarget, 0, 0, width, height);
|
|
264
|
+
const rowLength = width * 4;
|
|
265
|
+
const rowStride = height > 1 ? (data.length - rowLength) / (height - 1) : rowLength;
|
|
266
|
+
// the WebGPU backend reads rows bottom to top (render targets are sampled with flipped uvs),
|
|
267
|
+
// the WebGL backend top to bottom
|
|
268
|
+
const flip = renderer.backend.isWebGLBackend !== true;
|
|
269
|
+
if (rowStride === rowLength && !flip)
|
|
270
|
+
return data.length === rowLength * height ? data : data.subarray(0, rowLength * height);
|
|
271
|
+
const out = new data.constructor(rowLength * height);
|
|
272
|
+
for (let y = 0; y < height; y++) {
|
|
273
|
+
const sourceRow = flip ? height - 1 - y : y;
|
|
274
|
+
out.set(data.subarray(sourceRow * rowStride, sourceRow * rowStride + rowLength), y * rowLength);
|
|
275
|
+
}
|
|
276
|
+
return out;
|
|
277
|
+
};
|
|
278
|
+
|
|
279
|
+
// max half float value
|
|
280
|
+
const HALF_FLOAT_MAX$1 = 65504;
|
|
281
|
+
const CELL_SIZE = 2;
|
|
282
|
+
const isTextureData = (image) => typeof image === 'object' && image !== null && 'data' in image && 'width' in image && 'height' in image && !(image instanceof webgpu.Texture);
|
|
283
|
+
/**
|
|
284
|
+
* Finds the min or max value of each RGB channel of an HDR image, on the GPU.
|
|
285
|
+
*
|
|
286
|
+
* The image is reduced by 2x2 cells until it's 1x1, then the single remaining pixel is read back.
|
|
287
|
+
* Negative values are ignored when looking for the max, values above 65504 (max half float) when looking for the min.
|
|
288
|
+
*
|
|
289
|
+
* @category Utility
|
|
290
|
+
* @group Utility
|
|
291
|
+
*
|
|
292
|
+
* @example
|
|
293
|
+
* import { findTextureMinMax } from '@monogrid/gainmap-js/encode/webgpu'
|
|
294
|
+
*
|
|
295
|
+
* const [r, g, b] = await findTextureMinMax(exrTexture, 'max', renderer)
|
|
296
|
+
* const maxContentBoost = Math.max(r, g, b)
|
|
297
|
+
*
|
|
298
|
+
* @param image the HDR image: a texture, raw texture data or a TSL node (which requires `size`)
|
|
299
|
+
* @param mode
|
|
300
|
+
* @param renderer
|
|
301
|
+
* @param size size of the image, required when the image is a generic node
|
|
302
|
+
* @throws {Error} if the image is a generic node and `size` is not provided
|
|
303
|
+
*/
|
|
304
|
+
const findTextureMinMax = async (image, mode, renderer, size) => {
|
|
305
|
+
const rendererState = webgpu.RendererUtils.resetRendererState(renderer, {});
|
|
306
|
+
const renderTargets = [];
|
|
307
|
+
const quad = new webgpu.QuadMesh(new webgpu.NodeMaterial());
|
|
308
|
+
const createRenderTarget = (width, height) => {
|
|
309
|
+
const renderTarget = new webgpu.RenderTarget(width, height, {
|
|
310
|
+
type: webgpu.FloatType,
|
|
311
|
+
minFilter: webgpu.NearestFilter,
|
|
312
|
+
magFilter: webgpu.NearestFilter,
|
|
313
|
+
generateMipmaps: false,
|
|
314
|
+
depthBuffer: false
|
|
315
|
+
});
|
|
316
|
+
renderTargets.push(renderTarget);
|
|
317
|
+
return renderTarget;
|
|
318
|
+
};
|
|
319
|
+
const renderQuad = (material, renderTarget) => {
|
|
320
|
+
material.blending = webgpu.NoBlending;
|
|
321
|
+
material.depthTest = false;
|
|
322
|
+
material.depthWrite = false;
|
|
323
|
+
quad.material = material;
|
|
324
|
+
renderer.setRenderTarget(renderTarget);
|
|
325
|
+
quad.render(renderer);
|
|
326
|
+
};
|
|
327
|
+
try {
|
|
328
|
+
let source;
|
|
329
|
+
let width;
|
|
330
|
+
let height;
|
|
331
|
+
if (image instanceof webgpu.Texture || isTextureData(image)) {
|
|
332
|
+
source = image instanceof webgpu.Texture ? image : getDataTexture(image);
|
|
333
|
+
const sourceImage = source.image;
|
|
334
|
+
width = sourceImage.width;
|
|
335
|
+
height = sourceImage.height;
|
|
336
|
+
}
|
|
337
|
+
else {
|
|
338
|
+
// generic nodes are rendered at full resolution first
|
|
339
|
+
if (!size)
|
|
340
|
+
throw new Error('findTextureMinMax: size is required when the image is a node');
|
|
341
|
+
width = size.width;
|
|
342
|
+
height = size.height;
|
|
343
|
+
const material = new webgpu.NodeMaterial();
|
|
344
|
+
material.fragmentNode = tsl.vec4(image);
|
|
345
|
+
const renderTarget = createRenderTarget(width, height);
|
|
346
|
+
renderQuad(material, renderTarget);
|
|
347
|
+
material.dispose();
|
|
348
|
+
source = renderTarget.texture;
|
|
349
|
+
}
|
|
350
|
+
// creates a material reducing 2x2 cells of a texture into 1 pixel
|
|
351
|
+
const createReduceMaterial = (texture, width, height) => {
|
|
352
|
+
const sourceSize = tsl.uniform(new webgpu.Vector2(width, height));
|
|
353
|
+
const sourceTexture = tsl.textureLoad(texture);
|
|
354
|
+
const reduce = tsl.Fn(() => {
|
|
355
|
+
// the first pixel of the source cell
|
|
356
|
+
const sourcePixel = tsl.screenCoordinate.xy.floor().mul(CELL_SIZE);
|
|
357
|
+
const last = sourceSize.sub(1);
|
|
358
|
+
const result = tsl.vec4(tsl.float(mode === 'max' ? 0 : HALF_FLOAT_MAX$1)).toVar();
|
|
359
|
+
for (let y = 0; y < CELL_SIZE; y++) {
|
|
360
|
+
for (let x = 0; x < CELL_SIZE; x++) {
|
|
361
|
+
// pixels outside the source repeat the edge ones
|
|
362
|
+
const texel = sourceTexture.load(tsl.ivec2(tsl.min(sourcePixel.add(tsl.vec2(x, y)), last)));
|
|
363
|
+
result.assign(mode === 'max' ? tsl.max(result, texel) : tsl.min(result, texel));
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
return result;
|
|
367
|
+
});
|
|
368
|
+
const material = new webgpu.NodeMaterial();
|
|
369
|
+
material.fragmentNode = reduce();
|
|
370
|
+
return { material, sourceTexture, sourceSize };
|
|
371
|
+
};
|
|
372
|
+
// the source may have a different format from the intermediate (float) render targets,
|
|
373
|
+
// it is reduced by its own material
|
|
374
|
+
let reducer = createReduceMaterial(source, width, height);
|
|
375
|
+
let renderTarget;
|
|
376
|
+
while (width > 1 || height > 1 || !renderTarget) {
|
|
377
|
+
width = Math.max(1, Math.ceil(width / CELL_SIZE));
|
|
378
|
+
height = Math.max(1, Math.ceil(height / CELL_SIZE));
|
|
379
|
+
const sourceRenderTarget = renderTarget;
|
|
380
|
+
renderTarget = createRenderTarget(width, height);
|
|
381
|
+
if (sourceRenderTarget) {
|
|
382
|
+
if (reducer.sourceTexture.value === source) {
|
|
383
|
+
reducer.material.dispose();
|
|
384
|
+
reducer = createReduceMaterial(sourceRenderTarget.texture, sourceRenderTarget.width, sourceRenderTarget.height);
|
|
385
|
+
}
|
|
386
|
+
else {
|
|
387
|
+
reducer.sourceTexture.value = sourceRenderTarget.texture;
|
|
388
|
+
reducer.sourceSize.value.set(sourceRenderTarget.width, sourceRenderTarget.height);
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
renderQuad(reducer.material, renderTarget);
|
|
392
|
+
}
|
|
393
|
+
reducer.material.dispose();
|
|
394
|
+
const out = await readRenderTargetPixels(renderer, renderTarget);
|
|
395
|
+
return [out[0], out[1], out[2]];
|
|
396
|
+
}
|
|
397
|
+
finally {
|
|
398
|
+
webgpu.RendererUtils.restoreRendererState(renderer, rendererState);
|
|
399
|
+
renderTargets.forEach(renderTarget => renderTarget.dispose());
|
|
400
|
+
}
|
|
401
|
+
};
|
|
402
|
+
|
|
403
|
+
// max half float value
|
|
404
|
+
const HALF_FLOAT_MAX = 65504;
|
|
405
|
+
/**
|
|
406
|
+
* A TSL texture node holding the HDR image decoded from an SDR image + gain map.
|
|
407
|
+
*
|
|
408
|
+
* The decode runs on the GPU into a HalfFloat render target, and only when something changed
|
|
409
|
+
* (textures loaded/swapped or any uniform value changed): sampling the node costs a single
|
|
410
|
+
* texture read, like any other texture.
|
|
411
|
+
*
|
|
412
|
+
* The node updates itself before rendering whenever it is part of a rendered node graph
|
|
413
|
+
* (material, `scene.backgroundNode`, ...). When only its texture is used (`node.value`,
|
|
414
|
+
* e.g. `scene.environment = node.value`) call {@link GainMapNode.decode} yourself.
|
|
415
|
+
*
|
|
416
|
+
* Re-decoding also flags the texture for PMREM regeneration,
|
|
417
|
+
* so environment maps are recomputed only when the image actually changes.
|
|
418
|
+
*
|
|
419
|
+
* `node.value` gets its final size once loaded: three.js PMREMs don't follow texture resizes,
|
|
420
|
+
* so assign it to `scene.environment` (or `pmremTexture()`) after load.
|
|
421
|
+
*
|
|
422
|
+
* @category Nodes
|
|
423
|
+
* @group Nodes
|
|
424
|
+
*
|
|
425
|
+
* @example
|
|
426
|
+
* import { GainMapNode } from '@monogrid/gainmap-js/webgpu'
|
|
427
|
+
* import { equirectUV } from 'three/tsl'
|
|
428
|
+
*
|
|
429
|
+
* const hdr = new GainMapNode()
|
|
430
|
+
* .setTextures(sdrTexture, gainMapTexture)
|
|
431
|
+
* .setMetadata(metadata)
|
|
432
|
+
*
|
|
433
|
+
* material.colorNode = hdr
|
|
434
|
+
* scene.backgroundNode = hdr.sample(equirectUV())
|
|
435
|
+
* hdr.maxDisplayBoost.value = 2 // re-decodes once, on the next frame
|
|
436
|
+
*/
|
|
437
|
+
class GainMapNode extends RenderTargetNode {
|
|
438
|
+
static get type() { return 'GainMapNode'; }
|
|
439
|
+
/**
|
|
440
|
+
* Shared textures and uniforms
|
|
441
|
+
*/
|
|
442
|
+
uniforms;
|
|
443
|
+
// set when the textures are produced by other render target nodes (e.g. a gain map encoder)
|
|
444
|
+
_sdrSource = null;
|
|
445
|
+
_gainMapSource = null;
|
|
446
|
+
constructor() {
|
|
447
|
+
const material = new webgpu.MeshBasicNodeMaterial();
|
|
448
|
+
material.name = 'GainMapDecoder';
|
|
449
|
+
super(material, {
|
|
450
|
+
type: webgpu.HalfFloatType,
|
|
451
|
+
colorSpace: webgpu.LinearSRGBColorSpace,
|
|
452
|
+
generateMipmaps: true,
|
|
453
|
+
minFilter: webgpu.LinearMipmapLinearFilter,
|
|
454
|
+
magFilter: webgpu.LinearFilter
|
|
455
|
+
});
|
|
456
|
+
const u = this.uniforms = {
|
|
457
|
+
sdr: tsl.texture(new webgpu.Texture()),
|
|
458
|
+
gainMap: tsl.texture(new webgpu.Texture()),
|
|
459
|
+
gamma: tsl.uniform(new webgpu.Vector3(1, 1, 1)),
|
|
460
|
+
offsetSdr: tsl.uniform(new webgpu.Vector3()),
|
|
461
|
+
offsetHdr: tsl.uniform(new webgpu.Vector3()),
|
|
462
|
+
gainMapMin: tsl.uniform(new webgpu.Vector3()),
|
|
463
|
+
gainMapMax: tsl.uniform(new webgpu.Vector3(1, 1, 1)),
|
|
464
|
+
hdrCapacityMin: tsl.uniform(0),
|
|
465
|
+
hdrCapacityMax: tsl.uniform(1),
|
|
466
|
+
maxDisplayBoost: tsl.uniform(1)
|
|
467
|
+
};
|
|
468
|
+
const logRecovery = u.gainMap.rgb.pow(tsl.vec3(1).div(u.gamma));
|
|
469
|
+
const logBoost = tsl.mix(u.gainMapMin, u.gainMapMax, logRecovery);
|
|
470
|
+
const weight = tsl.saturate(tsl.log2(u.maxDisplayBoost).sub(u.hdrCapacityMin).div(u.hdrCapacityMax.sub(u.hdrCapacityMin)));
|
|
471
|
+
const hdr = u.sdr.rgb.add(u.offsetSdr).mul(tsl.exp2(logBoost.mul(weight))).sub(u.offsetHdr);
|
|
472
|
+
material.colorNode = tsl.vec4(hdr.clamp(-HALF_FLOAT_MAX, HALF_FLOAT_MAX), 1);
|
|
473
|
+
}
|
|
474
|
+
/** The SDR rendition texture (sRGB) */
|
|
475
|
+
get sdr() { return this.uniforms.sdr.value; }
|
|
476
|
+
/** The gain map recovery texture (linear) */
|
|
477
|
+
get gainMap() { return this.uniforms.gainMap.value; }
|
|
478
|
+
/** @see {@link GainMapMetadata.gamma} */
|
|
479
|
+
get gamma() { return this.uniforms.gamma; }
|
|
480
|
+
/** @see {@link GainMapMetadata.offsetSdr} */
|
|
481
|
+
get offsetSdr() { return this.uniforms.offsetSdr; }
|
|
482
|
+
/** @see {@link GainMapMetadata.offsetHdr} */
|
|
483
|
+
get offsetHdr() { return this.uniforms.offsetHdr; }
|
|
484
|
+
/** @see {@link GainMapMetadata.gainMapMin} */
|
|
485
|
+
get gainMapMin() { return this.uniforms.gainMapMin; }
|
|
486
|
+
/** @see {@link GainMapMetadata.gainMapMax} */
|
|
487
|
+
get gainMapMax() { return this.uniforms.gainMapMax; }
|
|
488
|
+
/** @see {@link GainMapMetadata.hdrCapacityMin} */
|
|
489
|
+
get hdrCapacityMin() { return this.uniforms.hdrCapacityMin; }
|
|
490
|
+
/** @see {@link GainMapMetadata.hdrCapacityMax} */
|
|
491
|
+
get hdrCapacityMax() { return this.uniforms.hdrCapacityMax; }
|
|
492
|
+
/**
|
|
493
|
+
* @see {@link GainmapDecodingParameters.maxDisplayBoost}
|
|
494
|
+
* @remarks Non Logarithmic space
|
|
495
|
+
*/
|
|
496
|
+
get maxDisplayBoost() { return this.uniforms.maxDisplayBoost; }
|
|
497
|
+
/** Width of the SDR image, 0 until loaded */
|
|
498
|
+
get width() {
|
|
499
|
+
if (this._sdrSource)
|
|
500
|
+
return this._sdrSource.width;
|
|
501
|
+
return this.sdr.image?.width ?? 0;
|
|
502
|
+
}
|
|
503
|
+
/** Height of the SDR image, 0 until loaded */
|
|
504
|
+
get height() {
|
|
505
|
+
if (this._sdrSource)
|
|
506
|
+
return this._sdrSource.height;
|
|
507
|
+
return this.sdr.image?.height ?? 0;
|
|
508
|
+
}
|
|
509
|
+
/**
|
|
510
|
+
* Sets the SDR and gain map textures.
|
|
511
|
+
* The SDR texture is expected in sRGB color space, the gain map in linear.
|
|
512
|
+
*
|
|
513
|
+
* Render target nodes (e.g. the `sdr` and `gainMap` nodes of a `GainMapEncoder`) are accepted as well:
|
|
514
|
+
* they are rendered before decoding and the image is decoded again whenever they change.
|
|
515
|
+
*
|
|
516
|
+
* @param sdr
|
|
517
|
+
* @param gainMap
|
|
518
|
+
*/
|
|
519
|
+
setTextures(sdr, gainMap) {
|
|
520
|
+
this._sdrSource = sdr instanceof RenderTargetNode ? sdr : null;
|
|
521
|
+
this._gainMapSource = gainMap instanceof RenderTargetNode ? gainMap : null;
|
|
522
|
+
this.uniforms.sdr.value = sdr instanceof RenderTargetNode ? sdr.value : sdr;
|
|
523
|
+
this.uniforms.gainMap.value = gainMap instanceof RenderTargetNode ? gainMap.value : gainMap;
|
|
524
|
+
// size the render target right away, so `value` has its final size before the first decode
|
|
525
|
+
if (this.width > 0 && this.height > 0)
|
|
526
|
+
this.renderTarget.setSize(this.width, this.height);
|
|
527
|
+
return this;
|
|
528
|
+
}
|
|
529
|
+
/**
|
|
530
|
+
* Copies the gain map metadata into the uniforms.
|
|
531
|
+
* Also sets `maxDisplayBoost` to fully restore the HDR range.
|
|
532
|
+
*
|
|
533
|
+
* @param metadata
|
|
534
|
+
*/
|
|
535
|
+
setMetadata(metadata) {
|
|
536
|
+
const u = this.uniforms;
|
|
537
|
+
u.gamma.value.fromArray(metadata.gamma);
|
|
538
|
+
u.offsetSdr.value.fromArray(metadata.offsetSdr);
|
|
539
|
+
u.offsetHdr.value.fromArray(metadata.offsetHdr);
|
|
540
|
+
u.gainMapMin.value.fromArray(metadata.gainMapMin);
|
|
541
|
+
u.gainMapMax.value.fromArray(metadata.gainMapMax);
|
|
542
|
+
u.hdrCapacityMin.value = metadata.hdrCapacityMin;
|
|
543
|
+
u.hdrCapacityMax.value = metadata.hdrCapacityMax;
|
|
544
|
+
u.maxDisplayBoost.value = Math.pow(2, metadata.hdrCapacityMax);
|
|
545
|
+
return this;
|
|
546
|
+
}
|
|
547
|
+
_getState() {
|
|
548
|
+
const u = this.uniforms;
|
|
549
|
+
return [
|
|
550
|
+
this.sdr.id, this.sdr.version, this.gainMap.id, this.gainMap.version,
|
|
551
|
+
...u.gamma.value.toArray(), ...u.offsetSdr.value.toArray(), ...u.offsetHdr.value.toArray(),
|
|
552
|
+
...u.gainMapMin.value.toArray(), ...u.gainMapMax.value.toArray(),
|
|
553
|
+
u.hdrCapacityMin.value, u.hdrCapacityMax.value, u.maxDisplayBoost.value
|
|
554
|
+
];
|
|
555
|
+
}
|
|
556
|
+
_getDependencies() {
|
|
557
|
+
const dependencies = [];
|
|
558
|
+
if (this._sdrSource)
|
|
559
|
+
dependencies.push(this._sdrSource);
|
|
560
|
+
if (this._gainMapSource)
|
|
561
|
+
dependencies.push(this._gainMapSource);
|
|
562
|
+
return dependencies;
|
|
563
|
+
}
|
|
564
|
+
_onRender() {
|
|
565
|
+
this.value.needsPMREMUpdate = true;
|
|
566
|
+
}
|
|
567
|
+
/**
|
|
568
|
+
* Decodes the image into {@link GainMapNode.renderTarget}, only if something changed since the last decode.
|
|
569
|
+
*
|
|
570
|
+
* Called automatically when the node is part of a rendered node graph.
|
|
571
|
+
*
|
|
572
|
+
* @param renderer
|
|
573
|
+
* @returns `true` if the image was decoded
|
|
574
|
+
*/
|
|
575
|
+
decode(renderer) {
|
|
576
|
+
return this.render(renderer);
|
|
577
|
+
}
|
|
578
|
+
/**
|
|
579
|
+
* Calls {@link GainMapNode.decode} once per render, before the node is evaluated.
|
|
580
|
+
*
|
|
581
|
+
* @param frame
|
|
582
|
+
*/
|
|
583
|
+
updateBefore(frame) {
|
|
584
|
+
if (frame.renderer)
|
|
585
|
+
this.decode(frame.renderer);
|
|
586
|
+
return undefined;
|
|
587
|
+
}
|
|
588
|
+
/**
|
|
589
|
+
* Disposes the render target, the SDR and gain map textures
|
|
590
|
+
* (unless they belong to other render target nodes)
|
|
591
|
+
*/
|
|
592
|
+
dispose() {
|
|
593
|
+
if (!this._sdrSource)
|
|
594
|
+
this.sdr.dispose();
|
|
595
|
+
if (!this._gainMapSource)
|
|
596
|
+
this.gainMap.dispose();
|
|
597
|
+
super.dispose();
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
// maxContentBoost must be > 1, a gain map can't encode an empty boost range
|
|
602
|
+
const MIN_MAX_CONTENT_BOOST = 1.0001;
|
|
603
|
+
/**
|
|
604
|
+
* A TSL texture node holding the gain map (recovery map) of an HDR image: the second step of gain map encoding.
|
|
605
|
+
*
|
|
606
|
+
* The gain map is computed from the HDR input of a {@link SDRRenditionNode} and its SDR rendition,
|
|
607
|
+
* into an 8 bit linear render target. The result is identical to the one of the WebGL `GainMapEncoderMaterial`.
|
|
608
|
+
*
|
|
609
|
+
* It renders only when something changed (the SDR rendition or any uniform value),
|
|
610
|
+
* the SDR rendition is rendered first when needed.
|
|
611
|
+
*
|
|
612
|
+
* @category Nodes
|
|
613
|
+
* @group Nodes
|
|
614
|
+
*
|
|
615
|
+
* @example
|
|
616
|
+
* import { GainMapEncoderNode, SDRRenditionNode } from '@monogrid/gainmap-js/encode/webgpu'
|
|
617
|
+
*
|
|
618
|
+
* const sdr = new SDRRenditionNode(hdrTexture)
|
|
619
|
+
* const gainMap = new GainMapEncoderNode(sdr, { maxContentBoost: 8 })
|
|
620
|
+
*
|
|
621
|
+
* material.colorNode = gainMap
|
|
622
|
+
* gainMap.gamma.value.setScalar(1.2) // renders again once, on the next frame
|
|
623
|
+
* const metadata = gainMap.metadata
|
|
624
|
+
*/
|
|
625
|
+
class GainMapEncoderNode extends RenderTargetNode {
|
|
626
|
+
static get type() { return 'GainMapEncoderNode'; }
|
|
627
|
+
/**
|
|
628
|
+
* The SDR rendition this gain map is computed from
|
|
629
|
+
*/
|
|
630
|
+
sdr;
|
|
631
|
+
/**
|
|
632
|
+
* Shared uniforms
|
|
633
|
+
*/
|
|
634
|
+
uniforms;
|
|
635
|
+
_warned = [];
|
|
636
|
+
/**
|
|
637
|
+
* @param sdr the SDR rendition, its HDR input is the HDR input of the gain map
|
|
638
|
+
* @param params encoding parameters, all of them can be changed later through the uniforms
|
|
639
|
+
*/
|
|
640
|
+
constructor(sdr, params = {}) {
|
|
641
|
+
super(new webgpu.NodeMaterial(), {
|
|
642
|
+
type: webgpu.UnsignedByteType,
|
|
643
|
+
colorSpace: webgpu.LinearSRGBColorSpace,
|
|
644
|
+
minFilter: webgpu.LinearFilter,
|
|
645
|
+
magFilter: webgpu.LinearFilter
|
|
646
|
+
});
|
|
647
|
+
this.sdr = sdr;
|
|
648
|
+
const u = this.uniforms = {
|
|
649
|
+
gamma: tsl.uniform(new webgpu.Vector3().fromArray(params.gamma ?? [1, 1, 1])),
|
|
650
|
+
offsetSdr: tsl.uniform(new webgpu.Vector3().fromArray(params.offsetSdr ?? [1 / 64, 1 / 64, 1 / 64])),
|
|
651
|
+
offsetHdr: tsl.uniform(new webgpu.Vector3().fromArray(params.offsetHdr ?? [1 / 64, 1 / 64, 1 / 64])),
|
|
652
|
+
// 0 is not a valid min content boost
|
|
653
|
+
minContentBoost: tsl.uniform(params.minContentBoost || 1),
|
|
654
|
+
maxContentBoost: tsl.uniform(params.maxContentBoost ?? MIN_MAX_CONTENT_BOOST)
|
|
655
|
+
};
|
|
656
|
+
// logarithms are computed on the CPU (in double precision), like the WebGL encoder does
|
|
657
|
+
const minLog2 = tsl.uniform(0).onRenderUpdate(() => Math.log2(this.metadataMinContentBoost));
|
|
658
|
+
const maxLog2 = tsl.uniform(0).onRenderUpdate(() => Math.log2(this.metadataMaxContentBoost));
|
|
659
|
+
const sdrColor = tsl.texture(sdr.value).rgb;
|
|
660
|
+
const hdrColor = tsl.vec4(sdr.hdr).rgb;
|
|
661
|
+
const pixelGain = hdrColor.add(u.offsetHdr).div(sdrColor.add(u.offsetSdr));
|
|
662
|
+
const logRecovery = tsl.log2(pixelGain).sub(minLog2).div(maxLog2.sub(minLog2));
|
|
663
|
+
const clampedRecovery = tsl.saturate(logRecovery);
|
|
664
|
+
this._material.name = 'GainMapEncoder';
|
|
665
|
+
this._material.blending = webgpu.NoBlending;
|
|
666
|
+
this._material.depthTest = false;
|
|
667
|
+
this._material.depthWrite = false;
|
|
668
|
+
this._material.fragmentNode = tsl.vec4(tsl.pow(clampedRecovery, u.gamma), 1.0);
|
|
669
|
+
}
|
|
670
|
+
/** @see {@link GainmapEncodingParameters.gamma} */
|
|
671
|
+
get gamma() { return this.uniforms.gamma; }
|
|
672
|
+
/** @see {@link GainmapEncodingParameters.offsetSdr} */
|
|
673
|
+
get offsetSdr() { return this.uniforms.offsetSdr; }
|
|
674
|
+
/** @see {@link GainmapEncodingParameters.offsetHdr} */
|
|
675
|
+
get offsetHdr() { return this.uniforms.offsetHdr; }
|
|
676
|
+
/**
|
|
677
|
+
* @see {@link GainmapEncodingParameters.minContentBoost}
|
|
678
|
+
* @remarks Non logarithmic space
|
|
679
|
+
*/
|
|
680
|
+
get minContentBoost() { return this.uniforms.minContentBoost; }
|
|
681
|
+
/**
|
|
682
|
+
* @see {@link GainmapEncodingParameters.maxContentBoost}
|
|
683
|
+
* @remarks Non logarithmic space, values <= 1 are clamped to 1.0001 since a gain map can't encode an empty boost range
|
|
684
|
+
*/
|
|
685
|
+
get maxContentBoost() { return this.uniforms.maxContentBoost; }
|
|
686
|
+
/** Same size as the SDR rendition */
|
|
687
|
+
get width() { return this.sdr.width; }
|
|
688
|
+
/** Same size as the SDR rendition */
|
|
689
|
+
get height() { return this.sdr.height; }
|
|
690
|
+
/** The min content boost actually encoded */
|
|
691
|
+
get metadataMinContentBoost() { return this.uniforms.minContentBoost.value; }
|
|
692
|
+
/** The max content boost actually encoded, clamped to a valid range */
|
|
693
|
+
get metadataMaxContentBoost() { return Math.max(this.uniforms.maxContentBoost.value, MIN_MAX_CONTENT_BOOST); }
|
|
694
|
+
/**
|
|
695
|
+
* The gain map metadata matching the current uniform values
|
|
696
|
+
*/
|
|
697
|
+
get metadata() {
|
|
698
|
+
const u = this.uniforms;
|
|
699
|
+
const gainMapMin = Math.log2(this.metadataMinContentBoost);
|
|
700
|
+
const gainMapMax = Math.log2(this.metadataMaxContentBoost);
|
|
701
|
+
return {
|
|
702
|
+
gamma: u.gamma.value.toArray(),
|
|
703
|
+
offsetSdr: u.offsetSdr.value.toArray(),
|
|
704
|
+
offsetHdr: u.offsetHdr.value.toArray(),
|
|
705
|
+
gainMapMin: [gainMapMin, gainMapMin, gainMapMin],
|
|
706
|
+
gainMapMax: [gainMapMax, gainMapMax, gainMapMax],
|
|
707
|
+
hdrCapacityMin: Math.max(0, gainMapMin),
|
|
708
|
+
hdrCapacityMax: Math.max(0, gainMapMax)
|
|
709
|
+
};
|
|
710
|
+
}
|
|
711
|
+
_getState() {
|
|
712
|
+
const u = this.uniforms;
|
|
713
|
+
return [
|
|
714
|
+
...u.gamma.value.toArray(), ...u.offsetSdr.value.toArray(), ...u.offsetHdr.value.toArray(),
|
|
715
|
+
u.minContentBoost.value, u.maxContentBoost.value
|
|
716
|
+
];
|
|
717
|
+
}
|
|
718
|
+
_getDependencies() {
|
|
719
|
+
return [this.sdr];
|
|
720
|
+
}
|
|
721
|
+
_onRender() {
|
|
722
|
+
// warn once per invalid combination of parameters
|
|
723
|
+
const { minContentBoost, maxContentBoost } = this.uniforms;
|
|
724
|
+
const state = [minContentBoost.value, maxContentBoost.value];
|
|
725
|
+
if (state.every((v, i) => v === this._warned[i]))
|
|
726
|
+
return;
|
|
727
|
+
this._warned = state;
|
|
728
|
+
if (maxContentBoost.value <= 1) {
|
|
729
|
+
console.warn(`gainmap-js: maxContentBoost is ${maxContentBoost.value} (<= 1), the source image has no HDR content. It will be clamped to ${MIN_MAX_CONTENT_BOOST} and the result will be equivalent to an SDR image.`);
|
|
730
|
+
}
|
|
731
|
+
if (this.metadataMinContentBoost >= this.metadataMaxContentBoost) {
|
|
732
|
+
console.warn(`gainmap-js: minContentBoost (${this.metadataMinContentBoost}) must be lower than maxContentBoost (${this.metadataMaxContentBoost}), the resulting gain map will be invalid.`);
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
/**
|
|
737
|
+
* TSL function creating a {@link GainMapEncoderNode}
|
|
738
|
+
*
|
|
739
|
+
* @param sdr the SDR rendition, its HDR input is the HDR input of the gain map
|
|
740
|
+
* @param params encoding parameters
|
|
741
|
+
*/
|
|
742
|
+
const gainMapEncoder = (sdr, params) => new GainMapEncoderNode(sdr, params);
|
|
743
|
+
|
|
744
|
+
const textureSize = (texture) => {
|
|
745
|
+
const image = texture.image;
|
|
746
|
+
return { width: image?.width ?? 0, height: image?.height ?? 0 };
|
|
747
|
+
};
|
|
748
|
+
/**
|
|
749
|
+
* A TSL texture node holding the SDR rendition of an HDR image: the first step of gain map encoding.
|
|
750
|
+
*
|
|
751
|
+
* The HDR input is exposed, tone mapped (with the three.js TSL tone mapping functions)
|
|
752
|
+
* and adjusted (brightness, contrast, saturation) into an 8 bit sRGB render target.
|
|
753
|
+
*
|
|
754
|
+
* It renders only when something changed (input, tone mapping or any uniform value):
|
|
755
|
+
* sampling the node costs a single texture read, like any other texture.
|
|
756
|
+
*
|
|
757
|
+
* @category Nodes
|
|
758
|
+
* @group Nodes
|
|
759
|
+
*
|
|
760
|
+
* @example
|
|
761
|
+
* import { SDRRenditionNode } from '@monogrid/gainmap-js/encode/webgpu'
|
|
762
|
+
* import { AgXToneMapping, LinearToneMapping } from 'three/webgpu'
|
|
763
|
+
*
|
|
764
|
+
* const sdr = new SDRRenditionNode(hdrTexture, { toneMapping: AgXToneMapping })
|
|
765
|
+
* material.colorNode = sdr
|
|
766
|
+
* sdr.exposure.value = 0.8 // renders again once, on the next frame
|
|
767
|
+
* sdr.setToneMapping(LinearToneMapping)
|
|
768
|
+
*/
|
|
769
|
+
class SDRRenditionNode extends RenderTargetNode {
|
|
770
|
+
static get type() { return 'SDRRenditionNode'; }
|
|
771
|
+
/**
|
|
772
|
+
* The HDR input, as a node
|
|
773
|
+
*/
|
|
774
|
+
hdr;
|
|
775
|
+
/**
|
|
776
|
+
* Shared uniforms
|
|
777
|
+
*/
|
|
778
|
+
uniforms;
|
|
779
|
+
_hdrTexture;
|
|
780
|
+
_hdrSource;
|
|
781
|
+
_width;
|
|
782
|
+
_height;
|
|
783
|
+
_toneMapping = webgpu.ACESFilmicToneMapping;
|
|
784
|
+
/**
|
|
785
|
+
* @param hdr HDR input, a texture or a TSL node returning a linear HDR color
|
|
786
|
+
* @param options
|
|
787
|
+
* @throws {Error} if the input is a generic node and `width` or `height` are not provided
|
|
788
|
+
*/
|
|
789
|
+
constructor(hdr, options = {}) {
|
|
790
|
+
super(new webgpu.NodeMaterial(), {
|
|
791
|
+
type: webgpu.UnsignedByteType,
|
|
792
|
+
colorSpace: webgpu.SRGBColorSpace,
|
|
793
|
+
minFilter: webgpu.LinearFilter,
|
|
794
|
+
magFilter: webgpu.LinearFilter
|
|
795
|
+
});
|
|
796
|
+
this._hdrTexture = hdr instanceof webgpu.Texture ? hdr : hdr instanceof webgpu.TextureNode ? hdr.value : null;
|
|
797
|
+
this._hdrSource = hdr instanceof RenderTargetNode ? hdr : null;
|
|
798
|
+
this.hdr = hdr instanceof webgpu.Texture ? tsl.texture(hdr) : hdr;
|
|
799
|
+
this._width = options.width;
|
|
800
|
+
this._height = options.height;
|
|
801
|
+
if (!this._hdrTexture && (!this._width || !this._height)) {
|
|
802
|
+
throw new Error('SDRRenditionNode: width and height are required when the HDR input is not a texture');
|
|
803
|
+
}
|
|
804
|
+
this.uniforms = {
|
|
805
|
+
exposure: tsl.uniform(1),
|
|
806
|
+
brightness: tsl.uniform(0),
|
|
807
|
+
contrast: tsl.uniform(1),
|
|
808
|
+
saturation: tsl.uniform(1)
|
|
809
|
+
};
|
|
810
|
+
this._material.name = 'SDRRendition';
|
|
811
|
+
this._material.blending = webgpu.NoBlending;
|
|
812
|
+
this._material.depthTest = false;
|
|
813
|
+
this._material.depthWrite = false;
|
|
814
|
+
this.setToneMapping(options.toneMapping ?? webgpu.ACESFilmicToneMapping);
|
|
815
|
+
}
|
|
816
|
+
/** Exposure applied to the HDR input before tone mapping */
|
|
817
|
+
get exposure() { return this.uniforms.exposure; }
|
|
818
|
+
/** Brightness offset applied after tone mapping */
|
|
819
|
+
get brightness() { return this.uniforms.brightness; }
|
|
820
|
+
/** Contrast applied after tone mapping */
|
|
821
|
+
get contrast() { return this.uniforms.contrast; }
|
|
822
|
+
/** Saturation applied after tone mapping */
|
|
823
|
+
get saturation() { return this.uniforms.saturation; }
|
|
824
|
+
/**
|
|
825
|
+
* The tone mapping applied to the SDR rendition
|
|
826
|
+
*/
|
|
827
|
+
getToneMapping() { return this._toneMapping; }
|
|
828
|
+
/**
|
|
829
|
+
* Sets the tone mapping applied to the SDR rendition
|
|
830
|
+
* (`toneMapping` can't be used as a property name: it's a TSL method of every node)
|
|
831
|
+
*
|
|
832
|
+
* @param value any three.js tone mapping, e.g. `ACESFilmicToneMapping`, `AgXToneMapping`, `NeutralToneMapping`
|
|
833
|
+
* or `LinearToneMapping` (which keeps the SDR rendition closest to the HDR input)
|
|
834
|
+
*/
|
|
835
|
+
setToneMapping(value) {
|
|
836
|
+
this._toneMapping = value;
|
|
837
|
+
this._material.fragmentNode = this._buildOutput();
|
|
838
|
+
this._material.needsUpdate = true;
|
|
839
|
+
return this;
|
|
840
|
+
}
|
|
841
|
+
/** Width of the output, 0 while the input texture is not loaded */
|
|
842
|
+
get width() {
|
|
843
|
+
if (this._width)
|
|
844
|
+
return this._width;
|
|
845
|
+
if (this._hdrSource)
|
|
846
|
+
return this._hdrSource.width;
|
|
847
|
+
return this._hdrTexture ? textureSize(this._hdrTexture).width : 0;
|
|
848
|
+
}
|
|
849
|
+
/** Height of the output, 0 while the input texture is not loaded */
|
|
850
|
+
get height() {
|
|
851
|
+
if (this._height)
|
|
852
|
+
return this._height;
|
|
853
|
+
if (this._hdrSource)
|
|
854
|
+
return this._hdrSource.height;
|
|
855
|
+
return this._hdrTexture ? textureSize(this._hdrTexture).height : 0;
|
|
856
|
+
}
|
|
857
|
+
_buildOutput() {
|
|
858
|
+
const u = this.uniforms;
|
|
859
|
+
const color = tsl.vec4(this.hdr);
|
|
860
|
+
// exposure is applied here rather than by the tone mapping function, so it works with `NoToneMapping` too
|
|
861
|
+
const toneMapped = tsl.vec4(tsl.toneMapping(this._toneMapping, tsl.float(1), color.rgb.mul(u.exposure)), color.a);
|
|
862
|
+
const b = u.brightness;
|
|
863
|
+
const brightnessMatrix = tsl.mat4(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, b, b, b, 1);
|
|
864
|
+
const c = u.contrast;
|
|
865
|
+
const t = tsl.float(1.0).sub(c).div(2.0);
|
|
866
|
+
const contrastMatrix = tsl.mat4(c, 0, 0, 0, 0, c, 0, 0, 0, 0, c, 0, t, t, t, 1);
|
|
867
|
+
const luminance = tsl.vec3(0.3086, 0.6094, 0.0820);
|
|
868
|
+
const oneMinusSat = tsl.float(1.0).sub(u.saturation);
|
|
869
|
+
const red = tsl.vec3(luminance.x.mul(oneMinusSat)).add(tsl.vec3(u.saturation, 0, 0));
|
|
870
|
+
const green = tsl.vec3(luminance.y.mul(oneMinusSat)).add(tsl.vec3(0, u.saturation, 0));
|
|
871
|
+
const blue = tsl.vec3(luminance.z.mul(oneMinusSat)).add(tsl.vec3(0, 0, u.saturation));
|
|
872
|
+
const saturationMatrix = tsl.mat4(tsl.vec4(red, 0), tsl.vec4(green, 0), tsl.vec4(blue, 0), tsl.vec4(0, 0, 0, 1));
|
|
873
|
+
return brightnessMatrix.mul(contrastMatrix).mul(saturationMatrix).mul(toneMapped);
|
|
874
|
+
}
|
|
875
|
+
_getState() {
|
|
876
|
+
const u = this.uniforms;
|
|
877
|
+
return [
|
|
878
|
+
this._hdrTexture?.id, this._hdrTexture?.version, this._toneMapping,
|
|
879
|
+
u.exposure.value, u.brightness.value, u.contrast.value, u.saturation.value
|
|
880
|
+
];
|
|
881
|
+
}
|
|
882
|
+
_getDependencies() {
|
|
883
|
+
return this._hdrSource ? [this._hdrSource] : [];
|
|
884
|
+
}
|
|
885
|
+
}
|
|
886
|
+
/**
|
|
887
|
+
* TSL function creating a {@link SDRRenditionNode}
|
|
888
|
+
*
|
|
889
|
+
* @param hdr HDR input, a texture or a TSL node returning a linear HDR color
|
|
890
|
+
* @param options
|
|
891
|
+
*/
|
|
892
|
+
const sdrRendition = (hdr, options) => new SDRRenditionNode(hdr, options);
|
|
893
|
+
|
|
894
|
+
/**
|
|
895
|
+
* A gain map preview: a {@link GainMapNode} decoding the encoder output, following its metadata
|
|
896
|
+
*/
|
|
897
|
+
class EncoderPreviewNode extends GainMapNode {
|
|
898
|
+
_encoder;
|
|
899
|
+
constructor(encoder) {
|
|
900
|
+
super();
|
|
901
|
+
this._encoder = encoder;
|
|
902
|
+
this.setTextures(encoder.sdr, encoder.gainMap).setMetadata(encoder.metadata);
|
|
903
|
+
}
|
|
904
|
+
_getState() {
|
|
905
|
+
// follow the encoder metadata, except the display boost which belongs to the viewer
|
|
906
|
+
const { gamma, offsetSdr, offsetHdr, gainMapMin, gainMapMax, hdrCapacityMin, hdrCapacityMax } = this._encoder.metadata;
|
|
907
|
+
const u = this.uniforms;
|
|
908
|
+
u.gamma.value.fromArray(gamma);
|
|
909
|
+
u.offsetSdr.value.fromArray(offsetSdr);
|
|
910
|
+
u.offsetHdr.value.fromArray(offsetHdr);
|
|
911
|
+
u.gainMapMin.value.fromArray(gainMapMin);
|
|
912
|
+
u.gainMapMax.value.fromArray(gainMapMax);
|
|
913
|
+
u.hdrCapacityMin.value = hdrCapacityMin;
|
|
914
|
+
u.hdrCapacityMax.value = hdrCapacityMax;
|
|
915
|
+
return super._getState();
|
|
916
|
+
}
|
|
917
|
+
}
|
|
918
|
+
/**
|
|
919
|
+
* Encodes an HDR image into an SDR rendition + a gain map, on the GPU, with TSL nodes.
|
|
920
|
+
*
|
|
921
|
+
* {@link GainMapEncoder.sdr} and {@link GainMapEncoder.gainMap} are live texture nodes:
|
|
922
|
+
* every encoding parameter is a uniform, changing one re-renders the affected nodes once, when they're next used.
|
|
923
|
+
* No renderer is needed until the result is read back with {@link GainMapEncoder.read} or {@link GainMapEncoder.compress}.
|
|
924
|
+
*
|
|
925
|
+
* Read back images are oriented top to bottom (like `ImageData`), no `flipY` is needed when compressing them.
|
|
926
|
+
*
|
|
927
|
+
* @category Encoding Functions
|
|
928
|
+
* @group Encoding Functions
|
|
929
|
+
*
|
|
930
|
+
* @example
|
|
931
|
+
* import { GainMapEncoder } from '@monogrid/gainmap-js/encode/webgpu'
|
|
932
|
+
* import { encodeJPEGMetadata } from '@monogrid/gainmap-js/libultrahdr'
|
|
933
|
+
* import { EXRLoader } from 'three/examples/jsm/loaders/EXRLoader.js'
|
|
934
|
+
* import { AgXToneMapping, MeshBasicNodeMaterial, WebGPURenderer } from 'three/webgpu'
|
|
935
|
+
*
|
|
936
|
+
* const renderer = new WebGPURenderer()
|
|
937
|
+
* await renderer.init()
|
|
938
|
+
*
|
|
939
|
+
* const image = await new EXRLoader().loadAsync('image.exr')
|
|
940
|
+
* const encoder = new GainMapEncoder(image, { toneMapping: AgXToneMapping })
|
|
941
|
+
* // encode the full HDR range
|
|
942
|
+
* await encoder.fitMaxContentBoost(renderer)
|
|
943
|
+
*
|
|
944
|
+
* // live previews, they follow any parameter change
|
|
945
|
+
* sdrMaterial.colorNode = encoder.sdr
|
|
946
|
+
* gainMapMaterial.colorNode = encoder.gainMap
|
|
947
|
+
* hdrMaterial.colorNode = encoder.createPreviewNode() // decodes the encoded result
|
|
948
|
+
*
|
|
949
|
+
* encoder.sdr.exposure.value = 0.9
|
|
950
|
+
* encoder.gainMap.gamma.value.setScalar(1.1)
|
|
951
|
+
*
|
|
952
|
+
* // compress and embed into a single JPEG file
|
|
953
|
+
* const result = await encoder.compress(renderer, { mimeType: 'image/jpeg', quality: 0.9 })
|
|
954
|
+
* const jpeg = encodeJPEGMetadata(result)
|
|
955
|
+
*/
|
|
956
|
+
class GainMapEncoder {
|
|
957
|
+
/**
|
|
958
|
+
* The SDR rendition node
|
|
959
|
+
*/
|
|
960
|
+
sdr;
|
|
961
|
+
/**
|
|
962
|
+
* The gain map node
|
|
963
|
+
*/
|
|
964
|
+
gainMap;
|
|
965
|
+
_ownedTexture;
|
|
966
|
+
/**
|
|
967
|
+
* @param image the HDR image: a texture, raw texture data (e.g. from a worker) or a TSL node (which requires `width` and `height`)
|
|
968
|
+
* @param options encoding parameters, all of them can be changed later through the node uniforms
|
|
969
|
+
*/
|
|
970
|
+
constructor(image, options = {}) {
|
|
971
|
+
let input;
|
|
972
|
+
if (image instanceof webgpu.Texture || !('data' in image)) {
|
|
973
|
+
input = image;
|
|
974
|
+
this._ownedTexture = null;
|
|
975
|
+
}
|
|
976
|
+
else {
|
|
977
|
+
input = this._ownedTexture = getDataTexture(image);
|
|
978
|
+
}
|
|
979
|
+
this.sdr = new SDRRenditionNode(input, options);
|
|
980
|
+
this.gainMap = new GainMapEncoderNode(this.sdr, options);
|
|
981
|
+
}
|
|
982
|
+
/** Width of the encoded images */
|
|
983
|
+
get width() { return this.sdr.width; }
|
|
984
|
+
/** Height of the encoded images */
|
|
985
|
+
get height() { return this.sdr.height; }
|
|
986
|
+
/**
|
|
987
|
+
* The gain map metadata matching the current parameters
|
|
988
|
+
*/
|
|
989
|
+
get metadata() {
|
|
990
|
+
return this.gainMap.metadata;
|
|
991
|
+
}
|
|
992
|
+
/**
|
|
993
|
+
* Finds the max value of the HDR image and uses it as `maxContentBoost`,
|
|
994
|
+
* so the full HDR range is encoded.
|
|
995
|
+
*
|
|
996
|
+
* @param renderer
|
|
997
|
+
* @returns the new `maxContentBoost`
|
|
998
|
+
*/
|
|
999
|
+
async fitMaxContentBoost(renderer) {
|
|
1000
|
+
const max = Math.max(...await findTextureMinMax(this.sdr.hdr, 'max', renderer, this));
|
|
1001
|
+
this.gainMap.maxContentBoost.value = max;
|
|
1002
|
+
return max;
|
|
1003
|
+
}
|
|
1004
|
+
/**
|
|
1005
|
+
* Creates a {@link GainMapNode} decoding the encoded result on the fly,
|
|
1006
|
+
* it follows any change to the encoding parameters.
|
|
1007
|
+
* Its `maxDisplayBoost` is initialized to restore the full HDR range, and is not changed afterwards.
|
|
1008
|
+
*/
|
|
1009
|
+
createPreviewNode() {
|
|
1010
|
+
return new EncoderPreviewNode(this);
|
|
1011
|
+
}
|
|
1012
|
+
/**
|
|
1013
|
+
* Renders the SDR rendition and the gain map, only if something changed since the last render
|
|
1014
|
+
*
|
|
1015
|
+
* @param renderer
|
|
1016
|
+
*/
|
|
1017
|
+
render(renderer) {
|
|
1018
|
+
// renders the SDR rendition first
|
|
1019
|
+
this.gainMap.render(renderer);
|
|
1020
|
+
}
|
|
1021
|
+
/**
|
|
1022
|
+
* Renders (if needed) and reads back the raw SDR rendition and gain map
|
|
1023
|
+
*
|
|
1024
|
+
* @param renderer
|
|
1025
|
+
*/
|
|
1026
|
+
async read(renderer) {
|
|
1027
|
+
this.render(renderer);
|
|
1028
|
+
const metadata = this.metadata;
|
|
1029
|
+
const [sdr, gainMap] = await Promise.all([
|
|
1030
|
+
readRenderTargetPixels(renderer, this.sdr.renderTarget),
|
|
1031
|
+
readRenderTargetPixels(renderer, this.gainMap.renderTarget)
|
|
1032
|
+
]);
|
|
1033
|
+
return {
|
|
1034
|
+
sdr: new ImageData(new Uint8ClampedArray(sdr), this.width, this.height),
|
|
1035
|
+
gainMap: new ImageData(new Uint8ClampedArray(gainMap), this.width, this.height),
|
|
1036
|
+
metadata
|
|
1037
|
+
};
|
|
1038
|
+
}
|
|
1039
|
+
/**
|
|
1040
|
+
* Renders (if needed), reads back and compresses the SDR rendition and gain map
|
|
1041
|
+
*
|
|
1042
|
+
* @param renderer
|
|
1043
|
+
* @param options compression options, `flipY` is not needed
|
|
1044
|
+
* @throws {Error} if the browser does not support [createImageBitmap](https://caniuse.com/createimagebitmap)
|
|
1045
|
+
*/
|
|
1046
|
+
async compress(renderer, options) {
|
|
1047
|
+
const { sdr, gainMap, metadata } = await this.read(renderer);
|
|
1048
|
+
const { withWorker, ...compressOptions } = options;
|
|
1049
|
+
if (withWorker) {
|
|
1050
|
+
const [compressedSDR, compressedGainMap] = await Promise.all([
|
|
1051
|
+
withWorker.compress({ ...compressOptions, source: sdr }),
|
|
1052
|
+
withWorker.compress({ ...compressOptions, source: gainMap })
|
|
1053
|
+
]);
|
|
1054
|
+
return { ...metadata, sdr: compressedSDR, gainMap: compressedGainMap, rawSDR: compressedSDR.source, rawGainMap: compressedGainMap.source };
|
|
1055
|
+
}
|
|
1056
|
+
const [compressedSDR, compressedGainMap] = await Promise.all([
|
|
1057
|
+
compress({ ...compressOptions, source: sdr }),
|
|
1058
|
+
compress({ ...compressOptions, source: gainMap })
|
|
1059
|
+
]);
|
|
1060
|
+
return { ...metadata, sdr: compressedSDR, gainMap: compressedGainMap, rawSDR: sdr.data, rawGainMap: gainMap.data };
|
|
1061
|
+
}
|
|
1062
|
+
/**
|
|
1063
|
+
* Disposes the nodes, and the HDR texture if it was created by the encoder from raw data
|
|
1064
|
+
*/
|
|
1065
|
+
dispose() {
|
|
1066
|
+
this.sdr.dispose();
|
|
1067
|
+
this.gainMap.dispose();
|
|
1068
|
+
this._ownedTexture?.dispose();
|
|
1069
|
+
}
|
|
1070
|
+
}
|
|
1071
|
+
|
|
1072
|
+
exports.GainMapEncoder = GainMapEncoder;
|
|
1073
|
+
exports.GainMapEncoderNode = GainMapEncoderNode;
|
|
1074
|
+
exports.RenderTargetNode = RenderTargetNode;
|
|
1075
|
+
exports.SDRRenditionNode = SDRRenditionNode;
|
|
1076
|
+
exports.compress = compress;
|
|
1077
|
+
exports.findTextureMinMax = findTextureMinMax;
|
|
1078
|
+
exports.gainMapEncoder = gainMapEncoder;
|
|
1079
|
+
exports.sdrRendition = sdrRendition;
|
|
1080
|
+
|
|
1081
|
+
}));
|