@monogrid/gainmap-js 3.6.1 → 3.7.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.
Files changed (60) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +86 -13
  3. package/dist/GainMapNode-Cz4_NIGH.js +5 -0
  4. package/dist/GainMapNode-Dl8yqSVg.js +342 -0
  5. package/dist/{warn-deprecated-DtCQWGKi.js → Loader-BNe3xn0l.js} +3 -19
  6. package/dist/{warn-deprecated-gLZfP_DV.js → Loader-DcZ7MyM7.js} +2 -2
  7. package/dist/{QuadRenderer-DMno-Vj6.js → QuadRenderer-BOS9Aas1.js} +1 -1
  8. package/dist/{QuadRenderer-Bhn3yOPC.js → QuadRenderer-BqD-oQ7D.js} +1 -1
  9. package/dist/{_commonjsHelpers-DFuDJEaJ.js → _commonjsHelpers-DrNnMDE-.js} +1 -1
  10. package/dist/{_commonjsHelpers-C8qmDUO8.js → _commonjsHelpers-pGJUN9hi.js} +1 -1
  11. package/dist/{compress-oIjJuPa8.js → compress-DA31yhmz.js} +1 -1
  12. package/dist/{compress-TBp7MS8D.js → compress-goZ8TdVo.js} +1 -1
  13. package/dist/core/webgpu/RenderTargetNode.d.ts +83 -0
  14. package/dist/decode/shared/utils/warn-deprecated.d.ts +1 -1
  15. package/dist/decode/webgl/decode.d.ts +0 -1
  16. package/dist/decode/webgl/index.d.ts +0 -1
  17. package/dist/decode/webgl/loaders/GainMapLoader.d.ts +1 -3
  18. package/dist/decode/webgl/loaders/HDRJPGLoader.d.ts +1 -3
  19. package/dist/decode/webgl/materials/GainMapDecoderMaterial.d.ts +0 -1
  20. package/dist/decode/webgpu/index.d.ts +1 -0
  21. package/dist/decode/webgpu/nodes/GainMapNode.d.ts +13 -19
  22. package/dist/decode.js +5 -18
  23. package/dist/decode.min.js +2 -2
  24. package/dist/decode.umd.cjs +1 -30
  25. package/dist/decode.umd.min.cjs +2 -2
  26. package/dist/decode.webgpu.js +27 -232
  27. package/dist/decode.webgpu.min.js +2 -2
  28. package/dist/decode.webgpu.umd.cjs +176 -65
  29. package/dist/decode.webgpu.umd.min.cjs +2 -2
  30. package/dist/encode/webgpu/GainMapEncoder.d.ts +142 -0
  31. package/dist/encode/webgpu/find-texture-min-max.d.ts +27 -0
  32. package/dist/encode/webgpu/index.d.ts +8 -0
  33. package/dist/encode/webgpu/nodes/GainMapEncoderNode.d.ts +92 -0
  34. package/dist/encode/webgpu/nodes/SDRRenditionNode.d.ts +120 -0
  35. package/dist/encode/webgpu/read-render-target-pixels.d.ts +11 -0
  36. package/dist/encode.js +5 -36
  37. package/dist/encode.min.js +2 -2
  38. package/dist/encode.umd.cjs +1 -1
  39. package/dist/encode.umd.min.cjs +1 -1
  40. package/dist/encode.webgpu.js +636 -0
  41. package/dist/encode.webgpu.min.js +5 -0
  42. package/dist/encode.webgpu.umd.cjs +1086 -0
  43. package/dist/encode.webgpu.umd.min.cjs +5 -0
  44. package/dist/get-data-texture-CpszSMzv.js +40 -0
  45. package/dist/get-data-texture-Dlg6zKSG.js +5 -0
  46. package/dist/{iso-gainmap-metadata-C1io5isX.js → iso-gainmap-metadata-BwLnWVQ-.js} +1 -1
  47. package/dist/{iso-gainmap-metadata-Oi7gAKNC.js → iso-gainmap-metadata-CuDCCi9d.js} +1 -1
  48. package/dist/libultrahdr.js +2 -2
  49. package/dist/libultrahdr.min.js +2 -2
  50. package/dist/libultrahdr.umd.cjs +1 -1
  51. package/dist/libultrahdr.umd.min.cjs +1 -1
  52. package/dist/worker-interface.js +2 -2
  53. package/dist/worker-interface.min.js +2 -2
  54. package/dist/worker-interface.umd.cjs +1 -1
  55. package/dist/worker-interface.umd.min.cjs +1 -1
  56. package/dist/worker.js +3 -3
  57. package/dist/worker.min.js +2 -2
  58. package/dist/worker.umd.cjs +1 -1
  59. package/dist/worker.umd.min.cjs +1 -1
  60. package/package.json +9 -1
