@monogrid/gainmap-js 3.5.0 → 3.6.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 (55) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/README.md +111 -133
  3. package/dist/{QuadRenderer-DPiEee1I.js → QuadRenderer-CXtNzoCY.js} +1 -1
  4. package/dist/{QuadRenderer-DIHDdKl6.js → QuadRenderer-DcBTBLz6.js} +1 -1
  5. package/dist/{_commonjsHelpers-S7tZmPW-.js → _commonjsHelpers-Cdw2adc2.js} +1 -1
  6. package/dist/{_commonjsHelpers-DVRbpukU.js → _commonjsHelpers-CnYhShyx.js} +1 -1
  7. package/dist/{compress-5gFn7Y4a.js → compress-C42bpk6O.js} +1 -1
  8. package/dist/{compress-CTBeaiI1.js → compress-CzMz2bpX.js} +1 -2
  9. package/dist/decode/shared/index.d.ts +1 -0
  10. package/dist/decode/shared/utils/create-textures.d.ts +26 -0
  11. package/dist/decode/shared/utils/warn-deprecated.d.ts +8 -0
  12. package/dist/decode/webgl/decode.d.ts +1 -0
  13. package/dist/decode/webgl/index.d.ts +4 -0
  14. package/dist/decode/webgl/loaders/GainMapLoader.d.ts +3 -1
  15. package/dist/decode/webgl/loaders/HDRJPGLoader.d.ts +3 -1
  16. package/dist/decode/webgl/materials/GainMapDecoderMaterial.d.ts +1 -0
  17. package/dist/decode/webgpu/core/QuadRenderer.d.ts +1 -0
  18. package/dist/decode/webgpu/decode.d.ts +1 -0
  19. package/dist/decode/webgpu/index.d.ts +7 -0
  20. package/dist/decode/webgpu/loaders/GainMapLoader.d.ts +3 -1
  21. package/dist/decode/webgpu/loaders/GainMapNodeLoader.d.ts +42 -0
  22. package/dist/decode/webgpu/loaders/HDRJPGLoader.d.ts +3 -1
  23. package/dist/decode/webgpu/loaders/HDRJPGNodeLoader.d.ts +41 -0
  24. package/dist/decode/webgpu/loaders/LoaderBaseNode.d.ts +24 -0
  25. package/dist/decode/webgpu/materials/GainMapDecoderMaterial.d.ts +1 -0
  26. package/dist/decode/webgpu/nodes/GainMapNode.d.ts +137 -0
  27. package/dist/decode.js +18 -5
  28. package/dist/decode.min.js +2 -2
  29. package/dist/decode.umd.cjs +86 -32
  30. package/dist/decode.umd.min.cjs +2 -2
  31. package/dist/decode.webgpu.js +453 -9
  32. package/dist/decode.webgpu.min.js +2 -2
  33. package/dist/decode.webgpu.umd.cjs +523 -34
  34. package/dist/decode.webgpu.umd.min.cjs +2 -2
  35. package/dist/encode.js +3 -3
  36. package/dist/encode.min.js +2 -2
  37. package/dist/encode.umd.cjs +1 -2
  38. package/dist/encode.umd.min.cjs +1 -1
  39. package/dist/{iso-gainmap-metadata-Dk2F4Eoz.js → iso-gainmap-metadata-ByNqnUPn.js} +1 -1
  40. package/dist/{iso-gainmap-metadata-DNTSE4Qp.js → iso-gainmap-metadata-CEaaU7RT.js} +1 -1
  41. package/dist/libultrahdr.js +2 -2
  42. package/dist/libultrahdr.min.js +2 -2
  43. package/dist/libultrahdr.umd.cjs +1 -1
  44. package/dist/libultrahdr.umd.min.cjs +1 -1
  45. package/dist/{Loader-CL7itwBq.js → warn-deprecated-Bk17fVbj.js} +74 -35
  46. package/dist/{Loader-BdKdEGSJ.js → warn-deprecated-D0kPpXtA.js} +2 -2
  47. package/dist/worker-interface.js +2 -2
  48. package/dist/worker-interface.min.js +2 -2
  49. package/dist/worker-interface.umd.cjs +1 -1
  50. package/dist/worker-interface.umd.min.cjs +1 -1
  51. package/dist/worker.js +3 -3
  52. package/dist/worker.min.js +2 -2
  53. package/dist/worker.umd.cjs +1 -2
  54. package/dist/worker.umd.min.cjs +1 -1
  55. package/package.json +34 -41
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @monogrid/gainmap-js v3.5.0
2
+ * @monogrid/gainmap-js v3.6.0
3
3
  * With ❤️, by MONOGRID <gainmap@monogrid.com>
4
4
  */
5
5
 
@@ -441,6 +441,57 @@
441
441
  });
442
442
  };
443
443
 
