@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
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("three")):"function"==typeof define&&define.amd?define(["exports","three"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["@monogrid/gainmap-js"]={},e.three)}(this,function(e,t){"use strict";const r=(e,r,a)=>{let i;switch(e){case t.UnsignedByteType:i=new Uint8ClampedArray(r*a*4);break;case t.HalfFloatType:i=new Uint16Array(r*a*4);break;case t.UnsignedIntType:i=new Uint32Array(r*a*4);break;case t.ByteType:i=new Int8Array(r*a*4);break;case t.ShortType:i=new Int16Array(r*a*4);break;case t.IntType:i=new Int32Array(r*a*4);break;case t.FloatType:i=new Float32Array(r*a*4);break;default:throw new Error("Unsupported data type")}return i};let a;class i{_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 n={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};if(this._material=e.material,e.renderer?this._renderer=e.renderer:(this._renderer=i.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(),!((e,i,n,s)=>{if(void 0!==a)return a;const o=new t.WebGLRenderTarget(1,1,s);i.setRenderTarget(o);const d=new t.Mesh(new t.PlaneGeometry,new t.MeshBasicMaterial({color:16777215}));i.render(d,n),i.setRenderTarget(null);const p=r(e,o.width,o.height);return i.readRenderTargetPixels(o,0,0,o.width,o.height,p),o.dispose(),d.geometry.dispose(),d.material.dispose(),a=0!==p[0],a})(this._type,this._renderer,this._camera,n)){let e;if(this._type===t.HalfFloatType)e=this._renderer.extensions.has("EXT_color_buffer_float")?t.FloatType:void 0;void 0!==e?(console.warn(`This browser does not support reading pixels from ${this._type} RenderTargets, switching to ${t.FloatType}`),this._type=e):(this._supportsReadPixels=!1,console.warn("This browser dos not support toArray or toDataTexture, calls to those methods will result in an error thrown"))}this._quad=new t.Mesh(new t.PlaneGeometry,this._material),this._quad.geometry.computeBoundingBox(),this._scene.add(this._quad),this._renderTarget=new t.WebGLRenderTarget(this.width,this.height,n),this._renderTarget.texture.mapping=void 0!==e.renderTargetOptions?.mapping?e.renderTargetOptions?.mapping:t.UVMapping}static instantiateRenderer(){const e=new t.WebGLRenderer;return e.setSize(128,128),e}render=()=>{this._renderer.setRenderTarget(this._renderTarget);try{this._renderer.render(this._scene,this._camera)}catch(e){throw this._renderer.setRenderTarget(null),e}this._renderer.setRenderTarget(null)};toArray(){if(!this._supportsReadPixels)throw new Error("Can't read pixels in this browser");const e=r(this._type,this._width,this._height);return this._renderer.readRenderTargetPixels(this._renderTarget,0,0,this._width,this._height,e),e}toDataTexture(e){const r=new t.DataTexture(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.generateMipmaps=void 0!==e?.generateMipmaps&&e?.generateMipmaps,r}disposeOnDemandRenderer(){this._renderer.setRenderTarget(null),this._rendererIsDisposable&&(this._renderer.dispose(),this._renderer.forceContextLoss())}dispose(e){this.disposeOnDemandRenderer(),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()}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}}function n(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 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,p=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},h=p(!1),l=p(!1);if(h>l)throw new Error("ISO 21496-1 metadata with HDR base image is not supported");const c=[],g=[],m=[],f=[],u=[];for(let e=0;e<o;e++)c.push(p(!0)),g.push(p(!0)),m.push(p(!1)),f.push(p(!0)),u.push(p(!0));const y=e=>3===o?e:[e[0],e[0],e[0]];return{gainMapMin:y(c),gainMapMax:y(g),gamma:y(m),offsetSdr:y(f),offsetHdr:y(u),hdrCapacityMin:h,hdrCapacityMax:l}},p=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+p.length;for(let a=0;a+r<e.length;a++){if(255!==e[a]||226!==e[a+1])continue;if(!p.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}}},l=(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=l(a,"hdrgm:GainMapMin","0"),t=l(a,"hdrgm:GainMapMax"),r=l(a,"hdrgm:Gamma","1"),i=l(a,"hdrgm:OffsetSDR","0.015625"),n=l(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 p=d[1];return{gainMapMin:Array.isArray(e)?e.map(e=>parseFloat(e)):[parseFloat(e),parseFloat(e),parseFloat(e)],gainMapMax:Array.isArray(t)?t.map(e=>parseFloat(e)):[parseFloat(t),parseFloat(t),parseFloat(t)],gamma:Array.isArray(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(p)}}catch(e){}r=t.indexOf("<x:xmpmeta",e)}};class g{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),p=o+2;let h=0;for(let e=p;e<p+12*d;e+=12)45057===i.getUint16(e,!n)&&(h=i.getUint32(e+8,!n));const l=o+2+12*d+4,c=[];for(let e=l;e<l+16*h;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=h(e)??c(e);if(!t)throw new o("Gain map XMP metadata not found");const r=new g({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}},f=e=>new Promise((t,r)=>{const a=document.createElement("img");a.onload=()=>{t(a)},a.onerror=e=>{r(e)},a.src=URL.createObjectURL(e)});class u 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})}async processImages(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?f(a):Promise.resolve(void 0),f(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}}createTextures(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}}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 extends t.ShaderMaterial{_maxDisplayBoost;_hdrCapacityMin;_hdrCapacityMax;constructor({gamma:e,offsetHdr:r,offsetSdr:a,gainMapMin:i,gainMapMax:n,maxDisplayBoost:s,hdrCapacityMin:o,hdrCapacityMax:d,sdr:p,gainMap:h}){super({name:"GainMapDecoderMaterial",vertexShader:"\nvarying vec2 vUv;\n\nvoid main() {\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}\n",fragmentShader:"\n// min half float value\n#define HALF_FLOAT_MIN vec3( -65504, -65504, -65504 )\n// max half float value\n#define HALF_FLOAT_MAX vec3( 65504, 65504, 65504 )\n\nuniform sampler2D sdr;\nuniform sampler2D gainMap;\nuniform vec3 gamma;\nuniform vec3 offsetHdr;\nuniform vec3 offsetSdr;\nuniform vec3 gainMapMin;\nuniform vec3 gainMapMax;\nuniform float weightFactor;\n\nvarying vec2 vUv;\n\nvoid main() {\n vec3 rgb = texture2D( sdr, vUv ).rgb;\n vec3 recovery = texture2D( gainMap, vUv ).rgb;\n vec3 logRecovery = pow( recovery, gamma );\n vec3 logBoost = gainMapMin * ( 1.0 - logRecovery ) + gainMapMax * logRecovery;\n vec3 hdrColor = (rgb + offsetSdr) * exp2( logBoost * weightFactor ) - offsetHdr;\n vec3 clampedHdrColor = max( HALF_FLOAT_MIN, min( HALF_FLOAT_MAX, hdrColor ));\n gl_FragColor = vec4( clampedHdrColor , 1.0 );\n}\n",uniforms:{sdr:{value:p},gainMap:{value:h},gamma:{value:new t.Vector3(1/e[0],1/e[1],1/e[2])},offsetHdr:{value:(new t.Vector3).fromArray(r)},offsetSdr:{value:(new t.Vector3).fromArray(a)},gainMapMin:{value:(new t.Vector3).fromArray(i)},gainMapMax:{value:(new t.Vector3).fromArray(n)},weightFactor:{value:(Math.log2(s)-o)/(d-o)}},blending:t.NoBlending,depthTest:!1,depthWrite:!1}),this._maxDisplayBoost=s,this._hdrCapacityMin=o,this._hdrCapacityMax=d,this.needsUpdate=!0,this.uniformsNeedUpdate=!0}get sdr(){return this.uniforms.sdr.value}set sdr(e){this.uniforms.sdr.value=e}get gainMap(){return this.uniforms.gainMap.value}set gainMap(e){this.uniforms.gainMap.value=e}get offsetHdr(){return this.uniforms.offsetHdr.value.toArray()}set offsetHdr(e){this.uniforms.offsetHdr.value.fromArray(e)}get offsetSdr(){return this.uniforms.offsetSdr.value.toArray()}set offsetSdr(e){this.uniforms.offsetSdr.value.fromArray(e)}get gainMapMin(){return this.uniforms.gainMapMin.value.toArray()}set gainMapMin(e){this.uniforms.gainMapMin.value.fromArray(e)}get gainMapMax(){return this.uniforms.gainMapMax.value.toArray()}set gainMapMax(e){this.uniforms.gainMapMax.value.fromArray(e)}get gamma(){const e=this.uniforms.gamma.value;return[1/e.x,1/e.y,1/e.z]}set gamma(e){const t=this.uniforms.gamma.value;t.x=1/e[0],t.y=1/e[1],t.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.uniforms.weightFactor.value=Math.max(0,Math.min(1,e))}}const w=n({renderer:t.WebGLRenderer,createMaterial:e=>new y(e),createQuadRenderer:e=>new i(e)});class M extends u{constructor(e,t){super({renderer:e,createMaterial:e=>new y(e),createQuadRenderer:e=>new i(e)},t)}async render(e,t,r,a){const{sdrImage:i,gainMapImage:n,needsFlip:s}=await this.processImages(r,a,"flipY"),{gainMap:o,sdr:d}=this.createTextures(i,n,s);this.updateQuadRenderer(e,i,o,d,t),e.render()}}class _ extends M{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,p,h;try{const e=await m(a);d=e.sdr,p=e.gainMap,h=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`),h={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,h,d.buffer,p?.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=y,e.GainMapLoader=class extends M{load([e,r,a],i,n,s){const o=this.prepareQuadRenderer();let d,p,h;const l=async()=>{if(d&&p&&h){try{await this.render(o,h,d,p)}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,g=0,m=0,f=!0,u=0,y=0,w=!0,M=0,_=0;const x=()=>{if("function"==typeof n){n(new ProgressEvent("progress",{lengthComputable:c&&f&&w,loaded:m+y+_,total:g+u+M}))}};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 l()},e=>{c=e.lengthComputable,m=e.loaded,g=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");p=e,await l()},e=>{f=e.lengthComputable,y=e.loaded,u=e.total,x()},e=>{this.manager.itemError(r),"function"==typeof s&&s(e)});const F=new t.FileLoader(this._internalLoadingManager);return F.setRequestHeader(this.requestHeader),F.setPath(this.path),F.setWithCredentials(this.withCredentials),F.load(a,async e=>{if("string"!=typeof e)throw new Error("Invalid metadata string");h=JSON.parse(e),await l()},e=>{w=e.lengthComputable,_=e.loaded,M=e.total,x()},e=>{this.manager.itemError(a),"function"==typeof s&&s(e)}),o}},e.GainMapNotFoundError=s,e.HDRJPGLoader=_,e.JPEGRLoader=_,e.LoaderBaseShared=u,e.MPFExtractor=g,e.QuadRenderer=i,e.XMPMetadataNotFoundError=o,e.createDecodeFunction=n,e.decode=e=>{if(!e.renderer)throw new Error("Renderer is required for decode function");const t=w({...e,renderer:e.renderer});try{t.render()}catch(e){throw t.disposeOnDemandRenderer(),e}return t},e.extractGainmapFromJPEG=m,e.extractISO=h,e.extractXMP=c});
5
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("three")):"function"==typeof define&&define.amd?define(["exports","three"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["@monogrid/gainmap-js"]={},e.three)}(this,function(e,t){"use strict";const r=(e,r,a)=>{let n;switch(e){case t.UnsignedByteType:n=new Uint8ClampedArray(r*a*4);break;case t.HalfFloatType:n=new Uint16Array(r*a*4);break;case t.UnsignedIntType:n=new Uint32Array(r*a*4);break;case t.ByteType:n=new Int8Array(r*a*4);break;case t.ShortType:n=new Int16Array(r*a*4);break;case t.IntType:n=new Int32Array(r*a*4);break;case t.FloatType:n=new Float32Array(r*a*4);break;default:throw new Error("Unsupported data type")}return n};let a;class n{_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 i={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};if(this._material=e.material,e.renderer?this._renderer=e.renderer:(this._renderer=n.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(),!((e,n,i,s)=>{if(void 0!==a)return a;const o=new t.WebGLRenderTarget(1,1,s);n.setRenderTarget(o);const d=new t.Mesh(new t.PlaneGeometry,new t.MeshBasicMaterial({color:16777215}));n.render(d,i),n.setRenderTarget(null);const p=r(e,o.width,o.height);return n.readRenderTargetPixels(o,0,0,o.width,o.height,p),o.dispose(),d.geometry.dispose(),d.material.dispose(),a=0!==p[0],a})(this._type,this._renderer,this._camera,i)){let e;if(this._type===t.HalfFloatType)e=this._renderer.extensions.has("EXT_color_buffer_float")?t.FloatType:void 0;void 0!==e?(console.warn(`This browser does not support reading pixels from ${this._type} RenderTargets, switching to ${t.FloatType}`),this._type=e):(this._supportsReadPixels=!1,console.warn("This browser dos not support toArray or toDataTexture, calls to those methods will result in an error thrown"))}this._quad=new t.Mesh(new t.PlaneGeometry,this._material),this._quad.geometry.computeBoundingBox(),this._scene.add(this._quad),this._renderTarget=new t.WebGLRenderTarget(this.width,this.height,i),this._renderTarget.texture.mapping=void 0!==e.renderTargetOptions?.mapping?e.renderTargetOptions?.mapping:t.UVMapping}static instantiateRenderer(){const e=new t.WebGLRenderer;return e.setSize(128,128),e}render=()=>{this._renderer.setRenderTarget(this._renderTarget);try{this._renderer.render(this._scene,this._camera)}catch(e){throw this._renderer.setRenderTarget(null),e}this._renderer.setRenderTarget(null)};toArray(){if(!this._supportsReadPixels)throw new Error("Can't read pixels in this browser");const e=r(this._type,this._width,this._height);return this._renderer.readRenderTargetPixels(this._renderTarget,0,0,this._width,this._height,e),e}toDataTexture(e){const r=new t.DataTexture(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.generateMipmaps=void 0!==e?.generateMipmaps&&e?.generateMipmaps,r}disposeOnDemandRenderer(){this._renderer.setRenderTarget(null),this._rendererIsDisposable&&(this._renderer.dispose(),this._renderer.forceContextLoss())}dispose(e){this.disposeOnDemandRenderer(),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()}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}}function i(e){return r=>{const{sdr:a,gainMap:n,renderer:i}=r;a.colorSpace!==t.SRGBColorSpace&&(console.warn("SDR Colorspace needs to be *SRGBColorSpace*, setting it automatically"),a.colorSpace=t.SRGBColorSpace),a.needsUpdate=!0,n.colorSpace!==t.LinearSRGBColorSpace&&(console.warn("Gainmap Colorspace needs to be *LinearSRGBColorSpace*, setting it automatically"),n.colorSpace=t.LinearSRGBColorSpace),n.needsUpdate=!0;const s=e.createMaterial({...r,sdr:a,gainMap:n});return e.createQuadRenderer({width:a.image.width,height:a.image.height,type:t.HalfFloatType,colorSpace:t.LinearSRGBColorSpace,material:s,renderer:i,renderTargetOptions:r.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},n=()=>{const e=t.getUint32(r);return r+=4,e},i=a();if(0!==i)throw new Error(`Unsupported ISO 21496-1 minimum_version ${i}`);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?n():void 0,p=e=>{const a=e?(()=>{const e=t.getInt32(r);return r+=4,e})():n(),i=d??n();if(0===i)throw new Error("Invalid ISO 21496-1 fraction with zero denominator");return a/i},h=p(!1),c=p(!1);if(h>c)throw new Error("ISO 21496-1 metadata with HDR base image is not supported");const g=[],l=[],m=[],f=[],u=[];for(let e=0;e<o;e++)g.push(p(!0)),l.push(p(!0)),m.push(p(!1)),f.push(p(!0)),u.push(p(!0));const y=e=>3===o?e:[e[0],e[0],e[0]];return{gainMapMin:y(g),gainMapMax:y(l),gamma:y(m),offsetSdr:y(f),offsetHdr:y(u),hdrCapacityMin:h,hdrCapacityMax:c}},p=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+p.length;for(let a=0;a+r<e.length;a++){if(255!==e[a]||226!==e[a+1])continue;if(!p.every((t,r)=>e[a+4+r]===t))continue;const n=Math.min(e.length,a+2+t.getUint16(a+2));if(!(n-(a+r)<=4))try{return d(e.subarray(a+r,n))}catch(e){return}}},c=(e,t,r)=>{const a=new RegExp(`${t}="([^"]*)"`,"i").exec(e);if(a)return a[1];const n=new RegExp(`<${t}[^>]*>([\\s\\S]*?)</${t}>`,"i").exec(e);if(n){const e=n[1].match(/<rdf:li>([^<]*)<\/rdf:li>/g);return e&&3===e.length?e.map(e=>e.replace(/<\/?rdf:li>/g,"")):n[1].trim()}if(void 0!==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=c(a,"hdrgm:GainMapMin","0"),t=c(a,"hdrgm:GainMapMax"),r=c(a,"hdrgm:Gamma","1"),n=c(a,"hdrgm:OffsetSDR","0.015625"),i=c(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 p=d[1];return{gainMapMin:Array.isArray(e)?e.map(e=>parseFloat(e)):[parseFloat(e),parseFloat(e),parseFloat(e)],gainMapMax:Array.isArray(t)?t.map(e=>parseFloat(e)):[parseFloat(t),parseFloat(t),parseFloat(t)],gamma:Array.isArray(r)?r.map(e=>parseFloat(e)):[parseFloat(r),parseFloat(r),parseFloat(r)],offsetSdr:Array.isArray(n)?n.map(e=>parseFloat(e)):[parseFloat(n),parseFloat(n),parseFloat(n)],offsetHdr:Array.isArray(i)?i.map(e=>parseFloat(e)):[parseFloat(i),parseFloat(i),parseFloat(i)],hdrCapacityMin:parseFloat(o),hdrCapacityMax:parseFloat(p)}}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,n=new DataView(e.buffer);if(65496!==n.getUint16(0))return void r(new Error("Not a valid jpeg"));const i=n.byteLength;let s,o=2,d=0;for(;o<i;){if(++d>250)return void r(new Error(`Found no marker after ${d} loops 😵`));if(255!==n.getUint8(o))return void r(new Error(`Not a valid marker at offset 0x${o.toString(16)}, found: 0x${n.getUint8(o).toString(16)}`));if(s=n.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===n.getUint32(e)){const a=e+4;let i;if(18761===n.getUint16(a))i=!1;else{if(19789!==n.getUint16(a))return void r(new Error("No valid endianness marker found in TIFF header"));i=!0}if(42!==n.getUint16(a+2,!i))return void r(new Error("Not valid TIFF data! (no 0x002A marker)"));const s=n.getUint32(a+4,!i);if(s<8)return void r(new Error("Not valid TIFF data! (First offset less than 8)"));const o=a+s,d=n.getUint16(o,!i),p=o+2;let h=0;for(let e=p;e<p+12*d;e+=12)45057===n.getUint16(e,!i)&&(h=n.getUint32(e+8,!i));const c=o+2+12*d+4,g=[];for(let e=c;e<c+16*h;e+=16){const t={MPType:n.getUint32(e,!i),size:n.getUint32(e+4,!i),dataOffset:n.getUint32(e+8,!i),dependantImages:n.getUint32(e+12,!i),start:-1,end:-1,isFII:!1};t.dataOffset?(t.start=a+t.dataOffset,t.isFII=!1):(t.start=0,t.isFII=!0),t.end=t.start+t.size,g.push(t)}if(this.options.extractNonFII&&g.length){const e=new Blob([n]),r=[];for(const t of g){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+n.getUint16(o+2)}})}}const m=async e=>{const t=h(e)??g(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}},f=e=>new Promise((t,r)=>{const a=document.createElement("img");a.onload=()=>{t(a)},a.onerror=e=>{r(e)},a.src=URL.createObjectURL(e)}),u=async(e,t,r)=>{const a=t?new Blob([t],{type:"image/jpeg"}):void 0,n=new Blob([e],{type:"image/jpeg"});let i,s,o=!1;if("undefined"==typeof createImageBitmap){const e=await Promise.all([a?f(a):Promise.resolve(void 0),f(n)]);s=e[0],i=e[1],o="flipY"===r}else{const e=await Promise.all([a?createImageBitmap(a,{imageOrientation:r||"flipY"}):Promise.resolve(void 0),createImageBitmap(n,{imageOrientation:r||"flipY"})]);s=e[0],i=e[1]}return{sdrImage:i,gainMapImage:s,needsFlip:o}},y=(e,r,a)=>{const n=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);n.flipY=a,n.needsUpdate=!0;const i=new t.Texture(e,t.UVMapping,t.ClampToEdgeWrapping,t.ClampToEdgeWrapping,t.LinearFilter,t.LinearMipMapLinearFilter,t.RGBAFormat,t.UnsignedByteType,1,t.SRGBColorSpace);return i.flipY=a,i.needsUpdate=!0,{gainMap:n,sdr:i}};class w 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 u(e,t,r)}createTextures(e,t,r){return y(e,t,r)}updateQuadRenderer(e,t,r,a,n){e.width=t.width,e.height=t.height,e.material.gainMap=r,e.material.sdr=a,e.material.gainMapMin=n.gainMapMin,e.material.gainMapMax=n.gainMapMax,e.material.offsetHdr=n.offsetHdr,e.material.offsetSdr=n.offsetSdr,e.material.gamma=n.gamma,e.material.hdrCapacityMin=n.hdrCapacityMin,e.material.hdrCapacityMax=n.hdrCapacityMax,e.material.maxDisplayBoost=Math.pow(2,n.hdrCapacityMax),e.material.needsUpdate=!0}}const M=new Set,_=(e,t,r)=>{const a=`${t}:${e}`;M.has(a)||(M.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`))};class x extends t.ShaderMaterial{_maxDisplayBoost;_hdrCapacityMin;_hdrCapacityMax;constructor({gamma:e,offsetHdr:r,offsetSdr:a,gainMapMin:n,gainMapMax:i,maxDisplayBoost:s,hdrCapacityMin:o,hdrCapacityMax:d,sdr:p,gainMap:h}){super({name:"GainMapDecoderMaterial",vertexShader:"\nvarying vec2 vUv;\n\nvoid main() {\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}\n",fragmentShader:"\n// min half float value\n#define HALF_FLOAT_MIN vec3( -65504, -65504, -65504 )\n// max half float value\n#define HALF_FLOAT_MAX vec3( 65504, 65504, 65504 )\n\nuniform sampler2D sdr;\nuniform sampler2D gainMap;\nuniform vec3 gamma;\nuniform vec3 offsetHdr;\nuniform vec3 offsetSdr;\nuniform vec3 gainMapMin;\nuniform vec3 gainMapMax;\nuniform float weightFactor;\n\nvarying vec2 vUv;\n\nvoid main() {\n vec3 rgb = texture2D( sdr, vUv ).rgb;\n vec3 recovery = texture2D( gainMap, vUv ).rgb;\n vec3 logRecovery = pow( recovery, gamma );\n vec3 logBoost = gainMapMin * ( 1.0 - logRecovery ) + gainMapMax * logRecovery;\n vec3 hdrColor = (rgb + offsetSdr) * exp2( logBoost * weightFactor ) - offsetHdr;\n vec3 clampedHdrColor = max( HALF_FLOAT_MIN, min( HALF_FLOAT_MAX, hdrColor ));\n gl_FragColor = vec4( clampedHdrColor , 1.0 );\n}\n",uniforms:{sdr:{value:p},gainMap:{value:h},gamma:{value:new t.Vector3(1/e[0],1/e[1],1/e[2])},offsetHdr:{value:(new t.Vector3).fromArray(r)},offsetSdr:{value:(new t.Vector3).fromArray(a)},gainMapMin:{value:(new t.Vector3).fromArray(n)},gainMapMax:{value:(new t.Vector3).fromArray(i)},weightFactor:{value:(Math.log2(s)-o)/(d-o)}},blending:t.NoBlending,depthTest:!1,depthWrite:!1}),this._maxDisplayBoost=s,this._hdrCapacityMin=o,this._hdrCapacityMax=d,this.needsUpdate=!0,this.uniformsNeedUpdate=!0}get sdr(){return this.uniforms.sdr.value}set sdr(e){this.uniforms.sdr.value=e}get gainMap(){return this.uniforms.gainMap.value}set gainMap(e){this.uniforms.gainMap.value=e}get offsetHdr(){return this.uniforms.offsetHdr.value.toArray()}set offsetHdr(e){this.uniforms.offsetHdr.value.fromArray(e)}get offsetSdr(){return this.uniforms.offsetSdr.value.toArray()}set offsetSdr(e){this.uniforms.offsetSdr.value.fromArray(e)}get gainMapMin(){return this.uniforms.gainMapMin.value.toArray()}set gainMapMin(e){this.uniforms.gainMapMin.value.fromArray(e)}get gainMapMax(){return this.uniforms.gainMapMax.value.toArray()}set gainMapMax(e){this.uniforms.gainMapMax.value.fromArray(e)}get gamma(){const e=this.uniforms.gamma.value;return[1/e.x,1/e.y,1/e.z]}set gamma(e){const t=this.uniforms.gamma.value;t.x=1/e[0],t.y=1/e[1],t.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.uniforms.weightFactor.value=Math.max(0,Math.min(1,e))}}const v=i({renderer:t.WebGLRenderer,createMaterial:e=>new x(e),createQuadRenderer:e=>new n(e)});class T extends w{constructor(e,t){super({renderer:e,createMaterial:e=>new x(e),createQuadRenderer:e=>new n(e)},t)}async render(e,t,r,a){const{sdrImage:n,gainMapImage:i,needsFlip:s}=await this.processImages(r,a,"flipY"),{gainMap:o,sdr:d}=this.createTextures(n,i,s);this.updateQuadRenderer(e,n,o,d,t),e.render()}}class F extends T{constructor(e,t){super(e,t),_("HDRJPGLoader","@monogrid/gainmap-js","HDRJPGNodeLoader")}load(e,r,a,n){const i=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,p,h;try{const e=await m(a);d=e.sdr,p=e.gainMap,h=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`),h={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(i,h,d.buffer,p?.buffer)}catch(t){return this.manager.itemError(e),"function"==typeof n&&n(t),void i.disposeOnDemandRenderer()}"function"==typeof r&&r(i),this.manager.itemEnd(e),i.disposeOnDemandRenderer()},a,t=>{this.manager.itemError(e),"function"==typeof n&&n(t)}),i}}e.GainMapDecoderMaterial=x,e.GainMapLoader=class extends T{constructor(e,t){super(e,t),_("GainMapLoader","@monogrid/gainmap-js","GainMapNodeLoader")}load([e,r,a],n,i,s){const o=this.prepareQuadRenderer();let d,p,h;const c=async()=>{if(d&&p&&h){try{await this.render(o,h,d,p)}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 n&&n(o),this.manager.itemEnd(e),this.manager.itemEnd(r),this.manager.itemEnd(a),o.disposeOnDemandRenderer()}};let g=!0,l=0,m=0,f=!0,u=0,y=0,w=!0,M=0,_=0;const x=()=>{if("function"==typeof i){i(new ProgressEvent("progress",{lengthComputable:g&&f&&w,loaded:m+y+_,total:l+u+M}))}};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 c()},e=>{g=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");p=e,await c()},e=>{f=e.lengthComputable,y=e.loaded,u=e.total,x()},e=>{this.manager.itemError(r),"function"==typeof s&&s(e)});const F=new t.FileLoader(this._internalLoadingManager);return F.setRequestHeader(this.requestHeader),F.setPath(this.path),F.setWithCredentials(this.withCredentials),F.load(a,async e=>{if("string"!=typeof e)throw new Error("Invalid metadata string");h=JSON.parse(e),await c()},e=>{w=e.lengthComputable,_=e.loaded,M=e.total,x()},e=>{this.manager.itemError(a),"function"==typeof s&&s(e)}),o}},e.GainMapNotFoundError=s,e.HDRJPGLoader=F,e.JPEGRLoader=F,e.LoaderBaseShared=w,e.MPFExtractor=l,e.QuadRenderer=n,e.XMPMetadataNotFoundError=o,e.createDecodeFunction=i,e.createTextures=y,e.decode=e=>{if(_("decode()","@monogrid/gainmap-js","gainMapNode()"),!e.renderer)throw new Error("Renderer is required for decode function");const t=v({...e,renderer:e.renderer});try{t.render()}catch(e){throw t.disposeOnDemandRenderer(),e}return t},e.extractGainmapFromJPEG=m,e.extractISO=h,e.extractXMP=g,e.processImages=u});
@@ -1,18 +1,19 @@
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
 