@@ -0,0 +1,636 @@
1
+ /**
2
+ * @monogrid/gainmap-js v3.7.1
3
+ * With ❤️, by MONOGRID <gainmap@monogrid.com>
4
+ */
5
+
6
+ import { R as RenderTargetNode, G as GainMapNode } from './GainMapNode-Dl8yqSVg.js';
7
+ import { c as compress } from './compress-DA31yhmz.js';
8
+ import { vec4, uniform, textureLoad, Fn, screenCoordinate, float, ivec2, min, vec2, max, texture, log2, saturate, pow, toneMapping, mat4, vec3 } from 'three/tsl';
9
+ import { RendererUtils, QuadMesh, NodeMaterial, Texture, Vector2, RenderTarget, NearestFilter, FloatType, NoBlending, LinearFilter, LinearSRGBColorSpace, UnsignedByteType, Vector3, ACESFilmicToneMapping, SRGBColorSpace, TextureNode } from 'three/webgpu';
10
+ import { g as getDataTexture } from './get-data-texture-CpszSMzv.js';
11
+ import 'three';
12
+
13
+ /**
14
+ * Reads the pixels of a render target, rows are returned top to bottom
15
+ * (like `ImageData`, regardless of the backend) and tightly packed
16
+ * (WebGPU pads each row to 256 bytes).
17
+ *
18
+ * @internal
19
+ * @param renderer
20
+ * @param renderTarget
21
+ */
22
+ const readRenderTargetPixels = async (renderer, renderTarget) => {
23
+ const { width, height } = renderTarget;
24
+ const data = await renderer.readRenderTargetPixelsAsync(renderTarget, 0, 0, width, height);
25
+ const rowLength = width * 4;
26
+ const rowStride = height > 1 ? (data.length - rowLength) / (height - 1) : rowLength;
27
+ // the WebGPU backend reads rows bottom to top (render targets are sampled with flipped uvs),
28
+ // the WebGL backend top to bottom
29
+ const flip = renderer.backend.isWebGLBackend !== true;
30
+ if (rowStride === rowLength && !flip)
31
+ return data.length === rowLength * height ? data : data.subarray(0, rowLength * height);
32
+ const out = new data.constructor(rowLength * height);
33
+ for (let y = 0; y < height; y++) {
34
+ const sourceRow = flip ? height - 1 - y : y;
35
+ out.set(data.subarray(sourceRow * rowStride, sourceRow * rowStride + rowLength), y * rowLength);
36
+ }
37
+ return out;
38
+ };
39
+
40
+ // max half float value
41
+ const HALF_FLOAT_MAX = 65504;
42
+ const CELL_SIZE = 2;
43
+ const isTextureData = (image) => typeof image === 'object' && image !== null && 'data' in image && 'width' in image && 'height' in image && !(image instanceof Texture);
44
+ /**
45
+ * Finds the min or max value of each RGB channel of an HDR image, on the GPU.
46
+ *
47
+ * The image is reduced by 2x2 cells until it's 1x1, then the single remaining pixel is read back.
48
+ * Negative values are ignored when looking for the max, values above 65504 (max half float) when looking for the min.
49
+ *
50
+ * @category Utility
51
+ * @group Utility
52
+ *
53
+ * @example
54
+ * import { findTextureMinMax } from '@monogrid/gainmap-js/encode/webgpu'
55
+ *
56
+ * const [r, g, b] = await findTextureMinMax(exrTexture, 'max', renderer)
57
+ * const maxContentBoost = Math.max(r, g, b)
58
+ *
59
+ * @param image the HDR image: a texture, raw texture data or a TSL node (which requires `size`)
60
+ * @param mode
61
+ * @param renderer
62
+ * @param size size of the image, required when the image is a generic node
63
+ * @throws {Error} if the image is a generic node and `size` is not provided
64
+ */
65
+ const findTextureMinMax = async (image, mode, renderer, size) => {
66
+ const rendererState = RendererUtils.resetRendererState(renderer, {});
67
+ const renderTargets = [];
68
+ const quad = new QuadMesh(new NodeMaterial());
69
+ const createRenderTarget = (width, height) => {
70
+ const renderTarget = new RenderTarget(width, height, {
71
+ type: FloatType,
72
+ minFilter: NearestFilter,
73
+ magFilter: NearestFilter,
74
+ generateMipmaps: false,
75
+ depthBuffer: false
76
+ });
77
+ renderTargets.push(renderTarget);
78
+ return renderTarget;
79
+ };
80
+ const renderQuad = (material, renderTarget) => {
81
+ material.blending = NoBlending;
82
+ material.depthTest = false;
83
+ material.depthWrite = false;
84
+ quad.material = material;
85
+ renderer.setRenderTarget(renderTarget);
86
+ quad.render(renderer);
87
+ };
88
+ try {
89
+ let source;
90
+ let width;
91
+ let height;
92
+ if (image instanceof Texture || isTextureData(image)) {
93
+ source = image instanceof Texture ? image : getDataTexture(image);
94
+ const sourceImage = source.image;
95
+ width = sourceImage.width;
96
+ height = sourceImage.height;
97
+ }
98
+ else {
99
+ // generic nodes are rendered at full resolution first
100
+ if (!size)
101
+ throw new Error('findTextureMinMax: size is required when the image is a node');
102
+ width = size.width;
103
+ height = size.height;
104
+ const material = new NodeMaterial();
105
+ material.fragmentNode = vec4(image);
106
+ const renderTarget = createRenderTarget(width, height);
107
+ renderQuad(material, renderTarget);
108
+ material.dispose();
109
+ source = renderTarget.texture;
110
+ }
111
+ // creates a material reducing 2x2 cells of a texture into 1 pixel
112
+ const createReduceMaterial = (texture, width, height) => {
113
+ const sourceSize = uniform(new Vector2(width, height));
114
+ const sourceTexture = textureLoad(texture);
115
+ const reduce = Fn(() => {
116
+ // the first pixel of the source cell
117
+ const sourcePixel = screenCoordinate.xy.floor().mul(CELL_SIZE);
118
+ const last = sourceSize.sub(1);
119
+ const result = vec4(float(mode === 'max' ? 0 : HALF_FLOAT_MAX)).toVar();
120
+ for (let y = 0; y < CELL_SIZE; y++) {
121
+ for (let x = 0; x < CELL_SIZE; x++) {
122
+ // pixels outside the source repeat the edge ones
123
+ const texel = sourceTexture.load(ivec2(min(sourcePixel.add(vec2(x, y)), last)));
124
+ result.assign(mode === 'max' ? max(result, texel) : min(result, texel));
125
+ }
126
+ }
127
+ return result;
128
+ });
129
+ const material = new NodeMaterial();
130
+ material.fragmentNode = reduce();
131
+ return { material, sourceTexture, sourceSize };
132
+ };
133
+ // the source may have a different format from the intermediate (float) render targets,
134
+ // it is reduced by its own material
135
+ let reducer = createReduceMaterial(source, width, height);
136
+ let renderTarget;
137
+ while (width > 1 || height > 1 || !renderTarget) {
138
+ width = Math.max(1, Math.ceil(width / CELL_SIZE));
139
+ height = Math.max(1, Math.ceil(height / CELL_SIZE));
140
+ const sourceRenderTarget = renderTarget;
141
+ renderTarget = createRenderTarget(width, height);
142
+ if (sourceRenderTarget) {
143
+ if (reducer.sourceTexture.value === source) {
144
+ reducer.material.dispose();
145
+ reducer = createReduceMaterial(sourceRenderTarget.texture, sourceRenderTarget.width, sourceRenderTarget.height);
146
+ }
147
+ else {
148
+ reducer.sourceTexture.value = sourceRenderTarget.texture;
149
+ reducer.sourceSize.value.set(sourceRenderTarget.width, sourceRenderTarget.height);
150
+ }
151
+ }
152
+ renderQuad(reducer.material, renderTarget);
153
+ }
154
+ reducer.material.dispose();
155
+ const out = await readRenderTargetPixels(renderer, renderTarget);
156
+ return [out[0], out[1], out[2]];
157
+ }
158
+ finally {
159
+ RendererUtils.restoreRendererState(renderer, rendererState);
160
+ renderTargets.forEach(renderTarget => renderTarget.dispose());
161
+ }
162
+ };
163
+
164
+ // maxContentBoost must be > 1, a gain map can't encode an empty boost range
165
+ const MIN_MAX_CONTENT_BOOST = 1.0001;
166
+ /**
167
+ * A TSL texture node holding the gain map (recovery map) of an HDR image: the second step of gain map encoding.
168
+ *
169
+ * The gain map is computed from the HDR input of a {@link SDRRenditionNode} and its SDR rendition,
170
+ * into an 8 bit linear render target. The result is identical to the one of the WebGL `GainMapEncoderMaterial`.
171
+ *
172
+ * It renders only when something changed (the SDR rendition or any uniform value),
173
+ * the SDR rendition is rendered first when needed.
174
+ *
175
+ * @category Nodes
176
+ * @group Nodes
177
+ *
178
+ * @example
179
+ * import { GainMapEncoderNode, SDRRenditionNode } from '@monogrid/gainmap-js/encode/webgpu'
180
+ *
181
+ * const sdr = new SDRRenditionNode(hdrTexture)
182
+ * const gainMap = new GainMapEncoderNode(sdr, { maxContentBoost: 8 })
183
+ *
184
+ * material.colorNode = gainMap
185
+ * gainMap.gamma.value.setScalar(1.2) // renders again once, on the next frame
186
+ * const metadata = gainMap.metadata
187
+ */
188
+ class GainMapEncoderNode extends RenderTargetNode {
189
+ static get type() { return 'GainMapEncoderNode'; }
190
+ /**
191
+ * The SDR rendition this gain map is computed from
192
+ */
193
+ sdr;
194
+ /**
195
+ * Shared uniforms
196
+ */
197
+ uniforms;
198
+ _warned = [];
199
+ /**
200
+ * @param sdr the SDR rendition, its HDR input is the HDR input of the gain map
201
+ * @param params encoding parameters, all of them can be changed later through the uniforms
202
+ */
203
+ constructor(sdr, params = {}) {
204
+ super(new NodeMaterial(), {
205
+ type: UnsignedByteType,
206
+ colorSpace: LinearSRGBColorSpace,
207
+ minFilter: LinearFilter,
208
+ magFilter: LinearFilter
209
+ });
210
+ this.sdr = sdr;
211
+ const u = this.uniforms = {
212
+ gamma: uniform(new Vector3().fromArray(params.gamma ?? [1, 1, 1])),
213
+ offsetSdr: uniform(new Vector3().fromArray(params.offsetSdr ?? [1 / 64, 1 / 64, 1 / 64])),
214
+ offsetHdr: uniform(new Vector3().fromArray(params.offsetHdr ?? [1 / 64, 1 / 64, 1 / 64])),
215
+ // 0 is not a valid min content boost
216
+ minContentBoost: uniform(params.minContentBoost || 1),
217
+ maxContentBoost: uniform(params.maxContentBoost ?? MIN_MAX_CONTENT_BOOST)
218
+ };
219
+ // logarithms are computed on the CPU (in double precision), like the WebGL encoder does
220
+ const minLog2 = uniform(0).onRenderUpdate(() => Math.log2(this.metadataMinContentBoost));
221
+ const maxLog2 = uniform(0).onRenderUpdate(() => Math.log2(this.metadataMaxContentBoost));
222
+ const sdrColor = texture(sdr.value).rgb;
223
+ const hdrColor = vec4(sdr.hdr).rgb;
224
+ const pixelGain = hdrColor.add(u.offsetHdr).div(sdrColor.add(u.offsetSdr));
225
+ const logRecovery = log2(pixelGain).sub(minLog2).div(maxLog2.sub(minLog2));
226
+ const clampedRecovery = saturate(logRecovery);
227
+ this._material.name = 'GainMapEncoder';
228
+ this._material.blending = NoBlending;
229
+ this._material.depthTest = false;
230
+ this._material.depthWrite = false;
231
+ this._material.fragmentNode = vec4(pow(clampedRecovery, u.gamma), 1.0);
232
+ }
233
+ /** @see {@link GainmapEncodingParameters.gamma} */
234
+ get gamma() { return this.uniforms.gamma; }
235
+ /** @see {@link GainmapEncodingParameters.offsetSdr} */
236
+ get offsetSdr() { return this.uniforms.offsetSdr; }
237
+ /** @see {@link GainmapEncodingParameters.offsetHdr} */
238
+ get offsetHdr() { return this.uniforms.offsetHdr; }
239
+ /**
240
+ * @see {@link GainmapEncodingParameters.minContentBoost}
241
+ * @remarks Non logarithmic space
242
+ */
243
+ get minContentBoost() { return this.uniforms.minContentBoost; }
244
+ /**
245
+ * @see {@link GainmapEncodingParameters.maxContentBoost}
246
+ * @remarks Non logarithmic space, values <= 1 are clamped to 1.0001 since a gain map can't encode an empty boost range
247
+ */
248
+ get maxContentBoost() { return this.uniforms.maxContentBoost; }
249
+ /** Same size as the SDR rendition */
250
+ get width() { return this.sdr.width; }
251
+ /** Same size as the SDR rendition */
252
+ get height() { return this.sdr.height; }
253
+ /** The min content boost actually encoded */
254
+ get metadataMinContentBoost() { return this.uniforms.minContentBoost.value; }
255
+ /** The max content boost actually encoded, clamped to a valid range */
256
+ get metadataMaxContentBoost() { return Math.max(this.uniforms.maxContentBoost.value, MIN_MAX_CONTENT_BOOST); }
257
+ /**
258
+ * The gain map metadata matching the current uniform values
259
+ */
260
+ get metadata() {
261
+ const u = this.uniforms;
262
+ const gainMapMin = Math.log2(this.metadataMinContentBoost);
263
+ const gainMapMax = Math.log2(this.metadataMaxContentBoost);
264
+ return {
265
+ gamma: u.gamma.value.toArray(),
266
+ offsetSdr: u.offsetSdr.value.toArray(),
267
+ offsetHdr: u.offsetHdr.value.toArray(),
268
+ gainMapMin: [gainMapMin, gainMapMin, gainMapMin],
269
+ gainMapMax: [gainMapMax, gainMapMax, gainMapMax],
270
+ hdrCapacityMin: Math.max(0, gainMapMin),
271
+ hdrCapacityMax: Math.max(0, gainMapMax)
272
+ };
273
+ }
274
+ _getState() {
275
+ const u = this.uniforms;
276
+ return [
277
+ ...u.gamma.value.toArray(), ...u.offsetSdr.value.toArray(), ...u.offsetHdr.value.toArray(),
278
+ u.minContentBoost.value, u.maxContentBoost.value
279
+ ];
280
+ }
281
+ _getDependencies() {
282
+ return [this.sdr];
283
+ }
284
+ _onRender() {
285
+ // warn once per invalid combination of parameters
286
+ const { minContentBoost, maxContentBoost } = this.uniforms;
287
+ const state = [minContentBoost.value, maxContentBoost.value];
288
+ if (state.every((v, i) => v === this._warned[i]))
289
+ return;
290
+ this._warned = state;
291
+ if (maxContentBoost.value <= 1) {
292
+ 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.`);
293
+ }
294
+ if (this.metadataMinContentBoost >= this.metadataMaxContentBoost) {
295
+ console.warn(`gainmap-js: minContentBoost (${this.metadataMinContentBoost}) must be lower than maxContentBoost (${this.metadataMaxContentBoost}), the resulting gain map will be invalid.`);
296
+ }
297
+ }
298
+ }
299
+ /**
300
+ * TSL function creating a {@link GainMapEncoderNode}
301
+ *
302
+ * @param sdr the SDR rendition, its HDR input is the HDR input of the gain map
303
+ * @param params encoding parameters
304
+ */
305
+ const gainMapEncoder = (sdr, params) => new GainMapEncoderNode(sdr, params);
306
+
307
+ const textureSize = (texture) => {
308
+ const image = texture.image;
309
+ return { width: image?.width ?? 0, height: image?.height ?? 0 };
310
+ };
311
+ /**
312
+ * A TSL texture node holding the SDR rendition of an HDR image: the first step of gain map encoding.
313
+ *
314
+ * The HDR input is exposed, tone mapped (with the three.js TSL tone mapping functions)
315
+ * and adjusted (brightness, contrast, saturation) into an 8 bit sRGB render target.
316
+ *
317
+ * It renders only when something changed (input, tone mapping or any uniform value):
318
+ * sampling the node costs a single texture read, like any other texture.
319
+ *
320
+ * @category Nodes
321
+ * @group Nodes
322
+ *
323
+ * @example
324
+ * import { SDRRenditionNode } from '@monogrid/gainmap-js/encode/webgpu'
325
+ * import { AgXToneMapping, LinearToneMapping } from 'three/webgpu'
326
+ *
327
+ * const sdr = new SDRRenditionNode(hdrTexture, { toneMapping: AgXToneMapping })
328
+ * material.colorNode = sdr
329
+ * sdr.exposure.value = 0.8 // renders again once, on the next frame
330
+ * sdr.setToneMapping(LinearToneMapping)
331
+ */
332
+ class SDRRenditionNode extends RenderTargetNode {
333
+ static get type() { return 'SDRRenditionNode'; }
334
+ /**
335
+ * The HDR input, as a node
336
+ */
337
+ hdr;
338
+ /**
339
+ * Shared uniforms
340
+ */
341
+ uniforms;
342
+ _hdrTexture;
343
+ _hdrSource;
344
+ _width;
345
+ _height;
346
+ _toneMapping = ACESFilmicToneMapping;
347
+ /**
348
+ * @param hdr HDR input, a texture or a TSL node returning a linear HDR color
349
+ * @param options
350
+ * @throws {Error} if the input is a generic node and `width` or `height` are not provided
351
+ */
352
+ constructor(hdr, options = {}) {
353
+ super(new NodeMaterial(), {
354
+ type: UnsignedByteType,
355
+ colorSpace: SRGBColorSpace,
356
+ minFilter: LinearFilter,
357
+ magFilter: LinearFilter
358
+ });
359
+ this._hdrTexture = hdr instanceof Texture ? hdr : hdr instanceof TextureNode ? hdr.value : null;
360
+ this._hdrSource = hdr instanceof RenderTargetNode ? hdr : null;
361
+ this.hdr = hdr instanceof Texture ? texture(hdr) : hdr;
362
+ this._width = options.width;
363
+ this._height = options.height;
364
+ if (!this._hdrTexture && (!this._width || !this._height)) {
365
+ throw new Error('SDRRenditionNode: width and height are required when the HDR input is not a texture');
366
+ }
367
+ this.uniforms = {
368
+ exposure: uniform(1),
369
+ brightness: uniform(0),
370
+ contrast: uniform(1),
371
+ saturation: uniform(1)
372
+ };
373
+ this._material.name = 'SDRRendition';
374
+ this._material.blending = NoBlending;
375
+ this._material.depthTest = false;
376
+ this._material.depthWrite = false;
377
+ this.setToneMapping(options.toneMapping ?? ACESFilmicToneMapping);
378
+ }
379
+ /** Exposure applied to the HDR input before tone mapping */
380
+ get exposure() { return this.uniforms.exposure; }
381
+ /** Brightness offset applied after tone mapping */
382
+ get brightness() { return this.uniforms.brightness; }
383
+ /** Contrast applied after tone mapping */
384
+ get contrast() { return this.uniforms.contrast; }
385
+ /** Saturation applied after tone mapping */
386
+ get saturation() { return this.uniforms.saturation; }
387
+ /**
388
+ * The tone mapping applied to the SDR rendition
389
+ */
390
+ getToneMapping() { return this._toneMapping; }
391
+ /**
392
+ * Sets the tone mapping applied to the SDR rendition
393
+ * (`toneMapping` can't be used as a property name: it's a TSL method of every node)
394
+ *
395
+ * @param value any three.js tone mapping, e.g. `ACESFilmicToneMapping`, `AgXToneMapping`, `NeutralToneMapping`
396
+ * or `LinearToneMapping` (which keeps the SDR rendition closest to the HDR input)
397
+ */
398
+ setToneMapping(value) {
399
+ this._toneMapping = value;
400
+ this._material.fragmentNode = this._buildOutput();
401
+ this._material.needsUpdate = true;
402
+ return this;
403
+ }
404
+ /** Width of the output, 0 while the input texture is not loaded */
405
+ get width() {
406
+ if (this._width)
407
+ return this._width;
408
+ if (this._hdrSource)
409
+ return this._hdrSource.width;
410
+ return this._hdrTexture ? textureSize(this._hdrTexture).width : 0;
411
+ }
412
+ /** Height of the output, 0 while the input texture is not loaded */
413
+ get height() {
414
+ if (this._height)
415
+ return this._height;
416
+ if (this._hdrSource)
417
+ return this._hdrSource.height;
418
+ return this._hdrTexture ? textureSize(this._hdrTexture).height : 0;
419
+ }
420
+ _buildOutput() {
421
+ const u = this.uniforms;
422
+ const color = vec4(this.hdr);
423
+ // exposure is applied here rather than by the tone mapping function, so it works with `NoToneMapping` too
424
+ // `.rgb` because ToneMappingNode declares a vec3 but its setup returns a vec4 (colour + alpha) when a tone mapping is set
425
+ const toneMapped = vec4(toneMapping(this._toneMapping, float(1), color.rgb.mul(u.exposure)).rgb, color.a);
426
+ const b = u.brightness;
427
+ const brightnessMatrix = mat4(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, b, b, b, 1);
428
+ const c = u.contrast;
429
+ const t = float(1.0).sub(c).div(2.0);
430
+ const contrastMatrix = mat4(c, 0, 0, 0, 0, c, 0, 0, 0, 0, c, 0, t, t, t, 1);
431
+ const luminance = vec3(0.3086, 0.6094, 0.0820);
432
+ const oneMinusSat = float(1.0).sub(u.saturation);
433
+ const red = vec3(luminance.x.mul(oneMinusSat)).add(vec3(u.saturation, 0, 0));
434
+ const green = vec3(luminance.y.mul(oneMinusSat)).add(vec3(0, u.saturation, 0));
435
+ const blue = vec3(luminance.z.mul(oneMinusSat)).add(vec3(0, 0, u.saturation));
436
+ const saturationMatrix = mat4(vec4(red, 0), vec4(green, 0), vec4(blue, 0), vec4(0, 0, 0, 1));
437
+ return brightnessMatrix.mul(contrastMatrix).mul(saturationMatrix).mul(toneMapped);
438
+ }
439
+ _getState() {
440
+ const u = this.uniforms;
441
+ return [
442
+ this._hdrTexture?.id, this._hdrTexture?.version, this._toneMapping,
443
+ u.exposure.value, u.brightness.value, u.contrast.value, u.saturation.value
444
+ ];
445
+ }
446
+ _getDependencies() {
447
+ return this._hdrSource ? [this._hdrSource] : [];
448
+ }
449
+ }
450
+ /**
451
+ * TSL function creating a {@link SDRRenditionNode}
452
+ *
453
+ * @param hdr HDR input, a texture or a TSL node returning a linear HDR color
454
+ * @param options
455
+ */
456
+ const sdrRendition = (hdr, options) => new SDRRenditionNode(hdr, options);
457
+
458
+ /**
459
+ * A gain map preview: a {@link GainMapNode} decoding the encoder output, following its metadata
460
+ */
461
+ class EncoderPreviewNode extends GainMapNode {
462
+ _encoder;
463
+ constructor(encoder) {
464
+ super();
465
+ this._encoder = encoder;
466
+ this.setTextures(encoder.sdr, encoder.gainMap).setMetadata(encoder.metadata);
467
+ }
468
+ _getState() {
469
+ // follow the encoder metadata, except the display boost which belongs to the viewer
470
+ const { gamma, offsetSdr, offsetHdr, gainMapMin, gainMapMax, hdrCapacityMin, hdrCapacityMax } = this._encoder.metadata;
471
+ const u = this.uniforms;
472
+ u.gamma.value.fromArray(gamma);
473
+ u.offsetSdr.value.fromArray(offsetSdr);
474
+ u.offsetHdr.value.fromArray(offsetHdr);
475
+ u.gainMapMin.value.fromArray(gainMapMin);
476
+ u.gainMapMax.value.fromArray(gainMapMax);
477
+ u.hdrCapacityMin.value = hdrCapacityMin;
478
+ u.hdrCapacityMax.value = hdrCapacityMax;
479
+ return super._getState();
480
+ }
481
+ }
482
+ /**
483
+ * Encodes an HDR image into an SDR rendition + a gain map, on the GPU, with TSL nodes.
484
+ *
485
+ * {@link GainMapEncoder.sdr} and {@link GainMapEncoder.gainMap} are live texture nodes:
486
+ * every encoding parameter is a uniform, changing one re-renders the affected nodes once, when they're next used.
487
+ * No renderer is needed until the result is read back with {@link GainMapEncoder.read} or {@link GainMapEncoder.compress}.
488
+ *
489
+ * Read back images are oriented top to bottom (like `ImageData`), no `flipY` is needed when compressing them.
490
+ *
491
+ * @category Encoding Functions
492
+ * @group Encoding Functions
493
+ *
494
+ * @example
495
+ * import { GainMapEncoder } from '@monogrid/gainmap-js/encode/webgpu'
496
+ * import { encodeJPEGMetadata } from '@monogrid/gainmap-js/libultrahdr'
497
+ * import { EXRLoader } from 'three/examples/jsm/loaders/EXRLoader.js'
498
+ * import { AgXToneMapping, MeshBasicNodeMaterial, WebGPURenderer } from 'three/webgpu'
499
+ *
500
+ * const renderer = new WebGPURenderer()
501
+ * await renderer.init()
502
+ *
503
+ * const image = await new EXRLoader().loadAsync('image.exr')
504
+ * const encoder = new GainMapEncoder(image, { toneMapping: AgXToneMapping })
505
+ * // encode the full HDR range
506
+ * await encoder.fitMaxContentBoost(renderer)
507
+ *
508
+ * // live previews, they follow any parameter change
509
+ * sdrMaterial.colorNode = encoder.sdr
510
+ * gainMapMaterial.colorNode = encoder.gainMap
511
+ * hdrMaterial.colorNode = encoder.createPreviewNode() // decodes the encoded result
512
+ *
513
+ * encoder.sdr.exposure.value = 0.9
514
+ * encoder.gainMap.gamma.value.setScalar(1.1)
515
+ *
516
+ * // compress and embed into a single JPEG file
517
+ * const result = await encoder.compress(renderer, { mimeType: 'image/jpeg', quality: 0.9 })
518
+ * const jpeg = encodeJPEGMetadata(result)
519
+ */
520
+ class GainMapEncoder {
521
+ /**
522
+ * The SDR rendition node
523
+ */
524
+ sdr;
525
+ /**
526
+ * The gain map node
527
+ */
528
+ gainMap;
529
+ _ownedTexture;
530
+ /**
531
+ * @param image the HDR image: a texture, raw texture data (e.g. from a worker) or a TSL node (which requires `width` and `height`)
532
+ * @param options encoding parameters, all of them can be changed later through the node uniforms
533
+ */
534
+ constructor(image, options = {}) {
535
+ let input;
536
+ if (image instanceof Texture || !('data' in image)) {
537
+ input = image;
538
+ this._ownedTexture = null;
539
+ }
540
+ else {
541
+ input = this._ownedTexture = getDataTexture(image);
542
+ }
543
+ this.sdr = new SDRRenditionNode(input, options);
544
+ this.gainMap = new GainMapEncoderNode(this.sdr, options);
545
+ }
546
+ /** Width of the encoded images */
547
+ get width() { return this.sdr.width; }
548
+ /** Height of the encoded images */
549
+ get height() { return this.sdr.height; }
550
+ /**
551
+ * The gain map metadata matching the current parameters
552
+ */
553
+ get metadata() {
554
+ return this.gainMap.metadata;
555
+ }
556
+ /**
557
+ * Finds the max value of the HDR image and uses it as `maxContentBoost`,
558
+ * so the full HDR range is encoded.
559
+ *
560
+ * @param renderer
561
+ * @returns the new `maxContentBoost`
562
+ */
563
+ async fitMaxContentBoost(renderer) {
564
+ const max = Math.max(...await findTextureMinMax(this.sdr.hdr, 'max', renderer, this));
565
+ this.gainMap.maxContentBoost.value = max;
566
+ return max;
567
+ }
568
+ /**
569
+ * Creates a {@link GainMapNode} decoding the encoded result on the fly,
570
+ * it follows any change to the encoding parameters.
571
+ * Its `maxDisplayBoost` is initialized to restore the full HDR range, and is not changed afterwards.
572
+ */
573
+ createPreviewNode() {
574
+ return new EncoderPreviewNode(this);
575
+ }
576
+ /**
577
+ * Renders the SDR rendition and the gain map, only if something changed since the last render
578
+ *
579
+ * @param renderer
580
+ */
581
+ render(renderer) {
582
+ // renders the SDR rendition first
583
+ this.gainMap.render(renderer);
584
+ }
585
+ /**
586
+ * Renders (if needed) and reads back the raw SDR rendition and gain map
587
+ *
588
+ * @param renderer
589
+ */
590
+ async read(renderer) {
591
+ this.render(renderer);
592
+ const metadata = this.metadata;
593
+ const [sdr, gainMap] = await Promise.all([
594
+ readRenderTargetPixels(renderer, this.sdr.renderTarget),
595
+ readRenderTargetPixels(renderer, this.gainMap.renderTarget)
596
+ ]);
597
+ return {
598
+ sdr: new ImageData(new Uint8ClampedArray(sdr), this.width, this.height),
599
+ gainMap: new ImageData(new Uint8ClampedArray(gainMap), this.width, this.height),
600
+ metadata
601
+ };
602
+ }
603
+ /**
604
+ * Renders (if needed), reads back and compresses the SDR rendition and gain map
605
+ *
606
+ * @param renderer
607
+ * @param options compression options, `flipY` is not needed
608
+ * @throws {Error} if the browser does not support [createImageBitmap](https://caniuse.com/createimagebitmap)
609
+ */
610
+ async compress(renderer, options) {
611
+ const { sdr, gainMap, metadata } = await this.read(renderer);
612
+ const { withWorker, ...compressOptions } = options;
613
+ if (withWorker) {
614
+ const [compressedSDR, compressedGainMap] = await Promise.all([
615
+ withWorker.compress({ ...compressOptions, source: sdr }),
616
+ withWorker.compress({ ...compressOptions, source: gainMap })
617
+ ]);
618
+ return { ...metadata, sdr: compressedSDR, gainMap: compressedGainMap, rawSDR: compressedSDR.source, rawGainMap: compressedGainMap.source };
619
+ }
620
+ const [compressedSDR, compressedGainMap] = await Promise.all([
621
+ compress({ ...compressOptions, source: sdr }),
622
+ compress({ ...compressOptions, source: gainMap })
623
+ ]);
624
+ return { ...metadata, sdr: compressedSDR, gainMap: compressedGainMap, rawSDR: sdr.data, rawGainMap: gainMap.data };
625
+ }
626
+ /**
627
+ * Disposes the nodes, and the HDR texture if it was created by the encoder from raw data
628
+ */
629
+ dispose() {
630
+ this.sdr.dispose();
631
+ this.gainMap.dispose();
632
+ this._ownedTexture?.dispose();
633
+ }
634
+ }
635
+
636
+ export { GainMapEncoder, GainMapEncoderNode, RenderTargetNode, SDRRenditionNode, compress, findTextureMinMax, gainMapEncoder, sdrRendition };
@@ -0,0 +1,5 @@
1
+ /**
2
+ * @monogrid/gainmap-js v3.7.1
3
+ * With ❤️, by MONOGRID <gainmap@monogrid.com>
4
+ */
5
+ import{R as t,G as e}from"./GainMapNode-Cz4_NIGH.js";import{c as r}from"./compress-goZ8TdVo.js";import{vec4 as a,uniform as n,textureLoad as s,Fn as i,screenCoordinate as o,float as h,ivec2 as d,min as u,vec2 as m,max as g,texture as l,log2 as c,saturate as p,pow as f,toneMapping as w,mat4 as M,vec3 as x}from"three/tsl";import{RendererUtils as _,QuadMesh as y,NodeMaterial as v,Texture as C,Vector2 as S,RenderTarget as B,NearestFilter as b,FloatType as T,NoBlending as R,LinearFilter as A,LinearSRGBColorSpace as D,UnsignedByteType as H,Vector3 as N,ACESFilmicToneMapping as G,SRGBColorSpace as j,TextureNode as F}from"three/webgpu";import{g as E}from"./get-data-texture-Dlg6zKSG.js";import"three";const P=async(t,e)=>{const{width:r,height:a}=e,n=await t.readRenderTargetPixelsAsync(e,0,0,r,a),s=4*r,i=a>1?(n.length-s)/(a-1):s,o=!0!==t.backend.isWebGLBackend;if(i===s&&!o)return n.length===s*a?n:n.subarray(0,s*a);const h=new n.constructor(s*a);for(let t=0;t<a;t++){const e=o?a-1-t:t;h.set(n.subarray(e*i,e*i+s),t*s)}return h},U=async(t,e,r,l)=>{const c=_.resetRendererState(r,{}),p=[],f=new y(new v),w=(t,e)=>{const r=new B(t,e,{type:T,minFilter:b,magFilter:b,generateMipmaps:!1,depthBuffer:!1});return p.push(r),r},M=(t,e)=>{t.blending=R,t.depthTest=!1,t.depthWrite=!1,f.material=t,r.setRenderTarget(e),f.render(r)};try{let c,p,f;if(t instanceof C||(t=>"object"==typeof t&&null!==t&&"data"in t&&"width"in t&&"height"in t&&!(t instanceof C))(t)){c=t instanceof C?t:E(t);const e=c.image;p=e.width,f=e.height}else{if(!l)throw new Error("findTextureMinMax: size is required when the image is a node");p=l.width,f=l.height;const e=new v;e.fragmentNode=a(t);const r=w(p,f);M(e,r),e.dispose(),c=r.texture}const x=(t,r,l)=>{const c=n(new S(r,l)),p=s(t),f=i(()=>{const t=o.xy.floor().mul(2),r=c.sub(1),n=a(h("max"===e?0:65504)).toVar();for(let a=0;a<2;a++)for(let s=0;s<2;s++){const i=p.load(d(u(t.add(m(s,a)),r)));n.assign("max"===e?g(n,i):u(n,i))}return n}),w=new v;return w.fragmentNode=f(),{material:w,sourceTexture:p,sourceSize:c}};let _,y=x(c,p,f);for(;p>1||f>1||!_;){p=Math.max(1,Math.ceil(p/2)),f=Math.max(1,Math.ceil(f/2));const t=_;_=w(p,f),t&&(y.sourceTexture.value===c?(y.material.dispose(),y=x(t.texture,t.width,t.height)):(y.sourceTexture.value=t.texture,y.sourceSize.value.set(t.width,t.height))),M(y.material,_)}y.material.dispose();const B=await P(r,_);return[B[0],B[1],B[2]]}finally{_.restoreRendererState(r,c),p.forEach(t=>t.dispose())}},W=1.0001;class z extends t{static get type(){return"GainMapEncoderNode"}sdr;uniforms;_warned=[];constructor(t,e={}){super(new v,{type:H,colorSpace:D,minFilter:A,magFilter:A}),this.sdr=t;const r=this.uniforms={gamma:n((new N).fromArray(e.gamma??[1,1,1])),offsetSdr:n((new N).fromArray(e.offsetSdr??[1/64,1/64,1/64])),offsetHdr:n((new N).fromArray(e.offsetHdr??[1/64,1/64,1/64])),minContentBoost:n(e.minContentBoost||1),maxContentBoost:n(e.maxContentBoost??W)},s=n(0).onRenderUpdate(()=>Math.log2(this.metadataMinContentBoost)),i=n(0).onRenderUpdate(()=>Math.log2(this.metadataMaxContentBoost)),o=l(t.value).rgb,h=a(t.hdr).rgb.add(r.offsetHdr).div(o.add(r.offsetSdr)),d=c(h).sub(s).div(i.sub(s)),u=p(d);this._material.name="GainMapEncoder",this._material.blending=R,this._material.depthTest=!1,this._material.depthWrite=!1,this._material.fragmentNode=a(f(u,r.gamma),1)}get gamma(){return this.uniforms.gamma}get offsetSdr(){return this.uniforms.offsetSdr}get offsetHdr(){return this.uniforms.offsetHdr}get minContentBoost(){return this.uniforms.minContentBoost}get maxContentBoost(){return this.uniforms.maxContentBoost}get width(){return this.sdr.width}get height(){return this.sdr.height}get metadataMinContentBoost(){return this.uniforms.minContentBoost.value}get metadataMaxContentBoost(){return Math.max(this.uniforms.maxContentBoost.value,W)}get metadata(){const t=this.uniforms,e=Math.log2(this.metadataMinContentBoost),r=Math.log2(this.metadataMaxContentBoost);return{gamma:t.gamma.value.toArray(),offsetSdr:t.offsetSdr.value.toArray(),offsetHdr:t.offsetHdr.value.toArray(),gainMapMin:[e,e,e],gainMapMax:[r,r,r],hdrCapacityMin:Math.max(0,e),hdrCapacityMax:Math.max(0,r)}}_getState(){const t=this.uniforms;return[...t.gamma.value.toArray(),...t.offsetSdr.value.toArray(),...t.offsetHdr.value.toArray(),t.minContentBoost.value,t.maxContentBoost.value]}_getDependencies(){return[this.sdr]}_onRender(){const{minContentBoost:t,maxContentBoost:e}=this.uniforms,r=[t.value,e.value];r.every((t,e)=>t===this._warned[e])||(this._warned=r,e.value<=1&&console.warn(`gainmap-js: maxContentBoost is ${e.value} (<= 1), the source image has no HDR content. It will be clamped to 1.0001 and the result will be equivalent to an SDR image.`),this.metadataMinContentBoost>=this.metadataMaxContentBoost&&console.warn(`gainmap-js: minContentBoost (${this.metadataMinContentBoost}) must be lower than maxContentBoost (${this.metadataMaxContentBoost}), the resulting gain map will be invalid.`))}}const k=(t,e)=>new z(t,e),q=t=>{const e=t.image;return{width:e?.width??0,height:e?.height??0}};class I extends t{static get type(){return"SDRRenditionNode"}hdr;uniforms;_hdrTexture;_hdrSource;_width;_height;_toneMapping=G;constructor(e,r={}){if(super(new v,{type:H,colorSpace:j,minFilter:A,magFilter:A}),this._hdrTexture=e instanceof C?e:e instanceof F?e.value:null,this._hdrSource=e instanceof t?e:null,this.hdr=e instanceof C?l(e):e,this._width=r.width,this._height=r.height,!(this._hdrTexture||this._width&&this._height))throw new Error("SDRRenditionNode: width and height are required when the HDR input is not a texture");this.uniforms={exposure:n(1),brightness:n(0),contrast:n(1),saturation:n(1)},this._material.name="SDRRendition",this._material.blending=R,this._material.depthTest=!1,this._material.depthWrite=!1,this.setToneMapping(r.toneMapping??G)}get exposure(){return this.uniforms.exposure}get brightness(){return this.uniforms.brightness}get contrast(){return this.uniforms.contrast}get saturation(){return this.uniforms.saturation}getToneMapping(){return this._toneMapping}setToneMapping(t){return this._toneMapping=t,this._material.fragmentNode=this._buildOutput(),this._material.needsUpdate=!0,this}get width(){return this._width?this._width:this._hdrSource?this._hdrSource.width:this._hdrTexture?q(this._hdrTexture).width:0}get height(){return this._height?this._height:this._hdrSource?this._hdrSource.height:this._hdrTexture?q(this._hdrTexture).height:0}_buildOutput(){const t=this.uniforms,e=a(this.hdr),r=a(w(this._toneMapping,h(1),e.rgb.mul(t.exposure)).rgb,e.a),n=t.brightness,s=M(1,0,0,0,0,1,0,0,0,0,1,0,n,n,n,1),i=t.contrast,o=h(1).sub(i).div(2),d=M(i,0,0,0,0,i,0,0,0,0,i,0,o,o,o,1),u=x(.3086,.6094,.082),m=h(1).sub(t.saturation),g=x(u.x.mul(m)).add(x(t.saturation,0,0)),l=x(u.y.mul(m)).add(x(0,t.saturation,0)),c=x(u.z.mul(m)).add(x(0,0,t.saturation)),p=M(a(g,0),a(l,0),a(c,0),a(0,0,0,1));return s.mul(d).mul(p).mul(r)}_getState(){const t=this.uniforms;return[this._hdrTexture?.id,this._hdrTexture?.version,this._toneMapping,t.exposure.value,t.brightness.value,t.contrast.value,t.saturation.value]}_getDependencies(){return this._hdrSource?[this._hdrSource]:[]}}const $=(t,e)=>new I(t,e);class O extends e{_encoder;constructor(t){super(),this._encoder=t,this.setTextures(t.sdr,t.gainMap).setMetadata(t.metadata)}_getState(){const{gamma:t,offsetSdr:e,offsetHdr:r,gainMapMin:a,gainMapMax:n,hdrCapacityMin:s,hdrCapacityMax:i}=this._encoder.metadata,o=this.uniforms;return o.gamma.value.fromArray(t),o.offsetSdr.value.fromArray(e),o.offsetHdr.value.fromArray(r),o.gainMapMin.value.fromArray(a),o.gainMapMax.value.fromArray(n),o.hdrCapacityMin.value=s,o.hdrCapacityMax.value=i,super._getState()}}class L{sdr;gainMap;_ownedTexture;constructor(t,e={}){let r;t instanceof C||!("data"in t)?(r=t,this._ownedTexture=null):r=this._ownedTexture=E(t),this.sdr=new I(r,e),this.gainMap=new z(this.sdr,e)}get width(){return this.sdr.width}get height(){return this.sdr.height}get metadata(){return this.gainMap.metadata}async fitMaxContentBoost(t){const e=Math.max(...await U(this.sdr.hdr,"max",t,this));return this.gainMap.maxContentBoost.value=e,e}createPreviewNode(){return new O(this)}render(t){this.gainMap.render(t)}async read(t){this.render(t);const e=this.metadata,[r,a]=await Promise.all([P(t,this.sdr.renderTarget),P(t,this.gainMap.renderTarget)]);return{sdr:new ImageData(new Uint8ClampedArray(r),this.width,this.height),gainMap:new ImageData(new Uint8ClampedArray(a),this.width,this.height),metadata:e}}async compress(t,e){const{sdr:a,gainMap:n,metadata:s}=await this.read(t),{withWorker:i,...o}=e;if(i){const[t,e]=await Promise.all([i.compress({...o,source:a}),i.compress({...o,source:n})]);return{...s,sdr:t,gainMap:e,rawSDR:t.source,rawGainMap:e.source}}const[h,d]=await Promise.all([r({...o,source:a}),r({...o,source:n})]);return{...s,sdr:h,gainMap:d,rawSDR:a.data,rawGainMap:n.data}}dispose(){this.sdr.dispose(),this.gainMap.dispose(),this._ownedTexture?.dispose()}}export{L as GainMapEncoder,z as GainMapEncoderNode,t as RenderTargetNode,I as SDRRenditionNode,r as compress,U as findTextureMinMax,k as gainMapEncoder,$ as sdrRendition};