@monogrid/gainmap-js 3.4.1 → 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 (61) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/README.md +111 -133
  3. package/dist/{QuadRenderer-Bl8ThfRL.js → QuadRenderer-CXtNzoCY.js} +1 -1
  4. package/dist/{QuadRenderer-D1rYlVRa.js → QuadRenderer-DcBTBLz6.js} +1 -1
  5. package/dist/{_commonjsHelpers-CHnLGTFq.js → _commonjsHelpers-Cdw2adc2.js} +1 -1
  6. package/dist/{_commonjsHelpers-D4ntYHBT.js → _commonjsHelpers-CnYhShyx.js} +1 -1
  7. package/dist/{compress-B5svUHuf.js → compress-C42bpk6O.js} +1 -1
  8. package/dist/{compress-DBGuVQfM.js → compress-CzMz2bpX.js} +1 -2
  9. package/dist/core/iso-gainmap-metadata.d.ts +40 -0
  10. package/dist/decode/shared/extract.d.ts +5 -3
  11. package/dist/decode/shared/index.d.ts +2 -0
  12. package/dist/decode/shared/utils/create-textures.d.ts +26 -0
  13. package/dist/decode/shared/utils/extractISO.d.ts +15 -0
  14. package/dist/decode/shared/utils/warn-deprecated.d.ts +8 -0
  15. package/dist/decode/webgl/decode.d.ts +1 -0
  16. package/dist/decode/webgl/index.d.ts +4 -0
  17. package/dist/decode/webgl/loaders/GainMapLoader.d.ts +3 -1
  18. package/dist/decode/webgl/loaders/HDRJPGLoader.d.ts +3 -1
  19. package/dist/decode/webgl/materials/GainMapDecoderMaterial.d.ts +1 -0
  20. package/dist/decode/webgpu/core/QuadRenderer.d.ts +1 -0
  21. package/dist/decode/webgpu/decode.d.ts +1 -0
  22. package/dist/decode/webgpu/index.d.ts +7 -0
  23. package/dist/decode/webgpu/loaders/GainMapLoader.d.ts +3 -1
  24. package/dist/decode/webgpu/loaders/GainMapNodeLoader.d.ts +42 -0
  25. package/dist/decode/webgpu/loaders/HDRJPGLoader.d.ts +3 -1
  26. package/dist/decode/webgpu/loaders/HDRJPGNodeLoader.d.ts +41 -0
  27. package/dist/decode/webgpu/loaders/LoaderBaseNode.d.ts +24 -0
  28. package/dist/decode/webgpu/materials/GainMapDecoderMaterial.d.ts +1 -0
  29. package/dist/decode/webgpu/nodes/GainMapNode.d.ts +137 -0
  30. package/dist/decode.js +18 -4
  31. package/dist/decode.min.js +2 -2
  32. package/dist/decode.umd.cjs +207 -36
  33. package/dist/decode.umd.min.cjs +2 -2
  34. package/dist/decode.webgpu.js +453 -8
  35. package/dist/decode.webgpu.min.js +2 -2
  36. package/dist/decode.webgpu.umd.cjs +644 -38
  37. package/dist/decode.webgpu.umd.min.cjs +2 -2
  38. package/dist/encode.js +4 -4
  39. package/dist/encode.min.js +2 -2
  40. package/dist/encode.umd.cjs +1 -2
  41. package/dist/encode.umd.min.cjs +1 -1
  42. package/dist/iso-gainmap-metadata-ByNqnUPn.js +141 -0
  43. package/dist/iso-gainmap-metadata-CEaaU7RT.js +5 -0
  44. package/dist/libultrahdr/jpeg-assembler.d.ts +2 -0
  45. package/dist/libultrahdr.js +30 -7
  46. package/dist/libultrahdr.min.js +2 -2
  47. package/dist/libultrahdr.umd.cjs +104 -7
  48. package/dist/libultrahdr.umd.min.cjs +2 -2
  49. package/dist/third-party.txt +69 -69
  50. package/dist/{Loader-Bi9FKrn4.js → warn-deprecated-Bk17fVbj.js} +117 -38
  51. package/dist/warn-deprecated-D0kPpXtA.js +5 -0
  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 -2
  59. package/dist/worker.umd.min.cjs +1 -1
  60. package/package.json +34 -37
  61. package/dist/Loader-uEDs4JZg.js +0 -5
@@ -1,17 +1,19 @@
1
1
  /**
2
- * @monogrid/gainmap-js v3.4.1
2
+ * @monogrid/gainmap-js v3.6.0
3
3
  * With ❤️, by MONOGRID <gainmap@monogrid.com>
4
4
  */
5
5
 
6
- import { c as createDecodeFunction, L as LoaderBaseShared, e as extractGainmapFromJPEG, X as XMPMetadataNotFoundError, G as GainMapNotFoundError } from './Loader-Bi9FKrn4.js';
7
- export { M as MPFExtractor, a as extractXMP } from './Loader-Bi9FKrn4.js';
8
- import { ClampToEdgeWrapping, LinearFilter, Scene, OrthographicCamera, Mesh, PlaneGeometry, RenderTarget, RGBAFormat, UVMapping, WebGPURenderer, DataTexture, LinearSRGBColorSpace, ShaderMaterial, Texture, MeshBasicNodeMaterial, NoBlending, Vector3, FileLoader } from 'three/webgpu';
6
+ import { w as warnDeprecated, c as createDecodeFunction, L as LoaderBaseShared, p as processImages, a as createTextures, e as extractGainmapFromJPEG, X as XMPMetadataNotFoundError, G as GainMapNotFoundError } from './warn-deprecated-Bk17fVbj.js';
7
+ export { M as MPFExtractor, b as extractISO, d as extractXMP } from './warn-deprecated-Bk17fVbj.js';
8
+ import { ClampToEdgeWrapping, LinearFilter, Scene, OrthographicCamera, Mesh, PlaneGeometry, RenderTarget, RGBAFormat, UVMapping, WebGPURenderer, DataTexture, LinearSRGBColorSpace, ShaderMaterial, Texture, MeshBasicNodeMaterial, NoBlending, Vector3, FileLoader, TextureNode, LinearMipmapLinearFilter, HalfFloatType, NodeUpdateType, QuadMesh, RendererUtils, Loader } from 'three/webgpu';
9
9
  import 'three';
10
- import { vec3, texture, uniform } from 'three/tsl';
10
+ import { vec3, texture, uniform, mix, saturate, log2, exp2, vec4 } from 'three/tsl';
11
+ import './iso-gainmap-metadata-ByNqnUPn.js';
11
12
 