6
- import { c as createDecodeFunction, L as LoaderBaseShared, e as extractGainmapFromJPEG, X as XMPMetadataNotFoundError, G as GainMapNotFoundError } from './Loader-CL7itwBq.js';
7
- export { M as MPFExtractor, a as extractISO, b as extractXMP } from './Loader-CL7itwBq.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';
11
- import './iso-gainmap-metadata-Dk2F4Eoz.js';
10
+ import { vec3, texture, uniform, mix, saturate, log2, exp2, vec4 } from 'three/tsl';
11
+ import './iso-gainmap-metadata-ByNqnUPn.js';
12
12
 
13
13
  /**
14
14
  * Utility class used for rendering a texture with a material (WebGPU version)
15
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).
16
17
  * @category Core
17
18
  * @group Core
18
19
  */
@@ -238,10 +239,11 @@ class QuadRenderer {
238
239
  // min half float value
239
240
  const HALF_FLOAT_MIN = vec3(-65504, -65504, -65504);
240
241
  // max half float value
241
- const HALF_FLOAT_MAX = vec3(65504, 65504, 65504);
242
+ const HALF_FLOAT_MAX$1 = vec3(65504, 65504, 65504);
242
243
  /**
243
244
  * A Material which is able to decode the Gainmap into a full HDR Representation using TSL (Three.js Shading Language)
244
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).
245
247
  * @category Materials
246
248
  * @group Materials
247
249
  */
@@ -292,7 +294,7 @@ class GainMapDecoderMaterial extends MeshBasicNodeMaterial {
292
294
  // the mathematically equivalent pow(2, x) which has proper vec3 typings.
293
295
  const gain = vec3(2).pow(logBoost.mul(this._weightFactorUniform));
294
296
  const hdrColor = rgb.add(this._offsetSdrUniform).mul(gain).sub(this._offsetHdrUniform);
295
- const clampedHdrColor = hdrColor.min(HALF_FLOAT_MAX).max(HALF_FLOAT_MIN);
297
+ const clampedHdrColor = hdrColor.min(HALF_FLOAT_MAX$1).max(HALF_FLOAT_MIN);
296
298
  this.colorNode = clampedHdrColor;
297
299
  }
298
300
  get sdr() { return this._sdrTexture.value; }
@@ -395,6 +397,7 @@ const decodeImpl = createDecodeFunction({
395
397
  /**
396
398
  * Decodes a gain map using WebGPU RenderTarget
397
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).
398
401
  * @category Decoding Functions
399
402
  * @group Decoding Functions
400
403
  * @example
@@ -448,6 +451,7 @@ const decodeImpl = createDecodeFunction({
448
451
  * @throws {Error} if the WebGPURenderer fails to render the gain map
449
452
  */
450
453
  const decode = async (params) => {
454
+ warnDeprecated('decode()', '@monogrid/gainmap-js/webgpu', 'gainMapNode()');
451
455
  // Ensure renderer is defined for the base function
452
456
  if (!params.renderer) {
453
457
  throw new Error('Renderer is required for decode function');
@@ -498,6 +502,7 @@ class LoaderBaseWebGPU extends LoaderBaseShared {
498
502
  /**
499
503
  * A Three.js Loader for the gain map format (WebGPU version).
500
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).
501
506
  * @category Loaders
502
507
  * @group Loaders
503
508
  *
@@ -544,6 +549,10 @@ class LoaderBaseWebGPU extends LoaderBaseShared {
544
549
  *
545
550
  */
546
551
  class GainMapLoader extends LoaderBaseWebGPU {
552
+ constructor(renderer, manager) {
553
+ super(renderer, manager);
554
+ warnDeprecated('GainMapLoader', '@monogrid/gainmap-js/webgpu', 'GainMapNodeLoader');
555
+ }
547
556
  /**
548
557
  * Loads a gainmap using separate data
549
558
  * * sdr image
@@ -681,9 +690,344 @@ class GainMapLoader extends LoaderBaseWebGPU {
681
690
  }
682
691
  }
683
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
+
684
1027
  /**
685
1028
  * A Three.js Loader for a JPEG with embedded gainmap metadata (WebGPU version).
686
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).
687
1031
  * @category Loaders
688
1032
  * @group Loaders
689
1033
  *
@@ -730,6 +1074,10 @@ class GainMapLoader extends LoaderBaseWebGPU {
730
1074
  *
731
1075
  */
732
1076
  class HDRJPGLoader extends LoaderBaseWebGPU {
1077
+ constructor(renderer, manager) {
1078
+ super(renderer, manager);
1079
+ warnDeprecated('HDRJPGLoader', '@monogrid/gainmap-js/webgpu', 'HDRJPGNodeLoader');
1080
+ }
733
1081
  /**
734
1082
  * Loads a JPEG containing gain map metadata
735
1083
  * Renders a normal SDR image if gainmap data is not found
@@ -808,4 +1156,100 @@ class HDRJPGLoader extends LoaderBaseWebGPU {
808
1156
  }
809
1157
  }
810
1158
 
811
- 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 };