444
+ /**
445
+ * Decodes the SDR and (optional) gain map JPEG buffers into images
446
+ *
447
+ * @param sdrBuffer
448
+ * @param gainMapBuffer
449
+ * @param imageOrientation
450
+ * @returns
451
+ */
452
+ const processImages = async (sdrBuffer, gainMapBuffer, imageOrientation) => {
453
+ const gainMapBlob = gainMapBuffer ? new Blob([gainMapBuffer], { type: 'image/jpeg' }) : undefined;
454
+ const sdrBlob = new Blob([sdrBuffer], { type: 'image/jpeg' });
455
+ let sdrImage;
456
+ let gainMapImage;
457
+ let needsFlip = false;
458
+ if (typeof createImageBitmap === 'undefined') {
459
+ const res = await Promise.all([
460
+ gainMapBlob ? getHTMLImageFromBlob(gainMapBlob) : Promise.resolve(undefined),
461
+ getHTMLImageFromBlob(sdrBlob)
462
+ ]);
463
+ gainMapImage = res[0];
464
+ sdrImage = res[1];
465
+ needsFlip = imageOrientation === 'flipY';
466
+ }
467
+ else {
468
+ const res = await Promise.all([
469
+ gainMapBlob ? createImageBitmap(gainMapBlob, { imageOrientation: imageOrientation || 'flipY' }) : Promise.resolve(undefined),
470
+ createImageBitmap(sdrBlob, { imageOrientation: imageOrientation || 'flipY' })
471
+ ]);
472
+ gainMapImage = res[0];
473
+ sdrImage = res[1];
474
+ }
475
+ return { sdrImage, gainMapImage, needsFlip };
476
+ };
477
+ /**
478
+ * Creates the SDR (sRGB) and gain map (linear) textures from decoded images
479
+ *
480
+ * @param sdrImage
481
+ * @param gainMapImage
482
+ * @param needsFlip
483
+ * @returns
484
+ */
485
+ const createTextures = (sdrImage, gainMapImage, needsFlip) => {
486
+ const gainMap = new three.Texture(gainMapImage || new ImageData(2, 2), three.UVMapping, three.ClampToEdgeWrapping, three.ClampToEdgeWrapping, three.LinearFilter, three.LinearMipMapLinearFilter, three.RGBAFormat, three.UnsignedByteType, 1, three.LinearSRGBColorSpace);
487
+ gainMap.flipY = needsFlip;
488
+ gainMap.needsUpdate = true;
489
+ const sdr = new three.Texture(sdrImage, three.UVMapping, three.ClampToEdgeWrapping, three.ClampToEdgeWrapping, three.LinearFilter, three.LinearMipMapLinearFilter, three.RGBAFormat, three.UnsignedByteType, 1, three.SRGBColorSpace);
490
+ sdr.flipY = needsFlip;
491
+ sdr.needsUpdate = true;
492
+ return { gainMap, sdr };
493
+ };
494
+
444
495
  /**
445
496
  * Shared base class for loaders that extracts common logic
446
497
  */
@@ -490,39 +541,11 @@
490
541
  renderTargetOptions: this._renderTargetOptions
491
542
  });
492
543
  }