12
13
  /**
13
14
  * Utility class used for rendering a texture with a material (WebGPU version)
14
15
  *
16
+ * @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).
15
17
  * @category Core
16
18
  * @group Core
17
19
  */
@@ -237,10 +239,11 @@ class QuadRenderer {
237
239
  // min half float value
238
240
  const HALF_FLOAT_MIN = vec3(-65504, -65504, -65504);
239
241
  // max half float value
240
- const HALF_FLOAT_MAX = vec3(65504, 65504, 65504);
242
+ const HALF_FLOAT_MAX$1 = vec3(65504, 65504, 65504);
241
243
  /**
242
244
  * A Material which is able to decode the Gainmap into a full HDR Representation using TSL (Three.js Shading Language)
243
245
  *
246
+ * @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).
244
247
  * @category Materials
245
248
  * @group Materials
246
249
  */
@@ -291,7 +294,7 @@ class GainMapDecoderMaterial extends MeshBasicNodeMaterial {
291
294
  // the mathematically equivalent pow(2, x) which has proper vec3 typings.
292
295
  const gain = vec3(2).pow(logBoost.mul(this._weightFactorUniform));
293
296
  const hdrColor = rgb.add(this._offsetSdrUniform).mul(gain).sub(this._offsetHdrUniform);
294
- const clampedHdrColor = hdrColor.min(HALF_FLOAT_MAX).max(HALF_FLOAT_MIN);
297
+ const clampedHdrColor = hdrColor.min(HALF_FLOAT_MAX$1).max(HALF_FLOAT_MIN);
295
298
  this.colorNode = clampedHdrColor;
296
299
  }
297
300
  get sdr() { return this._sdrTexture.value; }
@@ -394,6 +397,7 @@ const decodeImpl = createDecodeFunction({
394
397
  /**
395
398
  * Decodes a gain map using WebGPU RenderTarget
396
399
  *
400
+ * @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).
397
401
  * @category Decoding Functions
398
402
  * @group Decoding Functions
399
403
  * @example
@@ -447,6 +451,7 @@ const decodeImpl = createDecodeFunction({
447
451
  * @throws {Error} if the WebGPURenderer fails to render the gain map
448
452
  */
449
453
  const decode = async (params) => {
454
+ warnDeprecated('decode()', '@monogrid/gainmap-js/webgpu', 'gainMapNode()');
450
455
  // Ensure renderer is defined for the base function
451
456
  if (!params.renderer) {
452
457
  throw new Error('Renderer is required for decode function');
@@ -497,6 +502,7 @@ class LoaderBaseWebGPU extends LoaderBaseShared {
497
502
  /**
498
503
  * A Three.js Loader for the gain map format (WebGPU version).
499
504
  *
505
+ * @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).
500
506
  * @category Loaders
501
507
  * @group Loaders
502
508
  *
@@ -543,6 +549,10 @@ class LoaderBaseWebGPU extends LoaderBaseShared {
543
549
  *
544
550
  */
545
551
  class GainMapLoader extends LoaderBaseWebGPU {
552
+ constructor(renderer, manager) {
553
+ super(renderer, manager);
554
+ warnDeprecated('GainMapLoader', '@monogrid/gainmap-js/webgpu', 'GainMapNodeLoader');
555
+ }
546
556
  /**
547
557
  * Loads a gainmap using separate data
548
558
  * * sdr image
@@ -680,9 +690,344 @@ class GainMapLoader extends LoaderBaseWebGPU {
680
690
  }
681
691
  }
682
692
 
693
+ // max half float value
694
+ const HALF_FLOAT_MAX = 65504;
695
+ /**
696
+ * A TSL texture node holding the HDR image decoded from an SDR image + gain map.
697
+ *
698
+ * The decode runs on the GPU into a HalfFloat render target, and only when something changed
699
+ * (textures loaded/swapped or any uniform value changed): sampling the node costs a single
700
+ * texture read, like any other texture.
701
+ *
702
+ * The node updates itself before rendering whenever it is part of a rendered node graph
703
+ * (material, `scene.backgroundNode`, ...). When only its texture is used (`node.value`,
704
+ * e.g. `scene.environment = node.value`) call {@link GainMapNode.decode} yourself.
705
+ *
706
+ * Re-decoding also flags the texture for PMREM regeneration,
707
+ * so environment maps are recomputed only when the image actually changes.
708
+ *
709
+ * `node.value` gets its final size once loaded: three.js PMREMs don't follow texture resizes,
710
+ * so assign it to `scene.environment` (or `pmremTexture()`) after load.
711
+ *
712
+ * @category Nodes
713
+ * @group Nodes
714
+ *
715
+ * @example
716
+ * import { GainMapNode } from '@monogrid/gainmap-js/webgpu'
717
+ * import { equirectUV } from 'three/tsl'
718
+ *
719
+ * const hdr = new GainMapNode()
720
+ * .setTextures(sdrTexture, gainMapTexture)
721
+ * .setMetadata(metadata)
722
+ *
723
+ * material.colorNode = hdr
724
+ * scene.backgroundNode = hdr.sample(equirectUV())
725
+ * hdr.maxDisplayBoost.value = 2 // re-decodes once, on the next frame
726
+ */
727
+ class GainMapNode extends TextureNode {
728
+ static get type() { return 'GainMapNode'; }
729
+ /**
730
+ * Shared textures and uniforms
731
+ */
732
+ uniforms;
733
+ /**
734
+ * The render target holding the decoded HDR image
735
+ */
736
+ renderTarget;
737
+ _quadMesh;
738
+ _material;
739
+ // filled by RendererUtils.resetRendererState
740
+ _rendererState = {};
741
+ _state = [];
742
+ constructor() {
743
+ const renderTarget = new RenderTarget(1, 1, {
744
+ type: HalfFloatType,
745
+ colorSpace: LinearSRGBColorSpace,
746
+ depthBuffer: false,
747
+ generateMipmaps: true,
748
+ minFilter: LinearMipmapLinearFilter,
749
+ magFilter: LinearFilter
750
+ });
751
+ super(renderTarget.texture);
752
+ this.renderTarget = renderTarget;
753
+ this.updateBeforeType = NodeUpdateType.RENDER;
754
+ const u = this.uniforms = {
755
+ sdr: texture(new Texture()),
756
+ gainMap: texture(new Texture()),
757
+ gamma: uniform(new Vector3(1, 1, 1)),
758
+ offsetSdr: uniform(new Vector3()),
759
+ offsetHdr: uniform(new Vector3()),
760
+ gainMapMin: uniform(new Vector3()),
761
+ gainMapMax: uniform(new Vector3(1, 1, 1)),
762
+ hdrCapacityMin: uniform(0),
763
+ hdrCapacityMax: uniform(1),
764
+ maxDisplayBoost: uniform(1)
765
+ };
766
+ const logRecovery = u.gainMap.rgb.pow(vec3(1).div(u.gamma));
767
+ const logBoost = mix(u.gainMapMin, u.gainMapMax, logRecovery);
768
+ const weight = saturate(log2(u.maxDisplayBoost).sub(u.hdrCapacityMin).div(u.hdrCapacityMax.sub(u.hdrCapacityMin)));
769
+ const hdr = u.sdr.rgb.add(u.offsetSdr).mul(exp2(logBoost.mul(weight))).sub(u.offsetHdr);
770
+ this._material = new MeshBasicNodeMaterial();
771
+ this._material.name = 'GainMapDecoder';
772
+ this._material.colorNode = vec4(hdr.clamp(-HALF_FLOAT_MAX, HALF_FLOAT_MAX), 1);
773
+ this._quadMesh = new QuadMesh(this._material);
774
+ }
775
+ /** The SDR rendition texture (sRGB) */
776
+ get sdr() { return this.uniforms.sdr.value; }
777
+ /** The gain map recovery texture (linear) */
778
+ get gainMap() { return this.uniforms.gainMap.value; }
779
+ /** @see {@link GainMapMetadata.gamma} */
780
+ get gamma() { return this.uniforms.gamma; }
781
+ /** @see {@link GainMapMetadata.offsetSdr} */
782
+ get offsetSdr() { return this.uniforms.offsetSdr; }
783
+ /** @see {@link GainMapMetadata.offsetHdr} */
784
+ get offsetHdr() { return this.uniforms.offsetHdr; }
785
+ /** @see {@link GainMapMetadata.gainMapMin} */
786
+ get gainMapMin() { return this.uniforms.gainMapMin; }
787
+ /** @see {@link GainMapMetadata.gainMapMax} */
788
+ get gainMapMax() { return this.uniforms.gainMapMax; }
789
+ /** @see {@link GainMapMetadata.hdrCapacityMin} */
790
+ get hdrCapacityMin() { return this.uniforms.hdrCapacityMin; }
791
+ /** @see {@link GainMapMetadata.hdrCapacityMax} */
792
+ get hdrCapacityMax() { return this.uniforms.hdrCapacityMax; }
793
+ /**
794
+ * @see {@link GainmapDecodingParameters.maxDisplayBoost}
795
+ * @remarks Non Logarithmic space
796
+ */
797
+ get maxDisplayBoost() { return this.uniforms.maxDisplayBoost; }
798
+ /** Width of the SDR image, 0 until loaded */
799
+ get width() { return this.sdr.image?.width ?? 0; }
800
+ /** Height of the SDR image, 0 until loaded */
801
+ get height() { return this.sdr.image?.height ?? 0; }
802
+ /**
803
+ * Sets the SDR and gain map textures.
804
+ * The SDR texture is expected in sRGB color space, the gain map in linear.
805
+ *
806
+ * @param sdr
807
+ * @param gainMap
808
+ */
809
+ setTextures(sdr, gainMap) {
810
+ this.uniforms.sdr.value = sdr;
811
+ this.uniforms.gainMap.value = gainMap;
812
+ // size the render target right away, so `value` has its final size before the first decode
813
+ if (this.width > 0 && this.height > 0)
814
+ this.renderTarget.setSize(this.width, this.height);
815
+ return this;
816
+ }
817
+ /**
818
+ * Copies the gain map metadata into the uniforms.
819
+ * Also sets `maxDisplayBoost` to fully restore the HDR range.
820
+ *
821
+ * @param metadata
822
+ */
823
+ setMetadata(metadata) {
824
+ const u = this.uniforms;
825
+ u.gamma.value.fromArray(metadata.gamma);
826
+ u.offsetSdr.value.fromArray(metadata.offsetSdr);
827
+ u.offsetHdr.value.fromArray(metadata.offsetHdr);
828
+ u.gainMapMin.value.fromArray(metadata.gainMapMin);
829
+ u.gainMapMax.value.fromArray(metadata.gainMapMax);
830
+ u.hdrCapacityMin.value = metadata.hdrCapacityMin;
831
+ u.hdrCapacityMax.value = metadata.hdrCapacityMax;
832
+ u.maxDisplayBoost.value = Math.pow(2, metadata.hdrCapacityMax);
833
+ return this;
834
+ }
835
+ _currentState() {
836
+ const u = this.uniforms;
837
+ return [
838
+ this.sdr.id, this.sdr.version, this.gainMap.id, this.gainMap.version,
839
+ ...u.gamma.value.toArray(), ...u.offsetSdr.value.toArray(), ...u.offsetHdr.value.toArray(),
840
+ ...u.gainMapMin.value.toArray(), ...u.gainMapMax.value.toArray(),
841
+ u.hdrCapacityMin.value, u.hdrCapacityMax.value, u.maxDisplayBoost.value
842
+ ];
843
+ }
844
+ /**
845
+ * Decodes the image into {@link GainMapNode.renderTarget}, only if something changed since the last decode.
846
+ *
847
+ * Called automatically when the node is part of a rendered node graph.
848
+ *
849
+ * @param renderer
850
+ * @returns `true` if the image was decoded
851
+ */
852
+ decode(renderer) {
853
+ // not loaded yet
854
+ if (this.width === 0 || this.height === 0)
855
+ return false;
856
+ const state = this._currentState();
857
+ if (state.length === this._state.length && state.every((v, i) => v === this._state[i]))
858
+ return false;
859
+ this._state = state;
860
+ RendererUtils.resetRendererState(renderer, this._rendererState);
861
+ renderer.setRenderTarget(this.renderTarget);
862
+ this._quadMesh.render(renderer);
863
+ RendererUtils.restoreRendererState(renderer, this._rendererState);
864
+ this.value.needsPMREMUpdate = true;
865
+ return true;
866
+ }
867
+ updateBefore(frame) {
868
+ if (frame.renderer)
869
+ this.decode(frame.renderer);
870
+ return undefined;
871
+ }
872
+ set value(value) {
873
+ if (this.renderTarget && value !== this.renderTarget.texture) {
874
+ throw new Error('GainMapNode: the value of this node is its render target texture and can\'t be replaced');
875
+ }
876
+ }
877
+ get value() {
878
+ return this.renderTarget?.texture;
879
+ }
880
+ /**
881
+ * Clones created by `sample()` & co. are plain TextureNodes reading this node's texture,
882
+ * they keep it updated before rendering as well
883
+ */
884
+ clone() {
885
+ const node = new TextureNode(this.value, this.uvNode, this.levelNode, this.biasNode);
886
+ node.sampler = this.sampler;
887
+ node.updateBeforeType = NodeUpdateType.RENDER;
888
+ node.updateBefore = (frame) => this.updateBefore(frame);
889
+ return node;
890
+ }
891
+ /**
892
+ * Disposes the render target, the SDR and gain map textures
893
+ */
894
+ dispose() {
895
+ this.renderTarget.dispose();
896
+ this._material.dispose();
897
+ this.sdr.dispose();
898
+ this.gainMap.dispose();
899
+ super.dispose();
900
+ }
901
+ }
902
+ /**
903
+ * TSL function creating a {@link GainMapNode} from an SDR texture, a gain map texture and its metadata
904
+ *
905
+ * @param sdr
906
+ * @param gainMap
907
+ * @param metadata
908
+ */
909
+ const gainMapNode = (sdr, gainMap, metadata) => new GainMapNode().setTextures(sdr, gainMap).setMetadata(metadata);
910
+
911
+ /**
912
+ * Base class for loaders returning a {@link GainMapNode}
913
+ * @template TUrl - The type of URL used to load resources
914
+ */
915
+ class LoaderBaseNode extends Loader {
916
+ /**
917
+ * @private
918
+ * @param responseType
919
+ */
920
+ createFileLoader(responseType) {
921
+ const loader = new FileLoader(this.manager);
922
+ if (responseType)
923
+ loader.setResponseType(responseType);
924
+ loader.setRequestHeader(this.requestHeader);
925
+ loader.setPath(this.path);
926
+ loader.setWithCredentials(this.withCredentials);
927
+ return loader;
928
+ }
929
+ /**
930
+ * Decodes the images and feeds them to the node, together with the metadata
931
+ *
932
+ * @private
933
+ * @param node
934
+ * @param metadata
935
+ * @param sdrBuffer
936
+ * @param gainMapBuffer
937
+ */
938
+ async fillNode(node, metadata, sdrBuffer, gainMapBuffer) {
939
+ // flipY like any other three.js texture, so the node can be sampled with regular uvs
940
+ const { sdrImage, gainMapImage } = await processImages(sdrBuffer, gainMapBuffer, 'from-image');
941
+ const { sdr, gainMap } = createTextures(sdrImage, gainMapImage, true);
942
+ node.setTextures(sdr, gainMap).setMetadata(metadata);
943
+ }
944
+ }
945
+
946
+ /**
947
+ * A Three.js Loader for the gain map format stored as separate files (sdr image, gain map image, metadata json),
948
+ * returning a {@link GainMapNode} (a TSL texture node holding the decoded HDR image).
949
+ *
950
+ * No renderer is needed: `load` returns the node synchronously, it can be assigned to materials right away
951
+ * and it is decoded on the GPU once loaded.
952
+ *
953
+ * @category Loaders
954
+ * @group Loaders
955
+ *
956
+ * @example
957
+ * import { GainMapNodeLoader } from '@monogrid/gainmap-js/webgpu'
958
+ * import { MeshBasicNodeMaterial } from 'three/webgpu'
959
+ *
960
+ * const hdr = new GainMapNodeLoader().load([
961
+ * 'sdr.webp',
962
+ * 'gainmap.webp',
963
+ * 'metadata.json'
964
+ * ])
965
+ *
966
+ * const material = new MeshBasicNodeMaterial()
967
+ * material.colorNode = hdr
968
+ */
969
+ class GainMapNodeLoader extends LoaderBaseNode {
970
+ /**
971
+ * Loads a gainmap using separate data
972
+ * * sdr image
973
+ * * gain map image
974
+ * * metadata json
975
+ *
976
+ * useful for webp gain maps
977
+ *
978
+ * @param urls An array in the form of [sdr.jpg, gainmap.jpg, metadata.json]
979
+ * @param onLoad Load complete callback, will receive the node
980
+ * @param onProgress Progress callback, will receive a `ProgressEvent`
981
+ * @param onError Error callback
982
+ * @returns a node which can be used immediately, it will hold the image once loaded
983
+ */
984
+ load(urls, onLoad, onProgress, onError) {
985
+ const node = new GainMapNode();
986
+ const progress = urls.map(() => ({ lengthComputable: true, loaded: 0, total: 0 }));
987
+ const loadFile = (url, index, responseType) => new Promise((resolve, reject) => {
988
+ this.manager.itemStart(url);
989
+ this.createFileLoader(responseType).load(url, resolve, (e) => {
990
+ progress[index] = { lengthComputable: e.lengthComputable, loaded: e.loaded, total: e.total };
991
+ if (typeof onProgress === 'function') {
992
+ onProgress(new ProgressEvent('progress', {
993
+ lengthComputable: progress.every(p => p.lengthComputable),
994
+ loaded: progress.reduce((sum, p) => sum + p.loaded, 0),
995
+ total: progress.reduce((sum, p) => sum + p.total, 0)
996
+ }));
997
+ }
998
+ }, reject);
999
+ });
1000
+ const [sdrUrl, gainMapUrl, metadataUrl] = urls;
1001
+ Promise.all([
1002
+ loadFile(sdrUrl, 0, 'arraybuffer'),
1003
+ loadFile(gainMapUrl, 1, 'arraybuffer'),
1004
+ loadFile(metadataUrl, 2)
1005
+ ]).then(async ([sdr, gainMap, json]) => {
1006
+ /* istanbul ignore if
1007
+ this condition exists only because of three.js types + strict mode
1008
+ */
1009
+ if (typeof sdr === 'string' || typeof gainMap === 'string' || typeof json !== 'string')
1010
+ throw new Error('Invalid response types');
1011
+ // TODO: implement check on JSON file
1012
+ const metadata = JSON.parse(json);
1013
+ await this.fillNode(node, metadata, sdr, gainMap);
1014
+ }).then(() => {
1015
+ if (typeof onLoad === 'function')
1016
+ onLoad(node);
1017
+ urls.forEach(url => this.manager.itemEnd(url));
1018
+ }, (error) => {
1019
+ urls.forEach(url => this.manager.itemError(url));
1020
+ if (typeof onError === 'function')
1021
+ onError(error);
1022
+ });
1023
+ return node;
1024
+ }
1025
+ }
1026
+
683
1027
  /**
684
1028
  * A Three.js Loader for a JPEG with embedded gainmap metadata (WebGPU version).
685
1029
  *
1030
+ * @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).
686
1031
  * @category Loaders
687
1032
  * @group Loaders
688
1033
  *
@@ -729,6 +1074,10 @@ class GainMapLoader extends LoaderBaseWebGPU {
729
1074
  *
730
1075
  */
731
1076
  class HDRJPGLoader extends LoaderBaseWebGPU {
1077
+ constructor(renderer, manager) {
1078
+ super(renderer, manager);
1079
+ warnDeprecated('HDRJPGLoader', '@monogrid/gainmap-js/webgpu', 'HDRJPGNodeLoader');
1080
+ }
732
1081
  /**
733
1082
  * Loads a JPEG containing gain map metadata
734
1083
  * Renders a normal SDR image if gainmap data is not found
@@ -807,4 +1156,100 @@ class HDRJPGLoader extends LoaderBaseWebGPU {
807
1156
  }
808
1157
  }
809
1158
 
810
- export { GainMapDecoderMaterial, GainMapLoader, GainMapNotFoundError, HDRJPGLoader, HDRJPGLoader as JPEGRLoader, LoaderBaseShared, QuadRenderer, XMPMetadataNotFoundError, createDecodeFunction, decode, extractGainmapFromJPEG };
1159
+ /**
1160
+ * A Three.js Loader for a JPEG with embedded gain map metadata,
1161
+ * returning a {@link GainMapNode} (a TSL texture node holding the decoded HDR image).
1162
+ *
1163
+ * No renderer is needed: `load` returns the node synchronously
1164
+ * (like `TextureLoader` returns a `Texture`), it can be assigned to materials right away
1165
+ * and it is decoded on the GPU once loaded.
1166
+ *
1167
+ * @category Loaders
1168
+ * @group Loaders
1169
+ *
1170
+ * @example
1171
+ * import { HDRJPGNodeLoader } from '@monogrid/gainmap-js/webgpu'
1172
+ * import { equirectUV } from 'three/tsl'
1173
+ * import { MeshBasicNodeMaterial } from 'three/webgpu'
1174
+ *
1175
+ * const hdr = new HDRJPGNodeLoader().load('gainmap.jpeg')
1176
+ *
1177
+ * const material = new MeshBasicNodeMaterial()
1178
+ * material.colorNode = hdr
1179
+ *
1180
+ * scene.backgroundNode = hdr.sample(equirectUV())
1181
+ *
1182
+ * // all parameters are uniforms, changing them re-decodes the image once
1183
+ * hdr.maxDisplayBoost.value = 2
1184
+ */
1185
+ class HDRJPGNodeLoader extends LoaderBaseNode {
1186
+ /**
1187
+ * Loads a JPEG containing gain map metadata
1188
+ * Renders a normal SDR image if gainmap data is not found
1189
+ *
1190
+ * @param url Path to a JPEG file containing embedded gain map metadata
1191
+ * @param onLoad Load complete callback, will receive the node
1192
+ * @param onProgress Progress callback, will receive a `ProgressEvent`
1193
+ * @param onError Error callback
1194
+ * @returns a node which can be used immediately, it will hold the image once loaded
1195
+ */
1196
+ load(url, onLoad, onProgress, onError) {
1197
+ const node = new GainMapNode();
1198
+ this.manager.itemStart(url);
1199
+ this.createFileLoader('arraybuffer').load(url, async (jpeg) => {
1200
+ try {
1201
+ /* istanbul ignore if
1202
+ this condition exists only because of three.js types + strict mode
1203
+ */
1204
+ if (typeof jpeg === 'string')
1205
+ throw new Error('Invalid buffer, received [string], was expecting [ArrayBuffer]');
1206
+ const jpegBuffer = new Uint8Array(jpeg);
1207
+ let sdrJPEG;
1208
+ let gainMapJPEG;
1209
+ let metadata;
1210
+ try {
1211
+ const extractionResult = await extractGainmapFromJPEG(jpegBuffer);
1212
+ sdrJPEG = extractionResult.sdr;
1213
+ gainMapJPEG = extractionResult.gainMap;
1214
+ metadata = extractionResult.metadata;
1215
+ }
1216
+ catch (e) {
1217
+ // render the SDR version if this is not a gainmap
1218
+ if (e instanceof XMPMetadataNotFoundError || e instanceof GainMapNotFoundError) {
1219
+ console.warn(`Failure to reconstruct an HDR image from ${url}: Gain map metadata not found in the file, HDRJPGNodeLoader will render the SDR jpeg`);
1220
+ metadata = {
1221
+ gainMapMin: [0, 0, 0],
1222
+ gainMapMax: [1, 1, 1],
1223
+ gamma: [1, 1, 1],
1224
+ hdrCapacityMin: 0,
1225
+ hdrCapacityMax: 1,
1226
+ offsetHdr: [0, 0, 0],
1227
+ offsetSdr: [0, 0, 0]
1228
+ };
1229
+ sdrJPEG = jpegBuffer;
1230
+ }
1231
+ else {
1232
+ throw e;
1233
+ }
1234
+ }
1235
+ await this.fillNode(node, metadata, sdrJPEG.buffer, gainMapJPEG?.buffer);
1236
+ }
1237
+ catch (error) {
1238
+ this.manager.itemError(url);
1239
+ if (typeof onError === 'function')
1240
+ onError(error);
1241
+ return;
1242
+ }
1243
+ if (typeof onLoad === 'function')
1244
+ onLoad(node);
1245
+ this.manager.itemEnd(url);
1246
+ }, onProgress, (error) => {
1247
+ this.manager.itemError(url);
1248
+ if (typeof onError === 'function')
1249
+ onError(error);
1250
+ });
1251
+ return node;
1252
+ }
1253
+ }
1254
+
1255
+ export { GainMapDecoderMaterial, GainMapLoader, GainMapNode, GainMapNodeLoader, GainMapNotFoundError, HDRJPGLoader, HDRJPGNodeLoader, HDRJPGLoader as JPEGRLoader, LoaderBaseShared, QuadRenderer, XMPMetadataNotFoundError, createDecodeFunction, createTextures, decode, extractGainmapFromJPEG, gainMapNode, processImages };
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @monogrid/gainmap-js v3.4.1
2
+ * @monogrid/gainmap-js v3.6.0
3
3
  * With ❤️, by MONOGRID <gainmap@monogrid.com>
4
4
  */
5
- import{c as e,L as t,e as r,X as i,G as s}from"./Loader-uEDs4JZg.js";export{M as MPFExtractor,a as extractXMP}from"./Loader-uEDs4JZg.js";import{ClampToEdgeWrapping as n,LinearFilter as o,Scene as h,OrthographicCamera as d,Mesh as p,PlaneGeometry as m,RenderTarget as g,RGBAFormat as f,UVMapping as l,WebGPURenderer as _,DataTexture as c,LinearSRGBColorSpace as u,ShaderMaterial as y,Texture as w,MeshBasicNodeMaterial as x,NoBlending as v,Vector3 as T,FileLoader as U}from"three/webgpu";import"three";import{vec3 as R,texture as S,uniform as C}from"three/tsl";class O{_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:f,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:o,minFilter:void 0!==e.renderTargetOptions?.minFilter?e.renderTargetOptions?.minFilter:o,samples:void 0!==e.renderTargetOptions?.samples?e.renderTargetOptions?.samples:void 0,wrapS:void 0!==e.renderTargetOptions?.wrapS?e.renderTargetOptions?.wrapS:n,wrapT:void 0!==e.renderTargetOptions?.wrapT?e.renderTargetOptions?.wrapT:n};this._material=e.material,e.renderer?this._renderer=e.renderer:(this._renderer=O.instantiateRenderer(),this._rendererIsDisposable=!0),this._scene=new h,this._camera=new d,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 p(new m,this._material),this._quad.geometry.computeBoundingBox(),this._scene.add(this._quad),this._renderTarget=new g(this.width,this.height,t),this._renderTarget.texture.mapping=void 0!==e.renderTargetOptions?.mapping?e.renderTargetOptions?.mapping:l}static instantiateRenderer(){const e=new _;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");return await this._renderer.readRenderTargetPixelsAsync(this._renderTarget,0,0,this._width,this._height)}async toDataTexture(e){const t=new c(await this.toArray(),this.width,this.height,f,this._type,e?.mapping||l,e?.wrapS||n,e?.wrapT||n,e?.magFilter||o,e?.minFilter||o,e?.anisotropy||1,u);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 y&&Object.values(this.material.uniforms).forEach(e=>{e.value instanceof w&&e.value.dispose()}),Object.values(this.material).forEach(e=>{e instanceof w&&e.dispose()}),this.material.dispose(),this._quad.geometry.dispose(),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 b=R(-65504,-65504,-65504),D=R(65504,65504,65504);class E extends x{_maxDisplayBoost;_hdrCapacityMin;_hdrCapacityMax;_gammaUniform;_offsetHdrUniform;_offsetSdrUniform;_gainMapMinUniform;_gainMapMaxUniform;_weightFactorUniform;_sdrTexture;_gainMapTexture;constructor({gamma:e,offsetHdr:t,offsetSdr:r,gainMapMin:a,gainMapMax:i,maxDisplayBoost:s,hdrCapacityMin:n,hdrCapacityMax:o,sdr:h,gainMap:d}){super(),this.name="GainMapDecoderMaterial",this.blending=v,this.depthTest=!1,this.depthWrite=!1,this._sdrTexture=S(h),this._gainMapTexture=S(d),this._gammaUniform=C(new T(1/e[0],1/e[1],1/e[2])),this._offsetHdrUniform=C(new T(t[0],t[1],t[2])),this._offsetSdrUniform=C(new T(r[0],r[1],r[2])),this._gainMapMinUniform=C(new T(a[0],a[1],a[2])),this._gainMapMaxUniform=C(new T(i[0],i[1],i[2]));const p=(Math.log2(s)-n)/(o-n);this._weightFactorUniform=C(p,"float"),this._maxDisplayBoost=s,this._hdrCapacityMin=n,this._hdrCapacityMax=o;const m=this._sdrTexture.rgb,g=this._gainMapTexture.rgb.pow(this._gammaUniform),f=this._gainMapMinUniform.mul(g.oneMinus()).add(this._gainMapMaxUniform.mul(g)),l=R(2).pow(f.mul(this._weightFactorUniform)),_=m.add(this._offsetSdrUniform).mul(l).sub(this._offsetHdrUniform).min(D).max(b);this.colorNode=_}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 H=e({renderer:_,createMaterial:e=>new E(e),createQuadRenderer:e=>new O(e)}),F=async e=>{if(!e.renderer)throw new Error("Renderer is required for decode function");const t=H({...e,renderer:e.renderer});try{await t.render()}catch(e){throw t.disposeOnDemandRenderer(),e}return t};class q extends t{constructor(e,t){super({renderer:e,createMaterial:e=>new E(e),createQuadRenderer:e=>new O(e)},t)}async render(e,t,r,a){const{sdrImage:i,gainMapImage:s,needsFlip:n}=await this.processImages(r,a,"from-image"),{gainMap:o,sdr:h}=this.createTextures(i,s,n);this.updateQuadRenderer(e,i,o,h,t),await e.render()}}class z extends q{load([e,t,r],a,i,s){const n=this.prepareQuadRenderer();let o,h,d;const p=async()=>{if(o&&h&&d){try{await this.render(n,d,o,h)}catch(a){return this.manager.itemError(e),this.manager.itemError(t),this.manager.itemError(r),"function"==typeof s&&s(a),void n.disposeOnDemandRenderer()}"function"==typeof a&&a(n),this.manager.itemEnd(e),this.manager.itemEnd(t),this.manager.itemEnd(r),n.disposeOnDemandRenderer()}};let m=!0,g=0,f=0,l=!0,_=0,c=0,u=!0,M=0,y=0;const w=()=>{if("function"==typeof i){i(new ProgressEvent("progress",{lengthComputable:m&&l&&u,loaded:f+c+y,total:g+_+M}))}};this.manager.itemStart(e),this.manager.itemStart(t),this.manager.itemStart(r);const x=new U(this._internalLoadingManager);x.setResponseType("arraybuffer"),x.setRequestHeader(this.requestHeader),x.setPath(this.path),x.setWithCredentials(this.withCredentials),x.load(e,async e=>{if("string"==typeof e)throw new Error("Invalid sdr buffer");o=e,await p()},e=>{m=e.lengthComputable,f=e.loaded,g=e.total,w()},t=>{this.manager.itemError(e),"function"==typeof s&&s(t)});const v=new U(this._internalLoadingManager);v.setResponseType("arraybuffer"),v.setRequestHeader(this.requestHeader),v.setPath(this.path),v.setWithCredentials(this.withCredentials),v.load(t,async e=>{if("string"==typeof e)throw new Error("Invalid gainmap buffer");h=e,await p()},e=>{l=e.lengthComputable,c=e.loaded,_=e.total,w()},e=>{this.manager.itemError(t),"function"==typeof s&&s(e)});const T=new U(this._internalLoadingManager);return 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 metadata string");d=JSON.parse(e),await p()},e=>{u=e.lengthComputable,y=e.loaded,M=e.total,w()},e=>{this.manager.itemError(r),"function"==typeof s&&s(e)}),n}}class B extends q{load(e,t,a,n){const o=this.prepareQuadRenderer(),h=new U(this._internalLoadingManager);return h.setResponseType("arraybuffer"),h.setRequestHeader(this.requestHeader),h.setPath(this.path),h.setWithCredentials(this.withCredentials),this.manager.itemStart(e),h.load(e,async a=>{if("string"==typeof a)throw new Error("Invalid buffer, received [string], was expecting [ArrayBuffer]");const h=new Uint8Array(a);let d,p,m;try{const e=await r(h);d=e.sdr,p=e.gainMap,m=e.metadata}catch(t){if(!(t instanceof i||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`),m={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=h}try{await this.render(o,m,d.buffer,p?.buffer)}catch(t){return this.manager.itemError(e),"function"==typeof n&&n(t),void o.disposeOnDemandRenderer()}"function"==typeof t&&t(o),this.manager.itemEnd(e),o.disposeOnDemandRenderer()},a,t=>{this.manager.itemError(e),"function"==typeof n&&n(t)}),o}}export{E as GainMapDecoderMaterial,z as GainMapLoader,s as GainMapNotFoundError,B as HDRJPGLoader,B as JPEGRLoader,t as LoaderBaseShared,O as QuadRenderer,i as XMPMetadataNotFoundError,e as createDecodeFunction,F as decode,r as extractGainmapFromJPEG};
5
+ import{w as e,c as t,L as r,p as a,a as i,e as s,X as n,G as o}from"./warn-deprecated-D0kPpXtA.js";export{M as MPFExtractor,b as extractISO,d as extractXMP}from"./warn-deprecated-D0kPpXtA.js";import{ClampToEdgeWrapping as h,LinearFilter as p,Scene as m,OrthographicCamera as g,Mesh as f,PlaneGeometry as u,RenderTarget as l,RGBAFormat as c,UVMapping as _,WebGPURenderer as y,DataTexture as w,LinearSRGBColorSpace as x,ShaderMaterial as v,Texture as T,MeshBasicNodeMaterial as C,NoBlending as S,Vector3 as U,FileLoader as R,TextureNode as E,LinearMipmapLinearFilter as D,HalfFloatType as H,NodeUpdateType as O,QuadMesh as B,RendererUtils as F,Loader as P}from"three/webgpu";import"three";import{vec3 as q,texture as N,uniform as A,mix as I,saturate as z,log2 as L,exp2 as G,vec4 as j}from"three/tsl";import"./iso-gainmap-metadata-CEaaU7RT.js";class W{_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:c,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:p,minFilter:void 0!==e.renderTargetOptions?.minFilter?e.renderTargetOptions?.minFilter:p,samples:void 0!==e.renderTargetOptions?.samples?e.renderTargetOptions?.samples:void 0,wrapS:void 0!==e.renderTargetOptions?.wrapS?e.renderTargetOptions?.wrapS:h,wrapT:void 0!==e.renderTargetOptions?.wrapT?e.renderTargetOptions?.wrapT:h};this._material=e.material,e.renderer?this._renderer=e.renderer:(this._renderer=W.instantiateRenderer(),this._rendererIsDisposable=!0),this._scene=new m,this._camera=new g,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 f(new u,this._material),this._quad.geometry.computeBoundingBox(),this._scene.add(this._quad),this._renderTarget=new l(this.width,this.height,t),this._renderTarget.texture.mapping=void 0!==e.renderTargetOptions?.mapping?e.renderTargetOptions?.mapping:_}static instantiateRenderer(){const e=new y;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");return await this._renderer.readRenderTargetPixelsAsync(this._renderTarget,0,0,this._width,this._height)}async toDataTexture(e){const t=new w(await this.toArray(),this.width,this.height,c,this._type,e?.mapping||_,e?.wrapS||h,e?.wrapT||h,e?.magFilter||p,e?.minFilter||p,e?.anisotropy||1,x);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 v&&Object.values(this.material.uniforms).forEach(e=>{e.value instanceof T&&e.value.dispose()}),Object.values(this.material).forEach(e=>{e instanceof T&&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 J=q(-65504,-65504,-65504),Q=q(65504,65504,65504);class Y extends C{_maxDisplayBoost;_hdrCapacityMin;_hdrCapacityMax;_gammaUniform;_offsetHdrUniform;_offsetSdrUniform;_gainMapMinUniform;_gainMapMaxUniform;_weightFactorUniform;_sdrTexture;_gainMapTexture;constructor({gamma:e,offsetHdr:t,offsetSdr:r,gainMapMin:a,gainMapMax:i,maxDisplayBoost:s,hdrCapacityMin:n,hdrCapacityMax:o,sdr:h,gainMap:d}){super(),this.name="GainMapDecoderMaterial",this.blending=S,this.depthTest=!1,this.depthWrite=!1,this._sdrTexture=N(h),this._gainMapTexture=N(d),this._gammaUniform=A(new U(1/e[0],1/e[1],1/e[2])),this._offsetHdrUniform=A(new U(t[0],t[1],t[2])),this._offsetSdrUniform=A(new U(r[0],r[1],r[2])),this._gainMapMinUniform=A(new U(a[0],a[1],a[2])),this._gainMapMaxUniform=A(new U(i[0],i[1],i[2]));const p=(Math.log2(s)-n)/(o-n);this._weightFactorUniform=A(p,"float"),this._maxDisplayBoost=s,this._hdrCapacityMin=n,this._hdrCapacityMax=o;const m=this._sdrTexture.rgb,g=this._gainMapTexture.rgb.pow(this._gammaUniform),f=this._gainMapMinUniform.mul(g.oneMinus()).add(this._gainMapMaxUniform.mul(g)),u=q(2).pow(f.mul(this._weightFactorUniform)),l=m.add(this._offsetSdrUniform).mul(u).sub(this._offsetHdrUniform).min(Q).max(J);this.colorNode=l}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 X=t({renderer:y,createMaterial:e=>new Y(e),createQuadRenderer:e=>new W(e)}),$=async t=>{if(e("decode()","@monogrid/gainmap-js/webgpu","gainMapNode()"),!t.renderer)throw new Error("Renderer is required for decode function");const r=X({...t,renderer:t.renderer});try{await r.render()}catch(e){throw r.disposeOnDemandRenderer(),e}return r};class k extends r{constructor(e,t){super({renderer:e,createMaterial:e=>new Y(e),createQuadRenderer:e=>new W(e)},t)}async render(e,t,r,a){const{sdrImage:i,gainMapImage:s,needsFlip:n}=await this.processImages(r,a,"from-image"),{gainMap:o,sdr:h}=this.createTextures(i,s,n);this.updateQuadRenderer(e,i,o,h,t),await e.render()}}class K extends k{constructor(t,r){super(t,r),e("GainMapLoader","@monogrid/gainmap-js/webgpu","GainMapNodeLoader")}load([e,t,r],a,i,s){const n=this.prepareQuadRenderer();let o,h,d;const p=async()=>{if(o&&h&&d){try{await this.render(n,d,o,h)}catch(a){return this.manager.itemError(e),this.manager.itemError(t),this.manager.itemError(r),"function"==typeof s&&s(a),void n.disposeOnDemandRenderer()}"function"==typeof a&&a(n),this.manager.itemEnd(e),this.manager.itemEnd(t),this.manager.itemEnd(r),n.disposeOnDemandRenderer()}};let m=!0,g=0,f=0,u=!0,l=0,c=0,M=!0,_=0,y=0;const w=()=>{if("function"==typeof i){i(new ProgressEvent("progress",{lengthComputable:m&&u&&M,loaded:f+c+y,total:g+l+_}))}};this.manager.itemStart(e),this.manager.itemStart(t),this.manager.itemStart(r);const x=new R(this._internalLoadingManager);x.setResponseType("arraybuffer"),x.setRequestHeader(this.requestHeader),x.setPath(this.path),x.setWithCredentials(this.withCredentials),x.load(e,async e=>{if("string"==typeof e)throw new Error("Invalid sdr buffer");o=e,await p()},e=>{m=e.lengthComputable,f=e.loaded,g=e.total,w()},t=>{this.manager.itemError(e),"function"==typeof s&&s(t)});const v=new R(this._internalLoadingManager);v.setResponseType("arraybuffer"),v.setRequestHeader(this.requestHeader),v.setPath(this.path),v.setWithCredentials(this.withCredentials),v.load(t,async e=>{if("string"==typeof e)throw new Error("Invalid gainmap buffer");h=e,await p()},e=>{u=e.lengthComputable,c=e.loaded,l=e.total,w()},e=>{this.manager.itemError(t),"function"==typeof s&&s(e)});const T=new R(this._internalLoadingManager);return 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 metadata string");d=JSON.parse(e),await p()},e=>{M=e.lengthComputable,y=e.loaded,_=e.total,w()},e=>{this.manager.itemError(r),"function"==typeof s&&s(e)}),n}}class V extends E{static get type(){return"GainMapNode"}uniforms;renderTarget;_quadMesh;_material;_rendererState={};_state=[];constructor(){const e=new l(1,1,{type:H,colorSpace:x,depthBuffer:!1,generateMipmaps:!0,minFilter:D,magFilter:p});super(e.texture),this.renderTarget=e,this.updateBeforeType=O.RENDER;const t=this.uniforms={sdr:N(new T),gainMap:N(new T),gamma:A(new U(1,1,1)),offsetSdr:A(new U),offsetHdr:A(new U),gainMapMin:A(new U),gainMapMax:A(new U(1,1,1)),hdrCapacityMin:A(0),hdrCapacityMax:A(1),maxDisplayBoost:A(1)},r=t.gainMap.rgb.pow(q(1).div(t.gamma)),a=I(t.gainMapMin,t.gainMapMax,r),i=z(L(t.maxDisplayBoost).sub(t.hdrCapacityMin).div(t.hdrCapacityMax.sub(t.hdrCapacityMin))),s=t.sdr.rgb.add(t.offsetSdr).mul(G(a.mul(i))).sub(t.offsetHdr);this._material=new C,this._material.name="GainMapDecoder",this._material.colorNode=j(s.clamp(-65504,65504),1),this._quadMesh=new B(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,F.resetRendererState(e,this._rendererState),e.setRenderTarget(this.renderTarget),this._quadMesh.render(e),F.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 E(this.value,this.uvNode,this.levelNode,this.biasNode);return e.sampler=this.sampler,e.updateBeforeType=O.RENDER,e.updateBefore=e=>this.updateBefore(e),e}dispose(){this.renderTarget.dispose(),this._material.dispose(),this.sdr.dispose(),this.gainMap.dispose(),super.dispose()}}const Z=(e,t,r)=>(new V).setTextures(e,t).setMetadata(r);class ee extends P{createFileLoader(e){const t=new R(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,s){const{sdrImage:n,gainMapImage:o}=await a(r,s,"from-image"),{sdr:h,gainMap:d}=i(n,o,!0);e.setTextures(h,d).setMetadata(t)}}class te extends ee{load(e,t,r,a){const i=new V,s=e.map(()=>({lengthComputable:!0,loaded:0,total:0})),n=(e,t,a)=>new Promise((i,n)=>{this.manager.itemStart(e),this.createFileLoader(a).load(e,i,e=>{s[t]={lengthComputable:e.lengthComputable,loaded:e.loaded,total:e.total},"function"==typeof r&&r(new ProgressEvent("progress",{lengthComputable:s.every(e=>e.lengthComputable),loaded:s.reduce((e,t)=>e+t.loaded,0),total:s.reduce((e,t)=>e+t.total,0)}))},n)}),[o,h,d]=e;return Promise.all([n(o,0,"arraybuffer"),n(h,1,"arraybuffer"),n(d,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}}class re extends k{constructor(t,r){super(t,r),e("HDRJPGLoader","@monogrid/gainmap-js/webgpu","HDRJPGNodeLoader")}load(e,t,r,a){const i=this.prepareQuadRenderer(),h=new R(this._internalLoadingManager);return h.setResponseType("arraybuffer"),h.setRequestHeader(this.requestHeader),h.setPath(this.path),h.setWithCredentials(this.withCredentials),this.manager.itemStart(e),h.load(e,async r=>{if("string"==typeof r)throw new Error("Invalid buffer, received [string], was expecting [ArrayBuffer]");const h=new Uint8Array(r);let d,p,m;try{const e=await s(h);d=e.sdr,p=e.gainMap,m=e.metadata}catch(t){if(!(t instanceof n||t instanceof o))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`),m={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=h}try{await this.render(i,m,d.buffer,p?.buffer)}catch(t){return this.manager.itemError(e),"function"==typeof a&&a(t),void i.disposeOnDemandRenderer()}"function"==typeof t&&t(i),this.manager.itemEnd(e),i.disposeOnDemandRenderer()},r,t=>{this.manager.itemError(e),"function"==typeof a&&a(t)}),i}}class ae extends ee{load(e,t,r,a){const i=new V;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,h,d;try{const e=await s(t);a=e.sdr,h=e.gainMap,d=e.metadata}catch(r){if(!(r instanceof n||r instanceof o))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,h?.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}}export{Y as GainMapDecoderMaterial,K as GainMapLoader,V as GainMapNode,te as GainMapNodeLoader,o as GainMapNotFoundError,re as HDRJPGLoader,ae as HDRJPGNodeLoader,re as JPEGRLoader,r as LoaderBaseShared,W as QuadRenderer,n as XMPMetadataNotFoundError,t as createDecodeFunction,i as createTextures,$ as decode,s as extractGainmapFromJPEG,Z as gainMapNode,a as processImages};