@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.
Files changed (59) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +86 -13
  3. package/dist/GainMapNode-CntuYSg-.js +338 -0
  4. package/dist/GainMapNode-DtVNqKtN.js +5 -0
  5. package/dist/{warn-deprecated-DtCQWGKi.js → Loader-D82gF-Rq.js} +3 -19
  6. package/dist/{warn-deprecated-gLZfP_DV.js → Loader-EFF6JZel.js} +2 -2
  7. package/dist/{QuadRenderer-DMno-Vj6.js → QuadRenderer-DD6leG7y.js} +1 -1
  8. package/dist/{QuadRenderer-Bhn3yOPC.js → QuadRenderer-DoK2pW5M.js} +1 -1
  9. package/dist/{_commonjsHelpers-DFuDJEaJ.js → _commonjsHelpers-C0JuzTK_.js} +1 -1
  10. package/dist/{_commonjsHelpers-C8qmDUO8.js → _commonjsHelpers-p2JmW4Hh.js} +1 -1
  11. package/dist/{compress-TBp7MS8D.js → compress-BTsSIi_B.js} +1 -1
  12. package/dist/{compress-oIjJuPa8.js → compress-PmebyFxR.js} +1 -1
  13. package/dist/core/webgpu/RenderTargetNode.d.ts +79 -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/nodes/GainMapNode.d.ts +13 -19
  21. package/dist/decode.js +5 -18
  22. package/dist/decode.min.js +2 -2
  23. package/dist/decode.umd.cjs +1 -30
  24. package/dist/decode.umd.min.cjs +2 -2
  25. package/dist/decode.webgpu.js +27 -232
  26. package/dist/decode.webgpu.min.js +2 -2
  27. package/dist/decode.webgpu.umd.cjs +167 -61
  28. package/dist/decode.webgpu.umd.min.cjs +2 -2
  29. package/dist/encode/webgpu/GainMapEncoder.d.ts +142 -0
  30. package/dist/encode/webgpu/find-texture-min-max.d.ts +27 -0
  31. package/dist/encode/webgpu/index.d.ts +8 -0
  32. package/dist/encode/webgpu/nodes/GainMapEncoderNode.d.ts +92 -0
  33. package/dist/encode/webgpu/nodes/SDRRenditionNode.d.ts +120 -0
  34. package/dist/encode/webgpu/read-render-target-pixels.d.ts +11 -0
  35. package/dist/encode.js +5 -36
  36. package/dist/encode.min.js +2 -2
  37. package/dist/encode.umd.cjs +1 -1
  38. package/dist/encode.umd.min.cjs +1 -1
  39. package/dist/encode.webgpu.js +635 -0
  40. package/dist/encode.webgpu.min.js +5 -0
  41. package/dist/encode.webgpu.umd.cjs +1081 -0
  42. package/dist/encode.webgpu.umd.min.cjs +5 -0
  43. package/dist/get-data-texture-CkaFVcv-.js +5 -0
  44. package/dist/get-data-texture-DkHkbczN.js +40 -0
  45. package/dist/{iso-gainmap-metadata-Oi7gAKNC.js → iso-gainmap-metadata-BJxZGPtk.js} +1 -1
  46. package/dist/{iso-gainmap-metadata-C1io5isX.js → iso-gainmap-metadata-Bx6ha9th.js} +1 -1
  47. package/dist/libultrahdr.js +2 -2
  48. package/dist/libultrahdr.min.js +2 -2
  49. package/dist/libultrahdr.umd.cjs +1 -1
  50. package/dist/libultrahdr.umd.min.cjs +1 -1
  51. package/dist/worker-interface.js +2 -2
  52. package/dist/worker-interface.min.js +2 -2
  53. package/dist/worker-interface.umd.cjs +1 -1
  54. package/dist/worker-interface.umd.min.cjs +1 -1
  55. package/dist/worker.js +3 -3
  56. package/dist/worker.min.js +2 -2
  57. package/dist/worker.umd.cjs +1 -1
  58. package/dist/worker.umd.min.cjs +1 -1
  59. package/package.json +9 -1