493
- async processImages(sdrBuffer, gainMapBuffer, imageOrientation) {
494
- const gainMapBlob = gainMapBuffer ? new Blob([gainMapBuffer], { type: 'image/jpeg' }) : undefined;
495
- const sdrBlob = new Blob([sdrBuffer], { type: 'image/jpeg' });
496
- let sdrImage;
497
- let gainMapImage;
498
- let needsFlip = false;
499
- if (typeof createImageBitmap === 'undefined') {
500
- const res = await Promise.all([
501
- gainMapBlob ? getHTMLImageFromBlob(gainMapBlob) : Promise.resolve(undefined),
502
- getHTMLImageFromBlob(sdrBlob)
503
- ]);
504
- gainMapImage = res[0];
505
- sdrImage = res[1];
506
- needsFlip = imageOrientation === 'flipY';
507
- }
508
- else {
509
- const res = await Promise.all([
510
- gainMapBlob ? createImageBitmap(gainMapBlob, { imageOrientation: imageOrientation || 'flipY' }) : Promise.resolve(undefined),
511
- createImageBitmap(sdrBlob, { imageOrientation: imageOrientation || 'flipY' })
512
- ]);
513
- gainMapImage = res[0];
514
- sdrImage = res[1];
515
- }
516
- return { sdrImage, gainMapImage, needsFlip };
544
+ processImages(sdrBuffer, gainMapBuffer, imageOrientation) {
545
+ return processImages(sdrBuffer, gainMapBuffer, imageOrientation);
517
546
  }
518
547
  createTextures(sdrImage, gainMapImage, needsFlip) {
519
- const gainMap = new three.Texture(gainMapImage || new ImageData(2, 2), three.UVMapping, three.ClampToEdgeWrapping, three.ClampToEdgeWrapping, three.LinearFilter, three.LinearMipMapLinearFilter, three.RGBAFormat, three.UnsignedByteType, 1, three.LinearSRGBColorSpace);
520
- gainMap.flipY = needsFlip;
521
- gainMap.needsUpdate = true;
522
- const sdr = new three.Texture(sdrImage, three.UVMapping, three.ClampToEdgeWrapping, three.ClampToEdgeWrapping, three.LinearFilter, three.LinearMipMapLinearFilter, three.RGBAFormat, three.UnsignedByteType, 1, three.SRGBColorSpace);
523
- sdr.flipY = needsFlip;
524
- sdr.needsUpdate = true;
525
- return { gainMap, sdr };
548
+ return createTextures(sdrImage, gainMapImage, needsFlip);
526
549
  }
527
550
  updateQuadRenderer(quadRenderer, sdrImage, gainMap, sdr, metadata) {
528
551
  quadRenderer.width = sdrImage.width;
@@ -544,6 +567,7 @@
544
567
  /**
545
568
  * Utility class used for rendering a texture with a material (WebGPU version)
546
569
  *
570
+ * @deprecated Will be removed in v4.0.0. The WebGPU decode now happens in {@link GainMapNode}, use {@link HDRJPGNodeLoader}, {@link GainMapNodeLoader} or {@link gainMapNode}, see the [migration guide](https://github.com/MONOGRID/gainmap-js#migrating-to-v400).
547
571
  * @category Core
548
572
  * @group Core
549
573
  */
@@ -766,13 +790,30 @@
766
790
  get colorSpace() { return this._colorSpace; }
767
791
  }
768
792
 
793
+ const warned = new Set();
794
+ /**
795
+ * Warns once per API that a render target based decode API is going away in v4.0.0
796
+ *
797
+ * @param name deprecated API
798
+ * @param entry entry point exposing the deprecated API
799
+ * @param replacement node based API replacing it, from `@monogrid/gainmap-js/webgpu`
800
+ */
801
+ const warnDeprecated = (name, entry, replacement) => {
802
+ const key = `${entry}:${name}`;
803
+ if (warned.has(key))
804
+ return;
805
+ warned.add(key);
806
+ 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`);
807
+ };
808
+
769
809
  // min half float value
770
810
  const HALF_FLOAT_MIN = tsl.vec3(-65504, -65504, -65504);
771
811
  // max half float value
772
- const HALF_FLOAT_MAX = tsl.vec3(65504, 65504, 65504);
812
+ const HALF_FLOAT_MAX$1 = tsl.vec3(65504, 65504, 65504);
773
813
  /**
774
814
  * A Material which is able to decode the Gainmap into a full HDR Representation using TSL (Three.js Shading Language)
775
815
  *
816
+ * @deprecated Will be removed in v4.0.0. The decode now happens in {@link GainMapNode}, see the [migration guide](https://github.com/MONOGRID/gainmap-js#migrating-to-v400).
776
817
  * @category Materials
777
818
  * @group Materials
778
819
  */
@@ -823,7 +864,7 @@
823
864
  // the mathematically equivalent pow(2, x) which has proper vec3 typings.
824
865
  const gain = tsl.vec3(2).pow(logBoost.mul(this._weightFactorUniform));
825
866
  const hdrColor = rgb.add(this._offsetSdrUniform).mul(gain).sub(this._offsetHdrUniform);
826
- const clampedHdrColor = hdrColor.min(HALF_FLOAT_MAX).max(HALF_FLOAT_MIN);
867
+ const clampedHdrColor = hdrColor.min(HALF_FLOAT_MAX$1).max(HALF_FLOAT_MIN);
827
868
  this.colorNode = clampedHdrColor;
828
869
  }
829
870
  get sdr() { return this._sdrTexture.value; }
@@ -926,6 +967,7 @@
926
967
  /**
927
968
  * Decodes a gain map using WebGPU RenderTarget
928
969
  *
970
+ * @deprecated Will be removed in v4.0.0. Use {@link gainMapNode} instead: it is **not a drop-in replacement**, it returns a {@link GainMapNode} instead of a render target, see the [migration guide](https://github.com/MONOGRID/gainmap-js#migrating-to-v400).
929
971
  * @category Decoding Functions
930
972
  * @group Decoding Functions
931
973
  * @example
@@ -979,6 +1021,7 @@
979
1021
  * @throws {Error} if the WebGPURenderer fails to render the gain map
980
1022
  */
981
1023
  const decode = async (params) => {
1024
+ warnDeprecated('decode()', '@monogrid/gainmap-js/webgpu', 'gainMapNode()');
982
1025
  // Ensure renderer is defined for the base function
983
1026
  if (!params.renderer) {
984
1027
  throw new Error('Renderer is required for decode function');
@@ -1029,6 +1072,7 @@
1029
1072
  /**
1030
1073
  * A Three.js Loader for the gain map format (WebGPU version).
1031
1074
  *
1075
+ * @deprecated Will be removed in v4.0.0. Use {@link GainMapNodeLoader} instead: it is **not a drop-in replacement**, it returns a {@link GainMapNode} instead of a render target, see the [migration guide](https://github.com/MONOGRID/gainmap-js#migrating-to-v400).
1032
1076
  * @category Loaders
1033
1077
  * @group Loaders
1034
1078
  *
@@ -1075,6 +1119,10 @@
1075
1119
  *
1076
1120
  */
1077
1121
  class GainMapLoader extends LoaderBaseWebGPU {
1122
+ constructor(renderer, manager) {
1123
+ super(renderer, manager);
1124
+ warnDeprecated('GainMapLoader', '@monogrid/gainmap-js/webgpu', 'GainMapNodeLoader');
1125
+ }
1078
1126
  /**
1079
1127
  * Loads a gainmap using separate data
1080
1128
  * * sdr image
@@ -1212,9 +1260,344 @@
1212
1260
  }
1213
1261
  }
1214
1262
 
1263
+ // max half float value
1264
+ const HALF_FLOAT_MAX = 65504;
1265
+ /**
1266
+ * A TSL texture node holding the HDR image decoded from an SDR image + gain map.
1267
+ *
1268
+ * The decode runs on the GPU into a HalfFloat render target, and only when something changed
1269
+ * (textures loaded/swapped or any uniform value changed): sampling the node costs a single
1270
+ * texture read, like any other texture.
1271
+ *
1272
+ * The node updates itself before rendering whenever it is part of a rendered node graph
1273
+ * (material, `scene.backgroundNode`, ...). When only its texture is used (`node.value`,
1274
+ * e.g. `scene.environment = node.value`) call {@link GainMapNode.decode} yourself.
1275
+ *
1276
+ * Re-decoding also flags the texture for PMREM regeneration,
1277
+ * so environment maps are recomputed only when the image actually changes.
1278
+ *
1279
+ * `node.value` gets its final size once loaded: three.js PMREMs don't follow texture resizes,
1280
+ * so assign it to `scene.environment` (or `pmremTexture()`) after load.
1281
+ *
1282
+ * @category Nodes
1283
+ * @group Nodes
1284
+ *
1285
+ * @example
1286
+ * import { GainMapNode } from '@monogrid/gainmap-js/webgpu'
1287
+ * import { equirectUV } from 'three/tsl'
1288
+ *
1289
+ * const hdr = new GainMapNode()
1290
+ * .setTextures(sdrTexture, gainMapTexture)
1291
+ * .setMetadata(metadata)
1292
+ *
1293
+ * material.colorNode = hdr
1294
+ * scene.backgroundNode = hdr.sample(equirectUV())
1295
+ * hdr.maxDisplayBoost.value = 2 // re-decodes once, on the next frame
1296
+ */
1297
+ class GainMapNode extends webgpu.TextureNode {
1298
+ static get type() { return 'GainMapNode'; }
1299
+ /**
1300
+ * Shared textures and uniforms
1301
+ */
1302
+ uniforms;
1303
+ /**
1304
+ * The render target holding the decoded HDR image
1305
+ */
1306
+ renderTarget;
1307
+ _quadMesh;
1308
+ _material;
1309
+ // filled by RendererUtils.resetRendererState
1310
+ _rendererState = {};
1311
+ _state = [];
1312
+ constructor() {
1313
+ const renderTarget = new webgpu.RenderTarget(1, 1, {
1314
+ type: webgpu.HalfFloatType,
1315
+ colorSpace: webgpu.LinearSRGBColorSpace,
1316
+ depthBuffer: false,
1317
+ generateMipmaps: true,
1318
+ minFilter: webgpu.LinearMipmapLinearFilter,
1319
+ magFilter: webgpu.LinearFilter
1320
+ });
1321
+ super(renderTarget.texture);
1322
+ this.renderTarget = renderTarget;
1323
+ this.updateBeforeType = webgpu.NodeUpdateType.RENDER;
1324
+ const u = this.uniforms = {
1325
+ sdr: tsl.texture(new webgpu.Texture()),
1326
+ gainMap: tsl.texture(new webgpu.Texture()),
1327
+ gamma: tsl.uniform(new webgpu.Vector3(1, 1, 1)),
1328
+ offsetSdr: tsl.uniform(new webgpu.Vector3()),
1329
+ offsetHdr: tsl.uniform(new webgpu.Vector3()),
1330
+ gainMapMin: tsl.uniform(new webgpu.Vector3()),
1331
+ gainMapMax: tsl.uniform(new webgpu.Vector3(1, 1, 1)),
1332
+ hdrCapacityMin: tsl.uniform(0),
1333
+ hdrCapacityMax: tsl.uniform(1),
1334
+ maxDisplayBoost: tsl.uniform(1)
1335
+ };
1336
+ const logRecovery = u.gainMap.rgb.pow(tsl.vec3(1).div(u.gamma));
1337
+ const logBoost = tsl.mix(u.gainMapMin, u.gainMapMax, logRecovery);
1338
+ const weight = tsl.saturate(tsl.log2(u.maxDisplayBoost).sub(u.hdrCapacityMin).div(u.hdrCapacityMax.sub(u.hdrCapacityMin)));
1339
+ const hdr = u.sdr.rgb.add(u.offsetSdr).mul(tsl.exp2(logBoost.mul(weight))).sub(u.offsetHdr);
1340
+ this._material = new webgpu.MeshBasicNodeMaterial();
1341
+ this._material.name = 'GainMapDecoder';
1342
+ this._material.colorNode = tsl.vec4(hdr.clamp(-HALF_FLOAT_MAX, HALF_FLOAT_MAX), 1);
1343
+ this._quadMesh = new webgpu.QuadMesh(this._material);
1344
+ }
1345
+ /** The SDR rendition texture (sRGB) */
1346
+ get sdr() { return this.uniforms.sdr.value; }
1347
+ /** The gain map recovery texture (linear) */
1348
+ get gainMap() { return this.uniforms.gainMap.value; }
1349
+ /** @see {@link GainMapMetadata.gamma} */
1350
+ get gamma() { return this.uniforms.gamma; }
1351
+ /** @see {@link GainMapMetadata.offsetSdr} */
1352
+ get offsetSdr() { return this.uniforms.offsetSdr; }
1353
+ /** @see {@link GainMapMetadata.offsetHdr} */
1354
+ get offsetHdr() { return this.uniforms.offsetHdr; }
1355
+ /** @see {@link GainMapMetadata.gainMapMin} */
1356
+ get gainMapMin() { return this.uniforms.gainMapMin; }
1357
+ /** @see {@link GainMapMetadata.gainMapMax} */
1358
+ get gainMapMax() { return this.uniforms.gainMapMax; }
1359
+ /** @see {@link GainMapMetadata.hdrCapacityMin} */
1360
+ get hdrCapacityMin() { return this.uniforms.hdrCapacityMin; }
1361
+ /** @see {@link GainMapMetadata.hdrCapacityMax} */
1362
+ get hdrCapacityMax() { return this.uniforms.hdrCapacityMax; }
1363
+ /**
1364
+ * @see {@link GainmapDecodingParameters.maxDisplayBoost}
1365
+ * @remarks Non Logarithmic space
1366
+ */
1367
+ get maxDisplayBoost() { return this.uniforms.maxDisplayBoost; }
1368
+ /** Width of the SDR image, 0 until loaded */
1369
+ get width() { return this.sdr.image?.width ?? 0; }
1370
+ /** Height of the SDR image, 0 until loaded */
1371
+ get height() { return this.sdr.image?.height ?? 0; }
1372
+ /**
1373
+ * Sets the SDR and gain map textures.
1374
+ * The SDR texture is expected in sRGB color space, the gain map in linear.
1375
+ *
1376
+ * @param sdr
1377
+ * @param gainMap
1378
+ */
1379
+ setTextures(sdr, gainMap) {
1380
+ this.uniforms.sdr.value = sdr;
1381
+ this.uniforms.gainMap.value = gainMap;
1382
+ // size the render target right away, so `value` has its final size before the first decode
1383
+ if (this.width > 0 && this.height > 0)
1384
+ this.renderTarget.setSize(this.width, this.height);
1385
+ return this;
1386
+ }
1387
+ /**
1388
+ * Copies the gain map metadata into the uniforms.
1389
+ * Also sets `maxDisplayBoost` to fully restore the HDR range.
1390
+ *
1391
+ * @param metadata
1392
+ */
1393
+ setMetadata(metadata) {
1394
+ const u = this.uniforms;
1395
+ u.gamma.value.fromArray(metadata.gamma);
1396
+ u.offsetSdr.value.fromArray(metadata.offsetSdr);
1397
+ u.offsetHdr.value.fromArray(metadata.offsetHdr);
1398
+ u.gainMapMin.value.fromArray(metadata.gainMapMin);
1399
+ u.gainMapMax.value.fromArray(metadata.gainMapMax);
1400
+ u.hdrCapacityMin.value = metadata.hdrCapacityMin;
1401
+ u.hdrCapacityMax.value = metadata.hdrCapacityMax;
1402
+ u.maxDisplayBoost.value = Math.pow(2, metadata.hdrCapacityMax);
1403
+ return this;
1404
+ }
1405
+ _currentState() {
1406
+ const u = this.uniforms;
1407
+ return [
1408
+ this.sdr.id, this.sdr.version, this.gainMap.id, this.gainMap.version,
1409
+ ...u.gamma.value.toArray(), ...u.offsetSdr.value.toArray(), ...u.offsetHdr.value.toArray(),
1410
+ ...u.gainMapMin.value.toArray(), ...u.gainMapMax.value.toArray(),
1411
+ u.hdrCapacityMin.value, u.hdrCapacityMax.value, u.maxDisplayBoost.value
1412
+ ];
1413
+ }
1414
+ /**
1415
+ * Decodes the image into {@link GainMapNode.renderTarget}, only if something changed since the last decode.
1416
+ *
1417
+ * Called automatically when the node is part of a rendered node graph.
1418
+ *
1419
+ * @param renderer
1420
+ * @returns `true` if the image was decoded
1421
+ */
1422
+ decode(renderer) {
1423
+ // not loaded yet
1424
+ if (this.width === 0 || this.height === 0)
1425
+ return false;
1426
+ const state = this._currentState();
1427
+ if (state.length === this._state.length && state.every((v, i) => v === this._state[i]))
1428
+ return false;
1429
+ this._state = state;
1430
+ webgpu.RendererUtils.resetRendererState(renderer, this._rendererState);
1431
+ renderer.setRenderTarget(this.renderTarget);
1432
+ this._quadMesh.render(renderer);
1433
+ webgpu.RendererUtils.restoreRendererState(renderer, this._rendererState);
1434
+ this.value.needsPMREMUpdate = true;
1435
+ return true;
1436
+ }
1437
+ updateBefore(frame) {
1438
+ if (frame.renderer)
1439
+ this.decode(frame.renderer);
1440
+ return undefined;
1441
+ }
1442
+ set value(value) {
1443
+ if (this.renderTarget && value !== this.renderTarget.texture) {
1444
+ throw new Error('GainMapNode: the value of this node is its render target texture and can\'t be replaced');
1445
+ }
1446
+ }
1447
+ get value() {
1448
+ return this.renderTarget?.texture;
1449
+ }
1450
+ /**
1451
+ * Clones created by `sample()` & co. are plain TextureNodes reading this node's texture,
1452
+ * they keep it updated before rendering as well
1453
+ */
1454
+ clone() {
1455
+ const node = new webgpu.TextureNode(this.value, this.uvNode, this.levelNode, this.biasNode);
1456
+ node.sampler = this.sampler;
1457
+ node.updateBeforeType = webgpu.NodeUpdateType.RENDER;
1458
+ node.updateBefore = (frame) => this.updateBefore(frame);
1459
+ return node;
1460
+ }
1461
+ /**
1462
+ * Disposes the render target, the SDR and gain map textures
1463
+ */
1464
+ dispose() {
1465
+ this.renderTarget.dispose();
1466
+ this._material.dispose();
1467
+ this.sdr.dispose();
1468
+ this.gainMap.dispose();
1469
+ super.dispose();
1470
+ }
1471
+ }
1472
+ /**
1473
+ * TSL function creating a {@link GainMapNode} from an SDR texture, a gain map texture and its metadata
1474
+ *
1475
+ * @param sdr
1476
+ * @param gainMap
1477
+ * @param metadata
1478
+ */
1479
+ const gainMapNode = (sdr, gainMap, metadata) => new GainMapNode().setTextures(sdr, gainMap).setMetadata(metadata);
1480
+
1481
+ /**
1482
+ * Base class for loaders returning a {@link GainMapNode}
1483
+ * @template TUrl - The type of URL used to load resources
1484
+ */
1485
+ class LoaderBaseNode extends webgpu.Loader {
1486
+ /**
1487
+ * @private
1488
+ * @param responseType
1489
+ */
1490
+ createFileLoader(responseType) {
1491
+ const loader = new webgpu.FileLoader(this.manager);
1492
+ if (responseType)
1493
+ loader.setResponseType(responseType);
1494
+ loader.setRequestHeader(this.requestHeader);
1495
+ loader.setPath(this.path);
1496
+ loader.setWithCredentials(this.withCredentials);
1497
+ return loader;
1498
+ }
1499
+ /**
1500
+ * Decodes the images and feeds them to the node, together with the metadata
1501
+ *
1502
+ * @private
1503
+ * @param node
1504
+ * @param metadata
1505
+ * @param sdrBuffer
1506
+ * @param gainMapBuffer
1507
+ */
1508
+ async fillNode(node, metadata, sdrBuffer, gainMapBuffer) {
1509
+ // flipY like any other three.js texture, so the node can be sampled with regular uvs
1510
+ const { sdrImage, gainMapImage } = await processImages(sdrBuffer, gainMapBuffer, 'from-image');
1511
+ const { sdr, gainMap } = createTextures(sdrImage, gainMapImage, true);
1512
+ node.setTextures(sdr, gainMap).setMetadata(metadata);
1513
+ }
1514
+ }
1515
+
1516
+ /**
1517
+ * A Three.js Loader for the gain map format stored as separate files (sdr image, gain map image, metadata json),
1518
+ * returning a {@link GainMapNode} (a TSL texture node holding the decoded HDR image).
1519
+ *
1520
+ * No renderer is needed: `load` returns the node synchronously, it can be assigned to materials right away
1521
+ * and it is decoded on the GPU once loaded.
1522
+ *
1523
+ * @category Loaders
1524
+ * @group Loaders
1525
+ *
1526
+ * @example
1527
+ * import { GainMapNodeLoader } from '@monogrid/gainmap-js/webgpu'
1528
+ * import { MeshBasicNodeMaterial } from 'three/webgpu'
1529
+ *
1530
+ * const hdr = new GainMapNodeLoader().load([
1531
+ * 'sdr.webp',
1532
+ * 'gainmap.webp',
1533
+ * 'metadata.json'
1534
+ * ])
1535
+ *
1536
+ * const material = new MeshBasicNodeMaterial()
1537
+ * material.colorNode = hdr
1538
+ */
1539
+ class GainMapNodeLoader extends LoaderBaseNode {
1540
+ /**
1541
+ * Loads a gainmap using separate data
1542
+ * * sdr image
1543
+ * * gain map image
1544
+ * * metadata json
1545
+ *
1546
+ * useful for webp gain maps
1547
+ *
1548
+ * @param urls An array in the form of [sdr.jpg, gainmap.jpg, metadata.json]
1549
+ * @param onLoad Load complete callback, will receive the node
1550
+ * @param onProgress Progress callback, will receive a `ProgressEvent`
1551
+ * @param onError Error callback
1552
+ * @returns a node which can be used immediately, it will hold the image once loaded
1553
+ */
1554
+ load(urls, onLoad, onProgress, onError) {
1555
+ const node = new GainMapNode();
1556
+ const progress = urls.map(() => ({ lengthComputable: true, loaded: 0, total: 0 }));
1557
+ const loadFile = (url, index, responseType) => new Promise((resolve, reject) => {
1558
+ this.manager.itemStart(url);
1559
+ this.createFileLoader(responseType).load(url, resolve, (e) => {
1560
+ progress[index] = { lengthComputable: e.lengthComputable, loaded: e.loaded, total: e.total };
1561
+ if (typeof onProgress === 'function') {
1562
+ onProgress(new ProgressEvent('progress', {
1563
+ lengthComputable: progress.every(p => p.lengthComputable),
1564
+ loaded: progress.reduce((sum, p) => sum + p.loaded, 0),
1565
+ total: progress.reduce((sum, p) => sum + p.total, 0)
1566
+ }));
1567
+ }
1568
+ }, reject);
1569
+ });
1570
+ const [sdrUrl, gainMapUrl, metadataUrl] = urls;
1571
+ Promise.all([
1572
+ loadFile(sdrUrl, 0, 'arraybuffer'),
1573
+ loadFile(gainMapUrl, 1, 'arraybuffer'),
1574
+ loadFile(metadataUrl, 2)
1575
+ ]).then(async ([sdr, gainMap, json]) => {
1576
+ /* istanbul ignore if
1577
+ this condition exists only because of three.js types + strict mode
1578
+ */
1579
+ if (typeof sdr === 'string' || typeof gainMap === 'string' || typeof json !== 'string')
1580
+ throw new Error('Invalid response types');
1581
+ // TODO: implement check on JSON file
1582
+ const metadata = JSON.parse(json);
1583
+ await this.fillNode(node, metadata, sdr, gainMap);
1584
+ }).then(() => {
1585
+ if (typeof onLoad === 'function')
1586
+ onLoad(node);
1587
+ urls.forEach(url => this.manager.itemEnd(url));
1588
+ }, (error) => {
1589
+ urls.forEach(url => this.manager.itemError(url));
1590
+ if (typeof onError === 'function')
1591
+ onError(error);
1592
+ });
1593
+ return node;
1594
+ }
1595
+ }
1596
+
1215
1597
  /**
1216
1598
  * A Three.js Loader for a JPEG with embedded gainmap metadata (WebGPU version).
1217
1599
  *
1600
+ * @deprecated Will be removed in v4.0.0. Use {@link HDRJPGNodeLoader} instead: it is **not a drop-in replacement**, it returns a {@link GainMapNode} instead of a render target, see the [migration guide](https://github.com/MONOGRID/gainmap-js#migrating-to-v400).
1218
1601
  * @category Loaders
1219
1602
  * @group Loaders
1220
1603
  *
@@ -1261,6 +1644,10 @@
1261
1644
  *
1262
1645
  */
1263
1646
  class HDRJPGLoader extends LoaderBaseWebGPU {
1647
+ constructor(renderer, manager) {
1648
+ super(renderer, manager);
1649
+ warnDeprecated('HDRJPGLoader', '@monogrid/gainmap-js/webgpu', 'HDRJPGNodeLoader');
1650
+ }
1264
1651
  /**
1265
1652
  * Loads a JPEG containing gain map metadata
1266
1653
  * Renders a normal SDR image if gainmap data is not found
@@ -1339,19 +1726,121 @@
1339
1726
  }
1340
1727
  }
1341
1728
 
1729
+ /**
1730
+ * A Three.js Loader for a JPEG with embedded gain map metadata,
1731
+ * returning a {@link GainMapNode} (a TSL texture node holding the decoded HDR image).
1732
+ *
1733
+ * No renderer is needed: `load` returns the node synchronously
1734
+ * (like `TextureLoader` returns a `Texture`), it can be assigned to materials right away
1735
+ * and it is decoded on the GPU once loaded.
1736
+ *
1737
+ * @category Loaders
1738
+ * @group Loaders
1739
+ *
1740
+ * @example
1741
+ * import { HDRJPGNodeLoader } from '@monogrid/gainmap-js/webgpu'
1742
+ * import { equirectUV } from 'three/tsl'
1743
+ * import { MeshBasicNodeMaterial } from 'three/webgpu'
1744
+ *
1745
+ * const hdr = new HDRJPGNodeLoader().load('gainmap.jpeg')
1746
+ *
1747
+ * const material = new MeshBasicNodeMaterial()
1748
+ * material.colorNode = hdr
1749
+ *
1750
+ * scene.backgroundNode = hdr.sample(equirectUV())
1751
+ *
1752
+ * // all parameters are uniforms, changing them re-decodes the image once
1753
+ * hdr.maxDisplayBoost.value = 2
1754
+ */
1755
+ class HDRJPGNodeLoader extends LoaderBaseNode {
1756
+ /**
1757
+ * Loads a JPEG containing gain map metadata
1758
+ * Renders a normal SDR image if gainmap data is not found
1759
+ *
1760
+ * @param url Path to a JPEG file containing embedded gain map metadata
1761
+ * @param onLoad Load complete callback, will receive the node
1762
+ * @param onProgress Progress callback, will receive a `ProgressEvent`
1763
+ * @param onError Error callback
1764
+ * @returns a node which can be used immediately, it will hold the image once loaded
1765
+ */
1766
+ load(url, onLoad, onProgress, onError) {
1767
+ const node = new GainMapNode();
1768
+ this.manager.itemStart(url);
1769
+ this.createFileLoader('arraybuffer').load(url, async (jpeg) => {
1770
+ try {
1771
+ /* istanbul ignore if
1772
+ this condition exists only because of three.js types + strict mode
1773
+ */
1774
+ if (typeof jpeg === 'string')
1775
+ throw new Error('Invalid buffer, received [string], was expecting [ArrayBuffer]');
1776
+ const jpegBuffer = new Uint8Array(jpeg);
1777
+ let sdrJPEG;
1778
+ let gainMapJPEG;
1779
+ let metadata;
1780
+ try {
1781
+ const extractionResult = await extractGainmapFromJPEG(jpegBuffer);
1782
+ sdrJPEG = extractionResult.sdr;
1783
+ gainMapJPEG = extractionResult.gainMap;
1784
+ metadata = extractionResult.metadata;
1785
+ }
1786
+ catch (e) {
1787
+ // render the SDR version if this is not a gainmap
1788
+ if (e instanceof XMPMetadataNotFoundError || e instanceof GainMapNotFoundError) {
1789
+ console.warn(`Failure to reconstruct an HDR image from ${url}: Gain map metadata not found in the file, HDRJPGNodeLoader will render the SDR jpeg`);
1790
+ metadata = {
1791
+ gainMapMin: [0, 0, 0],
1792
+ gainMapMax: [1, 1, 1],
1793
+ gamma: [1, 1, 1],
1794
+ hdrCapacityMin: 0,
1795
+ hdrCapacityMax: 1,
1796
+ offsetHdr: [0, 0, 0],
1797
+ offsetSdr: [0, 0, 0]
1798
+ };
1799
+ sdrJPEG = jpegBuffer;
1800
+ }
1801
+ else {
1802
+ throw e;
1803
+ }
1804
+ }
1805
+ await this.fillNode(node, metadata, sdrJPEG.buffer, gainMapJPEG?.buffer);
1806
+ }
1807
+ catch (error) {
1808
+ this.manager.itemError(url);
1809
+ if (typeof onError === 'function')
1810
+ onError(error);
1811
+ return;
1812
+ }
1813
+ if (typeof onLoad === 'function')
1814
+ onLoad(node);
1815
+ this.manager.itemEnd(url);
1816
+ }, onProgress, (error) => {
1817
+ this.manager.itemError(url);
1818
+ if (typeof onError === 'function')
1819
+ onError(error);
1820
+ });
1821
+ return node;
1822
+ }
1823
+ }
1824
+
1342
1825
  exports.GainMapDecoderMaterial = GainMapDecoderMaterial;
1343
1826
  exports.GainMapLoader = GainMapLoader;
1827
+ exports.GainMapNode = GainMapNode;
1828
+ exports.GainMapNodeLoader = GainMapNodeLoader;
1344
1829
  exports.GainMapNotFoundError = GainMapNotFoundError;
1345
1830
  exports.HDRJPGLoader = HDRJPGLoader;
1831
+ exports.HDRJPGNodeLoader = HDRJPGNodeLoader;
1346
1832
  exports.JPEGRLoader = HDRJPGLoader;
1347
1833
  exports.LoaderBaseShared = LoaderBaseShared;
1348
1834
  exports.MPFExtractor = MPFExtractor;
1349
1835
  exports.QuadRenderer = QuadRenderer;
1350
1836
  exports.XMPMetadataNotFoundError = XMPMetadataNotFoundError;
1351
1837
  exports.createDecodeFunction = createDecodeFunction;
1838
+ exports.createTextures = createTextures;
1352
1839
  exports.decode = decode;
1353
1840
  exports.extractGainmapFromJPEG = extractGainmapFromJPEG;
1354
1841
  exports.extractISO = extractISO;
1355
1842
  exports.extractXMP = extractXMP;
1843
+ exports.gainMapNode = gainMapNode;
1844
+ exports.processImages = processImages;
1356
1845
 
1357
1846
  }));