@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
@@ -1,13 +1,140 @@
1
1
  /**
2
- * @monogrid/gainmap-js v3.6.1
2
+ * @monogrid/gainmap-js v3.7.1
3
3
  * With ❤️, by MONOGRID <gainmap@monogrid.com>
4
4
  */
5
5
 
6
6
  (function (global, factory) {
7
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('three'), require('three/webgpu'), require('three/tsl')) :
8
- typeof define === 'function' && define.amd ? define(['exports', 'three', 'three/webgpu', 'three/tsl'], factory) :
9
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["@monogrid/gainmap-js"] = {}, global.three, global["three/webgpu"], global["three/tsl"]));
10
- })(this, (function (exports, three, webgpu, tsl) { 'use strict';
7
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('three/webgpu'), require('three'), require('three/tsl')) :
8
+ typeof define === 'function' && define.amd ? define(['exports', 'three/webgpu', 'three', 'three/tsl'], factory) :
9
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["@monogrid/gainmap-js"] = {}, global["three/webgpu"], global.three, global["three/tsl"]));
10
+ })(this, (function (exports, webgpu, three, tsl) { 'use strict';
11
+
12
+ /**
13
+ * Base class for TSL texture nodes whose texture is a render target, filled by rendering a full screen quad.
14
+ *
15
+ * The quad is rendered only when something changed since the last render:
16
+ * subclasses list what the result depends on in {@link RenderTargetNode._getState}
17
+ * and the other render target nodes they read from in {@link RenderTargetNode._getDependencies}.
18
+ * Sampling the node costs a single texture read, like any other texture.
19
+ *
20
+ * The node renders itself before rendering whenever it is part of a rendered node graph
21
+ * (material, `scene.backgroundNode`, ...). When only its texture is used (`node.value`)
22
+ * call {@link RenderTargetNode.render} yourself.
23
+ *
24
+ * @category Nodes
25
+ * @group Nodes
26
+ */
27
+ class RenderTargetNode extends webgpu.TextureNode {
28
+ /**
29
+ * The render target holding the result
30
+ */
31
+ renderTarget;
32
+ /**
33
+ * Incremented every time the render target is rendered,
34
+ * nodes depending on this one use it to know when to render again
35
+ */
36
+ revision = 0;
37
+ _quadMesh;
38
+ _material;
39
+ // filled by RendererUtils.resetRendererState
40
+ _rendererState = {};
41
+ _state = [];
42
+ /**
43
+ * @param material the material rendered on the full screen quad
44
+ * @param renderTargetOptions options of the render target, it is created with a 1x1 size
45
+ * and resized to {@link RenderTargetNode.width} x {@link RenderTargetNode.height} before rendering
46
+ */
47
+ constructor(material, renderTargetOptions) {
48
+ const renderTarget = new webgpu.RenderTarget(1, 1, { depthBuffer: false, ...renderTargetOptions });
49
+ super(renderTarget.texture);
50
+ this.renderTarget = renderTarget;
51
+ this.updateBeforeType = webgpu.NodeUpdateType.RENDER;
52
+ this._material = material;
53
+ this._quadMesh = new webgpu.QuadMesh(material);
54
+ }
55
+ /**
56
+ * Render target nodes read by this node, rendered (if needed) before this one
57
+ */
58
+ _getDependencies() { return []; }
59
+ /**
60
+ * Called after the render target has been rendered
61
+ */
62
+ _onRender() { }
63
+ /**
64
+ * Forces a render the next time {@link RenderTargetNode.render} is called,
65
+ * use it when something the node can't track changed (e.g. a custom input node)
66
+ */
67
+ invalidate() {
68
+ this._state = [];
69
+ return this;
70
+ }
71
+ /**
72
+ * Renders into {@link RenderTargetNode.renderTarget}, only if something changed since the last render.
73
+ *
74
+ * Called automatically when the node is part of a rendered node graph.
75
+ *
76
+ * @param renderer
77
+ * @returns `true` if the render target was rendered
78
+ */
79
+ render(renderer) {
80
+ const dependencies = this._getDependencies();
81
+ for (const dependency of dependencies)
82
+ dependency.render(renderer);
83
+ const { width, height } = this;
84
+ // not ready yet
85
+ if (width === 0 || height === 0)
86
+ return false;
87
+ const state = [width, height, ...dependencies.map(d => d.revision), ...this._getState()];
88
+ if (state.length === this._state.length && state.every((v, i) => v === this._state[i]))
89
+ return false;
90
+ this._state = state;
91
+ if (this.renderTarget.width !== width || this.renderTarget.height !== height)
92
+ this.renderTarget.setSize(width, height);
93
+ webgpu.RendererUtils.resetRendererState(renderer, this._rendererState);
94
+ renderer.setRenderTarget(this.renderTarget);
95
+ this._quadMesh.render(renderer);
96
+ webgpu.RendererUtils.restoreRendererState(renderer, this._rendererState);
97
+ this.revision++;
98
+ this._onRender();
99
+ return true;
100
+ }
101
+ /**
102
+ * Called by three.js before rendering, renders the node when needed
103
+ * @internal
104
+ */
105
+ updateBefore(frame) {
106
+ if (frame.renderer)
107
+ this.render(frame.renderer);
108
+ return undefined;
109
+ }
110
+ set value(value) {
111
+ if (this.renderTarget && value !== this.renderTarget.texture) {
112
+ throw new Error(`${this.constructor.name}: the value of this node is its render target texture and can't be replaced`);
113
+ }
114
+ }
115
+ get value() {
116
+ return this.renderTarget?.texture;
117
+ }
118
+ /**
119
+ * Clones created by `sample()` & co. are plain TextureNodes reading this node's texture,
120
+ * they keep it updated before rendering as well
121
+ */
122
+ clone() {
123
+ const node = new webgpu.TextureNode(this.value, this.uvNode, this.levelNode, this.biasNode);
124
+ node.sampler = this.sampler;
125
+ node.updateBeforeType = webgpu.NodeUpdateType.RENDER;
126
+ node.updateBefore = (frame) => this.updateBefore(frame);
127
+ return node;
128
+ }
129
+ /**
130
+ * Disposes the render target and the material
131
+ */
132
+ dispose() {
133
+ this.renderTarget.dispose();
134
+ this._material.dispose();
135
+ super.dispose();
136
+ }
137
+ }
11
138
 
12
139
  /**
13
140
  * Shared decode implementation factory
@@ -1307,33 +1434,25 @@
1307
1434
  * scene.backgroundNode = hdr.sample(equirectUV())
1308
1435
  * hdr.maxDisplayBoost.value = 2 // re-decodes once, on the next frame
1309
1436
  */
1310
- class GainMapNode extends webgpu.TextureNode {
1437
+ class GainMapNode extends RenderTargetNode {
1311
1438
  static get type() { return 'GainMapNode'; }
1312
1439
  /**
1313
1440
  * Shared textures and uniforms
1314
1441
  */
1315
1442
  uniforms;
1316
- /**
1317
- * The render target holding the decoded HDR image
1318
- */
1319
- renderTarget;
1320
- _quadMesh;
1321
- _material;
1322
- // filled by RendererUtils.resetRendererState
1323
- _rendererState = {};
1324
- _state = [];
1443
+ // set when the textures are produced by other render target nodes (e.g. a gain map encoder)
1444
+ _sdrSource = null;
1445
+ _gainMapSource = null;
1325
1446
  constructor() {
1326
- const renderTarget = new webgpu.RenderTarget(1, 1, {
1447
+ const material = new webgpu.MeshBasicNodeMaterial();
1448
+ material.name = 'GainMapDecoder';
1449
+ super(material, {
1327
1450
  type: webgpu.HalfFloatType,
1328
1451
  colorSpace: webgpu.LinearSRGBColorSpace,
1329
- depthBuffer: false,
1330
1452
  generateMipmaps: true,
1331
1453
  minFilter: webgpu.LinearMipmapLinearFilter,
1332
1454
  magFilter: webgpu.LinearFilter
1333
1455
  });
1334
- super(renderTarget.texture);
1335
- this.renderTarget = renderTarget;
1336
- this.updateBeforeType = webgpu.NodeUpdateType.RENDER;
1337
1456
  const u = this.uniforms = {
1338
1457
  sdr: tsl.texture(new webgpu.Texture()),
1339
1458
  gainMap: tsl.texture(new webgpu.Texture()),
@@ -1350,10 +1469,7 @@
1350
1469
  const logBoost = tsl.mix(u.gainMapMin, u.gainMapMax, logRecovery);
1351
1470
  const weight = tsl.saturate(tsl.log2(u.maxDisplayBoost).sub(u.hdrCapacityMin).div(u.hdrCapacityMax.sub(u.hdrCapacityMin)));
1352
1471
  const hdr = u.sdr.rgb.add(u.offsetSdr).mul(tsl.exp2(logBoost.mul(weight))).sub(u.offsetHdr);
1353
- this._material = new webgpu.MeshBasicNodeMaterial();
1354
- this._material.name = 'GainMapDecoder';
1355
- this._material.colorNode = tsl.vec4(hdr.clamp(-HALF_FLOAT_MAX, HALF_FLOAT_MAX), 1);
1356
- this._quadMesh = new webgpu.QuadMesh(this._material);
1472
+ material.colorNode = tsl.vec4(hdr.clamp(-HALF_FLOAT_MAX, HALF_FLOAT_MAX), 1);
1357
1473
  }
1358
1474
  /** The SDR rendition texture (sRGB) */
1359
1475
  get sdr() { return this.uniforms.sdr.value; }
@@ -1379,19 +1495,32 @@
1379
1495
  */
1380
1496
  get maxDisplayBoost() { return this.uniforms.maxDisplayBoost; }
1381
1497
  /** Width of the SDR image, 0 until loaded */
1382
- get width() { return this.sdr.image?.width ?? 0; }
1498
+ get width() {
1499
+ if (this._sdrSource)
1500
+ return this._sdrSource.width;
1501
+ return this.sdr.image?.width ?? 0;
1502
+ }
1383
1503
  /** Height of the SDR image, 0 until loaded */
1384
- get height() { return this.sdr.image?.height ?? 0; }
1504
+ get height() {
1505
+ if (this._sdrSource)
1506
+ return this._sdrSource.height;
1507
+ return this.sdr.image?.height ?? 0;
1508
+ }
1385
1509
  /**
1386
1510
  * Sets the SDR and gain map textures.
1387
1511
  * The SDR texture is expected in sRGB color space, the gain map in linear.
1388
1512
  *
1513
+ * Render target nodes (e.g. the `sdr` and `gainMap` nodes of a `GainMapEncoder`) are accepted as well:
1514
+ * they are rendered before decoding and the image is decoded again whenever they change.
1515
+ *
1389
1516
  * @param sdr
1390
1517
  * @param gainMap
1391
1518
  */
1392
1519
  setTextures(sdr, gainMap) {
1393
- this.uniforms.sdr.value = sdr;
1394
- this.uniforms.gainMap.value = gainMap;
1520
+ this._sdrSource = sdr instanceof RenderTargetNode ? sdr : null;
1521
+ this._gainMapSource = gainMap instanceof RenderTargetNode ? gainMap : null;
1522
+ this.uniforms.sdr.value = sdr instanceof RenderTargetNode ? sdr.value : sdr;
1523
+ this.uniforms.gainMap.value = gainMap instanceof RenderTargetNode ? gainMap.value : gainMap;
1395
1524
  // size the render target right away, so `value` has its final size before the first decode
1396
1525
  if (this.width > 0 && this.height > 0)
1397
1526
  this.renderTarget.setSize(this.width, this.height);
@@ -1415,7 +1544,7 @@
1415
1544
  u.maxDisplayBoost.value = Math.pow(2, metadata.hdrCapacityMax);
1416
1545
  return this;
1417
1546
  }
1418
- _currentState() {
1547
+ _getState() {
1419
1548
  const u = this.uniforms;
1420
1549
  return [
1421
1550
  this.sdr.id, this.sdr.version, this.gainMap.id, this.gainMap.version,
@@ -1424,6 +1553,17 @@
1424
1553
  u.hdrCapacityMin.value, u.hdrCapacityMax.value, u.maxDisplayBoost.value
1425
1554
  ];
1426
1555
  }
1556
+ _getDependencies() {
1557
+ const dependencies = [];
1558
+ if (this._sdrSource)
1559
+ dependencies.push(this._sdrSource);
1560
+ if (this._gainMapSource)
1561
+ dependencies.push(this._gainMapSource);
1562
+ return dependencies;
1563
+ }
1564
+ _onRender() {
1565
+ this.value.needsPMREMUpdate = true;
1566
+ }
1427
1567
  /**
1428
1568
  * Decodes the image into {@link GainMapNode.renderTarget}, only if something changed since the last decode.
1429
1569
  *
@@ -1433,19 +1573,7 @@
1433
1573
  * @returns `true` if the image was decoded
1434
1574
  */
1435
1575
  decode(renderer) {
1436
- // not loaded yet
1437
- if (this.width === 0 || this.height === 0)
1438
- return false;
1439
- const state = this._currentState();
1440
- if (state.length === this._state.length && state.every((v, i) => v === this._state[i]))
1441
- return false;
1442
- this._state = state;
1443
- webgpu.RendererUtils.resetRendererState(renderer, this._rendererState);
1444
- renderer.setRenderTarget(this.renderTarget);
1445
- this._quadMesh.render(renderer);
1446
- webgpu.RendererUtils.restoreRendererState(renderer, this._rendererState);
1447
- this.value.needsPMREMUpdate = true;
1448
- return true;
1576
+ return this.render(renderer);
1449
1577
  }
1450
1578
  /**
1451
1579
  * Calls {@link GainMapNode.decode} once per render, before the node is evaluated.
@@ -1457,33 +1585,15 @@
1457
1585
  this.decode(frame.renderer);
1458
1586
  return undefined;
1459
1587
  }
1460
- set value(value) {
1461
- if (this.renderTarget && value !== this.renderTarget.texture) {
1462
- throw new Error('GainMapNode: the value of this node is its render target texture and can\'t be replaced');
1463
- }
1464
- }
1465
- get value() {
1466
- return this.renderTarget?.texture;
1467
- }
1468
- /**
1469
- * Clones created by `sample()` & co. are plain TextureNodes reading this node's texture,
1470
- * they keep it updated before rendering as well
1471
- */
1472
- clone() {
1473
- const node = new webgpu.TextureNode(this.value, this.uvNode, this.levelNode, this.biasNode);
1474
- node.sampler = this.sampler;
1475
- node.updateBeforeType = webgpu.NodeUpdateType.RENDER;
1476
- node.updateBefore = (frame) => this.updateBefore(frame);
1477
- return node;
1478
- }
1479
1588
  /**
1480
1589
  * Disposes the render target, the SDR and gain map textures
1590
+ * (unless they belong to other render target nodes)
1481
1591
  */
1482
1592
  dispose() {
1483
- this.renderTarget.dispose();
1484
- this._material.dispose();
1485
- this.sdr.dispose();
1486
- this.gainMap.dispose();
1593
+ if (!this._sdrSource)
1594
+ this.sdr.dispose();
1595
+ if (!this._gainMapSource)
1596
+ this.gainMap.dispose();
1487
1597
  super.dispose();
1488
1598
  }
1489
1599
  }
@@ -1851,6 +1961,7 @@
1851
1961
  exports.LoaderBaseShared = LoaderBaseShared;
1852
1962
  exports.MPFExtractor = MPFExtractor;
1853
1963
  exports.QuadRenderer = QuadRenderer;
1964
+ exports.RenderTargetNode = RenderTargetNode;
1854
1965
  exports.XMPMetadataNotFoundError = XMPMetadataNotFoundError;
1855
1966
  exports.createDecodeFunction = createDecodeFunction;
1856
1967
  exports.createTextures = createTextures;
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @monogrid/gainmap-js v3.6.1
2
+ * @monogrid/gainmap-js v3.7.1
3
3
  * With ❤️, by MONOGRID <gainmap@monogrid.com>
4
4
  */
5
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("three"),require("three/webgpu"),require("three/tsl")):"function"==typeof define&&define.amd?define(["exports","three","three/webgpu","three/tsl"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["@monogrid/gainmap-js"]={},e.three,e["three/webgpu"],e["three/tsl"])}(this,function(e,t,r,a){"use strict";function i(e){return r=>{const{sdr:a,gainMap:i,renderer:n}=r;a.colorSpace!==t.SRGBColorSpace&&(console.warn("SDR Colorspace needs to be *SRGBColorSpace*, setting it automatically"),a.colorSpace=t.SRGBColorSpace),a.needsUpdate=!0,i.colorSpace!==t.LinearSRGBColorSpace&&(console.warn("Gainmap Colorspace needs to be *LinearSRGBColorSpace*, setting it automatically"),i.colorSpace=t.LinearSRGBColorSpace),i.needsUpdate=!0;const s=e.createMaterial({...r,sdr:a,gainMap:i});return e.createQuadRenderer({width:a.image.width,height:a.image.height,type:t.HalfFloatType,colorSpace:t.LinearSRGBColorSpace,material:s,renderer:n,renderTargetOptions:r.renderTargetOptions})}}class n extends Error{}class s extends Error{}const o=e=>{const t=new DataView(e.buffer,e.byteOffset,e.byteLength);let r=0;const a=()=>{const e=t.getUint16(r);return r+=2,e},i=()=>{const e=t.getUint32(r);return r+=4,e},n=a();if(0!==n)throw new Error(`Unsupported ISO 21496-1 minimum_version ${n}`);a();const s=t.getUint8(r++);if(4&s)throw new Error("ISO 21496-1 metadata with HDR base image is not supported");const o=128&s?3:1,d=8&s?i():void 0,h=e=>{const a=e?(()=>{const e=t.getInt32(r);return r+=4,e})():i(),n=d??i();if(0===n)throw new Error("Invalid ISO 21496-1 fraction with zero denominator");return a/n},p=h(!1),g=h(!1);if(p>g)throw new Error("ISO 21496-1 metadata with HDR base image is not supported");const l=[],m=[],c=[],f=[],u=[];for(let e=0;e<o;e++)l.push(h(!0)),m.push(h(!0)),c.push(h(!1)),f.push(h(!0)),u.push(h(!0));const M=e=>3===o?e:[e[0],e[0],e[0]];return{gainMapMin:M(l),gainMapMax:M(m),gamma:M(c),offsetSdr:M(f),offsetHdr:M(u),hdrCapacityMin:p,hdrCapacityMax:g}},d=Array.from("urn:iso:std:iso:ts:21496:-1\0",e=>e.charCodeAt(0)),h=e=>{const t=new DataView(e.buffer,e.byteOffset,e.byteLength),r=4+d.length;for(let a=0;a+r<e.length;a++){if(255!==e[a]||226!==e[a+1])continue;if(!d.every((t,r)=>e[a+4+r]===t))continue;const i=Math.min(e.length,a+2+t.getUint16(a+2));if(!(i-(a+r)<=4))try{return o(e.subarray(a+r,i))}catch(e){return}}},p=(e,t,r)=>{const a=new RegExp(`${t}="([^"]*)"`,"i").exec(e);if(a)return a[1];const i=new RegExp(`<${t}[^>]*>([\\s\\S]*?)</${t}>`,"i").exec(e);if(i){const e=i[1].match(/<rdf:li>([^<]*)<\/rdf:li>/g);return e&&3===e.length?e.map(e=>e.replace(/<\/?rdf:li>/g,"")):i[1].trim()}if(void 0!==r)return r;throw new Error(`Can't find ${t} in gainmap metadata`)},g=e=>{let t;t="undefined"!=typeof TextDecoder?(new TextDecoder).decode(e):e.toString();let r=t.indexOf("<x:xmpmeta");for(;-1!==r;){const e=t.indexOf("x:xmpmeta>",r),a=t.slice(r,e+10);try{const e=p(a,"hdrgm:GainMapMin","0"),t=p(a,"hdrgm:GainMapMax"),r=p(a,"hdrgm:Gamma","1"),i=p(a,"hdrgm:OffsetSDR","0.015625"),n=p(a,"hdrgm:OffsetHDR","0.015625"),s=/hdrgm:HDRCapacityMin="([^"]*)"/.exec(a),o=s?s[1]:"0",d=/hdrgm:HDRCapacityMax="([^"]*)"/.exec(a);if(!d)throw new Error("Incomplete gainmap metadata");const h=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(r)?r.map(e=>parseFloat(e)):[parseFloat(r),parseFloat(r),parseFloat(r)],offsetSdr:Array.isArray(i)?i.map(e=>parseFloat(e)):[parseFloat(i),parseFloat(i),parseFloat(i)],offsetHdr:Array.isArray(n)?n.map(e=>parseFloat(e)):[parseFloat(n),parseFloat(n),parseFloat(n)],hdrCapacityMin:parseFloat(o),hdrCapacityMax:parseFloat(h)}}catch(e){}r=t.indexOf("<x:xmpmeta",e)}};class l{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,r)=>{const a=this.options.debug,i=new DataView(e.buffer);if(65496!==i.getUint16(0))return void r(new Error("Not a valid jpeg"));const n=i.byteLength;let s,o=2,d=0;for(;o<n;){if(++d>250)return void r(new Error(`Found no marker after ${d} loops 😵`));if(255!==i.getUint8(o))return void r(new Error(`Not a valid marker at offset 0x${o.toString(16)}, found: 0x${i.getUint8(o).toString(16)}`));if(s=i.getUint8(o+1),a&&console.log(`Marker: ${s.toString(16)}`),226===s){a&&console.log("Found APP2 marker (0xffe2)");const e=o+4;if(1297106432===i.getUint32(e)){const a=e+4;let n;if(18761===i.getUint16(a))n=!1;else{if(19789!==i.getUint16(a))return void r(new Error("No valid endianness marker found in TIFF header"));n=!0}if(42!==i.getUint16(a+2,!n))return void r(new Error("Not valid TIFF data! (no 0x002A marker)"));const s=i.getUint32(a+4,!n);if(s<8)return void r(new Error("Not valid TIFF data! (First offset less than 8)"));const o=a+s,d=i.getUint16(o,!n),h=o+2;let p=0;for(let e=h;e<h+12*d;e+=12)45057===i.getUint16(e,!n)&&(p=i.getUint32(e+8,!n));const g=o+2+12*d+4,l=[];for(let e=g;e<g+16*p;e+=16){const t={MPType:i.getUint32(e,!n),size:i.getUint32(e+4,!n),dataOffset:i.getUint32(e+8,!n),dependantImages:i.getUint32(e+12,!n),start:-1,end:-1,isFII:!1};t.dataOffset?(t.start=a+t.dataOffset,t.isFII=!1):(t.start=0,t.isFII=!0),t.end=t.start+t.size,l.push(t)}if(this.options.extractNonFII&&l.length){const e=new Blob([i]),r=[];for(const t of l){if(t.isFII&&!this.options.extractFII)continue;const a=e.slice(t.start,t.end+1,"image/jpeg");r.push(a)}t(r)}}}o+=2+i.getUint16(o+2)}})}}const m=async e=>{const t=h(e)??g(e);if(!t)throw new s("Gain map XMP metadata not found");const r=new l({extractFII:!0,extractNonFII:!0}),a=await r.extract(e);if(2!==a.length)throw new n("Gain map recovery image not found");return{sdr:new Uint8Array(await a[0].arrayBuffer()),gainMap:new Uint8Array(await a[1].arrayBuffer()),metadata:t}},c=e=>new Promise((t,r)=>{const a=document.createElement("img");a.onload=()=>{t(a)},a.onerror=e=>{r(e)},a.src=URL.createObjectURL(e)}),f=async(e,t,r)=>{const a=t?new Blob([t],{type:"image/jpeg"}):void 0,i=new Blob([e],{type:"image/jpeg"});let n,s,o=!1;if("undefined"==typeof createImageBitmap){const e=await Promise.all([a?c(a):Promise.resolve(void 0),c(i)]);s=e[0],n=e[1],o="flipY"===r}else{const e=await Promise.all([a?createImageBitmap(a,{imageOrientation:r||"flipY"}):Promise.resolve(void 0),createImageBitmap(i,{imageOrientation:r||"flipY"})]);s=e[0],n=e[1]}return{sdrImage:n,gainMapImage:s,needsFlip:o}},u=(e,r,a)=>{const i=new t.Texture(r||new ImageData(2,2),t.UVMapping,t.ClampToEdgeWrapping,t.ClampToEdgeWrapping,t.LinearFilter,t.LinearMipMapLinearFilter,t.RGBAFormat,t.UnsignedByteType,1,t.LinearSRGBColorSpace);i.flipY=a,i.needsUpdate=!0;const n=new t.Texture(e,t.UVMapping,t.ClampToEdgeWrapping,t.ClampToEdgeWrapping,t.LinearFilter,t.LinearMipMapLinearFilter,t.RGBAFormat,t.UnsignedByteType,1,t.SRGBColorSpace);return n.flipY=a,n.needsUpdate=!0,{gainMap:i,sdr:n}};class M extends t.Loader{_renderer;_renderTargetOptions;_internalLoadingManager;_config;constructor(e,r){super(r),this._config=e,e.renderer&&(this._renderer=e.renderer),this._internalLoadingManager=new t.LoadingManager}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 t.Texture,sdr:new t.Texture});return this._config.createQuadRenderer({width:16,height:16,type:t.HalfFloatType,colorSpace:t.LinearSRGBColorSpace,material:e,renderer:this._renderer,renderTargetOptions:this._renderTargetOptions})}processImages(e,t,r){return f(e,t,r)}createTextures(e,t,r){return u(e,t,r)}updateQuadRenderer(e,t,r,a,i){e.width=t.width,e.height=t.height,e.material.gainMap=r,e.material.sdr=a,e.material.gainMapMin=i.gainMapMin,e.material.gainMapMax=i.gainMapMax,e.material.offsetHdr=i.offsetHdr,e.material.offsetSdr=i.offsetSdr,e.material.gamma=i.gamma,e.material.hdrCapacityMin=i.hdrCapacityMin,e.material.hdrCapacityMax=i.hdrCapacityMax,e.material.maxDisplayBoost=Math.pow(2,i.hdrCapacityMax),e.material.needsUpdate=!0}}class y{_renderer;_rendererIsDisposable=!1;_material;_scene;_camera;_quad;_renderTarget;_width;_height;_type;_colorSpace;_supportsReadPixels=!0;constructor(e){this._width=e.width,this._height=e.height,this._type=e.type,this._colorSpace=e.colorSpace;const t={format:r.RGBAFormat,depthBuffer:!1,stencilBuffer:!1,type:this._type,colorSpace:this._colorSpace,anisotropy:void 0!==e.renderTargetOptions?.anisotropy?e.renderTargetOptions?.anisotropy:1,generateMipmaps:void 0!==e.renderTargetOptions?.generateMipmaps&&e.renderTargetOptions?.generateMipmaps,magFilter:void 0!==e.renderTargetOptions?.magFilter?e.renderTargetOptions?.magFilter:r.LinearFilter,minFilter:void 0!==e.renderTargetOptions?.minFilter?e.renderTargetOptions?.minFilter:r.LinearFilter,samples:void 0!==e.renderTargetOptions?.samples?e.renderTargetOptions?.samples:void 0,wrapS:void 0!==e.renderTargetOptions?.wrapS?e.renderTargetOptions?.wrapS:r.ClampToEdgeWrapping,wrapT:void 0!==e.renderTargetOptions?.wrapT?e.renderTargetOptions?.wrapT:r.ClampToEdgeWrapping};this._material=e.material,e.renderer?this._renderer=e.renderer:(this._renderer=y.instantiateRenderer(),this._rendererIsDisposable=!0),this._scene=new r.Scene,this._camera=new r.OrthographicCamera,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(),this._quad=new r.Mesh(new r.PlaneGeometry,this._material),this._quad.geometry.computeBoundingBox(),this._scene.add(this._quad),this._renderTarget=new r.RenderTarget(this.width,this.height,t),this._renderTarget.texture.mapping=void 0!==e.renderTargetOptions?.mapping?e.renderTargetOptions?.mapping:r.UVMapping}static instantiateRenderer(){const e=new r.WebGPURenderer;return e.setSize(128,128),e}render=async()=>{this._renderer.hasInitialized()||await this._renderer.init(),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)};async toArray(){if(!this._supportsReadPixels)throw new Error("Can't read pixels in this browser");const e=await this._renderer.readRenderTargetPixelsAsync(this._renderTarget,0,0,this._width,this._height);if(!this._renderer.backend.isWebGPUBackend)return e;const t=4*this._width,r=256*Math.ceil(t*e.BYTES_PER_ELEMENT/256)/e.BYTES_PER_ELEMENT,a=new e.constructor(t*this._height);for(let i=0;i<this._height;i++){const n=(this._height-1-i)*r;a.set(e.subarray(n,n+t),i*t)}return a}async toDataTexture(e){const t=new r.DataTexture(await this.toArray(),this.width,this.height,r.RGBAFormat,this._type,e?.mapping||r.UVMapping,e?.wrapS||r.ClampToEdgeWrapping,e?.wrapT||r.ClampToEdgeWrapping,e?.magFilter||r.LinearFilter,e?.minFilter||r.LinearFilter,e?.anisotropy||1,r.LinearSRGBColorSpace);return t.flipY=void 0===e?.flipY||e?.flipY,t.generateMipmaps=void 0!==e?.generateMipmaps&&e?.generateMipmaps,t}disposeOnDemandRenderer(){this._renderer.setRenderTarget(null),this._rendererIsDisposable&&this._renderer.dispose().catch(console.error)}dispose(e){e&&this.renderTarget.dispose(),this.material instanceof r.ShaderMaterial&&Object.values(this.material.uniforms).forEach(e=>{e.value instanceof r.Texture&&e.value.dispose()}),Object.values(this.material).forEach(e=>{e instanceof r.Texture&&e.dispose()}),this.material.dispose(),this._quad.geometry.dispose(),this.disposeOnDemandRenderer()}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}}const w=new Set,_=(e,t,r)=>{const a=`${t}:${e}`;w.has(a)||(w.add(a),console.warn(`gainmap-js: ${e} from '${t}' is deprecated and will be removed in v4.0.0. Use ${r} 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`))},x=a.vec3(-65504,-65504,-65504),v=a.vec3(65504,65504,65504);class T extends r.MeshBasicNodeMaterial{_maxDisplayBoost;_hdrCapacityMin;_hdrCapacityMax;_gammaUniform;_offsetHdrUniform;_offsetSdrUniform;_gainMapMinUniform;_gainMapMaxUniform;_weightFactorUniform;_sdrTexture;_gainMapTexture;constructor({gamma:e,offsetHdr:t,offsetSdr:i,gainMapMin:n,gainMapMax:s,maxDisplayBoost:o,hdrCapacityMin:d,hdrCapacityMax:h,sdr:p,gainMap:g}){super(),this.name="GainMapDecoderMaterial",this.blending=r.NoBlending,this.depthTest=!1,this.depthWrite=!1,this._sdrTexture=a.texture(p),this._gainMapTexture=a.texture(g),this._gammaUniform=a.uniform(new r.Vector3(1/e[0],1/e[1],1/e[2])),this._offsetHdrUniform=a.uniform(new r.Vector3(t[0],t[1],t[2])),this._offsetSdrUniform=a.uniform(new r.Vector3(i[0],i[1],i[2])),this._gainMapMinUniform=a.uniform(new r.Vector3(n[0],n[1],n[2])),this._gainMapMaxUniform=a.uniform(new r.Vector3(s[0],s[1],s[2]));const l=(Math.log2(o)-d)/(h-d);this._weightFactorUniform=a.uniform(l,"float"),this._maxDisplayBoost=o,this._hdrCapacityMin=d,this._hdrCapacityMax=h;const m=this._sdrTexture.rgb,c=this._gainMapTexture.rgb.pow(this._gammaUniform),f=this._gainMapMinUniform.mul(c.oneMinus()).add(this._gainMapMaxUniform.mul(c)),u=a.vec3(2).pow(f.mul(this._weightFactorUniform)),M=m.add(this._offsetSdrUniform).mul(u).sub(this._offsetHdrUniform).min(v).max(x);this.colorNode=M}get sdr(){return this._sdrTexture.value}set sdr(e){this._sdrTexture.value=e}get gainMap(){return this._gainMapTexture.value}set gainMap(e){this._gainMapTexture.value=e}get offsetHdr(){return[this._offsetHdrUniform.value.x,this._offsetHdrUniform.value.y,this._offsetHdrUniform.value.z]}set offsetHdr(e){this._offsetHdrUniform.value.x=e[0],this._offsetHdrUniform.value.y=e[1],this._offsetHdrUniform.value.z=e[2]}get offsetSdr(){return[this._offsetSdrUniform.value.x,this._offsetSdrUniform.value.y,this._offsetSdrUniform.value.z]}set offsetSdr(e){this._offsetSdrUniform.value.x=e[0],this._offsetSdrUniform.value.y=e[1],this._offsetSdrUniform.value.z=e[2]}get gainMapMin(){return[this._gainMapMinUniform.value.x,this._gainMapMinUniform.value.y,this._gainMapMinUniform.value.z]}set gainMapMin(e){this._gainMapMinUniform.value.x=e[0],this._gainMapMinUniform.value.y=e[1],this._gainMapMinUniform.value.z=e[2]}get gainMapMax(){return[this._gainMapMaxUniform.value.x,this._gainMapMaxUniform.value.y,this._gainMapMaxUniform.value.z]}set gainMapMax(e){this._gainMapMaxUniform.value.x=e[0],this._gainMapMaxUniform.value.y=e[1],this._gainMapMaxUniform.value.z=e[2]}get gamma(){return[1/this._gammaUniform.value.x,1/this._gammaUniform.value.y,1/this._gammaUniform.value.z]}set gamma(e){this._gammaUniform.value.x=1/e[0],this._gammaUniform.value.y=1/e[1],this._gammaUniform.value.z=1/e[2]}get hdrCapacityMin(){return this._hdrCapacityMin}set hdrCapacityMin(e){this._hdrCapacityMin=e,this.calculateWeight()}get hdrCapacityMax(){return this._hdrCapacityMax}set hdrCapacityMax(e){this._hdrCapacityMax=e,this.calculateWeight()}get maxDisplayBoost(){return this._maxDisplayBoost}set maxDisplayBoost(e){this._maxDisplayBoost=Math.max(1,Math.min(65504,e)),this.calculateWeight()}calculateWeight(){const e=(Math.log2(this._maxDisplayBoost)-this._hdrCapacityMin)/(this._hdrCapacityMax-this._hdrCapacityMin);this._weightFactorUniform.value=Math.max(0,Math.min(1,e))}}const S=i({renderer:r.WebGPURenderer,createMaterial:e=>new T(e),createQuadRenderer:e=>new y(e)});class U extends M{constructor(e,t){super({renderer:e,createMaterial:e=>new T(e),createQuadRenderer:e=>new y(e)},t)}async render(e,t,r,a){const{sdrImage:i,gainMapImage:n,needsFlip:s}=await this.processImages(r,a,"from-image"),{gainMap:o,sdr:d}=this.createTextures(i,n,s);this.updateQuadRenderer(e,i,o,d,t),await e.render()}}class R extends r.TextureNode{static get type(){return"GainMapNode"}uniforms;renderTarget;_quadMesh;_material;_rendererState={};_state=[];constructor(){const e=new r.RenderTarget(1,1,{type:r.HalfFloatType,colorSpace:r.LinearSRGBColorSpace,depthBuffer:!1,generateMipmaps:!0,minFilter:r.LinearMipmapLinearFilter,magFilter:r.LinearFilter});super(e.texture),this.renderTarget=e,this.updateBeforeType=r.NodeUpdateType.RENDER;const t=this.uniforms={sdr:a.texture(new r.Texture),gainMap:a.texture(new r.Texture),gamma:a.uniform(new r.Vector3(1,1,1)),offsetSdr:a.uniform(new r.Vector3),offsetHdr:a.uniform(new r.Vector3),gainMapMin:a.uniform(new r.Vector3),gainMapMax:a.uniform(new r.Vector3(1,1,1)),hdrCapacityMin:a.uniform(0),hdrCapacityMax:a.uniform(1),maxDisplayBoost:a.uniform(1)},i=t.gainMap.rgb.pow(a.vec3(1).div(t.gamma)),n=a.mix(t.gainMapMin,t.gainMapMax,i),s=a.saturate(a.log2(t.maxDisplayBoost).sub(t.hdrCapacityMin).div(t.hdrCapacityMax.sub(t.hdrCapacityMin))),o=t.sdr.rgb.add(t.offsetSdr).mul(a.exp2(n.mul(s))).sub(t.offsetHdr);this._material=new r.MeshBasicNodeMaterial,this._material.name="GainMapDecoder",this._material.colorNode=a.vec4(o.clamp(-65504,65504),1),this._quadMesh=new r.QuadMesh(this._material)}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.sdr.image?.width??0}get height(){return this.sdr.image?.height??0}setTextures(e,t){return this.uniforms.sdr.value=e,this.uniforms.gainMap.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}_currentState(){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]}decode(e){if(0===this.width||0===this.height)return!1;const t=this._currentState();return(t.length!==this._state.length||!t.every((e,t)=>e===this._state[t]))&&(this._state=t,r.RendererUtils.resetRendererState(e,this._rendererState),e.setRenderTarget(this.renderTarget),this._quadMesh.render(e),r.RendererUtils.restoreRendererState(e,this._rendererState),this.value.needsPMREMUpdate=!0,!0)}updateBefore(e){e.renderer&&this.decode(e.renderer)}set value(e){if(this.renderTarget&&e!==this.renderTarget.texture)throw new Error("GainMapNode: 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 r.TextureNode(this.value,this.uvNode,this.levelNode,this.biasNode);return e.sampler=this.sampler,e.updateBeforeType=r.NodeUpdateType.RENDER,e.updateBefore=e=>this.updateBefore(e),e}dispose(){this.renderTarget.dispose(),this._material.dispose(),this.sdr.dispose(),this.gainMap.dispose(),super.dispose()}}class C extends r.Loader{createFileLoader(e){const t=new r.FileLoader(this.manager);return e&&t.setResponseType(e),t.setRequestHeader(this.requestHeader),t.setPath(this.path),t.setWithCredentials(this.withCredentials),t}async fillNode(e,t,r,a){const{sdrImage:i,gainMapImage:n}=await f(r,a,"from-image"),{sdr:s,gainMap:o}=u(i,n,!0);e.setTextures(s,o).setMetadata(t)}}class F extends U{constructor(e,t){super(e,t),_("HDRJPGLoader","@monogrid/gainmap-js/webgpu","HDRJPGNodeLoader")}load(e,t,a,i){const o=this.prepareQuadRenderer(),d=new r.FileLoader(this._internalLoadingManager);return d.setResponseType("arraybuffer"),d.setRequestHeader(this.requestHeader),d.setPath(this.path),d.setWithCredentials(this.withCredentials),this.manager.itemStart(e),d.load(e,async r=>{if("string"==typeof r)throw new Error("Invalid buffer, received [string], was expecting [ArrayBuffer]");const a=new Uint8Array(r);let d,h,p;try{const e=await m(a);d=e.sdr,h=e.gainMap,p=e.metadata}catch(t){if(!(t instanceof s||t instanceof n))throw t;console.warn(`Failure to reconstruct an HDR image from ${e}: Gain map metadata not found in the file, HDRJPGLoader will render the SDR jpeg`),p={gainMapMin:[0,0,0],gainMapMax:[1,1,1],gamma:[1,1,1],hdrCapacityMin:0,hdrCapacityMax:1,offsetHdr:[0,0,0],offsetSdr:[0,0,0]},d=a}try{await this.render(o,p,d.buffer,h?.buffer)}catch(t){return this.manager.itemError(e),"function"==typeof i&&i(t),void o.disposeOnDemandRenderer()}"function"==typeof t&&t(o),this.manager.itemEnd(e),o.disposeOnDemandRenderer()},a,t=>{this.manager.itemError(e),"function"==typeof i&&i(t)}),o}}e.GainMapDecoderMaterial=T,e.GainMapLoader=class extends U{constructor(e,t){super(e,t),_("GainMapLoader","@monogrid/gainmap-js/webgpu","GainMapNodeLoader")}load([e,t,a],i,n,s){const o=this.prepareQuadRenderer();let d,h,p;const g=async()=>{if(d&&h&&p){try{await this.render(o,p,d,h)}catch(r){return this.manager.itemError(e),this.manager.itemError(t),this.manager.itemError(a),"function"==typeof s&&s(r),void o.disposeOnDemandRenderer()}"function"==typeof i&&i(o),this.manager.itemEnd(e),this.manager.itemEnd(t),this.manager.itemEnd(a),o.disposeOnDemandRenderer()}};let l=!0,m=0,c=0,f=!0,u=0,M=0,y=!0,w=0,_=0;const x=()=>{if("function"==typeof n){n(new ProgressEvent("progress",{lengthComputable:l&&f&&y,loaded:c+M+_,total:m+u+w}))}};this.manager.itemStart(e),this.manager.itemStart(t),this.manager.itemStart(a);const v=new r.FileLoader(this._internalLoadingManager);v.setResponseType("arraybuffer"),v.setRequestHeader(this.requestHeader),v.setPath(this.path),v.setWithCredentials(this.withCredentials),v.load(e,async e=>{if("string"==typeof e)throw new Error("Invalid sdr buffer");d=e,await g()},e=>{l=e.lengthComputable,c=e.loaded,m=e.total,x()},t=>{this.manager.itemError(e),"function"==typeof s&&s(t)});const T=new r.FileLoader(this._internalLoadingManager);T.setResponseType("arraybuffer"),T.setRequestHeader(this.requestHeader),T.setPath(this.path),T.setWithCredentials(this.withCredentials),T.load(t,async e=>{if("string"==typeof e)throw new Error("Invalid gainmap buffer");h=e,await g()},e=>{f=e.lengthComputable,M=e.loaded,u=e.total,x()},e=>{this.manager.itemError(t),"function"==typeof s&&s(e)});const S=new r.FileLoader(this._internalLoadingManager);return S.setRequestHeader(this.requestHeader),S.setPath(this.path),S.setWithCredentials(this.withCredentials),S.load(a,async e=>{if("string"!=typeof e)throw new Error("Invalid metadata string");p=JSON.parse(e),await g()},e=>{y=e.lengthComputable,_=e.loaded,w=e.total,x()},e=>{this.manager.itemError(a),"function"==typeof s&&s(e)}),o}},e.GainMapNode=R,e.GainMapNodeLoader=class extends C{load(e,t,r,a){const i=new R,n=e.map(()=>({lengthComputable:!0,loaded:0,total:0})),s=(e,t,a)=>new Promise((i,s)=>{this.manager.itemStart(e),this.createFileLoader(a).load(e,i,e=>{n[t]={lengthComputable:e.lengthComputable,loaded:e.loaded,total:e.total},"function"==typeof r&&r(new ProgressEvent("progress",{lengthComputable:n.every(e=>e.lengthComputable),loaded:n.reduce((e,t)=>e+t.loaded,0),total:n.reduce((e,t)=>e+t.total,0)}))},s)}),[o,d,h]=e;return Promise.all([s(o,0,"arraybuffer"),s(d,1,"arraybuffer"),s(h,2)]).then(async([e,t,r])=>{if("string"==typeof e||"string"==typeof t||"string"!=typeof r)throw new Error("Invalid response types");const a=JSON.parse(r);await this.fillNode(i,a,e,t)}).then(()=>{"function"==typeof t&&t(i),e.forEach(e=>this.manager.itemEnd(e))},t=>{e.forEach(e=>this.manager.itemError(e)),"function"==typeof a&&a(t)}),i}},e.GainMapNotFoundError=n,e.HDRJPGLoader=F,e.HDRJPGNodeLoader=class extends C{load(e,t,r,a){const i=new R;return this.manager.itemStart(e),this.createFileLoader("arraybuffer").load(e,async r=>{try{if("string"==typeof r)throw new Error("Invalid buffer, received [string], was expecting [ArrayBuffer]");const t=new Uint8Array(r);let a,o,d;try{const e=await m(t);a=e.sdr,o=e.gainMap,d=e.metadata}catch(r){if(!(r instanceof s||r instanceof n))throw r;console.warn(`Failure to reconstruct an HDR image from ${e}: Gain map metadata not found in the file, HDRJPGNodeLoader will render the SDR jpeg`),d={gainMapMin:[0,0,0],gainMapMax:[1,1,1],gamma:[1,1,1],hdrCapacityMin:0,hdrCapacityMax:1,offsetHdr:[0,0,0],offsetSdr:[0,0,0]},a=t}await this.fillNode(i,d,a.buffer,o?.buffer)}catch(t){return this.manager.itemError(e),void("function"==typeof a&&a(t))}"function"==typeof t&&t(i),this.manager.itemEnd(e)},r,t=>{this.manager.itemError(e),"function"==typeof a&&a(t)}),i}},e.JPEGRLoader=F,e.LoaderBaseShared=M,e.MPFExtractor=l,e.QuadRenderer=y,e.XMPMetadataNotFoundError=s,e.createDecodeFunction=i,e.createTextures=u,e.decode=async e=>{if(_("decode()","@monogrid/gainmap-js/webgpu","gainMapNode()"),!e.renderer)throw new Error("Renderer is required for decode function");const t=S({...e,renderer:e.renderer});try{await t.render()}catch(e){throw t.disposeOnDemandRenderer(),e}return t},e.extractGainmapFromJPEG=m,e.extractISO=h,e.extractXMP=g,e.gainMapNode=(e,t,r)=>(new R).setTextures(e,t).setMetadata(r),e.processImages=f});
5
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("three/webgpu"),require("three"),require("three/tsl")):"function"==typeof define&&define.amd?define(["exports","three/webgpu","three","three/tsl"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["@monogrid/gainmap-js"]={},e["three/webgpu"],e.three,e["three/tsl"])}(this,function(e,t,r,a){"use strict";class i extends t.TextureNode{renderTarget;revision=0;_quadMesh;_material;_rendererState={};_state=[];constructor(e,r){const a=new t.RenderTarget(1,1,{depthBuffer:!1,...r});super(a.texture),this.renderTarget=a,this.updateBeforeType=t.NodeUpdateType.RENDER,this._material=e,this._quadMesh=new t.QuadMesh(e)}_getDependencies(){return[]}_onRender(){}invalidate(){return this._state=[],this}render(e){const r=this._getDependencies();for(const t of r)t.render(e);const{width:a,height:i}=this;if(0===a||0===i)return!1;const n=[a,i,...r.map(e=>e.revision),...this._getState()];return(n.length!==this._state.length||!n.every((e,t)=>e===this._state[t]))&&(this._state=n,this.renderTarget.width===a&&this.renderTarget.height===i||this.renderTarget.setSize(a,i),t.RendererUtils.resetRendererState(e,this._rendererState),e.setRenderTarget(this.renderTarget),this._quadMesh.render(e),t.RendererUtils.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 t.TextureNode(this.value,this.uvNode,this.levelNode,this.biasNode);return e.sampler=this.sampler,e.updateBeforeType=t.NodeUpdateType.RENDER,e.updateBefore=e=>this.updateBefore(e),e}dispose(){this.renderTarget.dispose(),this._material.dispose(),super.dispose()}}function n(e){return t=>{const{sdr:a,gainMap:i,renderer:n}=t;a.colorSpace!==r.SRGBColorSpace&&(console.warn("SDR Colorspace needs to be *SRGBColorSpace*, setting it automatically"),a.colorSpace=r.SRGBColorSpace),a.needsUpdate=!0,i.colorSpace!==r.LinearSRGBColorSpace&&(console.warn("Gainmap Colorspace needs to be *LinearSRGBColorSpace*, setting it automatically"),i.colorSpace=r.LinearSRGBColorSpace),i.needsUpdate=!0;const s=e.createMaterial({...t,sdr:a,gainMap:i});return e.createQuadRenderer({width:a.image.width,height:a.image.height,type:r.HalfFloatType,colorSpace:r.LinearSRGBColorSpace,material:s,renderer:n,renderTargetOptions:t.renderTargetOptions})}}class s extends Error{}class o extends Error{}const d=e=>{const t=new DataView(e.buffer,e.byteOffset,e.byteLength);let r=0;const a=()=>{const e=t.getUint16(r);return r+=2,e},i=()=>{const e=t.getUint32(r);return r+=4,e},n=a();if(0!==n)throw new Error(`Unsupported ISO 21496-1 minimum_version ${n}`);a();const s=t.getUint8(r++);if(4&s)throw new Error("ISO 21496-1 metadata with HDR base image is not supported");const o=128&s?3:1,d=8&s?i():void 0,h=e=>{const a=e?(()=>{const e=t.getInt32(r);return r+=4,e})():i(),n=d??i();if(0===n)throw new Error("Invalid ISO 21496-1 fraction with zero denominator");return a/n},p=h(!1),g=h(!1);if(p>g)throw new Error("ISO 21496-1 metadata with HDR base image is not supported");const c=[],l=[],m=[],u=[],f=[];for(let e=0;e<o;e++)c.push(h(!0)),l.push(h(!0)),m.push(h(!1)),u.push(h(!0)),f.push(h(!0));const M=e=>3===o?e:[e[0],e[0],e[0]];return{gainMapMin:M(c),gainMapMax:M(l),gamma:M(m),offsetSdr:M(u),offsetHdr:M(f),hdrCapacityMin:p,hdrCapacityMax:g}},h=Array.from("urn:iso:std:iso:ts:21496:-1\0",e=>e.charCodeAt(0)),p=e=>{const t=new DataView(e.buffer,e.byteOffset,e.byteLength),r=4+h.length;for(let a=0;a+r<e.length;a++){if(255!==e[a]||226!==e[a+1])continue;if(!h.every((t,r)=>e[a+4+r]===t))continue;const i=Math.min(e.length,a+2+t.getUint16(a+2));if(!(i-(a+r)<=4))try{return d(e.subarray(a+r,i))}catch(e){return}}},g=(e,t,r)=>{const a=new RegExp(`${t}="([^"]*)"`,"i").exec(e);if(a)return a[1];const i=new RegExp(`<${t}[^>]*>([\\s\\S]*?)</${t}>`,"i").exec(e);if(i){const e=i[1].match(/<rdf:li>([^<]*)<\/rdf:li>/g);return e&&3===e.length?e.map(e=>e.replace(/<\/?rdf:li>/g,"")):i[1].trim()}if(void 0!==r)return r;throw new Error(`Can't find ${t} in gainmap metadata`)},c=e=>{let t;t="undefined"!=typeof TextDecoder?(new TextDecoder).decode(e):e.toString();let r=t.indexOf("<x:xmpmeta");for(;-1!==r;){const e=t.indexOf("x:xmpmeta>",r),a=t.slice(r,e+10);try{const e=g(a,"hdrgm:GainMapMin","0"),t=g(a,"hdrgm:GainMapMax"),r=g(a,"hdrgm:Gamma","1"),i=g(a,"hdrgm:OffsetSDR","0.015625"),n=g(a,"hdrgm:OffsetHDR","0.015625"),s=/hdrgm:HDRCapacityMin="([^"]*)"/.exec(a),o=s?s[1]:"0",d=/hdrgm:HDRCapacityMax="([^"]*)"/.exec(a);if(!d)throw new Error("Incomplete gainmap metadata");const h=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(r)?r.map(e=>parseFloat(e)):[parseFloat(r),parseFloat(r),parseFloat(r)],offsetSdr:Array.isArray(i)?i.map(e=>parseFloat(e)):[parseFloat(i),parseFloat(i),parseFloat(i)],offsetHdr:Array.isArray(n)?n.map(e=>parseFloat(e)):[parseFloat(n),parseFloat(n),parseFloat(n)],hdrCapacityMin:parseFloat(o),hdrCapacityMax:parseFloat(h)}}catch(e){}r=t.indexOf("<x:xmpmeta",e)}};class l{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,r)=>{const a=this.options.debug,i=new DataView(e.buffer);if(65496!==i.getUint16(0))return void r(new Error("Not a valid jpeg"));const n=i.byteLength;let s,o=2,d=0;for(;o<n;){if(++d>250)return void r(new Error(`Found no marker after ${d} loops 😵`));if(255!==i.getUint8(o))return void r(new Error(`Not a valid marker at offset 0x${o.toString(16)}, found: 0x${i.getUint8(o).toString(16)}`));if(s=i.getUint8(o+1),a&&console.log(`Marker: ${s.toString(16)}`),226===s){a&&console.log("Found APP2 marker (0xffe2)");const e=o+4;if(1297106432===i.getUint32(e)){const a=e+4;let n;if(18761===i.getUint16(a))n=!1;else{if(19789!==i.getUint16(a))return void r(new Error("No valid endianness marker found in TIFF header"));n=!0}if(42!==i.getUint16(a+2,!n))return void r(new Error("Not valid TIFF data! (no 0x002A marker)"));const s=i.getUint32(a+4,!n);if(s<8)return void r(new Error("Not valid TIFF data! (First offset less than 8)"));const o=a+s,d=i.getUint16(o,!n),h=o+2;let p=0;for(let e=h;e<h+12*d;e+=12)45057===i.getUint16(e,!n)&&(p=i.getUint32(e+8,!n));const g=o+2+12*d+4,c=[];for(let e=g;e<g+16*p;e+=16){const t={MPType:i.getUint32(e,!n),size:i.getUint32(e+4,!n),dataOffset:i.getUint32(e+8,!n),dependantImages:i.getUint32(e+12,!n),start:-1,end:-1,isFII:!1};t.dataOffset?(t.start=a+t.dataOffset,t.isFII=!1):(t.start=0,t.isFII=!0),t.end=t.start+t.size,c.push(t)}if(this.options.extractNonFII&&c.length){const e=new Blob([i]),r=[];for(const t of c){if(t.isFII&&!this.options.extractFII)continue;const a=e.slice(t.start,t.end+1,"image/jpeg");r.push(a)}t(r)}}}o+=2+i.getUint16(o+2)}})}}const m=async e=>{const t=p(e)??c(e);if(!t)throw new o("Gain map XMP metadata not found");const r=new l({extractFII:!0,extractNonFII:!0}),a=await r.extract(e);if(2!==a.length)throw new s("Gain map recovery image not found");return{sdr:new Uint8Array(await a[0].arrayBuffer()),gainMap:new Uint8Array(await a[1].arrayBuffer()),metadata:t}},u=e=>new Promise((t,r)=>{const a=document.createElement("img");a.onload=()=>{t(a)},a.onerror=e=>{r(e)},a.src=URL.createObjectURL(e)}),f=async(e,t,r)=>{const a=t?new Blob([t],{type:"image/jpeg"}):void 0,i=new Blob([e],{type:"image/jpeg"});let n,s,o=!1;if("undefined"==typeof createImageBitmap){const e=await Promise.all([a?u(a):Promise.resolve(void 0),u(i)]);s=e[0],n=e[1],o="flipY"===r}else{const e=await Promise.all([a?createImageBitmap(a,{imageOrientation:r||"flipY"}):Promise.resolve(void 0),createImageBitmap(i,{imageOrientation:r||"flipY"})]);s=e[0],n=e[1]}return{sdrImage:n,gainMapImage:s,needsFlip:o}},M=(e,t,a)=>{const i=new r.Texture(t||new ImageData(2,2),r.UVMapping,r.ClampToEdgeWrapping,r.ClampToEdgeWrapping,r.LinearFilter,r.LinearMipMapLinearFilter,r.RGBAFormat,r.UnsignedByteType,1,r.LinearSRGBColorSpace);i.flipY=a,i.needsUpdate=!0;const n=new r.Texture(e,r.UVMapping,r.ClampToEdgeWrapping,r.ClampToEdgeWrapping,r.LinearFilter,r.LinearMipMapLinearFilter,r.RGBAFormat,r.UnsignedByteType,1,r.SRGBColorSpace);return n.flipY=a,n.needsUpdate=!0,{gainMap:i,sdr:n}};class y extends r.Loader{_renderer;_renderTargetOptions;_internalLoadingManager;_config;constructor(e,t){super(t),this._config=e,e.renderer&&(this._renderer=e.renderer),this._internalLoadingManager=new r.LoadingManager}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.Texture,sdr:new r.Texture});return this._config.createQuadRenderer({width:16,height:16,type:r.HalfFloatType,colorSpace:r.LinearSRGBColorSpace,material:e,renderer:this._renderer,renderTargetOptions:this._renderTargetOptions})}processImages(e,t,r){return f(e,t,r)}createTextures(e,t,r){return M(e,t,r)}updateQuadRenderer(e,t,r,a,i){e.width=t.width,e.height=t.height,e.material.gainMap=r,e.material.sdr=a,e.material.gainMapMin=i.gainMapMin,e.material.gainMapMax=i.gainMapMax,e.material.offsetHdr=i.offsetHdr,e.material.offsetSdr=i.offsetSdr,e.material.gamma=i.gamma,e.material.hdrCapacityMin=i.hdrCapacityMin,e.material.hdrCapacityMax=i.hdrCapacityMax,e.material.maxDisplayBoost=Math.pow(2,i.hdrCapacityMax),e.material.needsUpdate=!0}}class _{_renderer;_rendererIsDisposable=!1;_material;_scene;_camera;_quad;_renderTarget;_width;_height;_type;_colorSpace;_supportsReadPixels=!0;constructor(e){this._width=e.width,this._height=e.height,this._type=e.type,this._colorSpace=e.colorSpace;const r={format:t.RGBAFormat,depthBuffer:!1,stencilBuffer:!1,type:this._type,colorSpace:this._colorSpace,anisotropy:void 0!==e.renderTargetOptions?.anisotropy?e.renderTargetOptions?.anisotropy:1,generateMipmaps:void 0!==e.renderTargetOptions?.generateMipmaps&&e.renderTargetOptions?.generateMipmaps,magFilter:void 0!==e.renderTargetOptions?.magFilter?e.renderTargetOptions?.magFilter:t.LinearFilter,minFilter:void 0!==e.renderTargetOptions?.minFilter?e.renderTargetOptions?.minFilter:t.LinearFilter,samples:void 0!==e.renderTargetOptions?.samples?e.renderTargetOptions?.samples:void 0,wrapS:void 0!==e.renderTargetOptions?.wrapS?e.renderTargetOptions?.wrapS:t.ClampToEdgeWrapping,wrapT:void 0!==e.renderTargetOptions?.wrapT?e.renderTargetOptions?.wrapT:t.ClampToEdgeWrapping};this._material=e.material,e.renderer?this._renderer=e.renderer:(this._renderer=_.instantiateRenderer(),this._rendererIsDisposable=!0),this._scene=new t.Scene,this._camera=new t.OrthographicCamera,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(),this._quad=new t.Mesh(new t.PlaneGeometry,this._material),this._quad.geometry.computeBoundingBox(),this._scene.add(this._quad),this._renderTarget=new t.RenderTarget(this.width,this.height,r),this._renderTarget.texture.mapping=void 0!==e.renderTargetOptions?.mapping?e.renderTargetOptions?.mapping:t.UVMapping}static instantiateRenderer(){const e=new t.WebGPURenderer;return e.setSize(128,128),e}render=async()=>{this._renderer.hasInitialized()||await this._renderer.init(),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)};async toArray(){if(!this._supportsReadPixels)throw new Error("Can't read pixels in this browser");const e=await this._renderer.readRenderTargetPixelsAsync(this._renderTarget,0,0,this._width,this._height);if(!this._renderer.backend.isWebGPUBackend)return e;const t=4*this._width,r=256*Math.ceil(t*e.BYTES_PER_ELEMENT/256)/e.BYTES_PER_ELEMENT,a=new e.constructor(t*this._height);for(let i=0;i<this._height;i++){const n=(this._height-1-i)*r;a.set(e.subarray(n,n+t),i*t)}return a}async toDataTexture(e){const r=new t.DataTexture(await this.toArray(),this.width,this.height,t.RGBAFormat,this._type,e?.mapping||t.UVMapping,e?.wrapS||t.ClampToEdgeWrapping,e?.wrapT||t.ClampToEdgeWrapping,e?.magFilter||t.LinearFilter,e?.minFilter||t.LinearFilter,e?.anisotropy||1,t.LinearSRGBColorSpace);return r.flipY=void 0===e?.flipY||e?.flipY,r.generateMipmaps=void 0!==e?.generateMipmaps&&e?.generateMipmaps,r}disposeOnDemandRenderer(){this._renderer.setRenderTarget(null),this._rendererIsDisposable&&this._renderer.dispose().catch(console.error)}dispose(e){e&&this.renderTarget.dispose(),this.material instanceof t.ShaderMaterial&&Object.values(this.material.uniforms).forEach(e=>{e.value instanceof t.Texture&&e.value.dispose()}),Object.values(this.material).forEach(e=>{e instanceof t.Texture&&e.dispose()}),this.material.dispose(),this._quad.geometry.dispose(),this.disposeOnDemandRenderer()}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}}const w=new Set,x=(e,t,r)=>{const a=`${t}:${e}`;w.has(a)||(w.add(a),console.warn(`gainmap-js: ${e} from '${t}' is deprecated and will be removed in v4.0.0. Use ${r} 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`))},v=a.vec3(-65504,-65504,-65504),T=a.vec3(65504,65504,65504);class S extends t.MeshBasicNodeMaterial{_maxDisplayBoost;_hdrCapacityMin;_hdrCapacityMax;_gammaUniform;_offsetHdrUniform;_offsetSdrUniform;_gainMapMinUniform;_gainMapMaxUniform;_weightFactorUniform;_sdrTexture;_gainMapTexture;constructor({gamma:e,offsetHdr:r,offsetSdr:i,gainMapMin:n,gainMapMax:s,maxDisplayBoost:o,hdrCapacityMin:d,hdrCapacityMax:h,sdr:p,gainMap:g}){super(),this.name="GainMapDecoderMaterial",this.blending=t.NoBlending,this.depthTest=!1,this.depthWrite=!1,this._sdrTexture=a.texture(p),this._gainMapTexture=a.texture(g),this._gammaUniform=a.uniform(new t.Vector3(1/e[0],1/e[1],1/e[2])),this._offsetHdrUniform=a.uniform(new t.Vector3(r[0],r[1],r[2])),this._offsetSdrUniform=a.uniform(new t.Vector3(i[0],i[1],i[2])),this._gainMapMinUniform=a.uniform(new t.Vector3(n[0],n[1],n[2])),this._gainMapMaxUniform=a.uniform(new t.Vector3(s[0],s[1],s[2]));const c=(Math.log2(o)-d)/(h-d);this._weightFactorUniform=a.uniform(c,"float"),this._maxDisplayBoost=o,this._hdrCapacityMin=d,this._hdrCapacityMax=h;const l=this._sdrTexture.rgb,m=this._gainMapTexture.rgb.pow(this._gammaUniform),u=this._gainMapMinUniform.mul(m.oneMinus()).add(this._gainMapMaxUniform.mul(m)),f=a.vec3(2).pow(u.mul(this._weightFactorUniform)),M=l.add(this._offsetSdrUniform).mul(f).sub(this._offsetHdrUniform).min(T).max(v);this.colorNode=M}get sdr(){return this._sdrTexture.value}set sdr(e){this._sdrTexture.value=e}get gainMap(){return this._gainMapTexture.value}set gainMap(e){this._gainMapTexture.value=e}get offsetHdr(){return[this._offsetHdrUniform.value.x,this._offsetHdrUniform.value.y,this._offsetHdrUniform.value.z]}set offsetHdr(e){this._offsetHdrUniform.value.x=e[0],this._offsetHdrUniform.value.y=e[1],this._offsetHdrUniform.value.z=e[2]}get offsetSdr(){return[this._offsetSdrUniform.value.x,this._offsetSdrUniform.value.y,this._offsetSdrUniform.value.z]}set offsetSdr(e){this._offsetSdrUniform.value.x=e[0],this._offsetSdrUniform.value.y=e[1],this._offsetSdrUniform.value.z=e[2]}get gainMapMin(){return[this._gainMapMinUniform.value.x,this._gainMapMinUniform.value.y,this._gainMapMinUniform.value.z]}set gainMapMin(e){this._gainMapMinUniform.value.x=e[0],this._gainMapMinUniform.value.y=e[1],this._gainMapMinUniform.value.z=e[2]}get gainMapMax(){return[this._gainMapMaxUniform.value.x,this._gainMapMaxUniform.value.y,this._gainMapMaxUniform.value.z]}set gainMapMax(e){this._gainMapMaxUniform.value.x=e[0],this._gainMapMaxUniform.value.y=e[1],this._gainMapMaxUniform.value.z=e[2]}get gamma(){return[1/this._gammaUniform.value.x,1/this._gammaUniform.value.y,1/this._gammaUniform.value.z]}set gamma(e){this._gammaUniform.value.x=1/e[0],this._gammaUniform.value.y=1/e[1],this._gammaUniform.value.z=1/e[2]}get hdrCapacityMin(){return this._hdrCapacityMin}set hdrCapacityMin(e){this._hdrCapacityMin=e,this.calculateWeight()}get hdrCapacityMax(){return this._hdrCapacityMax}set hdrCapacityMax(e){this._hdrCapacityMax=e,this.calculateWeight()}get maxDisplayBoost(){return this._maxDisplayBoost}set maxDisplayBoost(e){this._maxDisplayBoost=Math.max(1,Math.min(65504,e)),this.calculateWeight()}calculateWeight(){const e=(Math.log2(this._maxDisplayBoost)-this._hdrCapacityMin)/(this._hdrCapacityMax-this._hdrCapacityMin);this._weightFactorUniform.value=Math.max(0,Math.min(1,e))}}const R=n({renderer:t.WebGPURenderer,createMaterial:e=>new S(e),createQuadRenderer:e=>new _(e)});class U extends y{constructor(e,t){super({renderer:e,createMaterial:e=>new S(e),createQuadRenderer:e=>new _(e)},t)}async render(e,t,r,a){const{sdrImage:i,gainMapImage:n,needsFlip:s}=await this.processImages(r,a,"from-image"),{gainMap:o,sdr:d}=this.createTextures(i,n,s);this.updateQuadRenderer(e,i,o,d,t),await e.render()}}class C extends i{static get type(){return"GainMapNode"}uniforms;_sdrSource=null;_gainMapSource=null;constructor(){const e=new t.MeshBasicNodeMaterial;e.name="GainMapDecoder",super(e,{type:t.HalfFloatType,colorSpace:t.LinearSRGBColorSpace,generateMipmaps:!0,minFilter:t.LinearMipmapLinearFilter,magFilter:t.LinearFilter});const r=this.uniforms={sdr:a.texture(new t.Texture),gainMap:a.texture(new t.Texture),gamma:a.uniform(new t.Vector3(1,1,1)),offsetSdr:a.uniform(new t.Vector3),offsetHdr:a.uniform(new t.Vector3),gainMapMin:a.uniform(new t.Vector3),gainMapMax:a.uniform(new t.Vector3(1,1,1)),hdrCapacityMin:a.uniform(0),hdrCapacityMax:a.uniform(1),maxDisplayBoost:a.uniform(1)},i=r.gainMap.rgb.pow(a.vec3(1).div(r.gamma)),n=a.mix(r.gainMapMin,r.gainMapMax,i),s=a.saturate(a.log2(r.maxDisplayBoost).sub(r.hdrCapacityMin).div(r.hdrCapacityMax.sub(r.hdrCapacityMin))),o=r.sdr.rgb.add(r.offsetSdr).mul(a.exp2(n.mul(s))).sub(r.offsetHdr);e.colorNode=a.vec4(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 i?e:null,this._gainMapSource=t instanceof i?t:null,this.uniforms.sdr.value=e instanceof i?e.value:e,this.uniforms.gainMap.value=t instanceof i?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()}}class F extends t.Loader{createFileLoader(e){const r=new t.FileLoader(this.manager);return e&&r.setResponseType(e),r.setRequestHeader(this.requestHeader),r.setPath(this.path),r.setWithCredentials(this.withCredentials),r}async fillNode(e,t,r,a){const{sdrImage:i,gainMapImage:n}=await f(r,a,"from-image"),{sdr:s,gainMap:o}=M(i,n,!0);e.setTextures(s,o).setMetadata(t)}}class b extends U{constructor(e,t){super(e,t),x("HDRJPGLoader","@monogrid/gainmap-js/webgpu","HDRJPGNodeLoader")}load(e,r,a,i){const n=this.prepareQuadRenderer(),d=new t.FileLoader(this._internalLoadingManager);return d.setResponseType("arraybuffer"),d.setRequestHeader(this.requestHeader),d.setPath(this.path),d.setWithCredentials(this.withCredentials),this.manager.itemStart(e),d.load(e,async t=>{if("string"==typeof t)throw new Error("Invalid buffer, received [string], was expecting [ArrayBuffer]");const a=new Uint8Array(t);let d,h,p;try{const e=await m(a);d=e.sdr,h=e.gainMap,p=e.metadata}catch(t){if(!(t instanceof o||t instanceof s))throw t;console.warn(`Failure to reconstruct an HDR image from ${e}: Gain map metadata not found in the file, HDRJPGLoader will render the SDR jpeg`),p={gainMapMin:[0,0,0],gainMapMax:[1,1,1],gamma:[1,1,1],hdrCapacityMin:0,hdrCapacityMax:1,offsetHdr:[0,0,0],offsetSdr:[0,0,0]},d=a}try{await this.render(n,p,d.buffer,h?.buffer)}catch(t){return this.manager.itemError(e),"function"==typeof i&&i(t),void n.disposeOnDemandRenderer()}"function"==typeof r&&r(n),this.manager.itemEnd(e),n.disposeOnDemandRenderer()},a,t=>{this.manager.itemError(e),"function"==typeof i&&i(t)}),n}}e.GainMapDecoderMaterial=S,e.GainMapLoader=class extends U{constructor(e,t){super(e,t),x("GainMapLoader","@monogrid/gainmap-js/webgpu","GainMapNodeLoader")}load([e,r,a],i,n,s){const o=this.prepareQuadRenderer();let d,h,p;const g=async()=>{if(d&&h&&p){try{await this.render(o,p,d,h)}catch(t){return this.manager.itemError(e),this.manager.itemError(r),this.manager.itemError(a),"function"==typeof s&&s(t),void o.disposeOnDemandRenderer()}"function"==typeof i&&i(o),this.manager.itemEnd(e),this.manager.itemEnd(r),this.manager.itemEnd(a),o.disposeOnDemandRenderer()}};let c=!0,l=0,m=0,u=!0,f=0,M=0,y=!0,_=0,w=0;const x=()=>{if("function"==typeof n){n(new ProgressEvent("progress",{lengthComputable:c&&u&&y,loaded:m+M+w,total:l+f+_}))}};this.manager.itemStart(e),this.manager.itemStart(r),this.manager.itemStart(a);const v=new t.FileLoader(this._internalLoadingManager);v.setResponseType("arraybuffer"),v.setRequestHeader(this.requestHeader),v.setPath(this.path),v.setWithCredentials(this.withCredentials),v.load(e,async e=>{if("string"==typeof e)throw new Error("Invalid sdr buffer");d=e,await g()},e=>{c=e.lengthComputable,m=e.loaded,l=e.total,x()},t=>{this.manager.itemError(e),"function"==typeof s&&s(t)});const T=new t.FileLoader(this._internalLoadingManager);T.setResponseType("arraybuffer"),T.setRequestHeader(this.requestHeader),T.setPath(this.path),T.setWithCredentials(this.withCredentials),T.load(r,async e=>{if("string"==typeof e)throw new Error("Invalid gainmap buffer");h=e,await g()},e=>{u=e.lengthComputable,M=e.loaded,f=e.total,x()},e=>{this.manager.itemError(r),"function"==typeof s&&s(e)});const S=new t.FileLoader(this._internalLoadingManager);return S.setRequestHeader(this.requestHeader),S.setPath(this.path),S.setWithCredentials(this.withCredentials),S.load(a,async e=>{if("string"!=typeof e)throw new Error("Invalid metadata string");p=JSON.parse(e),await g()},e=>{y=e.lengthComputable,w=e.loaded,_=e.total,x()},e=>{this.manager.itemError(a),"function"==typeof s&&s(e)}),o}},e.GainMapNode=C,e.GainMapNodeLoader=class extends F{load(e,t,r,a){const i=new C,n=e.map(()=>({lengthComputable:!0,loaded:0,total:0})),s=(e,t,a)=>new Promise((i,s)=>{this.manager.itemStart(e),this.createFileLoader(a).load(e,i,e=>{n[t]={lengthComputable:e.lengthComputable,loaded:e.loaded,total:e.total},"function"==typeof r&&r(new ProgressEvent("progress",{lengthComputable:n.every(e=>e.lengthComputable),loaded:n.reduce((e,t)=>e+t.loaded,0),total:n.reduce((e,t)=>e+t.total,0)}))},s)}),[o,d,h]=e;return Promise.all([s(o,0,"arraybuffer"),s(d,1,"arraybuffer"),s(h,2)]).then(async([e,t,r])=>{if("string"==typeof e||"string"==typeof t||"string"!=typeof r)throw new Error("Invalid response types");const a=JSON.parse(r);await this.fillNode(i,a,e,t)}).then(()=>{"function"==typeof t&&t(i),e.forEach(e=>this.manager.itemEnd(e))},t=>{e.forEach(e=>this.manager.itemError(e)),"function"==typeof a&&a(t)}),i}},e.GainMapNotFoundError=s,e.HDRJPGLoader=b,e.HDRJPGNodeLoader=class extends F{load(e,t,r,a){const i=new C;return this.manager.itemStart(e),this.createFileLoader("arraybuffer").load(e,async r=>{try{if("string"==typeof r)throw new Error("Invalid buffer, received [string], was expecting [ArrayBuffer]");const t=new Uint8Array(r);let a,n,d;try{const e=await m(t);a=e.sdr,n=e.gainMap,d=e.metadata}catch(r){if(!(r instanceof o||r instanceof s))throw r;console.warn(`Failure to reconstruct an HDR image from ${e}: Gain map metadata not found in the file, HDRJPGNodeLoader will render the SDR jpeg`),d={gainMapMin:[0,0,0],gainMapMax:[1,1,1],gamma:[1,1,1],hdrCapacityMin:0,hdrCapacityMax:1,offsetHdr:[0,0,0],offsetSdr:[0,0,0]},a=t}await this.fillNode(i,d,a.buffer,n?.buffer)}catch(t){return this.manager.itemError(e),void("function"==typeof a&&a(t))}"function"==typeof t&&t(i),this.manager.itemEnd(e)},r,t=>{this.manager.itemError(e),"function"==typeof a&&a(t)}),i}},e.JPEGRLoader=b,e.LoaderBaseShared=y,e.MPFExtractor=l,e.QuadRenderer=_,e.RenderTargetNode=i,e.XMPMetadataNotFoundError=o,e.createDecodeFunction=n,e.createTextures=M,e.decode=async e=>{if(x("decode()","@monogrid/gainmap-js/webgpu","gainMapNode()"),!e.renderer)throw new Error("Renderer is required for decode function");const t=R({...e,renderer:e.renderer});try{await t.render()}catch(e){throw t.disposeOnDemandRenderer(),e}return t},e.extractGainmapFromJPEG=m,e.extractISO=p,e.extractXMP=c,e.gainMapNode=(e,t,r)=>(new C).setTextures(e,t).setMetadata(r),e.processImages=f});
@@ -0,0 +1,142 @@
1
+ import { type DataTextureLoaderTexData, type WebGPURenderer } from 'three/webgpu';
2
+ import { type GainMapMetadata } from '../../core/types';
3
+ import { GainMapNode } from '../../decode/webgpu/nodes/GainMapNode';
4
+ import { type WorkerInterfaceImplementation } from '../../worker-types';
5
+ import { type CompressedImage, type CompressOptions, type GainmapEncodingParameters } from '../types';
6
+ import { GainMapEncoderNode } from './nodes/GainMapEncoderNode';
7
+ import { type HDRInput, SDRRenditionNode, type SDRRenditionNodeOptions } from './nodes/SDRRenditionNode';
8
+ /**
9
+ * Options of a {@link GainMapEncoder}
10
+ *
11
+ * @category Encoding Parameters
12
+ * @group Encoding Parameters
13
+ */
14
+ export type GainMapEncoderOptions = Partial<GainmapEncodingParameters> & SDRRenditionNodeOptions;
15
+ /**
16
+ * Raw (uncompressed) result of a {@link GainMapEncoder}
17
+ *
18
+ * @category Encoding Parameters
19
+ * @group Encoding Parameters
20
+ */
21
+ export type GainMapEncoderRawResult = {
22
+ /** SDR rendition, rows top to bottom */
23
+ sdr: ImageData;
24
+ /** Gain map, rows top to bottom */
25
+ gainMap: ImageData;
26
+ metadata: GainMapMetadata;
27
+ };
28
+ /**
29
+ * Compressed result of a {@link GainMapEncoder},
30
+ * can be passed as is to `encodeJPEGMetadata` when compressed as `image/jpeg`
31
+ *
32
+ * @category Encoding Parameters
33
+ * @group Encoding Parameters
34
+ */
35
+ export type GainMapEncoderCompressedResult = GainMapMetadata & {
36
+ sdr: CompressedImage;
37
+ gainMap: CompressedImage;
38
+ rawSDR: Uint8ClampedArray;
39
+ rawGainMap: Uint8ClampedArray;
40
+ };
41
+ /**
42
+ * Encodes an HDR image into an SDR rendition + a gain map, on the GPU, with TSL nodes.
43
+ *
44
+ * {@link GainMapEncoder.sdr} and {@link GainMapEncoder.gainMap} are live texture nodes:
45
+ * every encoding parameter is a uniform, changing one re-renders the affected nodes once, when they're next used.
46
+ * No renderer is needed until the result is read back with {@link GainMapEncoder.read} or {@link GainMapEncoder.compress}.
47
+ *
48
+ * Read back images are oriented top to bottom (like `ImageData`), no `flipY` is needed when compressing them.
49
+ *
50
+ * @category Encoding Functions
51
+ * @group Encoding Functions
52
+ *
53
+ * @example
54
+ * import { GainMapEncoder } from '@monogrid/gainmap-js/encode/webgpu'
55
+ * import { encodeJPEGMetadata } from '@monogrid/gainmap-js/libultrahdr'
56
+ * import { EXRLoader } from 'three/examples/jsm/loaders/EXRLoader.js'
57
+ * import { AgXToneMapping, MeshBasicNodeMaterial, WebGPURenderer } from 'three/webgpu'
58
+ *
59
+ * const renderer = new WebGPURenderer()
60
+ * await renderer.init()
61
+ *
62
+ * const image = await new EXRLoader().loadAsync('image.exr')
63
+ * const encoder = new GainMapEncoder(image, { toneMapping: AgXToneMapping })
64
+ * // encode the full HDR range
65
+ * await encoder.fitMaxContentBoost(renderer)
66
+ *
67
+ * // live previews, they follow any parameter change
68
+ * sdrMaterial.colorNode = encoder.sdr
69
+ * gainMapMaterial.colorNode = encoder.gainMap
70
+ * hdrMaterial.colorNode = encoder.createPreviewNode() // decodes the encoded result
71
+ *
72
+ * encoder.sdr.exposure.value = 0.9
73
+ * encoder.gainMap.gamma.value.setScalar(1.1)
74
+ *
75
+ * // compress and embed into a single JPEG file
76
+ * const result = await encoder.compress(renderer, { mimeType: 'image/jpeg', quality: 0.9 })
77
+ * const jpeg = encodeJPEGMetadata(result)
78
+ */
79
+ export declare class GainMapEncoder {
80
+ /**
81
+ * The SDR rendition node
82
+ */
83
+ readonly sdr: SDRRenditionNode;
84
+ /**
85
+ * The gain map node
86
+ */
87
+ readonly gainMap: GainMapEncoderNode;
88
+ private _ownedTexture;
89
+ /**
90
+ * @param image the HDR image: a texture, raw texture data (e.g. from a worker) or a TSL node (which requires `width` and `height`)
91
+ * @param options encoding parameters, all of them can be changed later through the node uniforms
92
+ */
93
+ constructor(image: HDRInput | DataTextureLoaderTexData, options?: GainMapEncoderOptions);
94
+ /** Width of the encoded images */
95
+ get width(): number;
96
+ /** Height of the encoded images */
97
+ get height(): number;
98
+ /**
99
+ * The gain map metadata matching the current parameters
100
+ */
101
+ get metadata(): GainMapMetadata;
102
+ /**
103
+ * Finds the max value of the HDR image and uses it as `maxContentBoost`,
104
+ * so the full HDR range is encoded.
105
+ *
106
+ * @param renderer
107
+ * @returns the new `maxContentBoost`
108
+ */
109
+ fitMaxContentBoost(renderer: WebGPURenderer): Promise<number>;
110
+ /**
111
+ * Creates a {@link GainMapNode} decoding the encoded result on the fly,
112
+ * it follows any change to the encoding parameters.
113
+ * Its `maxDisplayBoost` is initialized to restore the full HDR range, and is not changed afterwards.
114
+ */
115
+ createPreviewNode(): GainMapNode;
116
+ /**
117
+ * Renders the SDR rendition and the gain map, only if something changed since the last render
118
+ *
119
+ * @param renderer
120
+ */
121
+ render(renderer: WebGPURenderer): void;
122
+ /**
123
+ * Renders (if needed) and reads back the raw SDR rendition and gain map
124
+ *
125
+ * @param renderer
126
+ */
127
+ read(renderer: WebGPURenderer): Promise<GainMapEncoderRawResult>;
128
+ /**
129
+ * Renders (if needed), reads back and compresses the SDR rendition and gain map
130
+ *
131
+ * @param renderer
132
+ * @param options compression options, `flipY` is not needed
133
+ * @throws {Error} if the browser does not support [createImageBitmap](https://caniuse.com/createimagebitmap)
134
+ */
135
+ compress(renderer: WebGPURenderer, options: CompressOptions & {
136
+ withWorker?: WorkerInterfaceImplementation;
137
+ }): Promise<GainMapEncoderCompressedResult>;
138
+ /**
139
+ * Disposes the nodes, and the HDR texture if it was created by the encoder from raw data
140
+ */
141
+ dispose(): void;
142
+ }
@@ -0,0 +1,27 @@
1
+ import { type DataTextureLoaderTexData, type WebGPURenderer } from 'three/webgpu';
2
+ import { type HDRInput } from './nodes/SDRRenditionNode';
3
+ /**
4
+ * Finds the min or max value of each RGB channel of an HDR image, on the GPU.
5
+ *
6
+ * The image is reduced by 2x2 cells until it's 1x1, then the single remaining pixel is read back.
7
+ * Negative values are ignored when looking for the max, values above 65504 (max half float) when looking for the min.
8
+ *
9
+ * @category Utility
10
+ * @group Utility
11
+ *
12
+ * @example
13
+ * import { findTextureMinMax } from '@monogrid/gainmap-js/encode/webgpu'
14
+ *
15
+ * const [r, g, b] = await findTextureMinMax(exrTexture, 'max', renderer)
16
+ * const maxContentBoost = Math.max(r, g, b)
17
+ *
18
+ * @param image the HDR image: a texture, raw texture data or a TSL node (which requires `size`)
19
+ * @param mode
20
+ * @param renderer
21
+ * @param size size of the image, required when the image is a generic node
22
+ * @throws {Error} if the image is a generic node and `size` is not provided
23
+ */
24
+ export declare const findTextureMinMax: (image: HDRInput | DataTextureLoaderTexData, mode: "min" | "max", renderer: WebGPURenderer, size?: {
25
+ width: number;
26
+ height: number;
27
+ }) => Promise<[number, number, number]>;
@@ -0,0 +1,8 @@
1
+ export * from '../../core/types';
2
+ export { RenderTargetNode } from '../../core/webgpu/RenderTargetNode';
3
+ export * from '../compress';
4
+ export * from '../types';
5
+ export * from './find-texture-min-max';
6
+ export * from './GainMapEncoder';
7
+ export * from './nodes/GainMapEncoderNode';
8
+ export * from './nodes/SDRRenditionNode';