package/CHANGELOG.md CHANGED
@@ -1,3 +1,15 @@
1
+ # [3.7.0](https://github.com/MONOGRID/gainmap-js/compare/v3.6.1...v3.7.0) (2026-10-19)
2
+
3
+
4
+ ### Bug Fixes
5
+
6
+ * **webgl:** legacy WebGLRenderer decode api not deprecated anymore ([6785697](https://github.com/MONOGRID/gainmap-js/commit/6785697200eccd93881868e1d2ffe59beb1f74bf))
7
+
8
+
9
+ ### Features
10
+
11
+ * **webgpu:** node-based gain map encoder ([#87](https://github.com/MONOGRID/gainmap-js/issues/87)) ([4bbfdfd](https://github.com/MONOGRID/gainmap-js/commit/4bbfdfd248a3a46af58d1ebdd690cb3c0eeaa849))
12
+
1
13
  ## [3.6.1](https://github.com/MONOGRID/gainmap-js/compare/v3.6.0...v3.6.1) (2026-10-19)
2
14
 
3
15
 
package/README.md CHANGED
@@ -173,27 +173,26 @@ renderer.render(scene, new PerspectiveCamera())
173
173
  hdr.dispose()
174
174
  ```
175
175
 
176
- #### Migrating to upcoming v4.0.0
176
+ #### Migrating to v4.0.0
177
177
 
178
178
  > [!WARNING]
179
- > All render target based decoding APIs are deprecated and **will be removed in v4.0.0**,
180
- > both from the main `@monogrid/gainmap-js` entry point (`WebGLRenderer`) and from `@monogrid/gainmap-js/webgpu`:
181
- > `HDRJPGLoader`, `JPEGRLoader`, `GainMapLoader`, `decode()` and `GainMapDecoderMaterial` (plus the WebGPU `QuadRenderer`).
179
+ > The render target based decoding APIs of `@monogrid/gainmap-js/webgpu` are deprecated and **will be removed in v4.0.0**:
180
+ > `HDRJPGLoader`, `JPEGRLoader`, `GainMapLoader`, `decode()`, `GainMapDecoderMaterial` and `QuadRenderer`.
182
181
  > The loaders and `decode()` log a deprecation warning once when used.
183
182
  >
184
- > From v4.0.0 the node loaders are the only way to decode gain maps.
183
+ > The `WebGLRenderer` APIs of the main `@monogrid/gainmap-js` entry point are **not** deprecated.
184
+ >
185
+ > From v4.0.0 the node loaders are the only way to decode gain maps with `WebGPURenderer`.
185
186
 
186
- If you are using `WebGLRenderer`, switch to `WebGPURenderer` from `three/webgpu`: it falls back to a WebGL2 backend
187
+ If you are using the `WebGPURenderer` render target based APIs, switch to the node loaders. If you are still on `WebGLRenderer` you can keep using `@monogrid/gainmap-js`, or move to `WebGPURenderer` from `three/webgpu`: it falls back to a WebGL2 backend
187
188
  where WebGPU is not available, so the node loaders work in the same browsers. Use `new WebGPURenderer({ forceWebGL: true })`
188
189
  to keep the WebGL2 backend everywhere. Materials need to be node materials (`MeshBasicNodeMaterial`, `MeshStandardNodeMaterial`, ...),
189
190
  or regular materials using `hdr.value` as a texture.
190
191
 
191
192
  The node loaders are **not a drop-in replacement**: they return a `GainMapNode` instead of a render target.
192
193
 
193
- | Before (deprecated) | After |
194
+ | Before (deprecated, `@monogrid/gainmap-js/webgpu`) | After |
194
195
  | --- | --- |
195
- | `import { ... } from '@monogrid/gainmap-js'` | `import { ... } from '@monogrid/gainmap-js/webgpu'` |
196
- | `new WebGLRenderer()` | `new WebGPURenderer()` + `await renderer.init()` |
197
196
  | `new HDRJPGLoader(renderer)` | `new HDRJPGNodeLoader()`, no renderer |
198
197
  | `new GainMapLoader(renderer)` | `new GainMapNodeLoader()`, no renderer |
199
198
  | `decode({ sdr, gainMap, renderer, ...metadata })` | `gainMapNode(sdr, gainMap, metadata)` |
@@ -209,10 +208,30 @@ The node loaders are **not a drop-in replacement**: they return a `GainMapNode`
209
208
  When the node is not part of a rendered node graph (e.g. only `scene.environment = hdr.value` is used),
210
209
  call `hdr.decode(renderer)` after load to update its texture.
211
210
 
212
- #### Decoding with WebGLRenderer (deprecated)
211
+ #### Switching from the WebGL encoder to the node based encoder
213
212
 
214
- > [!WARNING]
215
- > Deprecated, will be removed in v4.0.0, see [Migrating to v4.0.0](#migrating-to-v400).
213
+ The WebGL encoder is not deprecated, you can keep using it. The node based encoder is available as an alternative with `WebGPURenderer`.
214
+
215
+ With `LinearToneMapping` the node based encoder produces the same images as the WebGL encoder (byte for byte on the WebGL2 backend,
216
+ within 1/255 on a handful of pixels on the WebGPU backend, where shaders compile differently).
217
+ Other tone mappings use the three.js TSL tone mapping functions, so their SDR rendition differs from the one of the WebGL encoder.
218
+ Brightness, contrast and saturation are applied after tone mapping: `LinearToneMapping` now clamps values above 1 before they are applied.
219
+
220
+ | WebGL encoder (`@monogrid/gainmap-js/encode`) | Node based encoder (`@monogrid/gainmap-js/encode/webgpu`) |
221
+ | --- | --- |
222
+ | `encode({ image, maxContentBoost, ... })` | `new GainMapEncoder(image, { maxContentBoost, ... })`, no renderer |
223
+ | `findTextureMinMax(image)` | `await findTextureMinMax(image, 'max', renderer)`, or `await encoder.fitMaxContentBoost(renderer)` |
224
+ | `result.sdr.material.exposure = 0.9; result.sdr.render()` | `encoder.sdr.exposure.value = 0.9`, re-rendered when next used |
225
+ | `result.sdr.material.toneMapping = AgXToneMapping` | `encoder.sdr.setToneMapping(AgXToneMapping)` |
226
+ | `result.gainMap.material.gamma = [1.1, 1.1, 1.1]` | `encoder.gainMap.gamma.value.setScalar(1.1)` |
227
+ | `result.getMetadata()` | `encoder.metadata` |
228
+ | `result.sdr.renderTarget.texture` | `encoder.sdr` in node materials, `encoder.sdr.value` where a `Texture` is needed |
229
+ | `decode({ sdr: result.sdr.renderTarget.texture, ... })` to preview | `encoder.createPreviewNode()`, it follows parameter changes |
230
+ | `new ImageData(result.sdr.toArray(), ...)` + `compress({ flipY: true })` | `(await encoder.read(renderer)).sdr`, upright, no `flipY` |
231
+ | `await encodeAndCompress({ ... })` | `await encoder.compress(renderer, { mimeType, quality, withWorker })` |
232
+ | `result.sdr.dispose(); result.gainMap.dispose()` | `encoder.dispose()` |
233
+
234
+ #### Decoding with WebGLRenderer
216
235
 
217
236
  The main `@monogrid/gainmap-js` entry point exposes `HDRJPGLoader` and `GainMapLoader`, which decode into a `WebGLRenderTarget`.
218
237
 
@@ -235,11 +254,65 @@ scene.background = result.renderTarget.texture
235
254
  result.dispose()
236
255
  ```
237
256
 
238
- Other decoding APIs (the `GainMapNode` constructor, the deprecated `decode()` function and render target based
257
+ Other decoding APIs (the `GainMapNode` constructor, `decode()` and the deprecated render target based
239
258
  `HDRJPGLoader` / `GainMapLoader` for `WebGPURenderer`) are documented in the [WIKI](https://github.com/MONOGRID/gainmap-js/wiki).
240
259
 
241
260
  ### Encoding
242
261
 
262
+ Encoding a Gain map starting from an EXR file.
263
+
264
+ This is generally not useful in a `three.js` site but this library exposes methods
265
+ that allow to encode an `.exr` or `hdr` file into a `jpeg` with an embedded gain map.
266
+
267
+ `GainMapEncoder` encodes on the GPU with TSL nodes, no renderer is needed until the result is read back.
268
+ `encoder.sdr` (the SDR rendition) and `encoder.gainMap` are live texture nodes: every encoding parameter is a uniform,
269
+ changing one re-renders only the affected nodes, once, the next time they are used.
270
+ This makes it suitable for interactive editors as well.
271
+
272
+ ```ts
273
+ import { GainMapEncoder } from '@monogrid/gainmap-js/encode/webgpu'
274
+ import { encodeJPEGMetadata } from '@monogrid/gainmap-js/libultrahdr'
275
+ import { EXRLoader } from 'three/examples/jsm/loaders/EXRLoader.js'
276
+ import { AgXToneMapping, LinearToneMapping, WebGPURenderer } from 'three/webgpu'
277
+
278
+ const renderer = new WebGPURenderer()
279
+ await renderer.init()
280
+
281
+ // load an HDR file (raw texture data and TSL nodes are accepted too)
282
+ const image = await new EXRLoader().loadAsync('image.exr')
283
+
284
+ const encoder = new GainMapEncoder(image, { toneMapping: AgXToneMapping })
285
+ // encode the full HDR range
286
+ await encoder.fitMaxContentBoost(renderer)
287
+
288
+ // optional: live previews, they follow any parameter change
289
+ sdrMaterial.colorNode = encoder.sdr
290
+ gainMapMaterial.colorNode = encoder.gainMap
291
+ hdrMaterial.colorNode = encoder.createPreviewNode() // a GainMapNode decoding the encoded result
292
+
293
+ // every parameter is a uniform
294
+ encoder.sdr.exposure.value = 0.9
295
+ encoder.sdr.setToneMapping(LinearToneMapping)
296
+ encoder.gainMap.gamma.value.setScalar(1.1)
297
+
298
+ // read back and compress, no flipY needed
299
+ const result = await encoder.compress(renderer, { mimeType: 'image/jpeg', quality: 0.9 })
300
+
301
+ // embed the compressed images + metadata into a single JPEG file
302
+ const jpeg = encodeJPEGMetadata(result)
303
+
304
+ // `jpeg` will be an `Uint8Array` which can be saved somewhere
305
+
306
+ // the encoder must be manually disposed when no longer needed
307
+ encoder.dispose()
308
+ ```
309
+
310
+ The raw (uncompressed) images and the metadata are available with `await encoder.read(renderer)`,
311
+ `await findTextureMinMax(image, 'max', renderer)` finds the max (or min) value of each channel of an HDR image.
312
+
313
+ #### Encoding with WebGLRenderer
314
+
315
+
243
316
  Encoding a Gain map starting from an EXR file.
244
317
 
245
318
  This is generally not useful in a `three.js` site but this library exposes methods
@@ -0,0 +1,338 @@
1
+ /**
2
+ * @monogrid/gainmap-js v3.7.0
3
+ * With ❤️, by MONOGRID <gainmap@monogrid.com>
4
+ */
5
+
6
+ import { uniform, texture, vec3, mix, saturate, log2, exp2, vec4 } from 'three/tsl';
7
+ import { TextureNode, RenderTarget, NodeUpdateType, QuadMesh, RendererUtils, MeshBasicNodeMaterial, LinearFilter, LinearMipmapLinearFilter, LinearSRGBColorSpace, HalfFloatType, Vector3, Texture } from 'three/webgpu';
8
+
9
+ /**
10
+ * Base class for TSL texture nodes whose texture is a render target, filled by rendering a full screen quad.
11
+ *
12
+ * The quad is rendered only when something changed since the last render:
13
+ * subclasses list what the result depends on in {@link RenderTargetNode._getState}
14
+ * and the other render target nodes they read from in {@link RenderTargetNode._getDependencies}.
15
+ * Sampling the node costs a single texture read, like any other texture.
16
+ *
17
+ * The node renders itself before rendering whenever it is part of a rendered node graph
18
+ * (material, `scene.backgroundNode`, ...). When only its texture is used (`node.value`)
19
+ * call {@link RenderTargetNode.render} yourself.
20
+ *
21
+ * @category Nodes
22
+ * @group Nodes
23
+ */
24
+ class RenderTargetNode extends TextureNode {
25
+ /**
26
+ * The render target holding the result
27
+ */
28
+ renderTarget;
29
+ /**
30
+ * Incremented every time the render target is rendered,
31
+ * nodes depending on this one use it to know when to render again
32
+ */
33
+ revision = 0;
34
+ _quadMesh;
35
+ _material;
36
+ // filled by RendererUtils.resetRendererState
37
+ _rendererState = {};
38
+ _state = [];
39
+ /**
40
+ * @param material the material rendered on the full screen quad
41
+ * @param renderTargetOptions options of the render target, it is created with a 1x1 size
42
+ * and resized to {@link RenderTargetNode.width} x {@link RenderTargetNode.height} before rendering
43
+ */
44
+ constructor(material, renderTargetOptions) {
45
+ const renderTarget = new RenderTarget(1, 1, { depthBuffer: false, ...renderTargetOptions });
46
+ super(renderTarget.texture);
47
+ this.renderTarget = renderTarget;
48
+ this.updateBeforeType = NodeUpdateType.RENDER;
49
+ this._material = material;
50
+ this._quadMesh = new QuadMesh(material);
51
+ }
52
+ /**
53
+ * Render target nodes read by this node, rendered (if needed) before this one
54
+ */
55
+ _getDependencies() { return []; }
56
+ /**
57
+ * Called after the render target has been rendered
58
+ */
59
+ _onRender() { }
60
+ /**
61
+ * Forces a render the next time {@link RenderTargetNode.render} is called,
62
+ * use it when something the node can't track changed (e.g. a custom input node)
63
+ */
64
+ invalidate() {
65
+ this._state = [];
66
+ return this;
67
+ }
68
+ /**
69
+ * Renders into {@link RenderTargetNode.renderTarget}, only if something changed since the last render.
70
+ *
71
+ * Called automatically when the node is part of a rendered node graph.
72
+ *
73
+ * @param renderer
74
+ * @returns `true` if the render target was rendered
75
+ */
76
+ render(renderer) {
77
+ const dependencies = this._getDependencies();
78
+ for (const dependency of dependencies)
79
+ dependency.render(renderer);
80
+ const { width, height } = this;
81
+ // not ready yet
82
+ if (width === 0 || height === 0)
83
+ return false;
84
+ const state = [width, height, ...dependencies.map(d => d.revision), ...this._getState()];
85
+ if (state.length === this._state.length && state.every((v, i) => v === this._state[i]))
86
+ return false;
87
+ this._state = state;
88
+ if (this.renderTarget.width !== width || this.renderTarget.height !== height)
89
+ this.renderTarget.setSize(width, height);
90
+ RendererUtils.resetRendererState(renderer, this._rendererState);
91
+ renderer.setRenderTarget(this.renderTarget);
92
+ this._quadMesh.render(renderer);
93
+ RendererUtils.restoreRendererState(renderer, this._rendererState);
94
+ this.revision++;
95
+ this._onRender();
96
+ return true;
97
+ }
98
+ updateBefore(frame) {
99
+ if (frame.renderer)
100
+ this.render(frame.renderer);
101
+ return undefined;
102
+ }
103
+ set value(value) {
104
+ if (this.renderTarget && value !== this.renderTarget.texture) {
105
+ throw new Error(`${this.constructor.name}: the value of this node is its render target texture and can't be replaced`);
106
+ }
107
+ }
108
+ get value() {
109
+ return this.renderTarget?.texture;
110
+ }
111
+ /**
112
+ * Clones created by `sample()` & co. are plain TextureNodes reading this node's texture,
113
+ * they keep it updated before rendering as well
114
+ */
115
+ clone() {
116
+ const node = new TextureNode(this.value, this.uvNode, this.levelNode, this.biasNode);
117
+ node.sampler = this.sampler;
118
+ node.updateBeforeType = NodeUpdateType.RENDER;
119
+ node.updateBefore = (frame) => this.updateBefore(frame);
120
+ return node;
121
+ }
122
+ /**
123
+ * Disposes the render target and the material
124
+ */
125
+ dispose() {
126
+ this.renderTarget.dispose();
127
+ this._material.dispose();
128
+ super.dispose();
129
+ }
130
+ }
131
+
132
+ // max half float value
133
+ const HALF_FLOAT_MAX = 65504;
134
+ /**
135
+ * A TSL texture node holding the HDR image decoded from an SDR image + gain map.
136
+ *
137
+ * The decode runs on the GPU into a HalfFloat render target, and only when something changed
138
+ * (textures loaded/swapped or any uniform value changed): sampling the node costs a single
139
+ * texture read, like any other texture.
140
+ *
141
+ * The node updates itself before rendering whenever it is part of a rendered node graph
142
+ * (material, `scene.backgroundNode`, ...). When only its texture is used (`node.value`,
143
+ * e.g. `scene.environment = node.value`) call {@link GainMapNode.decode} yourself.
144
+ *
145
+ * Re-decoding also flags the texture for PMREM regeneration,
146
+ * so environment maps are recomputed only when the image actually changes.
147
+ *
148
+ * `node.value` gets its final size once loaded: three.js PMREMs don't follow texture resizes,
149
+ * so assign it to `scene.environment` (or `pmremTexture()`) after load.
150
+ *
151
+ * @category Nodes
152
+ * @group Nodes
153
+ *
154
+ * @example
155
+ * import { GainMapNode } from '@monogrid/gainmap-js/webgpu'
156
+ * import { equirectUV } from 'three/tsl'
157
+ *
158
+ * const hdr = new GainMapNode()
159
+ * .setTextures(sdrTexture, gainMapTexture)
160
+ * .setMetadata(metadata)
161
+ *
162
+ * material.colorNode = hdr
163
+ * scene.backgroundNode = hdr.sample(equirectUV())
164
+ * hdr.maxDisplayBoost.value = 2 // re-decodes once, on the next frame
165
+ */
166
+ class GainMapNode extends RenderTargetNode {
167
+ static get type() { return 'GainMapNode'; }
168
+ /**
169
+ * Shared textures and uniforms
170
+ */
171
+ uniforms;
172
+ // set when the textures are produced by other render target nodes (e.g. a gain map encoder)
173
+ _sdrSource = null;
174
+ _gainMapSource = null;
175
+ constructor() {
176
+ const material = new MeshBasicNodeMaterial();
177
+ material.name = 'GainMapDecoder';
178
+ super(material, {
179
+ type: HalfFloatType,
180
+ colorSpace: LinearSRGBColorSpace,
181
+ generateMipmaps: true,
182
+ minFilter: LinearMipmapLinearFilter,
183
+ magFilter: LinearFilter
184
+ });
185
+ const u = this.uniforms = {
186
+ sdr: texture(new Texture()),
187
+ gainMap: texture(new Texture()),
188
+ gamma: uniform(new Vector3(1, 1, 1)),
189
+ offsetSdr: uniform(new Vector3()),
190
+ offsetHdr: uniform(new Vector3()),
191
+ gainMapMin: uniform(new Vector3()),
192
+ gainMapMax: uniform(new Vector3(1, 1, 1)),
193
+ hdrCapacityMin: uniform(0),
194
+ hdrCapacityMax: uniform(1),
195
+ maxDisplayBoost: uniform(1)
196
+ };
197
+ const logRecovery = u.gainMap.rgb.pow(vec3(1).div(u.gamma));
198
+ const logBoost = mix(u.gainMapMin, u.gainMapMax, logRecovery);
199
+ const weight = saturate(log2(u.maxDisplayBoost).sub(u.hdrCapacityMin).div(u.hdrCapacityMax.sub(u.hdrCapacityMin)));
200
+ const hdr = u.sdr.rgb.add(u.offsetSdr).mul(exp2(logBoost.mul(weight))).sub(u.offsetHdr);
201
+ material.colorNode = vec4(hdr.clamp(-HALF_FLOAT_MAX, HALF_FLOAT_MAX), 1);
202
+ }
203
+ /** The SDR rendition texture (sRGB) */
204
+ get sdr() { return this.uniforms.sdr.value; }
205
+ /** The gain map recovery texture (linear) */
206
+ get gainMap() { return this.uniforms.gainMap.value; }
207
+ /** @see {@link GainMapMetadata.gamma} */
208
+ get gamma() { return this.uniforms.gamma; }
209
+ /** @see {@link GainMapMetadata.offsetSdr} */
210
+ get offsetSdr() { return this.uniforms.offsetSdr; }
211
+ /** @see {@link GainMapMetadata.offsetHdr} */
212
+ get offsetHdr() { return this.uniforms.offsetHdr; }
213
+ /** @see {@link GainMapMetadata.gainMapMin} */
214
+ get gainMapMin() { return this.uniforms.gainMapMin; }
215
+ /** @see {@link GainMapMetadata.gainMapMax} */
216
+ get gainMapMax() { return this.uniforms.gainMapMax; }
217
+ /** @see {@link GainMapMetadata.hdrCapacityMin} */
218
+ get hdrCapacityMin() { return this.uniforms.hdrCapacityMin; }
219
+ /** @see {@link GainMapMetadata.hdrCapacityMax} */
220
+ get hdrCapacityMax() { return this.uniforms.hdrCapacityMax; }
221
+ /**
222
+ * @see {@link GainmapDecodingParameters.maxDisplayBoost}
223
+ * @remarks Non Logarithmic space
224
+ */
225
+ get maxDisplayBoost() { return this.uniforms.maxDisplayBoost; }
226
+ /** Width of the SDR image, 0 until loaded */
227
+ get width() {
228
+ if (this._sdrSource)
229
+ return this._sdrSource.width;
230
+ return this.sdr.image?.width ?? 0;
231
+ }
232
+ /** Height of the SDR image, 0 until loaded */
233
+ get height() {
234
+ if (this._sdrSource)
235
+ return this._sdrSource.height;
236
+ return this.sdr.image?.height ?? 0;
237
+ }
238
+ /**
239
+ * Sets the SDR and gain map textures.
240
+ * The SDR texture is expected in sRGB color space, the gain map in linear.
241
+ *
242
+ * Render target nodes (e.g. the `sdr` and `gainMap` nodes of a `GainMapEncoder`) are accepted as well:
243
+ * they are rendered before decoding and the image is decoded again whenever they change.
244
+ *
245
+ * @param sdr
246
+ * @param gainMap
247
+ */
248
+ setTextures(sdr, gainMap) {
249
+ this._sdrSource = sdr instanceof RenderTargetNode ? sdr : null;
250
+ this._gainMapSource = gainMap instanceof RenderTargetNode ? gainMap : null;
251
+ this.uniforms.sdr.value = sdr instanceof RenderTargetNode ? sdr.value : sdr;
252
+ this.uniforms.gainMap.value = gainMap instanceof RenderTargetNode ? gainMap.value : gainMap;
253
+ // size the render target right away, so `value` has its final size before the first decode
254
+ if (this.width > 0 && this.height > 0)
255
+ this.renderTarget.setSize(this.width, this.height);
256
+ return this;
257
+ }
258
+ /**
259
+ * Copies the gain map metadata into the uniforms.
260
+ * Also sets `maxDisplayBoost` to fully restore the HDR range.
261
+ *
262
+ * @param metadata
263
+ */
264
+ setMetadata(metadata) {
265
+ const u = this.uniforms;
266
+ u.gamma.value.fromArray(metadata.gamma);
267
+ u.offsetSdr.value.fromArray(metadata.offsetSdr);
268
+ u.offsetHdr.value.fromArray(metadata.offsetHdr);
269
+ u.gainMapMin.value.fromArray(metadata.gainMapMin);
270
+ u.gainMapMax.value.fromArray(metadata.gainMapMax);
271
+ u.hdrCapacityMin.value = metadata.hdrCapacityMin;
272
+ u.hdrCapacityMax.value = metadata.hdrCapacityMax;
273
+ u.maxDisplayBoost.value = Math.pow(2, metadata.hdrCapacityMax);
274
+ return this;
275
+ }
276
+ _getState() {
277
+ const u = this.uniforms;
278
+ return [
279
+ this.sdr.id, this.sdr.version, this.gainMap.id, this.gainMap.version,
280
+ ...u.gamma.value.toArray(), ...u.offsetSdr.value.toArray(), ...u.offsetHdr.value.toArray(),
281
+ ...u.gainMapMin.value.toArray(), ...u.gainMapMax.value.toArray(),
282
+ u.hdrCapacityMin.value, u.hdrCapacityMax.value, u.maxDisplayBoost.value
283
+ ];
284
+ }
285
+ _getDependencies() {
286
+ const dependencies = [];
287
+ if (this._sdrSource)
288
+ dependencies.push(this._sdrSource);
289
+ if (this._gainMapSource)
290
+ dependencies.push(this._gainMapSource);
291
+ return dependencies;
292
+ }
293
+ _onRender() {
294
+ this.value.needsPMREMUpdate = true;
295
+ }
296
+ /**
297
+ * Decodes the image into {@link GainMapNode.renderTarget}, only if something changed since the last decode.
298
+ *
299
+ * Called automatically when the node is part of a rendered node graph.
300
+ *
301
+ * @param renderer
302
+ * @returns `true` if the image was decoded
303
+ */
304
+ decode(renderer) {
305
+ return this.render(renderer);
306
+ }
307
+ /**
308
+ * Calls {@link GainMapNode.decode} once per render, before the node is evaluated.
309
+ *
310
+ * @param frame
311
+ */
312
+ updateBefore(frame) {
313
+ if (frame.renderer)
314
+ this.decode(frame.renderer);
315
+ return undefined;
316
+ }
317
+ /**
318
+ * Disposes the render target, the SDR and gain map textures
319
+ * (unless they belong to other render target nodes)
320
+ */
321
+ dispose() {
322
+ if (!this._sdrSource)
323
+ this.sdr.dispose();
324
+ if (!this._gainMapSource)
325
+ this.gainMap.dispose();
326
+ super.dispose();
327
+ }
328
+ }
329
+ /**
330
+ * TSL function creating a {@link GainMapNode} from an SDR texture, a gain map texture and its metadata
331
+ *
332
+ * @param sdr
333
+ * @param gainMap
334
+ * @param metadata
335
+ */
336
+ const gainMapNode = (sdr, gainMap, metadata) => new GainMapNode().setTextures(sdr, gainMap).setMetadata(metadata);
337
+
338
+ export { GainMapNode as G, RenderTargetNode as R, gainMapNode as g };
@@ -0,0 +1,5 @@
1
+ /**
2
+ * @monogrid/gainmap-js v3.7.0
3
+ * With ❤️, by MONOGRID <gainmap@monogrid.com>
4
+ */
5
+ import{uniform as e,texture as t,vec3 as r,mix as a,saturate as s,log2 as i,exp2 as n,vec4 as o}from"three/tsl";import{TextureNode as d,RenderTarget as h,NodeUpdateType as u,QuadMesh as p,RendererUtils as g,MeshBasicNodeMaterial as c,LinearFilter as f,LinearMipmapLinearFilter as M,LinearSRGBColorSpace as l,HalfFloatType as m,Vector3 as v,Texture as y}from"three/webgpu";class _ extends d{renderTarget;revision=0;_quadMesh;_material;_rendererState={};_state=[];constructor(e,t){const r=new h(1,1,{depthBuffer:!1,...t});super(r.texture),this.renderTarget=r,this.updateBeforeType=u.RENDER,this._material=e,this._quadMesh=new p(e)}_getDependencies(){return[]}_onRender(){}invalidate(){return this._state=[],this}render(e){const t=this._getDependencies();for(const r of t)r.render(e);const{width:r,height:a}=this;if(0===r||0===a)return!1;const s=[r,a,...t.map(e=>e.revision),...this._getState()];return(s.length!==this._state.length||!s.every((e,t)=>e===this._state[t]))&&(this._state=s,this.renderTarget.width===r&&this.renderTarget.height===a||this.renderTarget.setSize(r,a),g.resetRendererState(e,this._rendererState),e.setRenderTarget(this.renderTarget),this._quadMesh.render(e),g.restoreRendererState(e,this._rendererState),this.revision++,this._onRender(),!0)}updateBefore(e){e.renderer&&this.render(e.renderer)}set value(e){if(this.renderTarget&&e!==this.renderTarget.texture)throw new Error(`${this.constructor.name}: the value of this node is its render target texture and can't be replaced`)}get value(){return this.renderTarget?.texture}clone(){const e=new d(this.value,this.uvNode,this.levelNode,this.biasNode);return e.sampler=this.sampler,e.updateBeforeType=u.RENDER,e.updateBefore=e=>this.updateBefore(e),e}dispose(){this.renderTarget.dispose(),this._material.dispose(),super.dispose()}}class S extends _{static get type(){return"GainMapNode"}uniforms;_sdrSource=null;_gainMapSource=null;constructor(){const d=new c;d.name="GainMapDecoder",super(d,{type:m,colorSpace:l,generateMipmaps:!0,minFilter:M,magFilter:f});const h=this.uniforms={sdr:t(new y),gainMap:t(new y),gamma:e(new v(1,1,1)),offsetSdr:e(new v),offsetHdr:e(new v),gainMapMin:e(new v),gainMapMax:e(new v(1,1,1)),hdrCapacityMin:e(0),hdrCapacityMax:e(1),maxDisplayBoost:e(1)},u=h.gainMap.rgb.pow(r(1).div(h.gamma)),p=a(h.gainMapMin,h.gainMapMax,u),g=s(i(h.maxDisplayBoost).sub(h.hdrCapacityMin).div(h.hdrCapacityMax.sub(h.hdrCapacityMin))),_=h.sdr.rgb.add(h.offsetSdr).mul(n(p.mul(g))).sub(h.offsetHdr);d.colorNode=o(_.clamp(-65504,65504),1)}get sdr(){return this.uniforms.sdr.value}get gainMap(){return this.uniforms.gainMap.value}get gamma(){return this.uniforms.gamma}get offsetSdr(){return this.uniforms.offsetSdr}get offsetHdr(){return this.uniforms.offsetHdr}get gainMapMin(){return this.uniforms.gainMapMin}get gainMapMax(){return this.uniforms.gainMapMax}get hdrCapacityMin(){return this.uniforms.hdrCapacityMin}get hdrCapacityMax(){return this.uniforms.hdrCapacityMax}get maxDisplayBoost(){return this.uniforms.maxDisplayBoost}get width(){return this._sdrSource?this._sdrSource.width:this.sdr.image?.width??0}get height(){return this._sdrSource?this._sdrSource.height:this.sdr.image?.height??0}setTextures(e,t){return this._sdrSource=e instanceof _?e:null,this._gainMapSource=t instanceof _?t:null,this.uniforms.sdr.value=e instanceof _?e.value:e,this.uniforms.gainMap.value=t instanceof _?t.value:t,this.width>0&&this.height>0&&this.renderTarget.setSize(this.width,this.height),this}setMetadata(e){const t=this.uniforms;return t.gamma.value.fromArray(e.gamma),t.offsetSdr.value.fromArray(e.offsetSdr),t.offsetHdr.value.fromArray(e.offsetHdr),t.gainMapMin.value.fromArray(e.gainMapMin),t.gainMapMax.value.fromArray(e.gainMapMax),t.hdrCapacityMin.value=e.hdrCapacityMin,t.hdrCapacityMax.value=e.hdrCapacityMax,t.maxDisplayBoost.value=Math.pow(2,e.hdrCapacityMax),this}_getState(){const e=this.uniforms;return[this.sdr.id,this.sdr.version,this.gainMap.id,this.gainMap.version,...e.gamma.value.toArray(),...e.offsetSdr.value.toArray(),...e.offsetHdr.value.toArray(),...e.gainMapMin.value.toArray(),...e.gainMapMax.value.toArray(),e.hdrCapacityMin.value,e.hdrCapacityMax.value,e.maxDisplayBoost.value]}_getDependencies(){const e=[];return this._sdrSource&&e.push(this._sdrSource),this._gainMapSource&&e.push(this._gainMapSource),e}_onRender(){this.value.needsPMREMUpdate=!0}decode(e){return this.render(e)}updateBefore(e){e.renderer&&this.decode(e.renderer)}dispose(){this._sdrSource||this.sdr.dispose(),this._gainMapSource||this.gainMap.dispose(),super.dispose()}}const x=(e,t,r)=>(new S).setTextures(e,t).setMetadata(r);export{S as G,_ as R,x as g};
@@ -1,10 +1,10 @@
1
1
  /**
2
- * @monogrid/gainmap-js v3.6.1
2
+ * @monogrid/gainmap-js v3.7.0
3
3
  * With ❤️, by MONOGRID <gainmap@monogrid.com>
4
4
  */
5
5
 
6
6
  import { SRGBColorSpace, LinearSRGBColorSpace, HalfFloatType, Texture, UVMapping, ClampToEdgeWrapping, LinearFilter, LinearMipMapLinearFilter, RGBAFormat, UnsignedByteType, Loader, LoadingManager } from 'three';
7
- import { I as ISO_NAMESPACE, d as decodeISOGainMapMetadata } from './iso-gainmap-metadata-C1io5isX.js';
7
+ import { I as ISO_NAMESPACE, d as decodeISOGainMapMetadata } from './iso-gainmap-metadata-Bx6ha9th.js';
8
8
 
9
9
  /**
10
10
  * Shared decode implementation factory
@@ -484,20 +484,4 @@ class LoaderBaseShared extends Loader {
484
484
  }
485
485
  }
486
486
 
487
- const warned = new Set();
488
- /**
489
- * Warns once per API that a render target based decode API is going away in v4.0.0
490
- *
491
- * @param name deprecated API
492
- * @param entry entry point exposing the deprecated API
493
- * @param replacement node based API replacing it, from `@monogrid/gainmap-js/webgpu`
494
- */
495
- const warnDeprecated = (name, entry, replacement) => {
496
- const key = `${entry}:${name}`;
497
- if (warned.has(key))
498
- return;
499
- warned.add(key);
500
- console.warn(`gainmap-js: ${name} from '${entry}' is deprecated and will be removed in v4.0.0. Use ${replacement} from '@monogrid/gainmap-js/webgpu' with WebGPURenderer (which also has a WebGL2 backend) instead. It is not a drop-in replacement (it returns a GainMapNode, not a render target), see https://github.com/MONOGRID/gainmap-js#migrating-to-v400`);
501
- };
502
-
503
- export { GainMapNotFoundError as G, LoaderBaseShared as L, MPFExtractor as M, XMPMetadataNotFoundError as X, createTextures as a, extractISO as b, createDecodeFunction as c, extractXMP as d, extractGainmapFromJPEG as e, processImages as p, warnDeprecated as w };
487
+ export { GainMapNotFoundError as G, LoaderBaseShared as L, MPFExtractor as M, XMPMetadataNotFoundError as X, createTextures as a, extractISO as b, createDecodeFunction as c, extractXMP as d, extractGainmapFromJPEG as e, processImages as p };
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @monogrid/gainmap-js v3.6.1
2
+ * @monogrid/gainmap-js v3.7.0
3
3
  * With ❤️, by MONOGRID <gainmap@monogrid.com>
4
4
  */
5
- import{SRGBColorSpace as e,LinearSRGBColorSpace as t,HalfFloatType as a,Texture as r,UVMapping as n,ClampToEdgeWrapping as i,LinearFilter as o,LinearMipMapLinearFilter as s,RGBAFormat as d,UnsignedByteType as p,Loader as c,LoadingManager as l}from"three";import{I as g,d as m}from"./iso-gainmap-metadata-Oi7gAKNC.js";function f(r){return n=>{const{sdr:i,gainMap:o,renderer:s}=n;i.colorSpace!==e&&(console.warn("SDR Colorspace needs to be *SRGBColorSpace*, setting it automatically"),i.colorSpace=e),i.needsUpdate=!0,o.colorSpace!==t&&(console.warn("Gainmap Colorspace needs to be *LinearSRGBColorSpace*, setting it automatically"),o.colorSpace=t),o.needsUpdate=!0;const d=r.createMaterial({...n,sdr:i,gainMap:o});return r.createQuadRenderer({width:i.image.width,height:i.image.height,type:a,colorSpace:t,material:d,renderer:s,renderTargetOptions:n.renderTargetOptions})}}class h extends Error{}class u extends Error{}const w=Array.from(g,e=>e.charCodeAt(0)),x=e=>{const t=new DataView(e.buffer,e.byteOffset,e.byteLength),a=4+w.length;for(let r=0;r+a<e.length;r++){if(255!==e[r]||226!==e[r+1])continue;if(!w.every((t,a)=>e[r+4+a]===t))continue;const n=Math.min(e.length,r+2+t.getUint16(r+2));if(!(n-(r+a)<=4))try{return m(e.subarray(r+a,n))}catch(e){return}}},M=(e,t,a)=>{const r=new RegExp(`${t}="([^"]*)"`,"i").exec(e);if(r)return r[1];const n=new RegExp(`<${t}[^>]*>([\\s\\S]*?)</${t}>`,"i").exec(e);if(n){const e=n[1].match(/<rdf:li>([^<]*)<\/rdf:li>/g);return e&&3===e.length?e.map(e=>e.replace(/<\/?rdf:li>/g,"")):n[1].trim()}if(void 0!==a)return a;throw new Error(`Can't find ${t} in gainmap metadata`)},y=e=>{let t;t="undefined"!=typeof TextDecoder?(new TextDecoder).decode(e):e.toString();let a=t.indexOf("<x:xmpmeta");for(;-1!==a;){const e=t.indexOf("x:xmpmeta>",a),r=t.slice(a,e+10);try{const e=M(r,"hdrgm:GainMapMin","0"),t=M(r,"hdrgm:GainMapMax"),a=M(r,"hdrgm:Gamma","1"),n=M(r,"hdrgm:OffsetSDR","0.015625"),i=M(r,"hdrgm:OffsetHDR","0.015625"),o=/hdrgm:HDRCapacityMin="([^"]*)"/.exec(r),s=o?o[1]:"0",d=/hdrgm:HDRCapacityMax="([^"]*)"/.exec(r);if(!d)throw new Error("Incomplete gainmap metadata");const p=d[1];return{gainMapMin:Array.isArray(e)?e.map(e=>parseFloat(e)):[parseFloat(e),parseFloat(e),parseFloat(e)],gainMapMax:Array.isArray(t)?t.map(e=>parseFloat(e)):[parseFloat(t),parseFloat(t),parseFloat(t)],gamma:Array.isArray(a)?a.map(e=>parseFloat(e)):[parseFloat(a),parseFloat(a),parseFloat(a)],offsetSdr:Array.isArray(n)?n.map(e=>parseFloat(e)):[parseFloat(n),parseFloat(n),parseFloat(n)],offsetHdr:Array.isArray(i)?i.map(e=>parseFloat(e)):[parseFloat(i),parseFloat(i),parseFloat(i)],hdrCapacityMin:parseFloat(s),hdrCapacityMax:parseFloat(p)}}catch(e){}a=t.indexOf("<x:xmpmeta",e)}};class F{options;constructor(e){this.options={debug:!(!e||void 0===e.debug)&&e.debug,extractFII:!e||void 0===e.extractFII||e.extractFII,extractNonFII:!e||void 0===e.extractNonFII||e.extractNonFII}}extract(e){return new Promise((t,a)=>{const r=this.options.debug,n=new DataView(e.buffer);if(65496!==n.getUint16(0))return void a(new Error("Not a valid jpeg"));const i=n.byteLength;let o,s=2,d=0;for(;s<i;){if(++d>250)return void a(new Error(`Found no marker after ${d} loops 😵`));if(255!==n.getUint8(s))return void a(new Error(`Not a valid marker at offset 0x${s.toString(16)}, found: 0x${n.getUint8(s).toString(16)}`));if(o=n.getUint8(s+1),r&&console.log(`Marker: ${o.toString(16)}`),226===o){r&&console.log("Found APP2 marker (0xffe2)");const e=s+4;if(1297106432===n.getUint32(e)){const r=e+4;let i;if(18761===n.getUint16(r))i=!1;else{if(19789!==n.getUint16(r))return void a(new Error("No valid endianness marker found in TIFF header"));i=!0}if(42!==n.getUint16(r+2,!i))return void a(new Error("Not valid TIFF data! (no 0x002A marker)"));const o=n.getUint32(r+4,!i);if(o<8)return void a(new Error("Not valid TIFF data! (First offset less than 8)"));const s=r+o,d=n.getUint16(s,!i),p=s+2;let c=0;for(let e=p;e<p+12*d;e+=12)45057===n.getUint16(e,!i)&&(c=n.getUint32(e+8,!i));const l=s+2+12*d+4,g=[];for(let e=l;e<l+16*c;e+=16){const t={MPType:n.getUint32(e,!i),size:n.getUint32(e+4,!i),dataOffset:n.getUint32(e+8,!i),dependantImages:n.getUint32(e+12,!i),start:-1,end:-1,isFII:!1};t.dataOffset?(t.start=r+t.dataOffset,t.isFII=!1):(t.start=0,t.isFII=!0),t.end=t.start+t.size,g.push(t)}if(this.options.extractNonFII&&g.length){const e=new Blob([n]),a=[];for(const t of g){if(t.isFII&&!this.options.extractFII)continue;const r=e.slice(t.start,t.end+1,"image/jpeg");a.push(r)}t(a)}}}s+=2+n.getUint16(s+2)}})}}const I=async e=>{const t=x(e)??y(e);if(!t)throw new u("Gain map XMP metadata not found");const a=new F({extractFII:!0,extractNonFII:!0}),r=await a.extract(e);if(2!==r.length)throw new h("Gain map recovery image not found");return{sdr:new Uint8Array(await r[0].arrayBuffer()),gainMap:new Uint8Array(await r[1].arrayBuffer()),metadata:t}},U=e=>new Promise((t,a)=>{const r=document.createElement("img");r.onload=()=>{t(r)},r.onerror=e=>{a(e)},r.src=URL.createObjectURL(e)}),v=async(e,t,a)=>{const r=t?new Blob([t],{type:"image/jpeg"}):void 0,n=new Blob([e],{type:"image/jpeg"});let i,o,s=!1;if("undefined"==typeof createImageBitmap){const e=await Promise.all([r?U(r):Promise.resolve(void 0),U(n)]);o=e[0],i=e[1],s="flipY"===a}else{const e=await Promise.all([r?createImageBitmap(r,{imageOrientation:a||"flipY"}):Promise.resolve(void 0),createImageBitmap(n,{imageOrientation:a||"flipY"})]);o=e[0],i=e[1]}return{sdrImage:i,gainMapImage:o,needsFlip:s}},b=(a,c,l)=>{const g=new r(c||new ImageData(2,2),n,i,i,o,s,d,p,1,t);g.flipY=l,g.needsUpdate=!0;const m=new r(a,n,i,i,o,s,d,p,1,e);return m.flipY=l,m.needsUpdate=!0,{gainMap:g,sdr:m}};class R extends c{_renderer;_renderTargetOptions;_internalLoadingManager;_config;constructor(e,t){super(t),this._config=e,e.renderer&&(this._renderer=e.renderer),this._internalLoadingManager=new l}setRenderer(e){return this._renderer=e,this}setRenderTargetOptions(e){return this._renderTargetOptions=e,this}prepareQuadRenderer(){this._renderer||console.warn("WARNING: A Renderer was not passed to this Loader constructor or in setRenderer, the result of this Loader will need to be converted to a Data Texture with toDataTexture() before you can use it in your renderer.");const e=this._config.createMaterial({gainMapMax:[1,1,1],gainMapMin:[0,0,0],gamma:[1,1,1],offsetHdr:[1,1,1],offsetSdr:[1,1,1],hdrCapacityMax:1,hdrCapacityMin:0,maxDisplayBoost:1,gainMap:new r,sdr:new r});return this._config.createQuadRenderer({width:16,height:16,type:a,colorSpace:t,material:e,renderer:this._renderer,renderTargetOptions:this._renderTargetOptions})}processImages(e,t,a){return v(e,t,a)}createTextures(e,t,a){return b(e,t,a)}updateQuadRenderer(e,t,a,r,n){e.width=t.width,e.height=t.height,e.material.gainMap=a,e.material.sdr=r,e.material.gainMapMin=n.gainMapMin,e.material.gainMapMax=n.gainMapMax,e.material.offsetHdr=n.offsetHdr,e.material.offsetSdr=n.offsetSdr,e.material.gamma=n.gamma,e.material.hdrCapacityMin=n.hdrCapacityMin,e.material.hdrCapacityMax=n.hdrCapacityMax,e.material.maxDisplayBoost=Math.pow(2,n.hdrCapacityMax),e.material.needsUpdate=!0}}const S=new Set,O=(e,t,a)=>{const r=`${t}:${e}`;S.has(r)||(S.add(r),console.warn(`gainmap-js: ${e} from '${t}' is deprecated and will be removed in v4.0.0. Use ${a} from '@monogrid/gainmap-js/webgpu' with WebGPURenderer (which also has a WebGL2 backend) instead. It is not a drop-in replacement (it returns a GainMapNode, not a render target), see https://github.com/MONOGRID/gainmap-js#migrating-to-v400`))};export{h as G,R as L,F as M,u as X,b as a,x as b,f as c,y as d,I as e,v as p,O as w};
5
+ import{SRGBColorSpace as e,LinearSRGBColorSpace as t,HalfFloatType as a,Texture as r,UVMapping as n,ClampToEdgeWrapping as i,LinearFilter as o,LinearMipMapLinearFilter as s,RGBAFormat as d,UnsignedByteType as c,Loader as p,LoadingManager as l}from"three";import{I as g,d as f}from"./iso-gainmap-metadata-BJxZGPtk.js";function m(r){return n=>{const{sdr:i,gainMap:o,renderer:s}=n;i.colorSpace!==e&&(console.warn("SDR Colorspace needs to be *SRGBColorSpace*, setting it automatically"),i.colorSpace=e),i.needsUpdate=!0,o.colorSpace!==t&&(console.warn("Gainmap Colorspace needs to be *LinearSRGBColorSpace*, setting it automatically"),o.colorSpace=t),o.needsUpdate=!0;const d=r.createMaterial({...n,sdr:i,gainMap:o});return r.createQuadRenderer({width:i.image.width,height:i.image.height,type:a,colorSpace:t,material:d,renderer:s,renderTargetOptions:n.renderTargetOptions})}}class h extends Error{}class u extends Error{}const x=Array.from(g,e=>e.charCodeAt(0)),w=e=>{const t=new DataView(e.buffer,e.byteOffset,e.byteLength),a=4+x.length;for(let r=0;r+a<e.length;r++){if(255!==e[r]||226!==e[r+1])continue;if(!x.every((t,a)=>e[r+4+a]===t))continue;const n=Math.min(e.length,r+2+t.getUint16(r+2));if(!(n-(r+a)<=4))try{return f(e.subarray(r+a,n))}catch(e){return}}},y=(e,t,a)=>{const r=new RegExp(`${t}="([^"]*)"`,"i").exec(e);if(r)return r[1];const n=new RegExp(`<${t}[^>]*>([\\s\\S]*?)</${t}>`,"i").exec(e);if(n){const e=n[1].match(/<rdf:li>([^<]*)<\/rdf:li>/g);return e&&3===e.length?e.map(e=>e.replace(/<\/?rdf:li>/g,"")):n[1].trim()}if(void 0!==a)return a;throw new Error(`Can't find ${t} in gainmap metadata`)},M=e=>{let t;t="undefined"!=typeof TextDecoder?(new TextDecoder).decode(e):e.toString();let a=t.indexOf("<x:xmpmeta");for(;-1!==a;){const e=t.indexOf("x:xmpmeta>",a),r=t.slice(a,e+10);try{const e=y(r,"hdrgm:GainMapMin","0"),t=y(r,"hdrgm:GainMapMax"),a=y(r,"hdrgm:Gamma","1"),n=y(r,"hdrgm:OffsetSDR","0.015625"),i=y(r,"hdrgm:OffsetHDR","0.015625"),o=/hdrgm:HDRCapacityMin="([^"]*)"/.exec(r),s=o?o[1]:"0",d=/hdrgm:HDRCapacityMax="([^"]*)"/.exec(r);if(!d)throw new Error("Incomplete gainmap metadata");const c=d[1];return{gainMapMin:Array.isArray(e)?e.map(e=>parseFloat(e)):[parseFloat(e),parseFloat(e),parseFloat(e)],gainMapMax:Array.isArray(t)?t.map(e=>parseFloat(e)):[parseFloat(t),parseFloat(t),parseFloat(t)],gamma:Array.isArray(a)?a.map(e=>parseFloat(e)):[parseFloat(a),parseFloat(a),parseFloat(a)],offsetSdr:Array.isArray(n)?n.map(e=>parseFloat(e)):[parseFloat(n),parseFloat(n),parseFloat(n)],offsetHdr:Array.isArray(i)?i.map(e=>parseFloat(e)):[parseFloat(i),parseFloat(i),parseFloat(i)],hdrCapacityMin:parseFloat(s),hdrCapacityMax:parseFloat(c)}}catch(e){}a=t.indexOf("<x:xmpmeta",e)}};class F{options;constructor(e){this.options={debug:!(!e||void 0===e.debug)&&e.debug,extractFII:!e||void 0===e.extractFII||e.extractFII,extractNonFII:!e||void 0===e.extractNonFII||e.extractNonFII}}extract(e){return new Promise((t,a)=>{const r=this.options.debug,n=new DataView(e.buffer);if(65496!==n.getUint16(0))return void a(new Error("Not a valid jpeg"));const i=n.byteLength;let o,s=2,d=0;for(;s<i;){if(++d>250)return void a(new Error(`Found no marker after ${d} loops 😵`));if(255!==n.getUint8(s))return void a(new Error(`Not a valid marker at offset 0x${s.toString(16)}, found: 0x${n.getUint8(s).toString(16)}`));if(o=n.getUint8(s+1),r&&console.log(`Marker: ${o.toString(16)}`),226===o){r&&console.log("Found APP2 marker (0xffe2)");const e=s+4;if(1297106432===n.getUint32(e)){const r=e+4;let i;if(18761===n.getUint16(r))i=!1;else{if(19789!==n.getUint16(r))return void a(new Error("No valid endianness marker found in TIFF header"));i=!0}if(42!==n.getUint16(r+2,!i))return void a(new Error("Not valid TIFF data! (no 0x002A marker)"));const o=n.getUint32(r+4,!i);if(o<8)return void a(new Error("Not valid TIFF data! (First offset less than 8)"));const s=r+o,d=n.getUint16(s,!i),c=s+2;let p=0;for(let e=c;e<c+12*d;e+=12)45057===n.getUint16(e,!i)&&(p=n.getUint32(e+8,!i));const l=s+2+12*d+4,g=[];for(let e=l;e<l+16*p;e+=16){const t={MPType:n.getUint32(e,!i),size:n.getUint32(e+4,!i),dataOffset:n.getUint32(e+8,!i),dependantImages:n.getUint32(e+12,!i),start:-1,end:-1,isFII:!1};t.dataOffset?(t.start=r+t.dataOffset,t.isFII=!1):(t.start=0,t.isFII=!0),t.end=t.start+t.size,g.push(t)}if(this.options.extractNonFII&&g.length){const e=new Blob([n]),a=[];for(const t of g){if(t.isFII&&!this.options.extractFII)continue;const r=e.slice(t.start,t.end+1,"image/jpeg");a.push(r)}t(a)}}}s+=2+n.getUint16(s+2)}})}}const I=async e=>{const t=w(e)??M(e);if(!t)throw new u("Gain map XMP metadata not found");const a=new F({extractFII:!0,extractNonFII:!0}),r=await a.extract(e);if(2!==r.length)throw new h("Gain map recovery image not found");return{sdr:new Uint8Array(await r[0].arrayBuffer()),gainMap:new Uint8Array(await r[1].arrayBuffer()),metadata:t}},U=e=>new Promise((t,a)=>{const r=document.createElement("img");r.onload=()=>{t(r)},r.onerror=e=>{a(e)},r.src=URL.createObjectURL(e)}),v=async(e,t,a)=>{const r=t?new Blob([t],{type:"image/jpeg"}):void 0,n=new Blob([e],{type:"image/jpeg"});let i,o,s=!1;if("undefined"==typeof createImageBitmap){const e=await Promise.all([r?U(r):Promise.resolve(void 0),U(n)]);o=e[0],i=e[1],s="flipY"===a}else{const e=await Promise.all([r?createImageBitmap(r,{imageOrientation:a||"flipY"}):Promise.resolve(void 0),createImageBitmap(n,{imageOrientation:a||"flipY"})]);o=e[0],i=e[1]}return{sdrImage:i,gainMapImage:o,needsFlip:s}},S=(a,p,l)=>{const g=new r(p||new ImageData(2,2),n,i,i,o,s,d,c,1,t);g.flipY=l,g.needsUpdate=!0;const f=new r(a,n,i,i,o,s,d,c,1,e);return f.flipY=l,f.needsUpdate=!0,{gainMap:g,sdr:f}};class R extends p{_renderer;_renderTargetOptions;_internalLoadingManager;_config;constructor(e,t){super(t),this._config=e,e.renderer&&(this._renderer=e.renderer),this._internalLoadingManager=new l}setRenderer(e){return this._renderer=e,this}setRenderTargetOptions(e){return this._renderTargetOptions=e,this}prepareQuadRenderer(){this._renderer||console.warn("WARNING: A Renderer was not passed to this Loader constructor or in setRenderer, the result of this Loader will need to be converted to a Data Texture with toDataTexture() before you can use it in your renderer.");const e=this._config.createMaterial({gainMapMax:[1,1,1],gainMapMin:[0,0,0],gamma:[1,1,1],offsetHdr:[1,1,1],offsetSdr:[1,1,1],hdrCapacityMax:1,hdrCapacityMin:0,maxDisplayBoost:1,gainMap:new r,sdr:new r});return this._config.createQuadRenderer({width:16,height:16,type:a,colorSpace:t,material:e,renderer:this._renderer,renderTargetOptions:this._renderTargetOptions})}processImages(e,t,a){return v(e,t,a)}createTextures(e,t,a){return S(e,t,a)}updateQuadRenderer(e,t,a,r,n){e.width=t.width,e.height=t.height,e.material.gainMap=a,e.material.sdr=r,e.material.gainMapMin=n.gainMapMin,e.material.gainMapMax=n.gainMapMax,e.material.offsetHdr=n.offsetHdr,e.material.offsetSdr=n.offsetSdr,e.material.gamma=n.gamma,e.material.hdrCapacityMin=n.hdrCapacityMin,e.material.hdrCapacityMax=n.hdrCapacityMax,e.material.maxDisplayBoost=Math.pow(2,n.hdrCapacityMax),e.material.needsUpdate=!0}}export{h as G,R as L,F as M,u as X,S as a,w as b,m as c,M as d,I as e,v as p};
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @monogrid/gainmap-js v3.6.1
2
+ * @monogrid/gainmap-js v3.7.0
3
3
  * With ❤️, by MONOGRID <gainmap@monogrid.com>
4
4
  */
5
5
 
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @monogrid/gainmap-js v3.6.1
2
+ * @monogrid/gainmap-js v3.7.0
3
3
  * With ❤️, by MONOGRID <gainmap@monogrid.com>
4
4
  */
5
5
  import{ClampToEdgeWrapping as e,LinearFilter as r,Scene as t,OrthographicCamera as i,HalfFloatType as s,FloatType as a,Mesh as n,PlaneGeometry as h,WebGLRenderTarget as o,RGBAFormat as d,UVMapping as p,WebGLRenderer as _,DataTexture as g,LinearSRGBColorSpace as l,ShaderMaterial as c,Texture as w,MeshBasicMaterial as m,IntType as T,ShortType as u,ByteType as y,UnsignedIntType as f,UnsignedByteType as O}from"three";const b=(e,r,t)=>{let i;switch(e){case O:i=new Uint8ClampedArray(r*t*4);break;case s:i=new Uint16Array(r*t*4);break;case f:i=new Uint32Array(r*t*4);break;case y:i=new Int8Array(r*t*4);break;case u:i=new Int16Array(r*t*4);break;case T:i=new Int32Array(r*t*4);break;case a:i=new Float32Array(r*t*4);break;default:throw new Error("Unsupported data type")}return i};let v;class R{_renderer;_rendererIsDisposable=!1;_material;_scene;_camera;_quad;_renderTarget;_width;_height;_type;_colorSpace;_supportsReadPixels=!0;constructor(_){this._width=_.width,this._height=_.height,this._type=_.type,this._colorSpace=_.colorSpace;const g={format:d,depthBuffer:!1,stencilBuffer:!1,type:this._type,colorSpace:this._colorSpace,anisotropy:void 0!==_.renderTargetOptions?.anisotropy?_.renderTargetOptions?.anisotropy:1,generateMipmaps:void 0!==_.renderTargetOptions?.generateMipmaps&&_.renderTargetOptions?.generateMipmaps,magFilter:void 0!==_.renderTargetOptions?.magFilter?_.renderTargetOptions?.magFilter:r,minFilter:void 0!==_.renderTargetOptions?.minFilter?_.renderTargetOptions?.minFilter:r,samples:void 0!==_.renderTargetOptions?.samples?_.renderTargetOptions?.samples:void 0,wrapS:void 0!==_.renderTargetOptions?.wrapS?_.renderTargetOptions?.wrapS:e,wrapT:void 0!==_.renderTargetOptions?.wrapT?_.renderTargetOptions?.wrapT:e};if(this._material=_.material,_.renderer?this._renderer=_.renderer:(this._renderer=R.instantiateRenderer(),this._rendererIsDisposable=!0),this._scene=new t,this._camera=new i,this._camera.position.set(0,0,10),this._camera.left=-.5,this._camera.right=.5,this._camera.top=.5,this._camera.bottom=-.5,this._camera.updateProjectionMatrix(),!((e,r,t,i)=>{if(void 0!==v)return v;const s=new o(1,1,i);r.setRenderTarget(s);const a=new n(new h,new m({color:16777215}));r.render(a,t),r.setRenderTarget(null);const d=b(e,s.width,s.height);return r.readRenderTargetPixels(s,0,0,s.width,s.height,d),s.dispose(),a.geometry.dispose(),a.material.dispose(),v=0!==d[0],v})(this._type,this._renderer,this._camera,g)){let e;if(this._type===s)e=this._renderer.extensions.has("EXT_color_buffer_float")?a:void 0;void 0!==e?(console.warn(`This browser does not support reading pixels from ${this._type} RenderTargets, switching to ${a}`),this._type=e):(this._supportsReadPixels=!1,console.warn("This browser dos not support toArray or toDataTexture, calls to those methods will result in an error thrown"))}this._quad=new n(new h,this._material),this._quad.geometry.computeBoundingBox(),this._scene.add(this._quad),this._renderTarget=new o(this.width,this.height,g),this._renderTarget.texture.mapping=void 0!==_.renderTargetOptions?.mapping?_.renderTargetOptions?.mapping:p}static instantiateRenderer(){const e=new _;return e.setSize(128,128),e}render=()=>{this._renderer.setRenderTarget(this._renderTarget);try{this._renderer.render(this._scene,this._camera)}catch(e){throw this._renderer.setRenderTarget(null),e}this._renderer.setRenderTarget(null)};toArray(){if(!this._supportsReadPixels)throw new Error("Can't read pixels in this browser");const e=b(this._type,this._width,this._height);return this._renderer.readRenderTargetPixels(this._renderTarget,0,0,this._width,this._height,e),e}toDataTexture(t){const i=new g(this.toArray(),this.width,this.height,d,this._type,t?.mapping||p,t?.wrapS||e,t?.wrapT||e,t?.magFilter||r,t?.minFilter||r,t?.anisotropy||1,l);return i.generateMipmaps=void 0!==t?.generateMipmaps&&t?.generateMipmaps,i}disposeOnDemandRenderer(){this._renderer.setRenderTarget(null),this._rendererIsDisposable&&(this._renderer.dispose(),this._renderer.forceContextLoss())}dispose(e){this.disposeOnDemandRenderer(),e&&this.renderTarget.dispose(),this.material instanceof c&&Object.values(this.material.uniforms).forEach(e=>{e.value instanceof w&&e.value.dispose()}),Object.values(this.material).forEach(e=>{e instanceof w&&e.dispose()}),this.material.dispose(),this._quad.geometry.dispose()}get width(){return this._width}set width(e){this._width=e,this._renderTarget.setSize(this._width,this._height)}get height(){return this._height}set height(e){this._height=e,this._renderTarget.setSize(this._width,this._height)}get renderer(){return this._renderer}get renderTarget(){return this._renderTarget}set renderTarget(e){this._renderTarget=e,this._width=e.width,this._height=e.height}get material(){return this._material}get type(){return this._type}get colorSpace(){return this._colorSpace}}export{R as Q};
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @monogrid/gainmap-js v3.6.1
2
+ * @monogrid/gainmap-js v3.7.0
3
3
  * With ❤️, by MONOGRID <gainmap@monogrid.com>
4
4
  */
5
5
  var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function o(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}export{e as c,o as g};
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @monogrid/gainmap-js v3.6.1
2
+ * @monogrid/gainmap-js v3.7.0
3
3
  * With ❤️, by MONOGRID <gainmap@monogrid.com>
4
4
  */
5
5
 
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @monogrid/gainmap-js v3.6.1
2
+ * @monogrid/gainmap-js v3.7.0
3
3
  * With ❤️, by MONOGRID <gainmap@monogrid.com>
4
4
  */
5
5
  const e=async e=>{if("undefined"==typeof createImageBitmap)throw new Error("createImageBitmap() not supported.");const{source:t,mimeType:a,quality:n,flipY:r}=e;let o;if((t instanceof Uint8Array||t instanceof Uint8ClampedArray)&&"sourceMimeType"in e)o=new Blob([t],{type:e.sourceMimeType});else{if(!(t instanceof ImageData))throw new Error("Invalid source image");o=t}const i=await createImageBitmap(o),s=i.width,c=i.height;let f;"undefined"!=typeof OffscreenCanvas?f=new OffscreenCanvas(s,c):(f=document.createElement("canvas"),f.width=s,f.height=c);const m=f.getContext("2d");if(!m)throw new Error("Failed to create canvas Context");!0===r&&(m.translate(0,c),m.scale(1,-1)),m.drawImage(i,0,0,s,c);const w=await(async(e,t,a)=>{if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return e.convertToBlob({type:t,quality:a||.9});if(e instanceof HTMLCanvasElement)return new Promise((n,r)=>{e.toBlob(e=>{e?n(e):r(new Error("Failed to convert canvas to blob"))},t,a||.9)});throw new Error("Unsupported canvas element")})(f,a,n||.9);return{data:new Uint8Array(await w.arrayBuffer()),mimeType:a,width:s,height:c}};export{e as c};
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @monogrid/gainmap-js v3.6.1
2
+ * @monogrid/gainmap-js v3.7.0
3
3
  * With ❤️, by MONOGRID <gainmap@monogrid.com>
4
4
  */
5
5