@konfigure/sdk 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3811 @@
1
+ import {a as a$1,c,e,b,d}from'./chunk-OOVVLYAY.js';import {a}from'./chunk-XUSV3KOD.js';import {BufferGeometry,Matrix4,Vector3,Vector4,MeshBasicMaterial,BufferAttribute,Mesh,ShaderMaterial,NoBlending,Vector2,WebGLRenderTarget,NearestFilter,RGBAFormat,FloatType,PerspectiveCamera,HalfFloatType,DataTexture,LinearFilter,RepeatWrapping,RedFormat,ClampToEdgeWrapping,DataUtils,Quaternion,DataArrayTexture,DoubleSide,BackSide,FrontSide,Color,WebGLArrayRenderTarget,UnsignedByteType,NoToneMapping,Spherical,EquirectangularReflectionMapping,LinearMipMapLinearFilter,Clock,Scene,AdditiveBlending,NormalBlending,Camera,SpotLight,RectAreaLight,PMREMGenerator,MeshStandardMaterial,Matrix3,Source,RGFormat}from'three';import {FullScreenQuad}from'three/examples/jsm/postprocessing/Pass.js';function ee(i,e,t=0){if(i.isInterleavedBufferAttribute){let a=i.itemSize;for(let o=0,s=i.count;o<s;o++){let r=o+t;e.setX(r,i.getX(o)),a>=2&&e.setY(r,i.getY(o)),a>=3&&e.setZ(r,i.getZ(o)),a>=4&&e.setW(r,i.getW(o));}}else {let a=e.array,o=a.constructor,s=a.BYTES_PER_ELEMENT*i.itemSize*t;new o(a.buffer,s,i.array.length).set(i.array);}}a(ee,"copyAttributeContents");function A(i,e=null){let t=i.array.constructor,a=i.normalized,o=i.itemSize,s=e===null?i.count:e;return new BufferAttribute(new t(o*s),o,a)}a(A,"createAttributeClone");function F(i,e){if(!i&&!e)return true;if(!!i!=!!e)return false;let t=i.count===e.count,a=i.normalized===e.normalized,o=i.array.constructor===e.array.constructor,s=i.itemSize===e.itemSize;return !(!t||!a||!o||!s)}a(F,"validateAttributes");function Xr(i){let e=i[0].index!==null,t=new Set(Object.keys(i[0].attributes));if(!i[0].getAttribute("position"))throw new Error("StaticGeometryGenerator: position attribute is required.");for(let a=0;a<i.length;++a){let o=i[a],s=0;if(e!==(o.index!==null))throw new Error("StaticGeometryGenerator: All geometries must have compatible attributes; make sure index attribute exists among all geometries, or in none of them.");for(let r in o.attributes){if(!t.has(r))throw new Error('StaticGeometryGenerator: All geometries must have compatible attributes; make sure "'+r+'" attribute exists among all geometries, or in none of them.');s++;}if(s!==t.size)throw new Error("StaticGeometryGenerator: All geometries must have the same number of attributes.")}}a(Xr,"validateMergeability");function Kr(i){let e=0;for(let t=0,a=i.length;t<a;t++)e+=i[t].getIndex().count;return e}a(Kr,"getTotalIndexCount");function Zr(i){let e=0;for(let t=0,a=i.length;t<a;t++)e+=i[t].getAttribute("position").count;return e}a(Zr,"getTotalAttributeCount");function Jr(i,e,t){i.index&&i.index.count!==e&&i.setIndex(null);let a=i.attributes;for(let o in a)a[o].count!==t&&i.deleteAttribute(o);}a(Jr,"trimMismatchedAttributes");function dt(i,e={},t=new BufferGeometry){let{useGroups:a=false,forceUpdate:o=false,skipAssigningAttributes:s=[],overwriteIndex:r=true}=e;Xr(i);let l=i[0].index!==null,f=l?Kr(i):-1,d=Zr(i);if(Jr(t,f,d),a){let u=0;for(let n=0,x=i.length;n<x;n++){let p=i[n],g;l?g=p.getIndex().count:g=p.getAttribute("position").count,t.addGroup(u,g,n),u+=g;}}if(l){let u=false;if(t.index||(t.setIndex(new BufferAttribute(new Uint32Array(f),1,false)),u=true),u||r){let n=0,x=0,p=t.getIndex();for(let g=0,c=i.length;g<c;g++){let b=i[g],v=b.getIndex();if(!(!o&&!u&&s[g]))for(let T=0;T<v.count;++T)p.setX(n+T,v.getX(T)+x);n+=v.count,x+=b.getAttribute("position").count;}}}let m=Object.keys(i[0].attributes);for(let u=0,n=m.length;u<n;u++){let x=false,p=m[u];if(!t.getAttribute(p)){let b=i[0].getAttribute(p);t.setAttribute(p,A(b,d)),x=true;}let g=0,c=t.getAttribute(p);for(let b=0,v=i.length;b<v;b++){let y=i[b],T=!o&&!x&&s[b],w=y.getAttribute(p);if(!T)if(p==="color"&&c.itemSize!==w.itemSize)for(let I=g,M=w.count;I<M;I++)w.setXYZW(I,c.getX(I),c.getY(I),c.getZ(I),1);else ee(w,c,g);g+=w.count;}}}a(dt,"mergeGeometries");function pt(i,e,t){let a=i.index,s=i.attributes.position.count,r=a?a.count:s,l=i.groups;l.length===0&&(l=[{count:r,start:0,materialIndex:0}]);let f=i.getAttribute("materialIndex");if(!f||f.count!==s){let m;t.length<=255?m=new Uint8Array(s):m=new Uint16Array(s),f=new BufferAttribute(m,1,false),i.deleteAttribute("materialIndex"),i.setAttribute("materialIndex",f);}let d=f.array;for(let m=0;m<l.length;m++){let u=l[m],n=u.start,x=u.count,p=Math.min(x,r-n),g=Array.isArray(e)?e[u.materialIndex]:e,c=t.indexOf(g);for(let b=0;b<p;b++){let v=n+b;a&&(v=a.getX(v)),d[v]=c;}}}a(pt,"updateMaterialIndexAttribute");function gt(i,e){if(!i.index){let t=i.attributes.position.count,a=new Array(t);for(let o=0;o<t;o++)a[o]=o;i.setIndex(a);}if(!i.attributes.normal&&e&&e.includes("normal")&&i.computeVertexNormals(),!i.attributes.uv&&e&&e.includes("uv")){let t=i.attributes.position.count;i.setAttribute("uv",new BufferAttribute(new Float32Array(t*2),2,false));}if(!i.attributes.uv2&&e&&e.includes("uv2")){let t=i.attributes.position.count;i.setAttribute("uv2",new BufferAttribute(new Float32Array(t*2),2,false));}if(!i.attributes.tangent&&e&&e.includes("tangent"))if(i.attributes.uv&&i.attributes.normal)i.computeTangents();else {let t=i.attributes.position.count;i.setAttribute("tangent",new BufferAttribute(new Float32Array(t*4),4,false));}if(!i.attributes.color&&e&&e.includes("color")){let t=i.attributes.position.count,a=new Float32Array(t*4);a.fill(1),i.setAttribute("color",new BufferAttribute(a,4));}}a(gt,"setCommonAttributes");function O(i){let e=0;if(i.byteLength!==0){let t=new Uint8Array(i);for(let a=0;a<i.byteLength;a++){let o=t[a];e=(e<<5)-e+o,e|=0;}}return e}a(O,"bufferToHash");function vt(i){let e=i.uuid,t=Object.values(i.attributes);i.index&&(t.push(i.index),e+=`index|${i.index.version}`);let a=Object.keys(t).sort();for(let o of a){let s=t[o];e+=`${o}_${s.version}|`;}return e}a(vt,"getGeometryHash");function xt(i){let e=i.skeleton;return e?(e.boneTexture||e.computeBoneTexture(),`${O(e.boneTexture.image.data.buffer)}_${e.boneTexture.uuid}`):null}a(xt,"getSkeletonHash");var te=class{static{a(this,"MeshDiff");}constructor(e=null){this.matrixWorld=new Matrix4,this.geometryHash=null,this.skeletonHash=null,this.primitiveCount=-1,e!==null&&this.updateFrom(e);}updateFrom(e){let t=e.geometry,a=(t.index?t.index.count:t.attributes.position.count)/3;this.matrixWorld.copy(e.matrixWorld),this.geometryHash=vt(t),this.primitiveCount=a,this.skeletonHash=xt(e);}didChange(e){let t=e.geometry,a=(t.index?t.index.count:t.attributes.position.count)/3;return !(this.matrixWorld.equals(e.matrixWorld)&&this.geometryHash===vt(t)&&this.skeletonHash===xt(e)&&this.primitiveCount===a)}};var P=new Vector3,D=new Vector3,E=new Vector3,bt=new Vector4,re=new Vector3,We=new Vector3,yt=new Vector4,Tt=new Vector4,ae=new Matrix4,wt=new Matrix4;function St(i,e,t){let a=i.skeleton,o=i.geometry,s=a.bones,r=a.boneInverses;yt.fromBufferAttribute(o.attributes.skinIndex,e),Tt.fromBufferAttribute(o.attributes.skinWeight,e),ae.elements.fill(0);for(let l=0;l<4;l++){let f=Tt.getComponent(l);if(f!==0){let d=yt.getComponent(l);wt.multiplyMatrices(s[d].matrixWorld,r[d]),aa(ae,wt,f);}}return ae.multiply(i.bindMatrix).premultiply(i.bindMatrixInverse),t.transformDirection(ae),t}a(St,"boneNormalTransform");function He(i,e,t,a,o){re.set(0,0,0);for(let s=0,r=i.length;s<r;s++){let l=e[s],f=i[s];l!==0&&(We.fromBufferAttribute(f,a),t?re.addScaledVector(We,l):re.addScaledVector(We.sub(o),l));}o.add(re);}a(He,"applyMorphTarget");function aa(i,e,t){let a=i.elements,o=e.elements;for(let s=0,r=o.length;s<r;s++)a[s]+=o[s]*t;}a(aa,"addScaledMatrix");function ia(i){let{index:e,attributes:t}=i;if(e)for(let a=0,o=e.count;a<o;a+=3){let s=e.getX(a),r=e.getX(a+2);e.setX(a,r),e.setX(a+2,s);}else for(let a in t){let o=t[a],s=o.itemSize;for(let r=0,l=o.count;r<l;r+=3)for(let f=0;f<s;f++){let d=o.getComponent(r,f),m=o.getComponent(r+2,f);o.setComponent(r,f,m),o.setComponent(r+2,f,d);}}return i}a(ia,"invertGeometry");function Rt(i,e={},t=new BufferGeometry){e={applyWorldTransforms:true,attributes:[],...e};let a=i.geometry,o=e.applyWorldTransforms,s=e.attributes.includes("normal"),r=e.attributes.includes("tangent"),l=a.attributes,f=t.attributes;for(let v in t.attributes)(!e.attributes.includes(v)||!(v in a.attributes))&&t.deleteAttribute(v);!t.index&&a.index&&(t.index=a.index.clone()),f.position||t.setAttribute("position",A(l.position)),s&&!f.normal&&l.normal&&t.setAttribute("normal",A(l.normal)),r&&!f.tangent&&l.tangent&&t.setAttribute("tangent",A(l.tangent)),F(a.index,t.index),F(l.position,f.position),s&&F(l.normal,f.normal),r&&F(l.tangent,f.tangent);let d=l.position,m=s?l.normal:null,u=r?l.tangent:null,n=a.morphAttributes.position,x=a.morphAttributes.normal,p=a.morphAttributes.tangent,g=a.morphTargetsRelative,c=i.morphTargetInfluences,b=new Matrix3;b.getNormalMatrix(i.matrixWorld),a.index&&t.index.array.set(a.index.array);for(let v=0,y=l.position.count;v<y;v++)P.fromBufferAttribute(d,v),m&&D.fromBufferAttribute(m,v),u&&(bt.fromBufferAttribute(u,v),E.fromBufferAttribute(u,v)),c&&(n&&He(n,c,g,v,P),x&&He(x,c,g,v,D),p&&He(p,c,g,v,E)),i.isSkinnedMesh&&(i.applyBoneTransform(v,P),m&&St(i,v,D),u&&St(i,v,E)),o&&P.applyMatrix4(i.matrixWorld),f.position.setXYZ(v,P.x,P.y,P.z),m&&(o&&D.applyNormalMatrix(b),f.normal.setXYZ(v,D.x,D.y,D.z)),u&&(o&&E.transformDirection(i.matrixWorld),f.tangent.setXYZW(v,E.x,E.y,E.z,bt.w));for(let v in e.attributes){let y=e.attributes[v];y==="position"||y==="tangent"||y==="normal"||!(y in l)||(f[y]||t.setAttribute(y,A(l[y])),F(l[y],f[y]),ee(l[y],f[y]));}return i.matrixWorld.determinant()<0&&ia(t),t}a(Rt,"convertToStaticGeometry");var ie=class extends BufferGeometry{static{a(this,"BakedGeometry");}constructor(){super(),this.version=0,this.hash=null,this._diff=new te;}isCompatible(e,t){let a=e.geometry;for(let o=0;o<t.length;o++){let s=t[o],r=a.attributes[s],l=this.attributes[s];if(r&&!F(r,l))return false}return true}updateFrom(e,t){let a=this._diff;return a.didChange(e)?(Rt(e,t,this),a.updateFrom(e),this.version++,this.hash=`${this.uuid}_${this.version}`,true):false}};var se=0,Ge=1,Ue=2;function la(i,e){for(let t=0,a=i.length;t<a;t++)i[t].traverseVisible(s=>{s.isMesh&&e(s);});}a(la,"flatTraverseMeshes");function ca(i){let e=[];for(let t=0,a=i.length;t<a;t++){let o=i[t];Array.isArray(o.material)?e.push(...o.material):e.push(o.material);}return e}a(ca,"getMaterials");function ua(i,e,t){if(i.length===0){e.setIndex(null);let a=e.attributes;for(let o in a)e.deleteAttribute(o);for(let o in t.attributes)e.setAttribute(t.attributes[o],new BufferAttribute(new Float32Array(0),4,false));}else dt(i,t,e);for(let a in e.attributes)e.attributes[a].needsUpdate=true;}a(ua,"mergeGeometryList");var oe=class{static{a(this,"StaticGeometryGenerator");}constructor(e){this.objects=null,this.useGroups=true,this.applyWorldTransforms=true,this.generateMissingAttributes=true,this.overwriteIndex=true,this.attributes=["position","normal","color","tangent","uv","uv2"],this._intermediateGeometry=new Map,this._geometryMergeSets=new WeakMap,this._mergeOrder=[],this._dummyMesh=null,this.setObjects(e||[]);}_getDummyMesh(){if(!this._dummyMesh){let e=new MeshBasicMaterial,t=new BufferGeometry;t.setAttribute("position",new BufferAttribute(new Float32Array(9),3)),this._dummyMesh=new Mesh(t,e);}return this._dummyMesh}_getMeshes(){let e=[];return la(this.objects,t=>{e.push(t);}),e.sort((t,a)=>t.uuid>a.uuid?1:t.uuid<a.uuid?-1:0),e.length===0&&e.push(this._getDummyMesh()),e}_updateIntermediateGeometries(){let{_intermediateGeometry:e}=this,t=this._getMeshes(),a=new Set(e.keys()),o={attributes:this.attributes,applyWorldTransforms:this.applyWorldTransforms};for(let s=0,r=t.length;s<r;s++){let l=t[s],f=l.uuid;a.delete(f);let d=e.get(f);(!d||!d.isCompatible(l,this.attributes))&&(d&&d.dispose(),d=new ie,e.set(f,d)),d.updateFrom(l,o)&&this.generateMissingAttributes&&gt(d,this.attributes);}a.forEach(s=>{e.delete(s);});}setObjects(e){Array.isArray(e)?this.objects=[...e]:this.objects=[e];}generate(e=new BufferGeometry){let{useGroups:t,overwriteIndex:a,_intermediateGeometry:o,_geometryMergeSets:s}=this,r=this._getMeshes(),l=[],f=[],d=s.get(e)||[];this._updateIntermediateGeometries();let m=false;r.length!==d.length&&(m=true);for(let n=0,x=r.length;n<x;n++){let p=r[n],g=o.get(p.uuid);f.push(g);let c=d[n];!c||c.uuid!==g.uuid?(l.push(false),m=true):c.version!==g.version?l.push(false):l.push(true);}ua(f,e,{useGroups:t,forceUpdate:m,skipAssigningAttributes:l,overwriteIndex:a}),m&&e.dispose(),s.set(e,f.map(n=>({version:n.version,uuid:n.uuid})));let u=se;return m?u=Ue:l.includes(false)&&(u=Ge),{changeType:u,materials:ca(r),geometry:e}}};function ma(i){let e=new Set;for(let t=0,a=i.length;t<a;t++){let o=i[t];for(let s in o){let r=o[s];r&&r.isTexture&&e.add(r);}}return Array.from(e)}a(ma,"getTextures");function da(i){let e=[],t=new Set;for(let o=0,s=i.length;o<s;o++)i[o].traverse(r=>{r.visible&&(r.isRectAreaLight||r.isSpotLight||r.isPointLight||r.isDirectionalLight)&&(e.push(r),r.iesMap&&t.add(r.iesMap));});let a=Array.from(t).sort((o,s)=>o.uuid<s.uuid?1:o.uuid>s.uuid?-1:0);return {lights:e,iesTextures:a}}a(da,"getLights");var z=class{static{a(this,"PathTracingSceneGenerator");}get initialized(){return !!this.bvh}constructor(e){this.bvhOptions={},this.attributes=["position","normal","tangent","color","uv","uv2"],this.generateBVH=true,this.bvh=null,this.geometry=new BufferGeometry,this.staticGeometryGenerator=new oe(e),this._bvhWorker=null,this._pendingGenerate=null,this._buildAsync=false,this._materialUuids=null;}setObjects(e){this.staticGeometryGenerator.setObjects(e);}setBVHWorker(e){this._bvhWorker=e;}async generateAsync(e=null){if(!this._bvhWorker)throw new Error('PathTracingSceneGenerator: "setBVHWorker" must be called before "generateAsync" can be called.');if(this.bvh instanceof Promise)return this._pendingGenerate||(this._pendingGenerate=new Promise(async()=>(await this.bvh,this._pendingGenerate=null,this.generateAsync(e)))),this._pendingGenerate;{this._buildAsync=true;let t=this.generate(e);return this._buildAsync=false,t.bvh=this.bvh=await t.bvh,t}}generate(e=null){let{staticGeometryGenerator:t,geometry:a,attributes:o}=this,s=t.objects;t.attributes=o,s.forEach(n=>{n.traverse(x=>{x.isSkinnedMesh&&x.skeleton&&x.skeleton.update();});});let r=t.generate(a),l=r.materials,f=r.changeType!==se||this._materialUuids===null||this._materialUuids.length!==length;if(!f){for(let n=0,x=l.length;n<x;n++)if(l[n].uuid!==this._materialUuids[n]){f=true;break}}let d=ma(l),{lights:m,iesTextures:u}=da(s);if(f&&(pt(a,l,l),this._materialUuids=l.map(n=>n.uuid)),this.generateBVH){if(this.bvh instanceof Promise)throw new Error("PathTracingSceneGenerator: BVH is already building asynchronously.");if(r.changeType===Ue){let n={strategy:2,maxLeafTris:1,indirect:true,onProgress:e,...this.bvhOptions};this._buildAsync?this.bvh=this._bvhWorker.generate(a,n):this.bvh=new a$1(a,n);}else r.changeType===Ge&&this.bvh.refit();}return {bvhChanged:r.changeType!==se,bvh:this.bvh,needsMaterialIndexUpdate:f,lights:m,iesTextures:u,geometry:a,materials:l,textures:d,objects:s}}},Ft=class extends z{static{a(this,"DynamicPathTracingSceneGenerator");}constructor(...e){super(...e),console.warn('DynamicPathTracingSceneGenerator has been deprecated and renamed to "PathTracingSceneGenerator".');}},Ct=class extends z{static{a(this,"PathTracingSceneWorker");}constructor(...e){super(...e),console.warn('PathTracingSceneWorker has been deprecated and renamed to "PathTracingSceneGenerator".');}};var _=class extends ShaderMaterial{static{a(this,"MaterialBase");}set needsUpdate(e){super.needsUpdate=true,this.dispatchEvent({type:"recompilation"});}constructor(e){super(e);for(let t in this.uniforms)Object.defineProperty(this,t,{get(){return this.uniforms[t].value},set(a){this.uniforms[t].value=a;}});}setDefine(e,t=void 0){if(t==null){if(e in this.defines)return delete this.defines[e],this.needsUpdate=true,true}else if(this.defines[e]!==t)return this.defines[e]=t,this.needsUpdate=true,true;return false}};var ne=class extends _{static{a(this,"BlendMaterial");}constructor(e){super({blending:NoBlending,uniforms:{target1:{value:null},target2:{value:null},opacity:{value:1}},vertexShader:`
2
+
3
+ varying vec2 vUv;
4
+
5
+ void main() {
6
+
7
+ vUv = uv;
8
+ gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
9
+
10
+ }`,fragmentShader:`
11
+
12
+ uniform float opacity;
13
+
14
+ uniform sampler2D target1;
15
+ uniform sampler2D target2;
16
+
17
+ varying vec2 vUv;
18
+
19
+ void main() {
20
+
21
+ vec4 color1 = texture2D( target1, vUv );
22
+ vec4 color2 = texture2D( target2, vUv );
23
+
24
+ float invOpacity = 1.0 - opacity;
25
+ float totalAlpha = color1.a * invOpacity + color2.a * opacity;
26
+
27
+ if ( color1.a != 0.0 || color2.a != 0.0 ) {
28
+
29
+ gl_FragColor.rgb = color1.rgb * ( invOpacity * color1.a / totalAlpha ) + color2.rgb * ( opacity * color2.a / totalAlpha );
30
+ gl_FragColor.a = totalAlpha;
31
+
32
+ } else {
33
+
34
+ gl_FragColor = vec4( 0.0 );
35
+
36
+ }
37
+
38
+ }`}),this.setValues(e);}};function le(i=1){let e="uint";return i>1&&(e="uvec"+i),`
39
+ ${e} sobolReverseBits( ${e} x ) {
40
+
41
+ x = ( ( ( x & 0xaaaaaaaau ) >> 1 ) | ( ( x & 0x55555555u ) << 1 ) );
42
+ x = ( ( ( x & 0xccccccccu ) >> 2 ) | ( ( x & 0x33333333u ) << 2 ) );
43
+ x = ( ( ( x & 0xf0f0f0f0u ) >> 4 ) | ( ( x & 0x0f0f0f0fu ) << 4 ) );
44
+ x = ( ( ( x & 0xff00ff00u ) >> 8 ) | ( ( x & 0x00ff00ffu ) << 8 ) );
45
+ return ( ( x >> 16 ) | ( x << 16 ) );
46
+
47
+ }
48
+
49
+ ${e} sobolHashCombine( uint seed, ${e} v ) {
50
+
51
+ return seed ^ ( v + ${e}( ( seed << 6 ) + ( seed >> 2 ) ) );
52
+
53
+ }
54
+
55
+ ${e} sobolLaineKarrasPermutation( ${e} x, ${e} seed ) {
56
+
57
+ x += seed;
58
+ x ^= x * 0x6c50b47cu;
59
+ x ^= x * 0xb82f1e52u;
60
+ x ^= x * 0xc7afe638u;
61
+ x ^= x * 0x8d22f6e6u;
62
+ return x;
63
+
64
+ }
65
+
66
+ ${e} nestedUniformScrambleBase2( ${e} x, ${e} seed ) {
67
+
68
+ x = sobolLaineKarrasPermutation( x, seed );
69
+ x = sobolReverseBits( x );
70
+ return x;
71
+
72
+ }
73
+ `}a(le,"generateSobolFunctionVariants");function ce(i=1){let e="uint",t="float",a="",o=".r",s="1u";return i>1&&(e="uvec"+i,t="vec"+i,a=i+"",i===2?(o=".rg",s="uvec2( 1u, 2u )"):i===3?(o=".rgb",s="uvec3( 1u, 2u, 3u )"):(o="",s="uvec4( 1u, 2u, 3u, 4u )")),`
74
+
75
+ ${t} sobol${a}( int effect ) {
76
+
77
+ uint seed = sobolGetSeed( sobolBounceIndex, uint( effect ) );
78
+ uint index = sobolPathIndex;
79
+
80
+ uint shuffle_seed = sobolHashCombine( seed, 0u );
81
+ uint shuffled_index = nestedUniformScrambleBase2( sobolReverseBits( index ), shuffle_seed );
82
+ ${t} sobol_pt = sobolGetTexturePoint( shuffled_index )${o};
83
+ ${e} result = ${e}( sobol_pt * 16777216.0 );
84
+
85
+ ${e} seed2 = sobolHashCombine( seed, ${s} );
86
+ result = nestedUniformScrambleBase2( result, seed2 );
87
+
88
+ return SOBOL_FACTOR * ${t}( result >> 8 );
89
+
90
+ }
91
+ `}a(ce,"generateSobolSampleFunctions");var ue=`
92
+
93
+ // Utils
94
+ const float SOBOL_FACTOR = 1.0 / 16777216.0;
95
+ const uint SOBOL_MAX_POINTS = 256u * 256u;
96
+
97
+ ${le(1)}
98
+ ${le(2)}
99
+ ${le(3)}
100
+ ${le(4)}
101
+
102
+ uint sobolHash( uint x ) {
103
+
104
+ // finalizer from murmurhash3
105
+ x ^= x >> 16;
106
+ x *= 0x85ebca6bu;
107
+ x ^= x >> 13;
108
+ x *= 0xc2b2ae35u;
109
+ x ^= x >> 16;
110
+ return x;
111
+
112
+ }
113
+
114
+ `,At=`
115
+
116
+ const uint SOBOL_DIRECTIONS_1[ 32 ] = uint[ 32 ](
117
+ 0x80000000u, 0xc0000000u, 0xa0000000u, 0xf0000000u,
118
+ 0x88000000u, 0xcc000000u, 0xaa000000u, 0xff000000u,
119
+ 0x80800000u, 0xc0c00000u, 0xa0a00000u, 0xf0f00000u,
120
+ 0x88880000u, 0xcccc0000u, 0xaaaa0000u, 0xffff0000u,
121
+ 0x80008000u, 0xc000c000u, 0xa000a000u, 0xf000f000u,
122
+ 0x88008800u, 0xcc00cc00u, 0xaa00aa00u, 0xff00ff00u,
123
+ 0x80808080u, 0xc0c0c0c0u, 0xa0a0a0a0u, 0xf0f0f0f0u,
124
+ 0x88888888u, 0xccccccccu, 0xaaaaaaaau, 0xffffffffu
125
+ );
126
+
127
+ const uint SOBOL_DIRECTIONS_2[ 32 ] = uint[ 32 ](
128
+ 0x80000000u, 0xc0000000u, 0x60000000u, 0x90000000u,
129
+ 0xe8000000u, 0x5c000000u, 0x8e000000u, 0xc5000000u,
130
+ 0x68800000u, 0x9cc00000u, 0xee600000u, 0x55900000u,
131
+ 0x80680000u, 0xc09c0000u, 0x60ee0000u, 0x90550000u,
132
+ 0xe8808000u, 0x5cc0c000u, 0x8e606000u, 0xc5909000u,
133
+ 0x6868e800u, 0x9c9c5c00u, 0xeeee8e00u, 0x5555c500u,
134
+ 0x8000e880u, 0xc0005cc0u, 0x60008e60u, 0x9000c590u,
135
+ 0xe8006868u, 0x5c009c9cu, 0x8e00eeeeu, 0xc5005555u
136
+ );
137
+
138
+ const uint SOBOL_DIRECTIONS_3[ 32 ] = uint[ 32 ](
139
+ 0x80000000u, 0xc0000000u, 0x20000000u, 0x50000000u,
140
+ 0xf8000000u, 0x74000000u, 0xa2000000u, 0x93000000u,
141
+ 0xd8800000u, 0x25400000u, 0x59e00000u, 0xe6d00000u,
142
+ 0x78080000u, 0xb40c0000u, 0x82020000u, 0xc3050000u,
143
+ 0x208f8000u, 0x51474000u, 0xfbea2000u, 0x75d93000u,
144
+ 0xa0858800u, 0x914e5400u, 0xdbe79e00u, 0x25db6d00u,
145
+ 0x58800080u, 0xe54000c0u, 0x79e00020u, 0xb6d00050u,
146
+ 0x800800f8u, 0xc00c0074u, 0x200200a2u, 0x50050093u
147
+ );
148
+
149
+ const uint SOBOL_DIRECTIONS_4[ 32 ] = uint[ 32 ](
150
+ 0x80000000u, 0x40000000u, 0x20000000u, 0xb0000000u,
151
+ 0xf8000000u, 0xdc000000u, 0x7a000000u, 0x9d000000u,
152
+ 0x5a800000u, 0x2fc00000u, 0xa1600000u, 0xf0b00000u,
153
+ 0xda880000u, 0x6fc40000u, 0x81620000u, 0x40bb0000u,
154
+ 0x22878000u, 0xb3c9c000u, 0xfb65a000u, 0xddb2d000u,
155
+ 0x78022800u, 0x9c0b3c00u, 0x5a0fb600u, 0x2d0ddb00u,
156
+ 0xa2878080u, 0xf3c9c040u, 0xdb65a020u, 0x6db2d0b0u,
157
+ 0x800228f8u, 0x400b3cdcu, 0x200fb67au, 0xb00ddb9du
158
+ );
159
+
160
+ uint getMaskedSobol( uint index, uint directions[ 32 ] ) {
161
+
162
+ uint X = 0u;
163
+ for ( int bit = 0; bit < 32; bit ++ ) {
164
+
165
+ uint mask = ( index >> bit ) & 1u;
166
+ X ^= mask * directions[ bit ];
167
+
168
+ }
169
+ return X;
170
+
171
+ }
172
+
173
+ vec4 generateSobolPoint( uint index ) {
174
+
175
+ if ( index >= SOBOL_MAX_POINTS ) {
176
+
177
+ return vec4( 0.0 );
178
+
179
+ }
180
+
181
+ // NOTE: this sobol "direction" is also available but we can't write out 5 components
182
+ // uint x = index & 0x00ffffffu;
183
+ uint x = sobolReverseBits( getMaskedSobol( index, SOBOL_DIRECTIONS_1 ) ) & 0x00ffffffu;
184
+ uint y = sobolReverseBits( getMaskedSobol( index, SOBOL_DIRECTIONS_2 ) ) & 0x00ffffffu;
185
+ uint z = sobolReverseBits( getMaskedSobol( index, SOBOL_DIRECTIONS_3 ) ) & 0x00ffffffu;
186
+ uint w = sobolReverseBits( getMaskedSobol( index, SOBOL_DIRECTIONS_4 ) ) & 0x00ffffffu;
187
+
188
+ return vec4( x, y, z, w ) * SOBOL_FACTOR;
189
+
190
+ }
191
+
192
+ `,Pt=`
193
+
194
+ // Seeds
195
+ uniform sampler2D sobolTexture;
196
+ uint sobolPixelIndex = 0u;
197
+ uint sobolPathIndex = 0u;
198
+ uint sobolBounceIndex = 0u;
199
+
200
+ uint sobolGetSeed( uint bounce, uint effect ) {
201
+
202
+ return sobolHash(
203
+ sobolHashCombine(
204
+ sobolHashCombine(
205
+ sobolHash( bounce ),
206
+ sobolPixelIndex
207
+ ),
208
+ effect
209
+ )
210
+ );
211
+
212
+ }
213
+
214
+ vec4 sobolGetTexturePoint( uint index ) {
215
+
216
+ if ( index >= SOBOL_MAX_POINTS ) {
217
+
218
+ index = index % SOBOL_MAX_POINTS;
219
+
220
+ }
221
+
222
+ uvec2 dim = uvec2( textureSize( sobolTexture, 0 ).xy );
223
+ uint y = index / dim.x;
224
+ uint x = index - y * dim.x;
225
+ vec2 uv = vec2( x, y ) / vec2( dim );
226
+ return texture( sobolTexture, uv );
227
+
228
+ }
229
+
230
+ ${ce(1)}
231
+ ${ce(2)}
232
+ ${ce(3)}
233
+ ${ce(4)}
234
+
235
+ `;var Ve=class extends _{static{a(this,"SobolNumbersMaterial");}constructor(){super({blending:NoBlending,uniforms:{resolution:{value:new Vector2}},vertexShader:`
236
+
237
+ varying vec2 vUv;
238
+ void main() {
239
+
240
+ vUv = uv;
241
+ gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
242
+
243
+ }
244
+ `,fragmentShader:`
245
+
246
+ ${ue}
247
+ ${At}
248
+
249
+ varying vec2 vUv;
250
+ uniform vec2 resolution;
251
+ void main() {
252
+
253
+ uint index = uint( gl_FragCoord.y ) * uint( resolution.x ) + uint( gl_FragCoord.x );
254
+ gl_FragColor = generateSobolPoint( index );
255
+
256
+ }
257
+ `});}},fe=class{static{a(this,"SobolNumberMapGenerator");}generate(e,t=256){let a=new WebGLRenderTarget(t,t,{type:FloatType,format:RGBAFormat,minFilter:NearestFilter,magFilter:NearestFilter,generateMipmaps:false}),o=e.getRenderTarget();e.setRenderTarget(a);let s=new FullScreenQuad(new Ve);return s.material.resolution.set(t,t),s.render(e),e.setRenderTarget(o),s.dispose(),a}};var he=class extends PerspectiveCamera{static{a(this,"PhysicalCamera");}set bokehSize(e){this.fStop=this.getFocalLength()/e;}get bokehSize(){return this.getFocalLength()/this.fStop}constructor(...e){super(...e),this.fStop=1.4,this.apertureBlades=0,this.apertureRotation=0,this.focusDistance=25,this.anamorphicRatio=1;}copy(e,t){return super.copy(e,t),this.fStop=e.fStop,this.apertureBlades=e.apertureBlades,this.apertureRotation=e.apertureRotation,this.focusDistance=e.focusDistance,this.anamorphicRatio=e.anamorphicRatio,this}};var me=class{static{a(this,"PhysicalCameraUniform");}constructor(){this.bokehSize=0,this.apertureBlades=0,this.apertureRotation=0,this.focusDistance=10,this.anamorphicRatio=1;}updateFrom(e){e instanceof he?(this.bokehSize=e.bokehSize,this.apertureBlades=e.apertureBlades,this.apertureRotation=e.apertureRotation,this.focusDistance=e.focusDistance,this.anamorphicRatio=e.anamorphicRatio):(this.bokehSize=0,this.apertureRotation=0,this.apertureBlades=0,this.focusDistance=10,this.anamorphicRatio=1);}};function de(i){let e=new Uint16Array(i.length);for(let t=0,a=i.length;t<a;++t)e[t]=DataUtils.toHalfFloat(i[t]);return e}a(de,"toHalfFloatArray");function kt(i,e,t=0,a=i.length){let o=t,s=t+a-1;for(;o<s;){let r=o+s>>1;i[r]<e?o=r+1:s=r;}return o-t}a(kt,"binarySearchFindClosestIndexOf");function Ca(i,e,t){return .2126*i+.7152*e+.0722*t}a(Ca,"colorToLuminance");function Aa(i,e=HalfFloatType){let t=i.clone();t.source=new Source({...t.image});let{width:a,height:o,data:s}=t.image,r=s;if(t.type!==e){e===HalfFloatType?r=new Uint16Array(s.length):r=new Float32Array(s.length);let l;s instanceof Int8Array||s instanceof Int16Array||s instanceof Int32Array?l=2**(8*s.BYTES_PER_ELEMENT-1)-1:l=2**(8*s.BYTES_PER_ELEMENT)-1;for(let f=0,d=s.length;f<d;f++){let m=s[f];t.type===HalfFloatType&&(m=DataUtils.fromHalfFloat(s[f])),t.type!==FloatType&&t.type!==HalfFloatType&&(m/=l),e===HalfFloatType&&(r[f]=DataUtils.toHalfFloat(m));}t.image.data=r,t.type=e;}if(t.flipY){let l=r;r=r.slice();for(let f=0;f<o;f++)for(let d=0;d<a;d++){let m=o-f-1,u=4*(f*a+d),n=4*(m*a+d);r[n+0]=l[u+0],r[n+1]=l[u+1],r[n+2]=l[u+2],r[n+3]=l[u+3];}t.flipY=false,t.image.data=r;}return t}a(Aa,"preprocessEnvMap");var pe=class{static{a(this,"EquirectHdrInfoUniform");}constructor(){let e=new DataTexture(de(new Float32Array([0,0,0,0])),1,1);e.type=HalfFloatType,e.format=RGBAFormat,e.minFilter=LinearFilter,e.magFilter=LinearFilter,e.wrapS=RepeatWrapping,e.wrapT=RepeatWrapping,e.generateMipmaps=false,e.needsUpdate=true;let t=new DataTexture(de(new Float32Array([0,1])),1,2);t.type=HalfFloatType,t.format=RedFormat,t.minFilter=LinearFilter,t.magFilter=LinearFilter,t.generateMipmaps=false,t.needsUpdate=true;let a=new DataTexture(de(new Float32Array([0,0,1,1])),2,2);a.type=HalfFloatType,a.format=RedFormat,a.minFilter=LinearFilter,a.magFilter=LinearFilter,a.generateMipmaps=false,a.needsUpdate=true,this.map=e,this.marginalWeights=t,this.conditionalWeights=a,this.totalSum=0;}dispose(){this.marginalWeights.dispose(),this.conditionalWeights.dispose(),this.map.dispose();}updateFrom(e){let t=Aa(e);t.wrapS=RepeatWrapping,t.wrapT=ClampToEdgeWrapping;let{width:a,height:o,data:s}=t.image,r=new Float32Array(a*o),l=new Float32Array(a*o),f=new Float32Array(o),d=new Float32Array(o),m=0,u=0;for(let c=0;c<o;c++){let b=0;for(let v=0;v<a;v++){let y=c*a+v,T=DataUtils.fromHalfFloat(s[4*y+0]),w=DataUtils.fromHalfFloat(s[4*y+1]),I=DataUtils.fromHalfFloat(s[4*y+2]),M=Ca(T,w,I);b+=M,m+=M,r[y]=M,l[y]=b;}if(b!==0)for(let v=c*a,y=c*a+a;v<y;v++)r[v]/=b,l[v]/=b;u+=b,f[c]=b,d[c]=u;}if(u!==0)for(let c=0,b=f.length;c<b;c++)f[c]/=u,d[c]/=u;let n=new Uint16Array(o),x=new Uint16Array(a*o);for(let c=0;c<o;c++){let b=(c+1)/o,v=kt(d,b);n[c]=DataUtils.toHalfFloat((v+.5)/o);}for(let c=0;c<o;c++)for(let b=0;b<a;b++){let v=c*a+b,y=(b+1)/a,T=kt(l,y,c*a,a);x[v]=DataUtils.toHalfFloat((T+.5)/a);}this.dispose();let{marginalWeights:p,conditionalWeights:g}=this;p.image={width:o,height:1,data:n},p.needsUpdate=true,g.image={width:a,height:o,data:x},g.needsUpdate=true,this.totalSum=m,this.map=t;}};var je=6,Oa=0,za=1,Ba=2,Wa=3,Ha=4,R=new Vector3,S=new Vector3,zt=new Matrix4,W=new Quaternion,Bt=new Vector3,H=new Vector3,Na=new Vector3(0,1,0),ge=class{static{a(this,"LightsInfoUniformStruct");}constructor(){let e=new DataTexture(new Float32Array(4),1,1);e.format=RGBAFormat,e.type=FloatType,e.wrapS=ClampToEdgeWrapping,e.wrapT=ClampToEdgeWrapping,e.generateMipmaps=false,e.minFilter=NearestFilter,e.magFilter=NearestFilter,this.tex=e,this.count=0;}updateFrom(e,t=[]){let a=this.tex,o=Math.max(e.length*je,1),s=Math.ceil(Math.sqrt(o));a.image.width!==s&&(a.dispose(),a.image.data=new Float32Array(s*s*4),a.image.width=s,a.image.height=s);let r=a.image.data;for(let f=0,d=e.length;f<d;f++){let m=e[f],u=f*je*4,n=0;for(let p=0;p<je*4;p++)r[u+p]=0;m.getWorldPosition(S),r[u+n++]=S.x,r[u+n++]=S.y,r[u+n++]=S.z;let x=Oa;if(m.isRectAreaLight&&m.isCircular?x=za:m.isSpotLight?x=Ba:m.isDirectionalLight?x=Wa:m.isPointLight&&(x=Ha),r[u+n++]=x,r[u+n++]=m.color.r,r[u+n++]=m.color.g,r[u+n++]=m.color.b,r[u+n++]=m.intensity,m.getWorldQuaternion(W),m.isRectAreaLight)R.set(m.width,0,0).applyQuaternion(W),r[u+n++]=R.x,r[u+n++]=R.y,r[u+n++]=R.z,n++,S.set(0,m.height,0).applyQuaternion(W),r[u+n++]=S.x,r[u+n++]=S.y,r[u+n++]=S.z,r[u+n++]=R.cross(S).length()*(m.isCircular?Math.PI/4:1);else if(m.isSpotLight){let p=m.radius||0;Bt.setFromMatrixPosition(m.matrixWorld),H.setFromMatrixPosition(m.target.matrixWorld),zt.lookAt(Bt,H,Na),W.setFromRotationMatrix(zt),R.set(1,0,0).applyQuaternion(W),r[u+n++]=R.x,r[u+n++]=R.y,r[u+n++]=R.z,n++,S.set(0,1,0).applyQuaternion(W),r[u+n++]=S.x,r[u+n++]=S.y,r[u+n++]=S.z,r[u+n++]=Math.PI*p*p,r[u+n++]=p,r[u+n++]=m.decay,r[u+n++]=m.distance,r[u+n++]=Math.cos(m.angle),r[u+n++]=Math.cos(m.angle*(1-m.penumbra)),r[u+n++]=m.iesMap?t.indexOf(m.iesMap):-1;}else if(m.isPointLight){let p=R.setFromMatrixPosition(m.matrixWorld);r[u+n++]=p.x,r[u+n++]=p.y,r[u+n++]=p.z,n++,n+=4,n+=1,r[u+n++]=m.decay,r[u+n++]=m.distance;}else if(m.isDirectionalLight){let p=R.setFromMatrixPosition(m.matrixWorld),g=S.setFromMatrixPosition(m.target.matrixWorld);H.subVectors(p,g).normalize(),r[u+n++]=H.x,r[u+n++]=H.y,r[u+n++]=H.z;}}this.count=e.length;let l=O(r.buffer);return this.hash!==l?(this.hash=l,a.needsUpdate=true,true):false}};function Wt(i,e,t,a,o){if(e>a)throw new Error;let s=i.length/e,r=i.constructor.BYTES_PER_ELEMENT*8,l=1;switch(i.constructor){case Uint8Array:case Uint16Array:case Uint32Array:l=2**r-1;break;case Int8Array:case Int16Array:case Int32Array:l=2**(r-1)-1;break}for(let f=0;f<s;f++){let d=4*f,m=e*f;for(let u=0;u<a;u++)t[o+d+u]=e>=u+1?i[m+u]/l:0;}}a(Wt,"copyArrayToArray");var ve=class extends DataArrayTexture{static{a(this,"FloatAttributeTextureArray");}constructor(){super(),this._textures=[],this.type=FloatType,this.format=RGBAFormat,this.internalFormat="RGBA32F";}updateAttribute(e,t){let a=this._textures[e];a.updateFrom(t);let o=a.image,s=this.image;if(o.width!==s.width||o.height!==s.height)throw new Error("FloatAttributeTextureArray: Attribute must be the same dimensions when updating single layer.");let{width:r,height:l,data:f}=s,m=r*l*4*e,u=t.itemSize;u===3&&(u=4),Wt(a.image.data,u,f,4,m),this.dispose(),this.needsUpdate=true;}setAttributes(e){let t=e[0].count,a=e.length;for(let u=0,n=a;u<n;u++)if(e[u].count!==t)throw new Error("FloatAttributeTextureArray: All attributes must have the same item count.");let o=this._textures;for(;o.length<a;){let u=new c;o.push(u);}for(;o.length>a;)o.pop();for(let u=0,n=a;u<n;u++)o[u].updateFrom(e[u]);let r=o[0].image,l=this.image;(r.width!==l.width||r.height!==l.height||r.depth!==a)&&(l.width=r.width,l.height=r.height,l.depth=a,l.data=new Float32Array(l.width*l.height*l.depth*4));let{data:f,width:d,height:m}=l;for(let u=0,n=a;u<n;u++){let x=o[u],g=d*m*4*u,c=e[u].itemSize;c===3&&(c=4),Wt(x.image.data,c,f,4,g);}this.dispose(),this.needsUpdate=true;}};var xe=class extends ve{static{a(this,"AttributesTextureArray");}updateNormalAttribute(e){this.updateAttribute(0,e);}updateTangentAttribute(e){this.updateAttribute(1,e);}updateUvAttribute(e){this.updateAttribute(2,e);}updateColorAttribute(e){this.updateAttribute(3,e);}updateFrom(e,t,a,o){this.setAttributes([e,t,a,o]);}};function Ye(i,e){return i.uuid<e.uuid?1:i.uuid>e.uuid?-1:0}a(Ye,"uuidSort");function be(i){return `${i.source.uuid}:${i.colorSpace}`}a(be,"getTextureHash");function qa(i){let e=new Set,t=[];for(let a=0,o=i.length;a<o;a++){let s=i[a],r=be(s);e.has(r)||(e.add(r),t.push(s));}return t}a(qa,"reduceTexturesToUniqueSources");function Ht(i){let e=i.map(a=>a.iesMap||null).filter(a=>a),t=new Set(e);return Array.from(t).sort(Ye)}a(Ht,"getIesTextures");function Nt(i){let e=new Set;for(let a=0,o=i.length;a<o;a++){let s=i[a];for(let r in s){let l=s[r];l&&l.isTexture&&e.add(l);}}let t=Array.from(e);return qa(t).sort(Ye)}a(Nt,"getTextures");function Gt(i){let e=[];return i.traverse(t=>{t.visible&&(t.isRectAreaLight||t.isSpotLight||t.isPointLight||t.isDirectionalLight)&&e.push(t);}),e.sort(Ye)}a(Gt,"getLights");var Te=47,qt=Te*4,Qe=class{static{a(this,"MaterialFeatures");}constructor(){this._features={};}isUsed(e){return e in this._features}setUsed(e,t=true){t===false?delete this._features[e]:this._features[e]=true;}reset(){this._features={};}},ye=class extends DataTexture{static{a(this,"MaterialsTexture");}constructor(){super(new Float32Array(4),1,1),this.format=RGBAFormat,this.type=FloatType,this.wrapS=ClampToEdgeWrapping,this.wrapT=ClampToEdgeWrapping,this.minFilter=NearestFilter,this.magFilter=NearestFilter,this.generateMipmaps=false,this.features=new Qe;}updateFrom(e,t){function a$1(p,g,c=-1){if(g in p&&p[g]){let b=be(p[g]);return u[b]}else return c}a(a$1,"getTexture");function o(p,g,c){return g in p?p[g]:c}a(o,"getField");function s(p,g,c,b){let v=p[g]&&p[g].isTexture?p[g]:null;if(v){v.matrixAutoUpdate&&v.updateMatrix();let y=v.matrix.elements,T=0;c[b+T++]=y[0],c[b+T++]=y[3],c[b+T++]=y[6],T++,c[b+T++]=y[1],c[b+T++]=y[4],c[b+T++]=y[7],T++;}return 8}a(s,"writeTextureMatrixToArray");let r=0,l=e.length*Te,f=Math.ceil(Math.sqrt(l))||1,{image:d,features:m}=this,u={};for(let p=0,g=t.length;p<g;p++)u[be(t[p])]=p;d.width!==f&&(this.dispose(),d.data=new Float32Array(f*f*4),d.width=f,d.height=f);let n=d.data;m.reset();for(let p=0,g=e.length;p<g;p++){let c=e[p];if(c.isFogVolumeMaterial){m.setUsed("FOG");for(let y=0;y<qt;y++)n[r+y]=0;n[r+0+0]=c.color.r,n[r+0+1]=c.color.g,n[r+0+2]=c.color.b,n[r+8+3]=o(c,"emissiveIntensity",0),n[r+12+0]=c.emissive.r,n[r+12+1]=c.emissive.g,n[r+12+2]=c.emissive.b,n[r+52+1]=c.density,n[r+52+3]=0,n[r+56+2]=4,r+=qt;continue}n[r++]=c.color.r,n[r++]=c.color.g,n[r++]=c.color.b,n[r++]=a$1(c,"map"),n[r++]=o(c,"metalness",0),n[r++]=a$1(c,"metalnessMap"),n[r++]=o(c,"roughness",0),n[r++]=a$1(c,"roughnessMap"),n[r++]=o(c,"ior",1.5),n[r++]=o(c,"transmission",0),n[r++]=a$1(c,"transmissionMap"),n[r++]=o(c,"emissiveIntensity",0),"emissive"in c?(n[r++]=c.emissive.r,n[r++]=c.emissive.g,n[r++]=c.emissive.b):(n[r++]=0,n[r++]=0,n[r++]=0),n[r++]=a$1(c,"emissiveMap"),n[r++]=a$1(c,"normalMap"),"normalScale"in c?(n[r++]=c.normalScale.x,n[r++]=c.normalScale.y):(n[r++]=1,n[r++]=1),n[r++]=o(c,"clearcoat",0),n[r++]=a$1(c,"clearcoatMap"),n[r++]=o(c,"clearcoatRoughness",0),n[r++]=a$1(c,"clearcoatRoughnessMap"),n[r++]=a$1(c,"clearcoatNormalMap"),"clearcoatNormalScale"in c?(n[r++]=c.clearcoatNormalScale.x,n[r++]=c.clearcoatNormalScale.y):(n[r++]=1,n[r++]=1),r++,n[r++]=o(c,"sheen",0),"sheenColor"in c?(n[r++]=c.sheenColor.r,n[r++]=c.sheenColor.g,n[r++]=c.sheenColor.b):(n[r++]=0,n[r++]=0,n[r++]=0),n[r++]=a$1(c,"sheenColorMap"),n[r++]=o(c,"sheenRoughness",0),n[r++]=a$1(c,"sheenRoughnessMap"),n[r++]=a$1(c,"iridescenceMap"),n[r++]=a$1(c,"iridescenceThicknessMap"),n[r++]=o(c,"iridescence",0),n[r++]=o(c,"iridescenceIOR",1.3);let b=o(c,"iridescenceThicknessRange",[100,400]);n[r++]=b[0],n[r++]=b[1],"specularColor"in c?(n[r++]=c.specularColor.r,n[r++]=c.specularColor.g,n[r++]=c.specularColor.b):(n[r++]=1,n[r++]=1,n[r++]=1),n[r++]=a$1(c,"specularColorMap"),n[r++]=o(c,"specularIntensity",1),n[r++]=a$1(c,"specularIntensityMap");let v=o(c,"thickness",0)===0&&o(c,"attenuationDistance",1/0)===1/0;if(n[r++]=Number(v),r++,"attenuationColor"in c?(n[r++]=c.attenuationColor.r,n[r++]=c.attenuationColor.g,n[r++]=c.attenuationColor.b):(n[r++]=1,n[r++]=1,n[r++]=1),n[r++]=o(c,"attenuationDistance",1/0),n[r++]=a$1(c,"alphaMap"),n[r++]=c.opacity,n[r++]=c.alphaTest,!v&&c.transmission>0)n[r++]=0;else switch(c.side){case FrontSide:n[r++]=1;break;case BackSide:n[r++]=-1;break;case DoubleSide:n[r++]=0;break}n[r++]=Number(o(c,"matte",false)),n[r++]=Number(o(c,"castShadow",true)),n[r++]=Number(c.vertexColors)|Number(c.flatShading)<<1,n[r++]=Number(c.transparent),r+=s(c,"map",n,r),r+=s(c,"metalnessMap",n,r),r+=s(c,"roughnessMap",n,r),r+=s(c,"transmissionMap",n,r),r+=s(c,"emissiveMap",n,r),r+=s(c,"normalMap",n,r),r+=s(c,"clearcoatMap",n,r),r+=s(c,"clearcoatNormalMap",n,r),r+=s(c,"clearcoatRoughnessMap",n,r),r+=s(c,"sheenColorMap",n,r),r+=s(c,"sheenRoughnessMap",n,r),r+=s(c,"iridescenceMap",n,r),r+=s(c,"iridescenceThicknessMap",n,r),r+=s(c,"specularColorMap",n,r),r+=s(c,"specularIntensityMap",n,r),r+=s(c,"alphaMap",n,r);}let x=O(n.buffer);return this.hash!==x?(this.hash=x,this.needsUpdate=true,true):false}};var Yt=new Color;function oi(i){return i?`${i.uuid}:${i.version}`:null}a(oi,"getTextureHash");function si(i,e){for(let t in e)t in i&&(i[t]=e[t]);}a(si,"assignOptions");var j=class extends WebGLArrayRenderTarget{static{a(this,"RenderTarget2DArray");}constructor(e,t,a){let o={format:RGBAFormat,type:UnsignedByteType,minFilter:LinearFilter,magFilter:LinearFilter,wrapS:RepeatWrapping,wrapT:RepeatWrapping,generateMipmaps:false,...a};super(e,t,1,o),si(this.texture,o),this.texture.setTextures=(...r)=>{this.setTextures(...r);},this.hashes=[null];let s=new FullScreenQuad(new Xe);this.fsQuad=s;}setTextures(e,t,a=this.width,o=this.height){let s=e.getRenderTarget(),r=e.toneMapping,l=e.getClearAlpha();e.getClearColor(Yt);let f=t.length||1;(a!==this.width||o!==this.height||this.depth!==f)&&(this.setSize(a,o,f),this.hashes=new Array(f).fill(null)),e.setClearColor(0,0),e.toneMapping=NoToneMapping;let d=this.fsQuad,m=this.hashes,u=false;for(let n=0,x=f;n<x;n++){let p=t[n],g=oi(p);p&&(m[n]!==g||p.isWebGLRenderTarget)&&(p.matrixAutoUpdate=false,p.matrix.identity(),d.material.map=p,e.setRenderTarget(this,n),d.render(e),p.updateMatrix(),p.matrixAutoUpdate=true,m[n]=g,u=true);}return d.material.map=null,e.setClearColor(Yt,l),e.setRenderTarget(s),e.toneMapping=r,u}dispose(){super.dispose(),this.fsQuad.dispose();}},Xe=class extends ShaderMaterial{static{a(this,"CopyMaterial");}get map(){return this.uniforms.map.value}set map(e){this.uniforms.map.value=e;}constructor(){super({uniforms:{map:{value:null}},vertexShader:`
258
+ varying vec2 vUv;
259
+ void main() {
260
+
261
+ vUv = uv;
262
+ gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
263
+
264
+ }
265
+ `,fragmentShader:`
266
+ uniform sampler2D map;
267
+ varying vec2 vUv;
268
+ void main() {
269
+
270
+ gl_FragColor = texture2D( map, vUv );
271
+
272
+ }
273
+ `});}};function ni(i,e=Math.random()){for(let t=i.length-1;t>0;t--){let a=Math.floor(e()*(t+1)),o=i[t];i[t]=i[a],i[a]=o;}return i}a(ni,"shuffle");var we=class{static{a(this,"StratifiedSampler");}constructor(e,t,a=Math.random){let o=e**t,s=new Uint16Array(o),r=o;for(let l=0;l<o;l++)s[l]=l;this.samples=new Float32Array(t),this.strataCount=e,this.reset=function(){for(let l=0;l<o;l++)s[l]=l;r=0;},this.reshuffle=function(){r=0;},this.next=function(){let{samples:l}=this;r>=s.length&&(ni(s,a),this.reshuffle());let f=s[r++];for(let d=0;d<t;d++)l[d]=(f%e+a())/e,f=Math.floor(f/e);return l};}};var Se=class{static{a(this,"StratifiedSamplerCombined");}constructor(e,t,a=Math.random){let o=0;for(let f of t)o+=f;let s=new Float32Array(o),r=[],l=0;for(let f of t){let d=new we(e,f,a);d.samples=new Float32Array(s.buffer,l,d.samples.length),l+=d.samples.length*4,r.push(d);}this.samples=s,this.strataCount=e,this.next=function(){for(let f of r)f.next();return s},this.reshuffle=function(){for(let f of r)f.reshuffle();},this.reset=function(){for(let f of r)f.reset();};}};var Ke=class{static{a(this,"RandomGenerator");}constructor(e=0){this.m=2147483648,this.a=1103515245,this.c=12345,this.seed=e;}nextInt(){return this.seed=(this.a*this.seed+this.c)%this.m,this.seed}nextFloat(){return this.nextInt()/(this.m-1)}},_e=class extends DataTexture{static{a(this,"StratifiedSamplesTexture");}constructor(e=1,t=1,a=8){super(new Float32Array(1),1,1,RGBAFormat,FloatType),this.minFilter=NearestFilter,this.magFilter=NearestFilter,this.strata=a,this.sampler=null,this.generator=new Ke,this.stableNoise=false,this.random=()=>this.stableNoise?this.generator.nextFloat():Math.random(),this.init(e,t,a);}init(e=this.image.height,t=this.image.width,a=this.strata){let{image:o}=this;if(o.width===t&&o.height===e&&this.sampler!==null)return;let s=new Array(e*t).fill(4),r=new Se(a,s,this.random);o.width=t,o.height=e,o.data=r.samples,this.sampler=r,this.dispose(),this.next();}next(){this.sampler.next(),this.needsUpdate=true;}reset(){this.sampler.reset(),this.generator.seed=0;}};function Xt(i,e=Math.random){for(let t=i.length-1;t>0;t--){let a=~~((e()-1e-6)*t),o=i[t];i[t]=i[a],i[a]=o;}}a(Xt,"shuffleArray");function Kt(i,e){i.fill(0);for(let t=0;t<e;t++)i[t]=1;}a(Kt,"fillWithOnes");var Y=class{static{a(this,"BlueNoiseSamples");}constructor(e){this.count=0,this.size=-1,this.sigma=-1,this.radius=-1,this.lookupTable=null,this.score=null,this.binaryPattern=null,this.resize(e),this.setSigma(1.5);}findVoid(){let{score:e,binaryPattern:t}=this,a=1/0,o=-1;for(let s=0,r=t.length;s<r;s++){if(t[s]!==0)continue;let l=e[s];l<a&&(a=l,o=s);}return o}findCluster(){let{score:e,binaryPattern:t}=this,a=-1/0,o=-1;for(let s=0,r=t.length;s<r;s++){if(t[s]!==1)continue;let l=e[s];l>a&&(a=l,o=s);}return o}setSigma(e){if(e===this.sigma)return;let t=~~(Math.sqrt(20*e**2)+1),a=2*t+1,o=new Float32Array(a*a),s=e*e;for(let r=-t;r<=t;r++)for(let l=-t;l<=t;l++){let f=(t+l)*a+r+t,d=r*r+l*l;o[f]=Math.E**(-d/(2*s));}this.lookupTable=o,this.sigma=e,this.radius=t;}resize(e){this.size!==e&&(this.size=e,this.score=new Float32Array(e*e),this.binaryPattern=new Uint8Array(e*e));}invert(){let{binaryPattern:e,score:t,size:a}=this;t.fill(0);for(let o=0,s=e.length;o<s;o++)if(e[o]===0){let r=~~(o/a),l=o-r*a;this.updateScore(l,r,1),e[o]=1;}else e[o]=0;}updateScore(e,t,a){let{size:o,score:s,lookupTable:r}=this,l=this.radius,f=2*l+1;for(let d=-l;d<=l;d++)for(let m=-l;m<=l;m++){let u=(l+m)*f+d+l,n=r[u],x=e+d;x=x<0?o+x:x%o;let p=t+m;p=p<0?o+p:p%o;let g=p*o+x;s[g]+=a*n;}}addPointIndex(e){this.binaryPattern[e]=1;let t=this.size,a=~~(e/t),o=e-a*t;this.updateScore(o,a,1),this.count++;}removePointIndex(e){this.binaryPattern[e]=0;let t=this.size,a=~~(e/t),o=e-a*t;this.updateScore(o,a,-1),this.count--;}copy(e){this.resize(e.size),this.score.set(e.score),this.binaryPattern.set(e.binaryPattern),this.setSigma(e.sigma),this.count=e.count;}};var Re=class{static{a(this,"BlueNoiseGenerator");}constructor(){this.random=Math.random,this.sigma=1.5,this.size=64,this.majorityPointsRatio=.1,this.samples=new Y(1),this.savedSamples=new Y(1);}generate(){let{samples:e,savedSamples:t,sigma:a,majorityPointsRatio:o,size:s}=this;e.resize(s),e.setSigma(a);let r=Math.floor(s*s*o),l=e.binaryPattern;Kt(l,r),Xt(l,this.random);for(let u=0,n=l.length;u<n;u++)l[u]===1&&e.addPointIndex(u);for(;;){let u=e.findCluster();e.removePointIndex(u);let n=e.findVoid();if(u===n){e.addPointIndex(u);break}e.addPointIndex(n);}let f=new Uint32Array(s*s);t.copy(e);let d;for(d=e.count-1;d>=0;){let u=e.findCluster();e.removePointIndex(u),f[u]=d,d--;}let m=s*s;for(d=t.count;d<m/2;){let u=t.findVoid();t.addPointIndex(u),f[u]=d,d++;}for(t.invert();d<m;){let u=t.findCluster();t.removePointIndex(u),f[u]=d,d++;}return {data:f,maxValue:m}}};function pi(i){return i>=3?4:i}a(pi,"getStride");function gi(i){switch(i){case 1:return RedFormat;case 2:return RGFormat;default:return RGBAFormat}}a(gi,"getFormat");var Ie=class extends DataTexture{static{a(this,"BlueNoiseTexture");}constructor(e=64,t=1){super(new Float32Array(4),1,1,RGBAFormat,FloatType),this.minFilter=NearestFilter,this.magFilter=NearestFilter,this.size=e,this.channels=t,this.update();}update(){let e=this.channels,t=this.size,a=new Re;a.channels=e,a.size=t;let o=pi(e),s=gi(o);(this.image.width!==t||s!==this.format)&&(this.image.width=t,this.image.height=t,this.image.data=new Float32Array(t**2*o),this.format=s,this.dispose());let r=this.image.data;for(let l=0,f=e;l<f;l++){let d=a.generate(),m=d.data,u=d.maxValue;for(let n=0,x=m.length;n<x;n++){let p=m[n]/u;r[n*o+l]=p;}}this.needsUpdate=true;}};var er=`
274
+
275
+ struct PhysicalCamera {
276
+
277
+ float focusDistance;
278
+ float anamorphicRatio;
279
+ float bokehSize;
280
+ int apertureBlades;
281
+ float apertureRotation;
282
+
283
+ };
284
+
285
+ `;var tr=`
286
+
287
+ struct EquirectHdrInfo {
288
+
289
+ sampler2D marginalWeights;
290
+ sampler2D conditionalWeights;
291
+ sampler2D map;
292
+
293
+ float totalSum;
294
+
295
+ };
296
+
297
+ `;var rr=`
298
+
299
+ #define RECT_AREA_LIGHT_TYPE 0
300
+ #define CIRC_AREA_LIGHT_TYPE 1
301
+ #define SPOT_LIGHT_TYPE 2
302
+ #define DIR_LIGHT_TYPE 3
303
+ #define POINT_LIGHT_TYPE 4
304
+
305
+ struct LightsInfo {
306
+
307
+ sampler2D tex;
308
+ uint count;
309
+
310
+ };
311
+
312
+ struct Light {
313
+
314
+ vec3 position;
315
+ int type;
316
+
317
+ vec3 color;
318
+ float intensity;
319
+
320
+ vec3 u;
321
+ vec3 v;
322
+ float area;
323
+
324
+ // spot light fields
325
+ float radius;
326
+ float near;
327
+ float decay;
328
+ float distance;
329
+ float coneCos;
330
+ float penumbraCos;
331
+ int iesProfile;
332
+
333
+ };
334
+
335
+ Light readLightInfo( sampler2D tex, uint index ) {
336
+
337
+ uint i = index * 6u;
338
+
339
+ vec4 s0 = texelFetch1D( tex, i + 0u );
340
+ vec4 s1 = texelFetch1D( tex, i + 1u );
341
+ vec4 s2 = texelFetch1D( tex, i + 2u );
342
+ vec4 s3 = texelFetch1D( tex, i + 3u );
343
+
344
+ Light l;
345
+ l.position = s0.rgb;
346
+ l.type = int( round( s0.a ) );
347
+
348
+ l.color = s1.rgb;
349
+ l.intensity = s1.a;
350
+
351
+ l.u = s2.rgb;
352
+ l.v = s3.rgb;
353
+ l.area = s3.a;
354
+
355
+ if ( l.type == SPOT_LIGHT_TYPE || l.type == POINT_LIGHT_TYPE ) {
356
+
357
+ vec4 s4 = texelFetch1D( tex, i + 4u );
358
+ vec4 s5 = texelFetch1D( tex, i + 5u );
359
+ l.radius = s4.r;
360
+ l.decay = s4.g;
361
+ l.distance = s4.b;
362
+ l.coneCos = s4.a;
363
+
364
+ l.penumbraCos = s5.r;
365
+ l.iesProfile = int( round( s5.g ) );
366
+
367
+ } else {
368
+
369
+ l.radius = 0.0;
370
+ l.decay = 0.0;
371
+ l.distance = 0.0;
372
+
373
+ l.coneCos = 0.0;
374
+ l.penumbraCos = 0.0;
375
+ l.iesProfile = - 1;
376
+
377
+ }
378
+
379
+ return l;
380
+
381
+ }
382
+
383
+ `;var ar=`
384
+
385
+ struct Material {
386
+
387
+ vec3 color;
388
+ int map;
389
+
390
+ float metalness;
391
+ int metalnessMap;
392
+
393
+ float roughness;
394
+ int roughnessMap;
395
+
396
+ float ior;
397
+ float transmission;
398
+ int transmissionMap;
399
+
400
+ float emissiveIntensity;
401
+ vec3 emissive;
402
+ int emissiveMap;
403
+
404
+ int normalMap;
405
+ vec2 normalScale;
406
+
407
+ float clearcoat;
408
+ int clearcoatMap;
409
+ int clearcoatNormalMap;
410
+ vec2 clearcoatNormalScale;
411
+ float clearcoatRoughness;
412
+ int clearcoatRoughnessMap;
413
+
414
+ int iridescenceMap;
415
+ int iridescenceThicknessMap;
416
+ float iridescence;
417
+ float iridescenceIor;
418
+ float iridescenceThicknessMinimum;
419
+ float iridescenceThicknessMaximum;
420
+
421
+ vec3 specularColor;
422
+ int specularColorMap;
423
+
424
+ float specularIntensity;
425
+ int specularIntensityMap;
426
+ bool thinFilm;
427
+
428
+ vec3 attenuationColor;
429
+ float attenuationDistance;
430
+
431
+ int alphaMap;
432
+
433
+ bool castShadow;
434
+ float opacity;
435
+ float alphaTest;
436
+
437
+ float side;
438
+ bool matte;
439
+
440
+ float sheen;
441
+ vec3 sheenColor;
442
+ int sheenColorMap;
443
+ float sheenRoughness;
444
+ int sheenRoughnessMap;
445
+
446
+ bool vertexColors;
447
+ bool flatShading;
448
+ bool transparent;
449
+ bool fogVolume;
450
+
451
+ mat3 mapTransform;
452
+ mat3 metalnessMapTransform;
453
+ mat3 roughnessMapTransform;
454
+ mat3 transmissionMapTransform;
455
+ mat3 emissiveMapTransform;
456
+ mat3 normalMapTransform;
457
+ mat3 clearcoatMapTransform;
458
+ mat3 clearcoatNormalMapTransform;
459
+ mat3 clearcoatRoughnessMapTransform;
460
+ mat3 sheenColorMapTransform;
461
+ mat3 sheenRoughnessMapTransform;
462
+ mat3 iridescenceMapTransform;
463
+ mat3 iridescenceThicknessMapTransform;
464
+ mat3 specularColorMapTransform;
465
+ mat3 specularIntensityMapTransform;
466
+ mat3 alphaMapTransform;
467
+
468
+ };
469
+
470
+ mat3 readTextureTransform( sampler2D tex, uint index ) {
471
+
472
+ mat3 textureTransform;
473
+
474
+ vec4 row1 = texelFetch1D( tex, index );
475
+ vec4 row2 = texelFetch1D( tex, index + 1u );
476
+
477
+ textureTransform[0] = vec3(row1.r, row2.r, 0.0);
478
+ textureTransform[1] = vec3(row1.g, row2.g, 0.0);
479
+ textureTransform[2] = vec3(row1.b, row2.b, 1.0);
480
+
481
+ return textureTransform;
482
+
483
+ }
484
+
485
+ Material readMaterialInfo( sampler2D tex, uint index ) {
486
+
487
+ uint i = index * uint( MATERIAL_PIXELS );
488
+
489
+ vec4 s0 = texelFetch1D( tex, i + 0u );
490
+ vec4 s1 = texelFetch1D( tex, i + 1u );
491
+ vec4 s2 = texelFetch1D( tex, i + 2u );
492
+ vec4 s3 = texelFetch1D( tex, i + 3u );
493
+ vec4 s4 = texelFetch1D( tex, i + 4u );
494
+ vec4 s5 = texelFetch1D( tex, i + 5u );
495
+ vec4 s6 = texelFetch1D( tex, i + 6u );
496
+ vec4 s7 = texelFetch1D( tex, i + 7u );
497
+ vec4 s8 = texelFetch1D( tex, i + 8u );
498
+ vec4 s9 = texelFetch1D( tex, i + 9u );
499
+ vec4 s10 = texelFetch1D( tex, i + 10u );
500
+ vec4 s11 = texelFetch1D( tex, i + 11u );
501
+ vec4 s12 = texelFetch1D( tex, i + 12u );
502
+ vec4 s13 = texelFetch1D( tex, i + 13u );
503
+ vec4 s14 = texelFetch1D( tex, i + 14u );
504
+
505
+ Material m;
506
+ m.color = s0.rgb;
507
+ m.map = int( round( s0.a ) );
508
+
509
+ m.metalness = s1.r;
510
+ m.metalnessMap = int( round( s1.g ) );
511
+ m.roughness = s1.b;
512
+ m.roughnessMap = int( round( s1.a ) );
513
+
514
+ m.ior = s2.r;
515
+ m.transmission = s2.g;
516
+ m.transmissionMap = int( round( s2.b ) );
517
+ m.emissiveIntensity = s2.a;
518
+
519
+ m.emissive = s3.rgb;
520
+ m.emissiveMap = int( round( s3.a ) );
521
+
522
+ m.normalMap = int( round( s4.r ) );
523
+ m.normalScale = s4.gb;
524
+
525
+ m.clearcoat = s4.a;
526
+ m.clearcoatMap = int( round( s5.r ) );
527
+ m.clearcoatRoughness = s5.g;
528
+ m.clearcoatRoughnessMap = int( round( s5.b ) );
529
+ m.clearcoatNormalMap = int( round( s5.a ) );
530
+ m.clearcoatNormalScale = s6.rg;
531
+
532
+ m.sheen = s6.a;
533
+ m.sheenColor = s7.rgb;
534
+ m.sheenColorMap = int( round( s7.a ) );
535
+ m.sheenRoughness = s8.r;
536
+ m.sheenRoughnessMap = int( round( s8.g ) );
537
+
538
+ m.iridescenceMap = int( round( s8.b ) );
539
+ m.iridescenceThicknessMap = int( round( s8.a ) );
540
+ m.iridescence = s9.r;
541
+ m.iridescenceIor = s9.g;
542
+ m.iridescenceThicknessMinimum = s9.b;
543
+ m.iridescenceThicknessMaximum = s9.a;
544
+
545
+ m.specularColor = s10.rgb;
546
+ m.specularColorMap = int( round( s10.a ) );
547
+
548
+ m.specularIntensity = s11.r;
549
+ m.specularIntensityMap = int( round( s11.g ) );
550
+ m.thinFilm = bool( s11.b );
551
+
552
+ m.attenuationColor = s12.rgb;
553
+ m.attenuationDistance = s12.a;
554
+
555
+ m.alphaMap = int( round( s13.r ) );
556
+
557
+ m.opacity = s13.g;
558
+ m.alphaTest = s13.b;
559
+ m.side = s13.a;
560
+
561
+ m.matte = bool( s14.r );
562
+ m.castShadow = bool( s14.g );
563
+ m.vertexColors = bool( int( s14.b ) & 1 );
564
+ m.flatShading = bool( int( s14.b ) & 2 );
565
+ m.fogVolume = bool( int( s14.b ) & 4 );
566
+ m.transparent = bool( s14.a );
567
+
568
+ uint firstTextureTransformIdx = i + 15u;
569
+
570
+ // mat3( 1.0 ) is an identity matrix
571
+ m.mapTransform = m.map == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx );
572
+ m.metalnessMapTransform = m.metalnessMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 2u );
573
+ m.roughnessMapTransform = m.roughnessMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 4u );
574
+ m.transmissionMapTransform = m.transmissionMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 6u );
575
+ m.emissiveMapTransform = m.emissiveMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 8u );
576
+ m.normalMapTransform = m.normalMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 10u );
577
+ m.clearcoatMapTransform = m.clearcoatMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 12u );
578
+ m.clearcoatNormalMapTransform = m.clearcoatNormalMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 14u );
579
+ m.clearcoatRoughnessMapTransform = m.clearcoatRoughnessMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 16u );
580
+ m.sheenColorMapTransform = m.sheenColorMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 18u );
581
+ m.sheenRoughnessMapTransform = m.sheenRoughnessMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 20u );
582
+ m.iridescenceMapTransform = m.iridescenceMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 22u );
583
+ m.iridescenceThicknessMapTransform = m.iridescenceThicknessMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 24u );
584
+ m.specularColorMapTransform = m.specularColorMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 26u );
585
+ m.specularIntensityMapTransform = m.specularIntensityMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 28u );
586
+ m.alphaMapTransform = m.alphaMap == - 1 ? mat3( 1.0 ) : readTextureTransform( tex, firstTextureTransformIdx + 30u );
587
+
588
+ return m;
589
+
590
+ }
591
+
592
+ `;var ir=`
593
+
594
+ struct SurfaceRecord {
595
+
596
+ // surface type
597
+ bool volumeParticle;
598
+
599
+ // geometry
600
+ vec3 faceNormal;
601
+ bool frontFace;
602
+ vec3 normal;
603
+ mat3 normalBasis;
604
+ mat3 normalInvBasis;
605
+
606
+ // cached properties
607
+ float eta;
608
+ float f0;
609
+
610
+ // material
611
+ float roughness;
612
+ float filteredRoughness;
613
+ float metalness;
614
+ vec3 color;
615
+ vec3 emission;
616
+
617
+ // transmission
618
+ float ior;
619
+ float transmission;
620
+ bool thinFilm;
621
+ vec3 attenuationColor;
622
+ float attenuationDistance;
623
+
624
+ // clearcoat
625
+ vec3 clearcoatNormal;
626
+ mat3 clearcoatBasis;
627
+ mat3 clearcoatInvBasis;
628
+ float clearcoat;
629
+ float clearcoatRoughness;
630
+ float filteredClearcoatRoughness;
631
+
632
+ // sheen
633
+ float sheen;
634
+ vec3 sheenColor;
635
+ float sheenRoughness;
636
+
637
+ // iridescence
638
+ float iridescence;
639
+ float iridescenceIor;
640
+ float iridescenceThickness;
641
+
642
+ // specular
643
+ vec3 specularColor;
644
+ float specularIntensity;
645
+ };
646
+
647
+ struct ScatterRecord {
648
+ float specularPdf;
649
+ float pdf;
650
+ vec3 direction;
651
+ vec3 color;
652
+ };
653
+
654
+ `;var or=`
655
+
656
+ // samples the the given environment map in the given direction
657
+ vec3 sampleEquirectColor( sampler2D envMap, vec3 direction ) {
658
+
659
+ return texture2D( envMap, equirectDirectionToUv( direction ) ).rgb;
660
+
661
+ }
662
+
663
+ // gets the pdf of the given direction to sample
664
+ float equirectDirectionPdf( vec3 direction ) {
665
+
666
+ vec2 uv = equirectDirectionToUv( direction );
667
+ float theta = uv.y * PI;
668
+ float sinTheta = sin( theta );
669
+ if ( sinTheta == 0.0 ) {
670
+
671
+ return 0.0;
672
+
673
+ }
674
+
675
+ return 1.0 / ( 2.0 * PI * PI * sinTheta );
676
+
677
+ }
678
+
679
+ // samples the color given env map with CDF and returns the pdf of the direction
680
+ float sampleEquirect( vec3 direction, inout vec3 color ) {
681
+
682
+ float totalSum = envMapInfo.totalSum;
683
+ if ( totalSum == 0.0 ) {
684
+
685
+ color = vec3( 0.0 );
686
+ return 1.0;
687
+
688
+ }
689
+
690
+ vec2 uv = equirectDirectionToUv( direction );
691
+ color = texture2D( envMapInfo.map, uv ).rgb;
692
+
693
+ float lum = luminance( color );
694
+ ivec2 resolution = textureSize( envMapInfo.map, 0 );
695
+ float pdf = lum / totalSum;
696
+
697
+ return float( resolution.x * resolution.y ) * pdf * equirectDirectionPdf( direction );
698
+
699
+ }
700
+
701
+ // samples a direction of the envmap with color and retrieves pdf
702
+ float sampleEquirectProbability( vec2 r, inout vec3 color, inout vec3 direction ) {
703
+
704
+ // sample env map cdf
705
+ float v = texture2D( envMapInfo.marginalWeights, vec2( r.x, 0.0 ) ).x;
706
+ float u = texture2D( envMapInfo.conditionalWeights, vec2( r.y, v ) ).x;
707
+ vec2 uv = vec2( u, v );
708
+
709
+ vec3 derivedDirection = equirectUvToDirection( uv );
710
+ direction = derivedDirection;
711
+ color = texture2D( envMapInfo.map, uv ).rgb;
712
+
713
+ float totalSum = envMapInfo.totalSum;
714
+ float lum = luminance( color );
715
+ ivec2 resolution = textureSize( envMapInfo.map, 0 );
716
+ float pdf = lum / totalSum;
717
+
718
+ return float( resolution.x * resolution.y ) * pdf * equirectDirectionPdf( direction );
719
+
720
+ }
721
+ `;var sr=`
722
+
723
+ float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {
724
+
725
+ return smoothstep( coneCosine, penumbraCosine, angleCosine );
726
+
727
+ }
728
+
729
+ float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {
730
+
731
+ // based upon Frostbite 3 Moving to Physically-based Rendering
732
+ // page 32, equation 26: E[window1]
733
+ // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
734
+ float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), EPSILON );
735
+
736
+ if ( cutoffDistance > 0.0 ) {
737
+
738
+ distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );
739
+
740
+ }
741
+
742
+ return distanceFalloff;
743
+
744
+ }
745
+
746
+ float getPhotometricAttenuation( sampler2DArray iesProfiles, int iesProfile, vec3 posToLight, vec3 lightDir, vec3 u, vec3 v ) {
747
+
748
+ float cosTheta = dot( posToLight, lightDir );
749
+ float angle = acos( cosTheta ) / PI;
750
+
751
+ return texture2D( iesProfiles, vec3( angle, 0.0, iesProfile ) ).r;
752
+
753
+ }
754
+
755
+ struct LightRecord {
756
+
757
+ float dist;
758
+ vec3 direction;
759
+ float pdf;
760
+ vec3 emission;
761
+ int type;
762
+
763
+ };
764
+
765
+ bool intersectLightAtIndex( sampler2D lights, vec3 rayOrigin, vec3 rayDirection, uint l, inout LightRecord lightRec ) {
766
+
767
+ bool didHit = false;
768
+ Light light = readLightInfo( lights, l );
769
+
770
+ vec3 u = light.u;
771
+ vec3 v = light.v;
772
+
773
+ // check for backface
774
+ vec3 normal = normalize( cross( u, v ) );
775
+ if ( dot( normal, rayDirection ) > 0.0 ) {
776
+
777
+ u *= 1.0 / dot( u, u );
778
+ v *= 1.0 / dot( v, v );
779
+
780
+ float dist;
781
+
782
+ // MIS / light intersection is not supported for punctual lights.
783
+ if(
784
+ ( light.type == RECT_AREA_LIGHT_TYPE && intersectsRectangle( light.position, normal, u, v, rayOrigin, rayDirection, dist ) ) ||
785
+ ( light.type == CIRC_AREA_LIGHT_TYPE && intersectsCircle( light.position, normal, u, v, rayOrigin, rayDirection, dist ) )
786
+ ) {
787
+
788
+ float cosTheta = dot( rayDirection, normal );
789
+ didHit = true;
790
+ lightRec.dist = dist;
791
+ lightRec.pdf = ( dist * dist ) / ( light.area * cosTheta );
792
+ lightRec.emission = light.color * light.intensity;
793
+ lightRec.direction = rayDirection;
794
+ lightRec.type = light.type;
795
+
796
+ }
797
+
798
+ }
799
+
800
+ return didHit;
801
+
802
+ }
803
+
804
+ LightRecord randomAreaLightSample( Light light, vec3 rayOrigin, vec2 ruv ) {
805
+
806
+ vec3 randomPos;
807
+ if( light.type == RECT_AREA_LIGHT_TYPE ) {
808
+
809
+ // rectangular area light
810
+ randomPos = light.position + light.u * ( ruv.x - 0.5 ) + light.v * ( ruv.y - 0.5 );
811
+
812
+ } else if( light.type == CIRC_AREA_LIGHT_TYPE ) {
813
+
814
+ // circular area light
815
+ float r = 0.5 * sqrt( ruv.x );
816
+ float theta = ruv.y * 2.0 * PI;
817
+ float x = r * cos( theta );
818
+ float y = r * sin( theta );
819
+
820
+ randomPos = light.position + light.u * x + light.v * y;
821
+
822
+ }
823
+
824
+ vec3 toLight = randomPos - rayOrigin;
825
+ float lightDistSq = dot( toLight, toLight );
826
+ float dist = sqrt( lightDistSq );
827
+ vec3 direction = toLight / dist;
828
+ vec3 lightNormal = normalize( cross( light.u, light.v ) );
829
+
830
+ LightRecord lightRec;
831
+ lightRec.type = light.type;
832
+ lightRec.emission = light.color * light.intensity;
833
+ lightRec.dist = dist;
834
+ lightRec.direction = direction;
835
+
836
+ // TODO: the denominator is potentially zero
837
+ lightRec.pdf = lightDistSq / ( light.area * dot( direction, lightNormal ) );
838
+
839
+ return lightRec;
840
+
841
+ }
842
+
843
+ LightRecord randomSpotLightSample( Light light, sampler2DArray iesProfiles, vec3 rayOrigin, vec2 ruv ) {
844
+
845
+ float radius = light.radius * sqrt( ruv.x );
846
+ float theta = ruv.y * 2.0 * PI;
847
+ float x = radius * cos( theta );
848
+ float y = radius * sin( theta );
849
+
850
+ vec3 u = light.u;
851
+ vec3 v = light.v;
852
+ vec3 normal = normalize( cross( u, v ) );
853
+
854
+ float angle = acos( light.coneCos );
855
+ float angleTan = tan( angle );
856
+ float startDistance = light.radius / max( angleTan, EPSILON );
857
+
858
+ vec3 randomPos = light.position - normal * startDistance + u * x + v * y;
859
+ vec3 toLight = randomPos - rayOrigin;
860
+ float lightDistSq = dot( toLight, toLight );
861
+ float dist = sqrt( lightDistSq );
862
+
863
+ vec3 direction = toLight / max( dist, EPSILON );
864
+ float cosTheta = dot( direction, normal );
865
+
866
+ float spotAttenuation = light.iesProfile != - 1 ?
867
+ getPhotometricAttenuation( iesProfiles, light.iesProfile, direction, normal, u, v ) :
868
+ getSpotAttenuation( light.coneCos, light.penumbraCos, cosTheta );
869
+
870
+ float distanceAttenuation = getDistanceAttenuation( dist, light.distance, light.decay );
871
+ LightRecord lightRec;
872
+ lightRec.type = light.type;
873
+ lightRec.dist = dist;
874
+ lightRec.direction = direction;
875
+ lightRec.emission = light.color * light.intensity * distanceAttenuation * spotAttenuation;
876
+ lightRec.pdf = 1.0;
877
+
878
+ return lightRec;
879
+
880
+ }
881
+
882
+ LightRecord randomLightSample( sampler2D lights, sampler2DArray iesProfiles, uint lightCount, vec3 rayOrigin, vec3 ruv ) {
883
+
884
+ LightRecord result;
885
+
886
+ // pick a random light
887
+ uint l = uint( ruv.x * float( lightCount ) );
888
+ Light light = readLightInfo( lights, l );
889
+
890
+ if ( light.type == SPOT_LIGHT_TYPE ) {
891
+
892
+ result = randomSpotLightSample( light, iesProfiles, rayOrigin, ruv.yz );
893
+
894
+ } else if ( light.type == POINT_LIGHT_TYPE ) {
895
+
896
+ vec3 lightRay = light.u - rayOrigin;
897
+ float lightDist = length( lightRay );
898
+ float cutoffDistance = light.distance;
899
+ float distanceFalloff = 1.0 / max( pow( lightDist, light.decay ), 0.01 );
900
+ if ( cutoffDistance > 0.0 ) {
901
+
902
+ distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDist / cutoffDistance ) ) );
903
+
904
+ }
905
+
906
+ LightRecord rec;
907
+ rec.direction = normalize( lightRay );
908
+ rec.dist = length( lightRay );
909
+ rec.pdf = 1.0;
910
+ rec.emission = light.color * light.intensity * distanceFalloff;
911
+ rec.type = light.type;
912
+ result = rec;
913
+
914
+ } else if ( light.type == DIR_LIGHT_TYPE ) {
915
+
916
+ LightRecord rec;
917
+ rec.dist = 1e10;
918
+ rec.direction = light.u;
919
+ rec.pdf = 1.0;
920
+ rec.emission = light.color * light.intensity;
921
+ rec.type = light.type;
922
+
923
+ result = rec;
924
+
925
+ } else {
926
+
927
+ // sample the light
928
+ result = randomAreaLightSample( light, rayOrigin, ruv.yz );
929
+
930
+ }
931
+
932
+ return result;
933
+
934
+ }
935
+
936
+ `;var nr=`
937
+
938
+ vec3 sampleHemisphere( vec3 n, vec2 uv ) {
939
+
940
+ // https://www.rorydriscoll.com/2009/01/07/better-sampling/
941
+ // https://graphics.pixar.com/library/OrthonormalB/paper.pdf
942
+ float sign = n.z == 0.0 ? 1.0 : sign( n.z );
943
+ float a = - 1.0 / ( sign + n.z );
944
+ float b = n.x * n.y * a;
945
+ vec3 b1 = vec3( 1.0 + sign * n.x * n.x * a, sign * b, - sign * n.x );
946
+ vec3 b2 = vec3( b, sign + n.y * n.y * a, - n.y );
947
+
948
+ float r = sqrt( uv.x );
949
+ float theta = 2.0 * PI * uv.y;
950
+ float x = r * cos( theta );
951
+ float y = r * sin( theta );
952
+ return x * b1 + y * b2 + sqrt( 1.0 - uv.x ) * n;
953
+
954
+ }
955
+
956
+ vec2 sampleTriangle( vec2 a, vec2 b, vec2 c, vec2 r ) {
957
+
958
+ // get the edges of the triangle and the diagonal across the
959
+ // center of the parallelogram
960
+ vec2 e1 = a - b;
961
+ vec2 e2 = c - b;
962
+ vec2 diag = normalize( e1 + e2 );
963
+
964
+ // pick the point in the parallelogram
965
+ if ( r.x + r.y > 1.0 ) {
966
+
967
+ r = vec2( 1.0 ) - r;
968
+
969
+ }
970
+
971
+ return e1 * r.x + e2 * r.y;
972
+
973
+ }
974
+
975
+ vec2 sampleCircle( vec2 uv ) {
976
+
977
+ float angle = 2.0 * PI * uv.x;
978
+ float radius = sqrt( uv.y );
979
+ return vec2( cos( angle ), sin( angle ) ) * radius;
980
+
981
+ }
982
+
983
+ vec3 sampleSphere( vec2 uv ) {
984
+
985
+ float u = ( uv.x - 0.5 ) * 2.0;
986
+ float t = uv.y * PI * 2.0;
987
+ float f = sqrt( 1.0 - u * u );
988
+
989
+ return vec3( f * cos( t ), f * sin( t ), u );
990
+
991
+ }
992
+
993
+ vec2 sampleRegularPolygon( int sides, vec3 uvw ) {
994
+
995
+ sides = max( sides, 3 );
996
+
997
+ vec3 r = uvw;
998
+ float anglePerSegment = 2.0 * PI / float( sides );
999
+ float segment = floor( float( sides ) * r.x );
1000
+
1001
+ float angle1 = anglePerSegment * segment;
1002
+ float angle2 = angle1 + anglePerSegment;
1003
+ vec2 a = vec2( sin( angle1 ), cos( angle1 ) );
1004
+ vec2 b = vec2( 0.0, 0.0 );
1005
+ vec2 c = vec2( sin( angle2 ), cos( angle2 ) );
1006
+
1007
+ return sampleTriangle( a, b, c, r.yz );
1008
+
1009
+ }
1010
+
1011
+ // samples an aperture shape with the given number of sides. 0 means circle
1012
+ vec2 sampleAperture( int blades, vec3 uvw ) {
1013
+
1014
+ return blades == 0 ?
1015
+ sampleCircle( uvw.xy ) :
1016
+ sampleRegularPolygon( blades, uvw );
1017
+
1018
+ }
1019
+
1020
+
1021
+ `;var lr=`
1022
+
1023
+ bool totalInternalReflection( float cosTheta, float eta ) {
1024
+
1025
+ float sinTheta = sqrt( 1.0 - cosTheta * cosTheta );
1026
+ return eta * sinTheta > 1.0;
1027
+
1028
+ }
1029
+
1030
+ // https://google.github.io/filament/Filament.md.html#materialsystem/diffusebrdf
1031
+ float schlickFresnel( float cosine, float f0 ) {
1032
+
1033
+ return f0 + ( 1.0 - f0 ) * pow( 1.0 - cosine, 5.0 );
1034
+
1035
+ }
1036
+
1037
+ vec3 schlickFresnel( float cosine, vec3 f0 ) {
1038
+
1039
+ return f0 + ( 1.0 - f0 ) * pow( 1.0 - cosine, 5.0 );
1040
+
1041
+ }
1042
+
1043
+ vec3 schlickFresnel( float cosine, vec3 f0, vec3 f90 ) {
1044
+
1045
+ return f0 + ( f90 - f0 ) * pow( 1.0 - cosine, 5.0 );
1046
+
1047
+ }
1048
+
1049
+ float dielectricFresnel( float cosThetaI, float eta ) {
1050
+
1051
+ // https://schuttejoe.github.io/post/disneybsdf/
1052
+ float ni = eta;
1053
+ float nt = 1.0;
1054
+
1055
+ // Check for total internal reflection
1056
+ float sinThetaISq = 1.0f - cosThetaI * cosThetaI;
1057
+ float sinThetaTSq = eta * eta * sinThetaISq;
1058
+ if( sinThetaTSq >= 1.0 ) {
1059
+
1060
+ return 1.0;
1061
+
1062
+ }
1063
+
1064
+ float sinThetaT = sqrt( sinThetaTSq );
1065
+
1066
+ float cosThetaT = sqrt( max( 0.0, 1.0f - sinThetaT * sinThetaT ) );
1067
+ float rParallel = ( ( nt * cosThetaI ) - ( ni * cosThetaT ) ) / ( ( nt * cosThetaI ) + ( ni * cosThetaT ) );
1068
+ float rPerpendicular = ( ( ni * cosThetaI ) - ( nt * cosThetaT ) ) / ( ( ni * cosThetaI ) + ( nt * cosThetaT ) );
1069
+ return ( rParallel * rParallel + rPerpendicular * rPerpendicular ) / 2.0;
1070
+
1071
+ }
1072
+
1073
+ // https://raytracing.github.io/books/RayTracingInOneWeekend.html#dielectrics/schlickapproximation
1074
+ float iorRatioToF0( float eta ) {
1075
+
1076
+ return pow( ( 1.0 - eta ) / ( 1.0 + eta ), 2.0 );
1077
+
1078
+ }
1079
+
1080
+ vec3 evaluateFresnel( float cosTheta, float eta, vec3 f0, vec3 f90 ) {
1081
+
1082
+ if ( totalInternalReflection( cosTheta, eta ) ) {
1083
+
1084
+ return f90;
1085
+
1086
+ }
1087
+
1088
+ return schlickFresnel( cosTheta, f0, f90 );
1089
+
1090
+ }
1091
+
1092
+ // TODO: disney fresnel was removed and replaced with this fresnel function to better align with
1093
+ // the glTF but is causing blown out pixels. Should be revisited
1094
+ // float evaluateFresnelWeight( float cosTheta, float eta, float f0 ) {
1095
+
1096
+ // if ( totalInternalReflection( cosTheta, eta ) ) {
1097
+
1098
+ // return 1.0;
1099
+
1100
+ // }
1101
+
1102
+ // return schlickFresnel( cosTheta, f0 );
1103
+
1104
+ // }
1105
+
1106
+ // https://schuttejoe.github.io/post/disneybsdf/
1107
+ float disneyFresnel( vec3 wo, vec3 wi, vec3 wh, float f0, float eta, float metalness ) {
1108
+
1109
+ float dotHV = dot( wo, wh );
1110
+ if ( totalInternalReflection( dotHV, eta ) ) {
1111
+
1112
+ return 1.0;
1113
+
1114
+ }
1115
+
1116
+ float dotHL = dot( wi, wh );
1117
+ float dielectricFresnel = dielectricFresnel( abs( dotHV ), eta );
1118
+ float metallicFresnel = schlickFresnel( dotHL, f0 );
1119
+
1120
+ return mix( dielectricFresnel, metallicFresnel, metalness );
1121
+
1122
+ }
1123
+
1124
+ `;var cr=`
1125
+
1126
+ // Fast arccos approximation used to remove banding artifacts caused by numerical errors in acos.
1127
+ // This is a cubic Lagrange interpolating polynomial for x = [-1, -1/2, 0, 1/2, 1].
1128
+ // For more information see: https://github.com/gkjohnson/three-gpu-pathtracer/pull/171#issuecomment-1152275248
1129
+ float acosApprox( float x ) {
1130
+
1131
+ x = clamp( x, -1.0, 1.0 );
1132
+ return ( - 0.69813170079773212 * x * x - 0.87266462599716477 ) * x + 1.5707963267948966;
1133
+
1134
+ }
1135
+
1136
+ // An acos with input values bound to the range [-1, 1].
1137
+ float acosSafe( float x ) {
1138
+
1139
+ return acos( clamp( x, -1.0, 1.0 ) );
1140
+
1141
+ }
1142
+
1143
+ float saturateCos( float val ) {
1144
+
1145
+ return clamp( val, 0.001, 1.0 );
1146
+
1147
+ }
1148
+
1149
+ float square( float t ) {
1150
+
1151
+ return t * t;
1152
+
1153
+ }
1154
+
1155
+ vec2 square( vec2 t ) {
1156
+
1157
+ return t * t;
1158
+
1159
+ }
1160
+
1161
+ vec3 square( vec3 t ) {
1162
+
1163
+ return t * t;
1164
+
1165
+ }
1166
+
1167
+ vec4 square( vec4 t ) {
1168
+
1169
+ return t * t;
1170
+
1171
+ }
1172
+
1173
+ vec2 rotateVector( vec2 v, float t ) {
1174
+
1175
+ float ac = cos( t );
1176
+ float as = sin( t );
1177
+ return vec2(
1178
+ v.x * ac - v.y * as,
1179
+ v.x * as + v.y * ac
1180
+ );
1181
+
1182
+ }
1183
+
1184
+ // forms a basis with the normal vector as Z
1185
+ mat3 getBasisFromNormal( vec3 normal ) {
1186
+
1187
+ vec3 other;
1188
+ if ( abs( normal.x ) > 0.5 ) {
1189
+
1190
+ other = vec3( 0.0, 1.0, 0.0 );
1191
+
1192
+ } else {
1193
+
1194
+ other = vec3( 1.0, 0.0, 0.0 );
1195
+
1196
+ }
1197
+
1198
+ vec3 ortho = normalize( cross( normal, other ) );
1199
+ vec3 ortho2 = normalize( cross( normal, ortho ) );
1200
+ return mat3( ortho2, ortho, normal );
1201
+
1202
+ }
1203
+
1204
+ `;var ur=`
1205
+
1206
+ // Finds the point where the ray intersects the plane defined by u and v and checks if this point
1207
+ // falls in the bounds of the rectangle on that same plane.
1208
+ // Plane intersection: https://lousodrome.net/blog/light/2020/07/03/intersection-of-a-ray-and-a-plane/
1209
+ bool intersectsRectangle( vec3 center, vec3 normal, vec3 u, vec3 v, vec3 rayOrigin, vec3 rayDirection, inout float dist ) {
1210
+
1211
+ float t = dot( center - rayOrigin, normal ) / dot( rayDirection, normal );
1212
+
1213
+ if ( t > EPSILON ) {
1214
+
1215
+ vec3 p = rayOrigin + rayDirection * t;
1216
+ vec3 vi = p - center;
1217
+
1218
+ // check if p falls inside the rectangle
1219
+ float a1 = dot( u, vi );
1220
+ if ( abs( a1 ) <= 0.5 ) {
1221
+
1222
+ float a2 = dot( v, vi );
1223
+ if ( abs( a2 ) <= 0.5 ) {
1224
+
1225
+ dist = t;
1226
+ return true;
1227
+
1228
+ }
1229
+
1230
+ }
1231
+
1232
+ }
1233
+
1234
+ return false;
1235
+
1236
+ }
1237
+
1238
+ // Finds the point where the ray intersects the plane defined by u and v and checks if this point
1239
+ // falls in the bounds of the circle on that same plane. See above URL for a description of the plane intersection algorithm.
1240
+ bool intersectsCircle( vec3 position, vec3 normal, vec3 u, vec3 v, vec3 rayOrigin, vec3 rayDirection, inout float dist ) {
1241
+
1242
+ float t = dot( position - rayOrigin, normal ) / dot( rayDirection, normal );
1243
+
1244
+ if ( t > EPSILON ) {
1245
+
1246
+ vec3 hit = rayOrigin + rayDirection * t;
1247
+ vec3 vi = hit - position;
1248
+
1249
+ float a1 = dot( u, vi );
1250
+ float a2 = dot( v, vi );
1251
+
1252
+ if( length( vec2( a1, a2 ) ) <= 0.5 ) {
1253
+
1254
+ dist = t;
1255
+ return true;
1256
+
1257
+ }
1258
+
1259
+ }
1260
+
1261
+ return false;
1262
+
1263
+ }
1264
+
1265
+ `;var fr=`
1266
+
1267
+ // add texel fetch functions for texture arrays
1268
+ vec4 texelFetch1D( sampler2DArray tex, int layer, uint index ) {
1269
+
1270
+ uint width = uint( textureSize( tex, 0 ).x );
1271
+ uvec2 uv;
1272
+ uv.x = index % width;
1273
+ uv.y = index / width;
1274
+
1275
+ return texelFetch( tex, ivec3( uv, layer ), 0 );
1276
+
1277
+ }
1278
+
1279
+ vec4 textureSampleBarycoord( sampler2DArray tex, int layer, vec3 barycoord, uvec3 faceIndices ) {
1280
+
1281
+ return
1282
+ barycoord.x * texelFetch1D( tex, layer, faceIndices.x ) +
1283
+ barycoord.y * texelFetch1D( tex, layer, faceIndices.y ) +
1284
+ barycoord.z * texelFetch1D( tex, layer, faceIndices.z );
1285
+
1286
+ }
1287
+
1288
+ `;var N=`
1289
+
1290
+ // TODO: possibly this should be renamed something related to material or path tracing logic
1291
+
1292
+ #ifndef RAY_OFFSET
1293
+ #define RAY_OFFSET 1e-4
1294
+ #endif
1295
+
1296
+ // adjust the hit point by the surface normal by a factor of some offset and the
1297
+ // maximum component-wise value of the current point to accommodate floating point
1298
+ // error as values increase.
1299
+ vec3 stepRayOrigin( vec3 rayOrigin, vec3 rayDirection, vec3 offset, float dist ) {
1300
+
1301
+ vec3 point = rayOrigin + rayDirection * dist;
1302
+ vec3 absPoint = abs( point );
1303
+ float maxPoint = max( absPoint.x, max( absPoint.y, absPoint.z ) );
1304
+ return point + offset * ( maxPoint + 1.0 ) * RAY_OFFSET;
1305
+
1306
+ }
1307
+
1308
+ // https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_materials_volume/README.md#attenuation
1309
+ vec3 transmissionAttenuation( float dist, vec3 attColor, float attDist ) {
1310
+
1311
+ vec3 ot = - log( attColor ) / attDist;
1312
+ return exp( - ot * dist );
1313
+
1314
+ }
1315
+
1316
+ vec3 getHalfVector( vec3 wi, vec3 wo, float eta ) {
1317
+
1318
+ // get the half vector - assuming if the light incident vector is on the other side
1319
+ // of the that it's transmissive.
1320
+ vec3 h;
1321
+ if ( wi.z > 0.0 ) {
1322
+
1323
+ h = normalize( wi + wo );
1324
+
1325
+ } else {
1326
+
1327
+ // Scale by the ior ratio to retrieve the appropriate half vector
1328
+ // From Section 2.2 on computing the transmission half vector:
1329
+ // https://blog.selfshadow.com/publications/s2015-shading-course/burley/s2015_pbs_disney_bsdf_notes.pdf
1330
+ h = normalize( wi + wo * eta );
1331
+
1332
+ }
1333
+
1334
+ h *= sign( h.z );
1335
+ return h;
1336
+
1337
+ }
1338
+
1339
+ vec3 getHalfVector( vec3 a, vec3 b ) {
1340
+
1341
+ return normalize( a + b );
1342
+
1343
+ }
1344
+
1345
+ // The discrepancy between interpolated surface normal and geometry normal can cause issues when a ray
1346
+ // is cast that is on the top side of the geometry normal plane but below the surface normal plane. If
1347
+ // we find a ray like that we ignore it to avoid artifacts.
1348
+ // This function returns if the direction is on the same side of both planes.
1349
+ bool isDirectionValid( vec3 direction, vec3 surfaceNormal, vec3 geometryNormal ) {
1350
+
1351
+ bool aboveSurfaceNormal = dot( direction, surfaceNormal ) > 0.0;
1352
+ bool aboveGeometryNormal = dot( direction, geometryNormal ) > 0.0;
1353
+ return aboveSurfaceNormal == aboveGeometryNormal;
1354
+
1355
+ }
1356
+
1357
+ // ray sampling x and z are swapped to align with expected background view
1358
+ vec2 equirectDirectionToUv( vec3 direction ) {
1359
+
1360
+ // from Spherical.setFromCartesianCoords
1361
+ vec2 uv = vec2( atan( direction.z, direction.x ), acos( direction.y ) );
1362
+ uv /= vec2( 2.0 * PI, PI );
1363
+
1364
+ // apply adjustments to get values in range [0, 1] and y right side up
1365
+ uv.x += 0.5;
1366
+ uv.y = 1.0 - uv.y;
1367
+ return uv;
1368
+
1369
+ }
1370
+
1371
+ vec3 equirectUvToDirection( vec2 uv ) {
1372
+
1373
+ // undo above adjustments
1374
+ uv.x -= 0.5;
1375
+ uv.y = 1.0 - uv.y;
1376
+
1377
+ // from Vector3.setFromSphericalCoords
1378
+ float theta = uv.x * 2.0 * PI;
1379
+ float phi = uv.y * PI;
1380
+
1381
+ float sinPhi = sin( phi );
1382
+
1383
+ return vec3( sinPhi * cos( theta ), cos( phi ), sinPhi * sin( theta ) );
1384
+
1385
+ }
1386
+
1387
+ // power heuristic for multiple importance sampling
1388
+ float misHeuristic( float a, float b ) {
1389
+
1390
+ float aa = a * a;
1391
+ float bb = b * b;
1392
+ return aa / ( aa + bb );
1393
+
1394
+ }
1395
+
1396
+ // tentFilter from Peter Shirley's 'Realistic Ray Tracing (2nd Edition)' book, pg. 60
1397
+ // erichlof/THREE.js-PathTracing-Renderer/
1398
+ float tentFilter( float x ) {
1399
+
1400
+ return x < 0.5 ? sqrt( 2.0 * x ) - 1.0 : 1.0 - sqrt( 2.0 - ( 2.0 * x ) );
1401
+
1402
+ }
1403
+ `;var Ze=`
1404
+
1405
+ // https://www.shadertoy.com/view/wltcRS
1406
+ uvec4 WHITE_NOISE_SEED;
1407
+
1408
+ void rng_initialize( vec2 p, int frame ) {
1409
+
1410
+ // white noise seed
1411
+ WHITE_NOISE_SEED = uvec4( p, uint( frame ), uint( p.x ) + uint( p.y ) );
1412
+
1413
+ }
1414
+
1415
+ // https://www.pcg-random.org/
1416
+ void pcg4d( inout uvec4 v ) {
1417
+
1418
+ v = v * 1664525u + 1013904223u;
1419
+ v.x += v.y * v.w;
1420
+ v.y += v.z * v.x;
1421
+ v.z += v.x * v.y;
1422
+ v.w += v.y * v.z;
1423
+ v = v ^ ( v >> 16u );
1424
+ v.x += v.y*v.w;
1425
+ v.y += v.z*v.x;
1426
+ v.z += v.x*v.y;
1427
+ v.w += v.y*v.z;
1428
+
1429
+ }
1430
+
1431
+ // returns [ 0, 1 ]
1432
+ float pcgRand() {
1433
+
1434
+ pcg4d( WHITE_NOISE_SEED );
1435
+ return float( WHITE_NOISE_SEED.x ) / float( 0xffffffffu );
1436
+
1437
+ }
1438
+
1439
+ vec2 pcgRand2() {
1440
+
1441
+ pcg4d( WHITE_NOISE_SEED );
1442
+ return vec2( WHITE_NOISE_SEED.xy ) / float(0xffffffffu);
1443
+
1444
+ }
1445
+
1446
+ vec3 pcgRand3() {
1447
+
1448
+ pcg4d( WHITE_NOISE_SEED );
1449
+ return vec3( WHITE_NOISE_SEED.xyz ) / float( 0xffffffffu );
1450
+
1451
+ }
1452
+
1453
+ vec4 pcgRand4() {
1454
+
1455
+ pcg4d( WHITE_NOISE_SEED );
1456
+ return vec4( WHITE_NOISE_SEED ) / float( 0xffffffffu );
1457
+
1458
+ }
1459
+ `;var hr=`
1460
+
1461
+ uniform sampler2D stratifiedTexture;
1462
+ uniform sampler2D stratifiedOffsetTexture;
1463
+
1464
+ uint sobolPixelIndex = 0u;
1465
+ uint sobolPathIndex = 0u;
1466
+ uint sobolBounceIndex = 0u;
1467
+ vec4 pixelSeed = vec4( 0 );
1468
+
1469
+ vec4 rand4( int v ) {
1470
+
1471
+ ivec2 uv = ivec2( v, sobolBounceIndex );
1472
+ vec4 stratifiedSample = texelFetch( stratifiedTexture, uv, 0 );
1473
+ return fract( stratifiedSample + pixelSeed.r ); // blue noise + stratified samples
1474
+
1475
+ }
1476
+
1477
+ vec3 rand3( int v ) {
1478
+
1479
+ return rand4( v ).xyz;
1480
+
1481
+ }
1482
+
1483
+ vec2 rand2( int v ) {
1484
+
1485
+ return rand4( v ).xy;
1486
+
1487
+ }
1488
+
1489
+ float rand( int v ) {
1490
+
1491
+ return rand4( v ).x;
1492
+
1493
+ }
1494
+
1495
+ void rng_initialize( vec2 screenCoord, int frame ) {
1496
+
1497
+ // tile the small noise texture across the entire screen
1498
+ ivec2 noiseSize = ivec2( textureSize( stratifiedOffsetTexture, 0 ) );
1499
+ ivec2 pixel = ivec2( screenCoord.xy ) % noiseSize;
1500
+ vec2 pixelWidth = 1.0 / vec2( noiseSize );
1501
+ vec2 uv = vec2( pixel ) * pixelWidth + pixelWidth * 0.5;
1502
+
1503
+ // note that using "texelFetch" here seems to break Android for some reason
1504
+ pixelSeed = texture( stratifiedOffsetTexture, uv );
1505
+
1506
+ }
1507
+
1508
+ `;var mr=`
1509
+
1510
+ // diffuse
1511
+ float diffuseEval( vec3 wo, vec3 wi, vec3 wh, SurfaceRecord surf, inout vec3 color ) {
1512
+
1513
+ // https://schuttejoe.github.io/post/disneybsdf/
1514
+ float fl = schlickFresnel( wi.z, 0.0 );
1515
+ float fv = schlickFresnel( wo.z, 0.0 );
1516
+
1517
+ float metalFactor = ( 1.0 - surf.metalness );
1518
+ float transFactor = ( 1.0 - surf.transmission );
1519
+ float rr = 0.5 + 2.0 * surf.roughness * fl * fl;
1520
+ float retro = rr * ( fl + fv + fl * fv * ( rr - 1.0f ) );
1521
+ float lambert = ( 1.0f - 0.5f * fl ) * ( 1.0f - 0.5f * fv );
1522
+
1523
+ // TODO: subsurface approx?
1524
+
1525
+ // float F = evaluateFresnelWeight( dot( wo, wh ), surf.eta, surf.f0 );
1526
+ float F = disneyFresnel( wo, wi, wh, surf.f0, surf.eta, surf.metalness );
1527
+ color = ( 1.0 - F ) * transFactor * metalFactor * wi.z * surf.color * ( retro + lambert ) / PI;
1528
+
1529
+ return wi.z / PI;
1530
+
1531
+ }
1532
+
1533
+ vec3 diffuseDirection( vec3 wo, SurfaceRecord surf ) {
1534
+
1535
+ vec3 lightDirection = sampleSphere( rand2( 11 ) );
1536
+ lightDirection.z += 1.0;
1537
+ lightDirection = normalize( lightDirection );
1538
+
1539
+ return lightDirection;
1540
+
1541
+ }
1542
+
1543
+ // specular
1544
+ float specularEval( vec3 wo, vec3 wi, vec3 wh, SurfaceRecord surf, inout vec3 color ) {
1545
+
1546
+ // if roughness is set to 0 then D === NaN which results in black pixels
1547
+ float metalness = surf.metalness;
1548
+ float roughness = surf.filteredRoughness;
1549
+
1550
+ float eta = surf.eta;
1551
+ float f0 = surf.f0;
1552
+
1553
+ vec3 f0Color = mix( f0 * surf.specularColor * surf.specularIntensity, surf.color, surf.metalness );
1554
+ vec3 f90Color = vec3( mix( surf.specularIntensity, 1.0, surf.metalness ) );
1555
+ vec3 F = evaluateFresnel( dot( wo, wh ), eta, f0Color, f90Color );
1556
+
1557
+ vec3 iridescenceF = evalIridescence( 1.0, surf.iridescenceIor, dot( wi, wh ), surf.iridescenceThickness, f0Color );
1558
+ F = mix( F, iridescenceF, surf.iridescence );
1559
+
1560
+ // PDF
1561
+ // See 14.1.1 Microfacet BxDFs in https://www.pbr-book.org/
1562
+ float incidentTheta = acos( wo.z );
1563
+ float G = ggxShadowMaskG2( wi, wo, roughness );
1564
+ float D = ggxDistribution( wh, roughness );
1565
+ float G1 = ggxShadowMaskG1( incidentTheta, roughness );
1566
+ float ggxPdf = D * G1 * max( 0.0, abs( dot( wo, wh ) ) ) / abs ( wo.z );
1567
+
1568
+ color = wi.z * F * G * D / ( 4.0 * abs( wi.z * wo.z ) );
1569
+ return ggxPdf / ( 4.0 * dot( wo, wh ) );
1570
+
1571
+ }
1572
+
1573
+ vec3 specularDirection( vec3 wo, SurfaceRecord surf ) {
1574
+
1575
+ // sample ggx vndf distribution which gives a new normal
1576
+ float roughness = surf.filteredRoughness;
1577
+ vec3 halfVector = ggxDirection(
1578
+ wo,
1579
+ vec2( roughness ),
1580
+ rand2( 12 )
1581
+ );
1582
+
1583
+ // apply to new ray by reflecting off the new normal
1584
+ return - reflect( wo, halfVector );
1585
+
1586
+ }
1587
+
1588
+
1589
+ // transmission
1590
+ /*
1591
+ float transmissionEval( vec3 wo, vec3 wi, vec3 wh, SurfaceRecord surf, inout vec3 color ) {
1592
+
1593
+ // See section 4.2 in https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf
1594
+
1595
+ float filteredRoughness = surf.filteredRoughness;
1596
+ float eta = surf.eta;
1597
+ bool frontFace = surf.frontFace;
1598
+ bool thinFilm = surf.thinFilm;
1599
+
1600
+ color = surf.transmission * surf.color;
1601
+
1602
+ float denom = pow( eta * dot( wi, wh ) + dot( wo, wh ), 2.0 );
1603
+ return ggxPDF( wo, wh, filteredRoughness ) / denom;
1604
+
1605
+ }
1606
+
1607
+ vec3 transmissionDirection( vec3 wo, SurfaceRecord surf ) {
1608
+
1609
+ float filteredRoughness = surf.filteredRoughness;
1610
+ float eta = surf.eta;
1611
+ bool frontFace = surf.frontFace;
1612
+
1613
+ // sample ggx vndf distribution which gives a new normal
1614
+ vec3 halfVector = ggxDirection(
1615
+ wo,
1616
+ vec2( filteredRoughness ),
1617
+ rand2( 13 )
1618
+ );
1619
+
1620
+ vec3 lightDirection = refract( normalize( - wo ), halfVector, eta );
1621
+ if ( surf.thinFilm ) {
1622
+
1623
+ lightDirection = - refract( normalize( - lightDirection ), - vec3( 0.0, 0.0, 1.0 ), 1.0 / eta );
1624
+
1625
+ }
1626
+
1627
+ return normalize( lightDirection );
1628
+
1629
+ }
1630
+ */
1631
+
1632
+ // TODO: This is just using a basic cosine-weighted specular distribution with an
1633
+ // incorrect PDF value at the moment. Update it to correctly use a GGX distribution
1634
+ float transmissionEval( vec3 wo, vec3 wi, vec3 wh, SurfaceRecord surf, inout vec3 color ) {
1635
+
1636
+ color = surf.transmission * surf.color;
1637
+
1638
+ // PDF
1639
+ // float F = evaluateFresnelWeight( dot( wo, wh ), surf.eta, surf.f0 );
1640
+ // float F = disneyFresnel( wo, wi, wh, surf.f0, surf.eta, surf.metalness );
1641
+ // if ( F >= 1.0 ) {
1642
+
1643
+ // return 0.0;
1644
+
1645
+ // }
1646
+
1647
+ // return 1.0 / ( 1.0 - F );
1648
+
1649
+ // reverted to previous to transmission. The above was causing black pixels
1650
+ float eta = surf.eta;
1651
+ float f0 = surf.f0;
1652
+ float cosTheta = min( wo.z, 1.0 );
1653
+ float sinTheta = sqrt( 1.0 - cosTheta * cosTheta );
1654
+ float reflectance = schlickFresnel( cosTheta, f0 );
1655
+ bool cannotRefract = eta * sinTheta > 1.0;
1656
+ if ( cannotRefract ) {
1657
+
1658
+ return 0.0;
1659
+
1660
+ }
1661
+
1662
+ return 1.0 / ( 1.0 - reflectance );
1663
+
1664
+ }
1665
+
1666
+ vec3 transmissionDirection( vec3 wo, SurfaceRecord surf ) {
1667
+
1668
+ float roughness = surf.filteredRoughness;
1669
+ float eta = surf.eta;
1670
+ vec3 halfVector = normalize( vec3( 0.0, 0.0, 1.0 ) + sampleSphere( rand2( 13 ) ) * roughness );
1671
+ vec3 lightDirection = refract( normalize( - wo ), halfVector, eta );
1672
+
1673
+ if ( surf.thinFilm ) {
1674
+
1675
+ lightDirection = - refract( normalize( - lightDirection ), - vec3( 0.0, 0.0, 1.0 ), 1.0 / eta );
1676
+
1677
+ }
1678
+ return normalize( lightDirection );
1679
+
1680
+ }
1681
+
1682
+ // clearcoat
1683
+ float clearcoatEval( vec3 wo, vec3 wi, vec3 wh, SurfaceRecord surf, inout vec3 color ) {
1684
+
1685
+ float ior = 1.5;
1686
+ float f0 = iorRatioToF0( ior );
1687
+ bool frontFace = surf.frontFace;
1688
+ float roughness = surf.filteredClearcoatRoughness;
1689
+
1690
+ float eta = frontFace ? 1.0 / ior : ior;
1691
+ float G = ggxShadowMaskG2( wi, wo, roughness );
1692
+ float D = ggxDistribution( wh, roughness );
1693
+ float F = schlickFresnel( dot( wi, wh ), f0 );
1694
+
1695
+ float fClearcoat = F * D * G / ( 4.0 * abs( wi.z * wo.z ) );
1696
+ color = color * ( 1.0 - surf.clearcoat * F ) + fClearcoat * surf.clearcoat * wi.z;
1697
+
1698
+ // PDF
1699
+ // See equation (27) in http://jcgt.org/published/0003/02/03/
1700
+ return ggxPDF( wo, wh, roughness ) / ( 4.0 * dot( wi, wh ) );
1701
+
1702
+ }
1703
+
1704
+ vec3 clearcoatDirection( vec3 wo, SurfaceRecord surf ) {
1705
+
1706
+ // sample ggx vndf distribution which gives a new normal
1707
+ float roughness = surf.filteredClearcoatRoughness;
1708
+ vec3 halfVector = ggxDirection(
1709
+ wo,
1710
+ vec2( roughness ),
1711
+ rand2( 14 )
1712
+ );
1713
+
1714
+ // apply to new ray by reflecting off the new normal
1715
+ return - reflect( wo, halfVector );
1716
+
1717
+ }
1718
+
1719
+ // sheen
1720
+ vec3 sheenColor( vec3 wo, vec3 wi, vec3 wh, SurfaceRecord surf ) {
1721
+
1722
+ float cosThetaO = saturateCos( wo.z );
1723
+ float cosThetaI = saturateCos( wi.z );
1724
+ float cosThetaH = wh.z;
1725
+
1726
+ float D = velvetD( cosThetaH, surf.sheenRoughness );
1727
+ float G = velvetG( cosThetaO, cosThetaI, surf.sheenRoughness );
1728
+
1729
+ // See equation (1) in http://www.aconty.com/pdf/s2017_pbs_imageworks_sheen.pdf
1730
+ vec3 color = surf.sheenColor;
1731
+ color *= D * G / ( 4.0 * abs( cosThetaO * cosThetaI ) );
1732
+ color *= wi.z;
1733
+
1734
+ return color;
1735
+
1736
+ }
1737
+
1738
+ // bsdf
1739
+ void getLobeWeights(
1740
+ vec3 wo, vec3 wi, vec3 wh, vec3 clearcoatWo, SurfaceRecord surf,
1741
+ inout float diffuseWeight, inout float specularWeight, inout float transmissionWeight, inout float clearcoatWeight
1742
+ ) {
1743
+
1744
+ float metalness = surf.metalness;
1745
+ float transmission = surf.transmission;
1746
+ // float fEstimate = evaluateFresnelWeight( dot( wo, wh ), surf.eta, surf.f0 );
1747
+ float fEstimate = disneyFresnel( wo, wi, wh, surf.f0, surf.eta, surf.metalness );
1748
+
1749
+ float transSpecularProb = mix( max( 0.25, fEstimate ), 1.0, metalness );
1750
+ float diffSpecularProb = 0.5 + 0.5 * metalness;
1751
+
1752
+ diffuseWeight = ( 1.0 - transmission ) * ( 1.0 - diffSpecularProb );
1753
+ specularWeight = transmission * transSpecularProb + ( 1.0 - transmission ) * diffSpecularProb;
1754
+ transmissionWeight = transmission * ( 1.0 - transSpecularProb );
1755
+ clearcoatWeight = surf.clearcoat * schlickFresnel( clearcoatWo.z, 0.04 );
1756
+
1757
+ float totalWeight = diffuseWeight + specularWeight + transmissionWeight + clearcoatWeight;
1758
+ diffuseWeight /= totalWeight;
1759
+ specularWeight /= totalWeight;
1760
+ transmissionWeight /= totalWeight;
1761
+ clearcoatWeight /= totalWeight;
1762
+ }
1763
+
1764
+ float bsdfEval(
1765
+ vec3 wo, vec3 clearcoatWo, vec3 wi, vec3 clearcoatWi, SurfaceRecord surf,
1766
+ float diffuseWeight, float specularWeight, float transmissionWeight, float clearcoatWeight, inout float specularPdf, inout vec3 color
1767
+ ) {
1768
+
1769
+ float metalness = surf.metalness;
1770
+ float transmission = surf.transmission;
1771
+
1772
+ float spdf = 0.0;
1773
+ float dpdf = 0.0;
1774
+ float tpdf = 0.0;
1775
+ float cpdf = 0.0;
1776
+ color = vec3( 0.0 );
1777
+
1778
+ vec3 halfVector = getHalfVector( wi, wo, surf.eta );
1779
+
1780
+ // diffuse
1781
+ if ( diffuseWeight > 0.0 && wi.z > 0.0 ) {
1782
+
1783
+ dpdf = diffuseEval( wo, wi, halfVector, surf, color );
1784
+ color *= 1.0 - surf.transmission;
1785
+
1786
+ }
1787
+
1788
+ // ggx specular
1789
+ if ( specularWeight > 0.0 && wi.z > 0.0 ) {
1790
+
1791
+ vec3 outColor;
1792
+ spdf = specularEval( wo, wi, getHalfVector( wi, wo ), surf, outColor );
1793
+ color += outColor;
1794
+
1795
+ }
1796
+
1797
+ // transmission
1798
+ if ( transmissionWeight > 0.0 && wi.z < 0.0 ) {
1799
+
1800
+ tpdf = transmissionEval( wo, wi, halfVector, surf, color );
1801
+
1802
+ }
1803
+
1804
+ // sheen
1805
+ color *= mix( 1.0, sheenAlbedoScaling( wo, wi, surf ), surf.sheen );
1806
+ color += sheenColor( wo, wi, halfVector, surf ) * surf.sheen;
1807
+
1808
+ // clearcoat
1809
+ if ( clearcoatWi.z >= 0.0 && clearcoatWeight > 0.0 ) {
1810
+
1811
+ vec3 clearcoatHalfVector = getHalfVector( clearcoatWo, clearcoatWi );
1812
+ cpdf = clearcoatEval( clearcoatWo, clearcoatWi, clearcoatHalfVector, surf, color );
1813
+
1814
+ }
1815
+
1816
+ float pdf =
1817
+ dpdf * diffuseWeight
1818
+ + spdf * specularWeight
1819
+ + tpdf * transmissionWeight
1820
+ + cpdf * clearcoatWeight;
1821
+
1822
+ // retrieve specular rays for the shadows flag
1823
+ specularPdf = spdf * specularWeight + cpdf * clearcoatWeight;
1824
+
1825
+ return pdf;
1826
+
1827
+ }
1828
+
1829
+ float bsdfResult( vec3 worldWo, vec3 worldWi, SurfaceRecord surf, inout vec3 color ) {
1830
+
1831
+ if ( surf.volumeParticle ) {
1832
+
1833
+ color = surf.color / ( 4.0 * PI );
1834
+ return 1.0 / ( 4.0 * PI );
1835
+
1836
+ }
1837
+
1838
+ vec3 wo = normalize( surf.normalInvBasis * worldWo );
1839
+ vec3 wi = normalize( surf.normalInvBasis * worldWi );
1840
+
1841
+ vec3 clearcoatWo = normalize( surf.clearcoatInvBasis * worldWo );
1842
+ vec3 clearcoatWi = normalize( surf.clearcoatInvBasis * worldWi );
1843
+
1844
+ vec3 wh = getHalfVector( wo, wi, surf.eta );
1845
+ float diffuseWeight;
1846
+ float specularWeight;
1847
+ float transmissionWeight;
1848
+ float clearcoatWeight;
1849
+ getLobeWeights( wo, wi, wh, clearcoatWo, surf, diffuseWeight, specularWeight, transmissionWeight, clearcoatWeight );
1850
+
1851
+ float specularPdf;
1852
+ return bsdfEval( wo, clearcoatWo, wi, clearcoatWi, surf, diffuseWeight, specularWeight, transmissionWeight, clearcoatWeight, specularPdf, color );
1853
+
1854
+ }
1855
+
1856
+ ScatterRecord bsdfSample( vec3 worldWo, SurfaceRecord surf ) {
1857
+
1858
+ if ( surf.volumeParticle ) {
1859
+
1860
+ ScatterRecord sampleRec;
1861
+ sampleRec.specularPdf = 0.0;
1862
+ sampleRec.pdf = 1.0 / ( 4.0 * PI );
1863
+ sampleRec.direction = sampleSphere( rand2( 16 ) );
1864
+ sampleRec.color = surf.color / ( 4.0 * PI );
1865
+ return sampleRec;
1866
+
1867
+ }
1868
+
1869
+ vec3 wo = normalize( surf.normalInvBasis * worldWo );
1870
+ vec3 clearcoatWo = normalize( surf.clearcoatInvBasis * worldWo );
1871
+ mat3 normalBasis = surf.normalBasis;
1872
+ mat3 invBasis = surf.normalInvBasis;
1873
+ mat3 clearcoatNormalBasis = surf.clearcoatBasis;
1874
+ mat3 clearcoatInvBasis = surf.clearcoatInvBasis;
1875
+
1876
+ float diffuseWeight;
1877
+ float specularWeight;
1878
+ float transmissionWeight;
1879
+ float clearcoatWeight;
1880
+ // using normal and basically-reflected ray since we don't have proper half vector here
1881
+ getLobeWeights( wo, wo, vec3( 0, 0, 1 ), clearcoatWo, surf, diffuseWeight, specularWeight, transmissionWeight, clearcoatWeight );
1882
+
1883
+ float pdf[4];
1884
+ pdf[0] = diffuseWeight;
1885
+ pdf[1] = specularWeight;
1886
+ pdf[2] = transmissionWeight;
1887
+ pdf[3] = clearcoatWeight;
1888
+
1889
+ float cdf[4];
1890
+ cdf[0] = pdf[0];
1891
+ cdf[1] = pdf[1] + cdf[0];
1892
+ cdf[2] = pdf[2] + cdf[1];
1893
+ cdf[3] = pdf[3] + cdf[2];
1894
+
1895
+ if( cdf[3] != 0.0 ) {
1896
+
1897
+ float invMaxCdf = 1.0 / cdf[3];
1898
+ cdf[0] *= invMaxCdf;
1899
+ cdf[1] *= invMaxCdf;
1900
+ cdf[2] *= invMaxCdf;
1901
+ cdf[3] *= invMaxCdf;
1902
+
1903
+ } else {
1904
+
1905
+ cdf[0] = 1.0;
1906
+ cdf[1] = 0.0;
1907
+ cdf[2] = 0.0;
1908
+ cdf[3] = 0.0;
1909
+
1910
+ }
1911
+
1912
+ vec3 wi;
1913
+ vec3 clearcoatWi;
1914
+
1915
+ float r = rand( 15 );
1916
+ if ( r <= cdf[0] ) { // diffuse
1917
+
1918
+ wi = diffuseDirection( wo, surf );
1919
+ clearcoatWi = normalize( clearcoatInvBasis * normalize( normalBasis * wi ) );
1920
+
1921
+ } else if ( r <= cdf[1] ) { // specular
1922
+
1923
+ wi = specularDirection( wo, surf );
1924
+ clearcoatWi = normalize( clearcoatInvBasis * normalize( normalBasis * wi ) );
1925
+
1926
+ } else if ( r <= cdf[2] ) { // transmission / refraction
1927
+
1928
+ wi = transmissionDirection( wo, surf );
1929
+ clearcoatWi = normalize( clearcoatInvBasis * normalize( normalBasis * wi ) );
1930
+
1931
+ } else if ( r <= cdf[3] ) { // clearcoat
1932
+
1933
+ clearcoatWi = clearcoatDirection( clearcoatWo, surf );
1934
+ wi = normalize( invBasis * normalize( clearcoatNormalBasis * clearcoatWi ) );
1935
+
1936
+ }
1937
+
1938
+ ScatterRecord result;
1939
+ result.pdf = bsdfEval( wo, clearcoatWo, wi, clearcoatWi, surf, diffuseWeight, specularWeight, transmissionWeight, clearcoatWeight, result.specularPdf, result.color );
1940
+ result.direction = normalize( surf.normalBasis * wi );
1941
+
1942
+ return result;
1943
+
1944
+ }
1945
+
1946
+ `;var dr=`
1947
+
1948
+ // returns the hit distance given the material density
1949
+ float intersectFogVolume( Material material, float u ) {
1950
+
1951
+ // https://raytracing.github.io/books/RayTracingTheNextWeek.html#volumes/constantdensitymediums
1952
+ return material.opacity == 0.0 ? INFINITY : ( - 1.0 / material.opacity ) * log( u );
1953
+
1954
+ }
1955
+
1956
+ ScatterRecord sampleFogVolume( SurfaceRecord surf, vec2 uv ) {
1957
+
1958
+ ScatterRecord sampleRec;
1959
+ sampleRec.specularPdf = 0.0;
1960
+ sampleRec.pdf = 1.0 / ( 2.0 * PI );
1961
+ sampleRec.direction = sampleSphere( uv );
1962
+ sampleRec.color = surf.color;
1963
+ return sampleRec;
1964
+
1965
+ }
1966
+
1967
+ `;var pr=`
1968
+
1969
+ // The GGX functions provide sampling and distribution information for normals as output so
1970
+ // in order to get probability of scatter direction the half vector must be computed and provided.
1971
+ // [0] https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf
1972
+ // [1] https://hal.archives-ouvertes.fr/hal-01509746/document
1973
+ // [2] http://jcgt.org/published/0007/04/01/
1974
+ // [4] http://jcgt.org/published/0003/02/03/
1975
+
1976
+ // trowbridge-reitz === GGX === GTR
1977
+
1978
+ vec3 ggxDirection( vec3 incidentDir, vec2 roughness, vec2 uv ) {
1979
+
1980
+ // TODO: try GGXVNDF implementation from reference [2], here. Needs to update ggxDistribution
1981
+ // function below, as well
1982
+
1983
+ // Implementation from reference [1]
1984
+ // stretch view
1985
+ vec3 V = normalize( vec3( roughness * incidentDir.xy, incidentDir.z ) );
1986
+
1987
+ // orthonormal basis
1988
+ vec3 T1 = ( V.z < 0.9999 ) ? normalize( cross( V, vec3( 0.0, 0.0, 1.0 ) ) ) : vec3( 1.0, 0.0, 0.0 );
1989
+ vec3 T2 = cross( T1, V );
1990
+
1991
+ // sample point with polar coordinates (r, phi)
1992
+ float a = 1.0 / ( 1.0 + V.z );
1993
+ float r = sqrt( uv.x );
1994
+ float phi = ( uv.y < a ) ? uv.y / a * PI : PI + ( uv.y - a ) / ( 1.0 - a ) * PI;
1995
+ float P1 = r * cos( phi );
1996
+ float P2 = r * sin( phi ) * ( ( uv.y < a ) ? 1.0 : V.z );
1997
+
1998
+ // compute normal
1999
+ vec3 N = P1 * T1 + P2 * T2 + V * sqrt( max( 0.0, 1.0 - P1 * P1 - P2 * P2 ) );
2000
+
2001
+ // unstretch
2002
+ N = normalize( vec3( roughness * N.xy, max( 0.0, N.z ) ) );
2003
+
2004
+ return N;
2005
+
2006
+ }
2007
+
2008
+ // Below are PDF and related functions for use in a Monte Carlo path tracer
2009
+ // as specified in Appendix B of the following paper
2010
+ // See equation (34) from reference [0]
2011
+ float ggxLamda( float theta, float roughness ) {
2012
+
2013
+ float tanTheta = tan( theta );
2014
+ float tanTheta2 = tanTheta * tanTheta;
2015
+ float alpha2 = roughness * roughness;
2016
+
2017
+ float numerator = - 1.0 + sqrt( 1.0 + alpha2 * tanTheta2 );
2018
+ return numerator / 2.0;
2019
+
2020
+ }
2021
+
2022
+ // See equation (34) from reference [0]
2023
+ float ggxShadowMaskG1( float theta, float roughness ) {
2024
+
2025
+ return 1.0 / ( 1.0 + ggxLamda( theta, roughness ) );
2026
+
2027
+ }
2028
+
2029
+ // See equation (125) from reference [4]
2030
+ float ggxShadowMaskG2( vec3 wi, vec3 wo, float roughness ) {
2031
+
2032
+ float incidentTheta = acos( wi.z );
2033
+ float scatterTheta = acos( wo.z );
2034
+ return 1.0 / ( 1.0 + ggxLamda( incidentTheta, roughness ) + ggxLamda( scatterTheta, roughness ) );
2035
+
2036
+ }
2037
+
2038
+ // See equation (33) from reference [0]
2039
+ float ggxDistribution( vec3 halfVector, float roughness ) {
2040
+
2041
+ float a2 = roughness * roughness;
2042
+ a2 = max( EPSILON, a2 );
2043
+ float cosTheta = halfVector.z;
2044
+ float cosTheta4 = pow( cosTheta, 4.0 );
2045
+
2046
+ if ( cosTheta == 0.0 ) return 0.0;
2047
+
2048
+ float theta = acosSafe( halfVector.z );
2049
+ float tanTheta = tan( theta );
2050
+ float tanTheta2 = pow( tanTheta, 2.0 );
2051
+
2052
+ float denom = PI * cosTheta4 * pow( a2 + tanTheta2, 2.0 );
2053
+ return ( a2 / denom );
2054
+
2055
+ }
2056
+
2057
+ // See equation (3) from reference [2]
2058
+ float ggxPDF( vec3 wi, vec3 halfVector, float roughness ) {
2059
+
2060
+ float incidentTheta = acos( wi.z );
2061
+ float D = ggxDistribution( halfVector, roughness );
2062
+ float G1 = ggxShadowMaskG1( incidentTheta, roughness );
2063
+
2064
+ return D * G1 * max( 0.0, dot( wi, halfVector ) ) / wi.z;
2065
+
2066
+ }
2067
+
2068
+ `;var gr=`
2069
+
2070
+ // XYZ to sRGB color space
2071
+ const mat3 XYZ_TO_REC709 = mat3(
2072
+ 3.2404542, -0.9692660, 0.0556434,
2073
+ -1.5371385, 1.8760108, -0.2040259,
2074
+ -0.4985314, 0.0415560, 1.0572252
2075
+ );
2076
+
2077
+ vec3 fresnel0ToIor( vec3 fresnel0 ) {
2078
+
2079
+ vec3 sqrtF0 = sqrt( fresnel0 );
2080
+ return ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );
2081
+
2082
+ }
2083
+
2084
+ // Conversion FO/IOR
2085
+ vec3 iorToFresnel0( vec3 transmittedIor, float incidentIor ) {
2086
+
2087
+ return square( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );
2088
+
2089
+ }
2090
+
2091
+ // ior is a value between 1.0 and 3.0. 1.0 is air interface
2092
+ float iorToFresnel0( float transmittedIor, float incidentIor ) {
2093
+
2094
+ return square( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ) );
2095
+
2096
+ }
2097
+
2098
+ // Fresnel equations for dielectric/dielectric interfaces. See https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
2099
+ vec3 evalSensitivity( float OPD, vec3 shift ) {
2100
+
2101
+ float phase = 2.0 * PI * OPD * 1.0e-9;
2102
+
2103
+ vec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
2104
+ vec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
2105
+ vec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
2106
+
2107
+ vec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - square( phase ) * var );
2108
+ xyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * square( phase ) );
2109
+ xyz /= 1.0685e-7;
2110
+
2111
+ vec3 srgb = XYZ_TO_REC709 * xyz;
2112
+ return srgb;
2113
+
2114
+ }
2115
+
2116
+ // See Section 4. Analytic Spectral Integration, A Practical Extension to Microfacet Theory for the Modeling of Varying Iridescence, https://hal.archives-ouvertes.fr/hal-01518344/document
2117
+ vec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {
2118
+
2119
+ vec3 I;
2120
+
2121
+ // Force iridescenceIor -> outsideIOR when thinFilmThickness -> 0.0
2122
+ float iridescenceIor = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
2123
+
2124
+ // Evaluate the cosTheta on the base layer (Snell law)
2125
+ float sinTheta2Sq = square( outsideIOR / iridescenceIor ) * ( 1.0 - square( cosTheta1 ) );
2126
+
2127
+ // Handle TIR:
2128
+ float cosTheta2Sq = 1.0 - sinTheta2Sq;
2129
+ if ( cosTheta2Sq < 0.0 ) {
2130
+
2131
+ return vec3( 1.0 );
2132
+
2133
+ }
2134
+
2135
+ float cosTheta2 = sqrt( cosTheta2Sq );
2136
+
2137
+ // First interface
2138
+ float R0 = iorToFresnel0( iridescenceIor, outsideIOR );
2139
+ float R12 = schlickFresnel( cosTheta1, R0 );
2140
+ float R21 = R12;
2141
+ float T121 = 1.0 - R12;
2142
+ float phi12 = 0.0;
2143
+ if ( iridescenceIor < outsideIOR ) {
2144
+
2145
+ phi12 = PI;
2146
+
2147
+ }
2148
+
2149
+ float phi21 = PI - phi12;
2150
+
2151
+ // Second interface
2152
+ vec3 baseIOR = fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) ); // guard against 1.0
2153
+ vec3 R1 = iorToFresnel0( baseIOR, iridescenceIor );
2154
+ vec3 R23 = schlickFresnel( cosTheta2, R1 );
2155
+ vec3 phi23 = vec3( 0.0 );
2156
+ if ( baseIOR[0] < iridescenceIor ) {
2157
+
2158
+ phi23[ 0 ] = PI;
2159
+
2160
+ }
2161
+
2162
+ if ( baseIOR[1] < iridescenceIor ) {
2163
+
2164
+ phi23[ 1 ] = PI;
2165
+
2166
+ }
2167
+
2168
+ if ( baseIOR[2] < iridescenceIor ) {
2169
+
2170
+ phi23[ 2 ] = PI;
2171
+
2172
+ }
2173
+
2174
+ // Phase shift
2175
+ float OPD = 2.0 * iridescenceIor * thinFilmThickness * cosTheta2;
2176
+ vec3 phi = vec3( phi21 ) + phi23;
2177
+
2178
+ // Compound terms
2179
+ vec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );
2180
+ vec3 r123 = sqrt( R123 );
2181
+ vec3 Rs = square( T121 ) * R23 / ( vec3( 1.0 ) - R123 );
2182
+
2183
+ // Reflectance term for m = 0 (DC term amplitude)
2184
+ vec3 C0 = R12 + Rs;
2185
+ I = C0;
2186
+
2187
+ // Reflectance term for m > 0 (pairs of diracs)
2188
+ vec3 Cm = Rs - T121;
2189
+ for ( int m = 1; m <= 2; ++ m ) {
2190
+
2191
+ Cm *= r123;
2192
+ vec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );
2193
+ I += Cm * Sm;
2194
+
2195
+ }
2196
+
2197
+ // Since out of gamut colors might be produced, negative color values are clamped to 0.
2198
+ return max( I, vec3( 0.0 ) );
2199
+
2200
+ }
2201
+
2202
+ `;var vr=`
2203
+
2204
+ // See equation (2) in http://www.aconty.com/pdf/s2017_pbs_imageworks_sheen.pdf
2205
+ float velvetD( float cosThetaH, float roughness ) {
2206
+
2207
+ float alpha = max( roughness, 0.07 );
2208
+ alpha = alpha * alpha;
2209
+
2210
+ float invAlpha = 1.0 / alpha;
2211
+
2212
+ float sqrCosThetaH = cosThetaH * cosThetaH;
2213
+ float sinThetaH = max( 1.0 - sqrCosThetaH, 0.001 );
2214
+
2215
+ return ( 2.0 + invAlpha ) * pow( sinThetaH, 0.5 * invAlpha ) / ( 2.0 * PI );
2216
+
2217
+ }
2218
+
2219
+ float velvetParamsInterpolate( int i, float oneMinusAlphaSquared ) {
2220
+
2221
+ const float p0[5] = float[5]( 25.3245, 3.32435, 0.16801, -1.27393, -4.85967 );
2222
+ const float p1[5] = float[5]( 21.5473, 3.82987, 0.19823, -1.97760, -4.32054 );
2223
+
2224
+ return mix( p1[i], p0[i], oneMinusAlphaSquared );
2225
+
2226
+ }
2227
+
2228
+ float velvetL( float x, float alpha ) {
2229
+
2230
+ float oneMinusAlpha = 1.0 - alpha;
2231
+ float oneMinusAlphaSquared = oneMinusAlpha * oneMinusAlpha;
2232
+
2233
+ float a = velvetParamsInterpolate( 0, oneMinusAlphaSquared );
2234
+ float b = velvetParamsInterpolate( 1, oneMinusAlphaSquared );
2235
+ float c = velvetParamsInterpolate( 2, oneMinusAlphaSquared );
2236
+ float d = velvetParamsInterpolate( 3, oneMinusAlphaSquared );
2237
+ float e = velvetParamsInterpolate( 4, oneMinusAlphaSquared );
2238
+
2239
+ return a / ( 1.0 + b * pow( abs( x ), c ) ) + d * x + e;
2240
+
2241
+ }
2242
+
2243
+ // See equation (3) in http://www.aconty.com/pdf/s2017_pbs_imageworks_sheen.pdf
2244
+ float velvetLambda( float cosTheta, float alpha ) {
2245
+
2246
+ return abs( cosTheta ) < 0.5 ? exp( velvetL( cosTheta, alpha ) ) : exp( 2.0 * velvetL( 0.5, alpha ) - velvetL( 1.0 - cosTheta, alpha ) );
2247
+
2248
+ }
2249
+
2250
+ // See Section 3, Shadowing Term, in http://www.aconty.com/pdf/s2017_pbs_imageworks_sheen.pdf
2251
+ float velvetG( float cosThetaO, float cosThetaI, float roughness ) {
2252
+
2253
+ float alpha = max( roughness, 0.07 );
2254
+ alpha = alpha * alpha;
2255
+
2256
+ return 1.0 / ( 1.0 + velvetLambda( cosThetaO, alpha ) + velvetLambda( cosThetaI, alpha ) );
2257
+
2258
+ }
2259
+
2260
+ float directionalAlbedoSheen( float cosTheta, float alpha ) {
2261
+
2262
+ cosTheta = saturate( cosTheta );
2263
+
2264
+ float c = 1.0 - cosTheta;
2265
+ float c3 = c * c * c;
2266
+
2267
+ return 0.65584461 * c3 + 1.0 / ( 4.16526551 + exp( -7.97291361 * sqrt( alpha ) + 6.33516894 ) );
2268
+
2269
+ }
2270
+
2271
+ float sheenAlbedoScaling( vec3 wo, vec3 wi, SurfaceRecord surf ) {
2272
+
2273
+ float alpha = max( surf.sheenRoughness, 0.07 );
2274
+ alpha = alpha * alpha;
2275
+
2276
+ float maxSheenColor = max( max( surf.sheenColor.r, surf.sheenColor.g ), surf.sheenColor.b );
2277
+
2278
+ float eWo = directionalAlbedoSheen( saturateCos( wo.z ), alpha );
2279
+ float eWi = directionalAlbedoSheen( saturateCos( wi.z ), alpha );
2280
+
2281
+ return min( 1.0 - maxSheenColor * eWo, 1.0 - maxSheenColor * eWi );
2282
+
2283
+ }
2284
+
2285
+ // See Section 5, Layering, in http://www.aconty.com/pdf/s2017_pbs_imageworks_sheen.pdf
2286
+ float sheenAlbedoScaling( vec3 wo, SurfaceRecord surf ) {
2287
+
2288
+ float alpha = max( surf.sheenRoughness, 0.07 );
2289
+ alpha = alpha * alpha;
2290
+
2291
+ float maxSheenColor = max( max( surf.sheenColor.r, surf.sheenColor.g ), surf.sheenColor.b );
2292
+
2293
+ float eWo = directionalAlbedoSheen( saturateCos( wo.z ), alpha );
2294
+
2295
+ return 1.0 - maxSheenColor * eWo;
2296
+
2297
+ }
2298
+
2299
+ `;var xr=`
2300
+
2301
+ #ifndef FOG_CHECK_ITERATIONS
2302
+ #define FOG_CHECK_ITERATIONS 30
2303
+ #endif
2304
+
2305
+ // returns whether the given material is a fog material or not
2306
+ bool isMaterialFogVolume( sampler2D materials, uint materialIndex ) {
2307
+
2308
+ uint i = materialIndex * uint( MATERIAL_PIXELS );
2309
+ vec4 s14 = texelFetch1D( materials, i + 14u );
2310
+ return bool( int( s14.b ) & 4 );
2311
+
2312
+ }
2313
+
2314
+ // returns true if we're within the first fog volume we hit
2315
+ bool bvhIntersectFogVolumeHit(
2316
+ vec3 rayOrigin, vec3 rayDirection,
2317
+ usampler2D materialIndexAttribute, sampler2D materials,
2318
+ inout Material material
2319
+ ) {
2320
+
2321
+ material.fogVolume = false;
2322
+
2323
+ for ( int i = 0; i < FOG_CHECK_ITERATIONS; i ++ ) {
2324
+
2325
+ // find nearest hit
2326
+ uvec4 faceIndices = uvec4( 0u );
2327
+ vec3 faceNormal = vec3( 0.0, 0.0, 1.0 );
2328
+ vec3 barycoord = vec3( 0.0 );
2329
+ float side = 1.0;
2330
+ float dist = 0.0;
2331
+ bool hit = bvhIntersectFirstHit( bvh, rayOrigin, rayDirection, faceIndices, faceNormal, barycoord, side, dist );
2332
+ if ( hit ) {
2333
+
2334
+ // if it's a fog volume return whether we hit the front or back face
2335
+ uint materialIndex = uTexelFetch1D( materialIndexAttribute, faceIndices.x ).r;
2336
+ if ( isMaterialFogVolume( materials, materialIndex ) ) {
2337
+
2338
+ material = readMaterialInfo( materials, materialIndex );
2339
+ return side == - 1.0;
2340
+
2341
+ } else {
2342
+
2343
+ // move the ray forward
2344
+ rayOrigin = stepRayOrigin( rayOrigin, rayDirection, - faceNormal, dist );
2345
+
2346
+ }
2347
+
2348
+ } else {
2349
+
2350
+ return false;
2351
+
2352
+ }
2353
+
2354
+ }
2355
+
2356
+ return false;
2357
+
2358
+ }
2359
+
2360
+ `;var br=`
2361
+
2362
+ // step through multiple surface hits and accumulate color attenuation based on transmissive surfaces
2363
+ // returns true if a solid surface was hit
2364
+ bool attenuateHit(
2365
+ RenderState state,
2366
+ Ray ray, float rayDist,
2367
+ out vec3 color
2368
+ ) {
2369
+
2370
+ // store the original bounce index so we can reset it after
2371
+ uint originalBounceIndex = sobolBounceIndex;
2372
+
2373
+ int traversals = state.traversals;
2374
+ int transmissiveTraversals = state.transmissiveTraversals;
2375
+ bool isShadowRay = state.isShadowRay;
2376
+ Material fogMaterial = state.fogMaterial;
2377
+
2378
+ vec3 startPoint = ray.origin;
2379
+
2380
+ // hit results
2381
+ SurfaceHit surfaceHit;
2382
+
2383
+ color = vec3( 1.0 );
2384
+
2385
+ bool result = true;
2386
+ for ( int i = 0; i < traversals; i ++ ) {
2387
+
2388
+ sobolBounceIndex ++;
2389
+
2390
+ int hitType = traceScene( ray, fogMaterial, surfaceHit );
2391
+
2392
+ if ( hitType == FOG_HIT ) {
2393
+
2394
+ result = true;
2395
+ break;
2396
+
2397
+ } else if ( hitType == SURFACE_HIT ) {
2398
+
2399
+ float totalDist = distance( startPoint, ray.origin + ray.direction * surfaceHit.dist );
2400
+ if ( totalDist > rayDist ) {
2401
+
2402
+ result = false;
2403
+ break;
2404
+
2405
+ }
2406
+
2407
+ // TODO: attenuate the contribution based on the PDF of the resulting ray including refraction values
2408
+ // Should be able to work using the material BSDF functions which will take into account specularity, etc.
2409
+ // TODO: should we account for emissive surfaces here?
2410
+
2411
+ uint materialIndex = uTexelFetch1D( materialIndexAttribute, surfaceHit.faceIndices.x ).r;
2412
+ Material material = readMaterialInfo( materials, materialIndex );
2413
+
2414
+ // adjust the ray to the new surface
2415
+ bool isEntering = surfaceHit.side == 1.0;
2416
+ ray.origin = stepRayOrigin( ray.origin, ray.direction, - surfaceHit.faceNormal, surfaceHit.dist );
2417
+
2418
+ #if FEATURE_FOG
2419
+
2420
+ if ( material.fogVolume ) {
2421
+
2422
+ fogMaterial = material;
2423
+ fogMaterial.fogVolume = surfaceHit.side == 1.0;
2424
+ i -= sign( transmissiveTraversals );
2425
+ transmissiveTraversals --;
2426
+ continue;
2427
+
2428
+ }
2429
+
2430
+ #endif
2431
+
2432
+ if ( ! material.castShadow && isShadowRay ) {
2433
+
2434
+ continue;
2435
+
2436
+ }
2437
+
2438
+ vec2 uv = textureSampleBarycoord( attributesArray, ATTR_UV, surfaceHit.barycoord, surfaceHit.faceIndices.xyz ).xy;
2439
+ vec4 vertexColor = textureSampleBarycoord( attributesArray, ATTR_COLOR, surfaceHit.barycoord, surfaceHit.faceIndices.xyz );
2440
+
2441
+ // albedo
2442
+ vec4 albedo = vec4( material.color, material.opacity );
2443
+ if ( material.map != - 1 ) {
2444
+
2445
+ vec3 uvPrime = material.mapTransform * vec3( uv, 1 );
2446
+ albedo *= texture2D( textures, vec3( uvPrime.xy, material.map ) );
2447
+
2448
+ }
2449
+
2450
+ if ( material.vertexColors ) {
2451
+
2452
+ albedo *= vertexColor;
2453
+
2454
+ }
2455
+
2456
+ // alphaMap
2457
+ if ( material.alphaMap != - 1 ) {
2458
+
2459
+ vec3 uvPrime = material.alphaMapTransform * vec3( uv, 1 );
2460
+ albedo.a *= texture2D( textures, vec3( uvPrime.xy, material.alphaMap ) ).x;
2461
+
2462
+ }
2463
+
2464
+ // transmission
2465
+ float transmission = material.transmission;
2466
+ if ( material.transmissionMap != - 1 ) {
2467
+
2468
+ vec3 uvPrime = material.transmissionMapTransform * vec3( uv, 1 );
2469
+ transmission *= texture2D( textures, vec3( uvPrime.xy, material.transmissionMap ) ).r;
2470
+
2471
+ }
2472
+
2473
+ // metalness
2474
+ float metalness = material.metalness;
2475
+ if ( material.metalnessMap != - 1 ) {
2476
+
2477
+ vec3 uvPrime = material.metalnessMapTransform * vec3( uv, 1 );
2478
+ metalness *= texture2D( textures, vec3( uvPrime.xy, material.metalnessMap ) ).b;
2479
+
2480
+ }
2481
+
2482
+ float alphaTest = material.alphaTest;
2483
+ bool useAlphaTest = alphaTest != 0.0;
2484
+ float transmissionFactor = ( 1.0 - metalness ) * transmission;
2485
+ if (
2486
+ transmissionFactor < rand( 9 ) && ! (
2487
+ // material sidedness
2488
+ material.side != 0.0 && surfaceHit.side == material.side
2489
+
2490
+ // alpha test
2491
+ || useAlphaTest && albedo.a < alphaTest
2492
+
2493
+ // opacity
2494
+ || material.transparent && ! useAlphaTest && albedo.a < rand( 10 )
2495
+ )
2496
+ ) {
2497
+
2498
+ result = true;
2499
+ break;
2500
+
2501
+ }
2502
+
2503
+ if ( surfaceHit.side == 1.0 && isEntering ) {
2504
+
2505
+ // only attenuate by surface color on the way in
2506
+ color *= mix( vec3( 1.0 ), albedo.rgb, transmissionFactor );
2507
+
2508
+ } else if ( surfaceHit.side == - 1.0 ) {
2509
+
2510
+ // attenuate by medium once we hit the opposite side of the model
2511
+ color *= transmissionAttenuation( surfaceHit.dist, material.attenuationColor, material.attenuationDistance );
2512
+
2513
+ }
2514
+
2515
+ bool isTransmissiveRay = dot( ray.direction, surfaceHit.faceNormal * surfaceHit.side ) < 0.0;
2516
+ if ( ( isTransmissiveRay || isEntering ) && transmissiveTraversals > 0 ) {
2517
+
2518
+ i -= sign( transmissiveTraversals );
2519
+ transmissiveTraversals --;
2520
+
2521
+ }
2522
+
2523
+ } else {
2524
+
2525
+ result = false;
2526
+ break;
2527
+
2528
+ }
2529
+
2530
+ }
2531
+
2532
+ // reset the bounce index
2533
+ sobolBounceIndex = originalBounceIndex;
2534
+ return result;
2535
+
2536
+ }
2537
+
2538
+ `;var yr=`
2539
+
2540
+ vec3 ndcToRayOrigin( vec2 coord ) {
2541
+
2542
+ vec4 rayOrigin4 = cameraWorldMatrix * invProjectionMatrix * vec4( coord, - 1.0, 1.0 );
2543
+ return rayOrigin4.xyz / rayOrigin4.w;
2544
+ }
2545
+
2546
+ Ray getCameraRay() {
2547
+
2548
+ vec2 ssd = vec2( 1.0 ) / resolution;
2549
+
2550
+ // Jitter the camera ray by finding a uv coordinate at a random sample
2551
+ // around this pixel's UV coordinate for AA
2552
+ vec2 ruv = rand2( 0 );
2553
+ vec2 jitteredUv = vUv + vec2( tentFilter( ruv.x ) * ssd.x, tentFilter( ruv.y ) * ssd.y );
2554
+ Ray ray;
2555
+
2556
+ #if CAMERA_TYPE == 2
2557
+
2558
+ // Equirectangular projection
2559
+ vec4 rayDirection4 = vec4( equirectUvToDirection( jitteredUv ), 0.0 );
2560
+ vec4 rayOrigin4 = vec4( 0.0, 0.0, 0.0, 1.0 );
2561
+
2562
+ rayDirection4 = cameraWorldMatrix * rayDirection4;
2563
+ rayOrigin4 = cameraWorldMatrix * rayOrigin4;
2564
+
2565
+ ray.direction = normalize( rayDirection4.xyz );
2566
+ ray.origin = rayOrigin4.xyz / rayOrigin4.w;
2567
+
2568
+ #else
2569
+
2570
+ // get [- 1, 1] normalized device coordinates
2571
+ vec2 ndc = 2.0 * jitteredUv - vec2( 1.0 );
2572
+ ray.origin = ndcToRayOrigin( ndc );
2573
+
2574
+ #if CAMERA_TYPE == 1
2575
+
2576
+ // Orthographic projection
2577
+ ray.direction = ( cameraWorldMatrix * vec4( 0.0, 0.0, - 1.0, 0.0 ) ).xyz;
2578
+ ray.direction = normalize( ray.direction );
2579
+
2580
+ #else
2581
+
2582
+ // Perspective projection
2583
+ ray.direction = normalize( mat3( cameraWorldMatrix ) * ( invProjectionMatrix * vec4( ndc, 0.0, 1.0 ) ).xyz );
2584
+
2585
+ #endif
2586
+
2587
+ #endif
2588
+
2589
+ #if FEATURE_DOF
2590
+ {
2591
+
2592
+ // depth of field
2593
+ vec3 focalPoint = ray.origin + normalize( ray.direction ) * physicalCamera.focusDistance;
2594
+
2595
+ // get the aperture sample
2596
+ // if blades === 0 then we assume a circle
2597
+ vec3 shapeUVW= rand3( 1 );
2598
+ int blades = physicalCamera.apertureBlades;
2599
+ float anamorphicRatio = physicalCamera.anamorphicRatio;
2600
+ vec2 apertureSample = sampleAperture( blades, shapeUVW );
2601
+ apertureSample *= physicalCamera.bokehSize * 0.5 * 1e-3;
2602
+
2603
+ // rotate the aperture shape
2604
+ apertureSample =
2605
+ rotateVector( apertureSample, physicalCamera.apertureRotation ) *
2606
+ saturate( vec2( anamorphicRatio, 1.0 / anamorphicRatio ) );
2607
+
2608
+ // create the new ray
2609
+ ray.origin += ( cameraWorldMatrix * vec4( apertureSample, 0.0, 0.0 ) ).xyz;
2610
+ ray.direction = focalPoint - ray.origin;
2611
+
2612
+ }
2613
+ #endif
2614
+
2615
+ ray.direction = normalize( ray.direction );
2616
+
2617
+ return ray;
2618
+
2619
+ }
2620
+
2621
+ `;var Tr=`
2622
+
2623
+ vec3 directLightContribution( vec3 worldWo, SurfaceRecord surf, RenderState state, vec3 rayOrigin ) {
2624
+
2625
+ vec3 result = vec3( 0.0 );
2626
+
2627
+ // uniformly pick a light or environment map
2628
+ if( lightsDenom != 0.0 && rand( 5 ) < float( lights.count ) / lightsDenom ) {
2629
+
2630
+ // sample a light or environment
2631
+ LightRecord lightRec = randomLightSample( lights.tex, iesProfiles, lights.count, rayOrigin, rand3( 6 ) );
2632
+
2633
+ bool isSampleBelowSurface = ! surf.volumeParticle && dot( surf.faceNormal, lightRec.direction ) < 0.0;
2634
+ if ( isSampleBelowSurface ) {
2635
+
2636
+ lightRec.pdf = 0.0;
2637
+
2638
+ }
2639
+
2640
+ // check if a ray could even reach the light area
2641
+ Ray lightRay;
2642
+ lightRay.origin = rayOrigin;
2643
+ lightRay.direction = lightRec.direction;
2644
+ vec3 attenuatedColor;
2645
+ if (
2646
+ lightRec.pdf > 0.0 &&
2647
+ isDirectionValid( lightRec.direction, surf.normal, surf.faceNormal ) &&
2648
+ ! attenuateHit( state, lightRay, lightRec.dist, attenuatedColor )
2649
+ ) {
2650
+
2651
+ // get the material pdf
2652
+ vec3 sampleColor;
2653
+ float lightMaterialPdf = bsdfResult( worldWo, lightRec.direction, surf, sampleColor );
2654
+ bool isValidSampleColor = all( greaterThanEqual( sampleColor, vec3( 0.0 ) ) );
2655
+ if ( lightMaterialPdf > 0.0 && isValidSampleColor ) {
2656
+
2657
+ // weight the direct light contribution
2658
+ float lightPdf = lightRec.pdf / lightsDenom;
2659
+ float misWeight = lightRec.type == SPOT_LIGHT_TYPE || lightRec.type == DIR_LIGHT_TYPE || lightRec.type == POINT_LIGHT_TYPE ? 1.0 : misHeuristic( lightPdf, lightMaterialPdf );
2660
+ result = attenuatedColor * lightRec.emission * state.throughputColor * sampleColor * misWeight / lightPdf;
2661
+
2662
+ }
2663
+
2664
+ }
2665
+
2666
+ } else if ( envMapInfo.totalSum != 0.0 && environmentIntensity != 0.0 ) {
2667
+
2668
+ // find a sample in the environment map to include in the contribution
2669
+ vec3 envColor, envDirection;
2670
+ float envPdf = sampleEquirectProbability( rand2( 7 ), envColor, envDirection );
2671
+ envDirection = invEnvRotation3x3 * envDirection;
2672
+
2673
+ // this env sampling is not set up for transmissive sampling and yields overly bright
2674
+ // results so we ignore the sample in this case.
2675
+ // TODO: this should be improved but how? The env samples could traverse a few layers?
2676
+ bool isSampleBelowSurface = ! surf.volumeParticle && dot( surf.faceNormal, envDirection ) < 0.0;
2677
+ if ( isSampleBelowSurface ) {
2678
+
2679
+ envPdf = 0.0;
2680
+
2681
+ }
2682
+
2683
+ // check if a ray could even reach the surface
2684
+ Ray envRay;
2685
+ envRay.origin = rayOrigin;
2686
+ envRay.direction = envDirection;
2687
+ vec3 attenuatedColor;
2688
+ if (
2689
+ envPdf > 0.0 &&
2690
+ isDirectionValid( envDirection, surf.normal, surf.faceNormal ) &&
2691
+ ! attenuateHit( state, envRay, INFINITY, attenuatedColor )
2692
+ ) {
2693
+
2694
+ // get the material pdf
2695
+ vec3 sampleColor;
2696
+ float envMaterialPdf = bsdfResult( worldWo, envDirection, surf, sampleColor );
2697
+ bool isValidSampleColor = all( greaterThanEqual( sampleColor, vec3( 0.0 ) ) );
2698
+ if ( envMaterialPdf > 0.0 && isValidSampleColor ) {
2699
+
2700
+ // weight the direct light contribution
2701
+ envPdf /= lightsDenom;
2702
+ float misWeight = misHeuristic( envPdf, envMaterialPdf );
2703
+ result = attenuatedColor * environmentIntensity * envColor * state.throughputColor * sampleColor * misWeight / envPdf;
2704
+
2705
+ }
2706
+
2707
+ }
2708
+
2709
+ }
2710
+
2711
+ // Function changed to have a single return statement to potentially help with crashes on Mac OS.
2712
+ // See issue #470
2713
+ return result;
2714
+
2715
+ }
2716
+
2717
+ `;var wr=`
2718
+
2719
+ #define SKIP_SURFACE 0
2720
+ #define HIT_SURFACE 1
2721
+ int getSurfaceRecord(
2722
+ Material material, SurfaceHit surfaceHit, sampler2DArray attributesArray,
2723
+ float accumulatedRoughness,
2724
+ inout SurfaceRecord surf
2725
+ ) {
2726
+
2727
+ if ( material.fogVolume ) {
2728
+
2729
+ vec3 normal = vec3( 0, 0, 1 );
2730
+
2731
+ SurfaceRecord fogSurface;
2732
+ fogSurface.volumeParticle = true;
2733
+ fogSurface.color = material.color;
2734
+ fogSurface.emission = material.emissiveIntensity * material.emissive;
2735
+ fogSurface.normal = normal;
2736
+ fogSurface.faceNormal = normal;
2737
+ fogSurface.clearcoatNormal = normal;
2738
+
2739
+ surf = fogSurface;
2740
+ return HIT_SURFACE;
2741
+
2742
+ }
2743
+
2744
+ // uv coord for textures
2745
+ vec2 uv = textureSampleBarycoord( attributesArray, ATTR_UV, surfaceHit.barycoord, surfaceHit.faceIndices.xyz ).xy;
2746
+ vec4 vertexColor = textureSampleBarycoord( attributesArray, ATTR_COLOR, surfaceHit.barycoord, surfaceHit.faceIndices.xyz );
2747
+
2748
+ // albedo
2749
+ vec4 albedo = vec4( material.color, material.opacity );
2750
+ if ( material.map != - 1 ) {
2751
+
2752
+ vec3 uvPrime = material.mapTransform * vec3( uv, 1 );
2753
+ albedo *= texture2D( textures, vec3( uvPrime.xy, material.map ) );
2754
+
2755
+ }
2756
+
2757
+ if ( material.vertexColors ) {
2758
+
2759
+ albedo *= vertexColor;
2760
+
2761
+ }
2762
+
2763
+ // alphaMap
2764
+ if ( material.alphaMap != - 1 ) {
2765
+
2766
+ vec3 uvPrime = material.alphaMapTransform * vec3( uv, 1 );
2767
+ albedo.a *= texture2D( textures, vec3( uvPrime.xy, material.alphaMap ) ).x;
2768
+
2769
+ }
2770
+
2771
+ // possibly skip this sample if it's transparent, alpha test is enabled, or we hit the wrong material side
2772
+ // and it's single sided.
2773
+ // - alpha test is disabled when it === 0
2774
+ // - the material sidedness test is complicated because we want light to pass through the back side but still
2775
+ // be able to see the front side. This boolean checks if the side we hit is the front side on the first ray
2776
+ // and we're rendering the other then we skip it. Do the opposite on subsequent bounces to get incoming light.
2777
+ float alphaTest = material.alphaTest;
2778
+ bool useAlphaTest = alphaTest != 0.0;
2779
+ if (
2780
+ // material sidedness
2781
+ material.side != 0.0 && surfaceHit.side != material.side
2782
+
2783
+ // alpha test
2784
+ || useAlphaTest && albedo.a < alphaTest
2785
+
2786
+ // opacity
2787
+ || material.transparent && ! useAlphaTest && albedo.a < rand( 3 )
2788
+ ) {
2789
+
2790
+ return SKIP_SURFACE;
2791
+
2792
+ }
2793
+
2794
+ // fetch the interpolated smooth normal
2795
+ vec3 normal = normalize( textureSampleBarycoord(
2796
+ attributesArray,
2797
+ ATTR_NORMAL,
2798
+ surfaceHit.barycoord,
2799
+ surfaceHit.faceIndices.xyz
2800
+ ).xyz );
2801
+
2802
+ // roughness
2803
+ float roughness = material.roughness;
2804
+ if ( material.roughnessMap != - 1 ) {
2805
+
2806
+ vec3 uvPrime = material.roughnessMapTransform * vec3( uv, 1 );
2807
+ roughness *= texture2D( textures, vec3( uvPrime.xy, material.roughnessMap ) ).g;
2808
+
2809
+ }
2810
+
2811
+ // metalness
2812
+ float metalness = material.metalness;
2813
+ if ( material.metalnessMap != - 1 ) {
2814
+
2815
+ vec3 uvPrime = material.metalnessMapTransform * vec3( uv, 1 );
2816
+ metalness *= texture2D( textures, vec3( uvPrime.xy, material.metalnessMap ) ).b;
2817
+
2818
+ }
2819
+
2820
+ // emission
2821
+ vec3 emission = material.emissiveIntensity * material.emissive;
2822
+ if ( material.emissiveMap != - 1 ) {
2823
+
2824
+ vec3 uvPrime = material.emissiveMapTransform * vec3( uv, 1 );
2825
+ emission *= texture2D( textures, vec3( uvPrime.xy, material.emissiveMap ) ).xyz;
2826
+
2827
+ }
2828
+
2829
+ // transmission
2830
+ float transmission = material.transmission;
2831
+ if ( material.transmissionMap != - 1 ) {
2832
+
2833
+ vec3 uvPrime = material.transmissionMapTransform * vec3( uv, 1 );
2834
+ transmission *= texture2D( textures, vec3( uvPrime.xy, material.transmissionMap ) ).r;
2835
+
2836
+ }
2837
+
2838
+ // normal
2839
+ if ( material.flatShading ) {
2840
+
2841
+ // if we're rendering a flat shaded object then use the face normals - the face normal
2842
+ // is provided based on the side the ray hits the mesh so flip it to align with the
2843
+ // interpolated vertex normals.
2844
+ normal = surfaceHit.faceNormal * surfaceHit.side;
2845
+
2846
+ }
2847
+
2848
+ vec3 baseNormal = normal;
2849
+ if ( material.normalMap != - 1 ) {
2850
+
2851
+ vec4 tangentSample = textureSampleBarycoord(
2852
+ attributesArray,
2853
+ ATTR_TANGENT,
2854
+ surfaceHit.barycoord,
2855
+ surfaceHit.faceIndices.xyz
2856
+ );
2857
+
2858
+ // some provided tangents can be malformed (0, 0, 0) causing the normal to be degenerate
2859
+ // resulting in NaNs and slow path tracing.
2860
+ if ( length( tangentSample.xyz ) > 0.0 ) {
2861
+
2862
+ vec3 tangent = normalize( tangentSample.xyz );
2863
+ vec3 bitangent = normalize( cross( normal, tangent ) * tangentSample.w );
2864
+ mat3 vTBN = mat3( tangent, bitangent, normal );
2865
+
2866
+ vec3 uvPrime = material.normalMapTransform * vec3( uv, 1 );
2867
+ vec3 texNormal = texture2D( textures, vec3( uvPrime.xy, material.normalMap ) ).xyz * 2.0 - 1.0;
2868
+ texNormal.xy *= material.normalScale;
2869
+ normal = vTBN * texNormal;
2870
+
2871
+ }
2872
+
2873
+ }
2874
+
2875
+ normal *= surfaceHit.side;
2876
+
2877
+ // clearcoat
2878
+ float clearcoat = material.clearcoat;
2879
+ if ( material.clearcoatMap != - 1 ) {
2880
+
2881
+ vec3 uvPrime = material.clearcoatMapTransform * vec3( uv, 1 );
2882
+ clearcoat *= texture2D( textures, vec3( uvPrime.xy, material.clearcoatMap ) ).r;
2883
+
2884
+ }
2885
+
2886
+ // clearcoatRoughness
2887
+ float clearcoatRoughness = material.clearcoatRoughness;
2888
+ if ( material.clearcoatRoughnessMap != - 1 ) {
2889
+
2890
+ vec3 uvPrime = material.clearcoatRoughnessMapTransform * vec3( uv, 1 );
2891
+ clearcoatRoughness *= texture2D( textures, vec3( uvPrime.xy, material.clearcoatRoughnessMap ) ).g;
2892
+
2893
+ }
2894
+
2895
+ // clearcoatNormal
2896
+ vec3 clearcoatNormal = baseNormal;
2897
+ if ( material.clearcoatNormalMap != - 1 ) {
2898
+
2899
+ vec4 tangentSample = textureSampleBarycoord(
2900
+ attributesArray,
2901
+ ATTR_TANGENT,
2902
+ surfaceHit.barycoord,
2903
+ surfaceHit.faceIndices.xyz
2904
+ );
2905
+
2906
+ // some provided tangents can be malformed (0, 0, 0) causing the normal to be degenerate
2907
+ // resulting in NaNs and slow path tracing.
2908
+ if ( length( tangentSample.xyz ) > 0.0 ) {
2909
+
2910
+ vec3 tangent = normalize( tangentSample.xyz );
2911
+ vec3 bitangent = normalize( cross( clearcoatNormal, tangent ) * tangentSample.w );
2912
+ mat3 vTBN = mat3( tangent, bitangent, clearcoatNormal );
2913
+
2914
+ vec3 uvPrime = material.clearcoatNormalMapTransform * vec3( uv, 1 );
2915
+ vec3 texNormal = texture2D( textures, vec3( uvPrime.xy, material.clearcoatNormalMap ) ).xyz * 2.0 - 1.0;
2916
+ texNormal.xy *= material.clearcoatNormalScale;
2917
+ clearcoatNormal = vTBN * texNormal;
2918
+
2919
+ }
2920
+
2921
+ }
2922
+
2923
+ clearcoatNormal *= surfaceHit.side;
2924
+
2925
+ // sheenColor
2926
+ vec3 sheenColor = material.sheenColor;
2927
+ if ( material.sheenColorMap != - 1 ) {
2928
+
2929
+ vec3 uvPrime = material.sheenColorMapTransform * vec3( uv, 1 );
2930
+ sheenColor *= texture2D( textures, vec3( uvPrime.xy, material.sheenColorMap ) ).rgb;
2931
+
2932
+ }
2933
+
2934
+ // sheenRoughness
2935
+ float sheenRoughness = material.sheenRoughness;
2936
+ if ( material.sheenRoughnessMap != - 1 ) {
2937
+
2938
+ vec3 uvPrime = material.sheenRoughnessMapTransform * vec3( uv, 1 );
2939
+ sheenRoughness *= texture2D( textures, vec3( uvPrime.xy, material.sheenRoughnessMap ) ).a;
2940
+
2941
+ }
2942
+
2943
+ // iridescence
2944
+ float iridescence = material.iridescence;
2945
+ if ( material.iridescenceMap != - 1 ) {
2946
+
2947
+ vec3 uvPrime = material.iridescenceMapTransform * vec3( uv, 1 );
2948
+ iridescence *= texture2D( textures, vec3( uvPrime.xy, material.iridescenceMap ) ).r;
2949
+
2950
+ }
2951
+
2952
+ // iridescence thickness
2953
+ float iridescenceThickness = material.iridescenceThicknessMaximum;
2954
+ if ( material.iridescenceThicknessMap != - 1 ) {
2955
+
2956
+ vec3 uvPrime = material.iridescenceThicknessMapTransform * vec3( uv, 1 );
2957
+ float iridescenceThicknessSampled = texture2D( textures, vec3( uvPrime.xy, material.iridescenceThicknessMap ) ).g;
2958
+ iridescenceThickness = mix( material.iridescenceThicknessMinimum, material.iridescenceThicknessMaximum, iridescenceThicknessSampled );
2959
+
2960
+ }
2961
+
2962
+ iridescence = iridescenceThickness == 0.0 ? 0.0 : iridescence;
2963
+
2964
+ // specular color
2965
+ vec3 specularColor = material.specularColor;
2966
+ if ( material.specularColorMap != - 1 ) {
2967
+
2968
+ vec3 uvPrime = material.specularColorMapTransform * vec3( uv, 1 );
2969
+ specularColor *= texture2D( textures, vec3( uvPrime.xy, material.specularColorMap ) ).rgb;
2970
+
2971
+ }
2972
+
2973
+ // specular intensity
2974
+ float specularIntensity = material.specularIntensity;
2975
+ if ( material.specularIntensityMap != - 1 ) {
2976
+
2977
+ vec3 uvPrime = material.specularIntensityMapTransform * vec3( uv, 1 );
2978
+ specularIntensity *= texture2D( textures, vec3( uvPrime.xy, material.specularIntensityMap ) ).a;
2979
+
2980
+ }
2981
+
2982
+ surf.volumeParticle = false;
2983
+
2984
+ surf.faceNormal = surfaceHit.faceNormal;
2985
+ surf.normal = normal;
2986
+
2987
+ surf.metalness = metalness;
2988
+ surf.color = albedo.rgb;
2989
+ surf.emission = emission;
2990
+
2991
+ surf.ior = material.ior;
2992
+ surf.transmission = transmission;
2993
+ surf.thinFilm = material.thinFilm;
2994
+ surf.attenuationColor = material.attenuationColor;
2995
+ surf.attenuationDistance = material.attenuationDistance;
2996
+
2997
+ surf.clearcoatNormal = clearcoatNormal;
2998
+ surf.clearcoat = clearcoat;
2999
+
3000
+ surf.sheen = material.sheen;
3001
+ surf.sheenColor = sheenColor;
3002
+
3003
+ surf.iridescence = iridescence;
3004
+ surf.iridescenceIor = material.iridescenceIor;
3005
+ surf.iridescenceThickness = iridescenceThickness;
3006
+
3007
+ surf.specularColor = specularColor;
3008
+ surf.specularIntensity = specularIntensity;
3009
+
3010
+ // apply perceptual roughness factor from gltf. sheen perceptual roughness is
3011
+ // applied by its brdf function
3012
+ // https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#microfacet-surfaces
3013
+ surf.roughness = roughness * roughness;
3014
+ surf.clearcoatRoughness = clearcoatRoughness * clearcoatRoughness;
3015
+ surf.sheenRoughness = sheenRoughness;
3016
+
3017
+ // frontFace is used to determine transmissive properties and PDF. If no transmission is used
3018
+ // then we can just always assume this is a front face.
3019
+ surf.frontFace = surfaceHit.side == 1.0 || transmission == 0.0;
3020
+ surf.eta = material.thinFilm || surf.frontFace ? 1.0 / material.ior : material.ior;
3021
+ surf.f0 = iorRatioToF0( surf.eta );
3022
+
3023
+ // Compute the filtered roughness value to use during specular reflection computations.
3024
+ // The accumulated roughness value is scaled by a user setting and a "magic value" of 5.0.
3025
+ // If we're exiting something transmissive then scale the factor down significantly so we can retain
3026
+ // sharp internal reflections
3027
+ surf.filteredRoughness = applyFilteredGlossy( surf.roughness, accumulatedRoughness );
3028
+ surf.filteredClearcoatRoughness = applyFilteredGlossy( surf.clearcoatRoughness, accumulatedRoughness );
3029
+
3030
+ // get the normal frames
3031
+ surf.normalBasis = getBasisFromNormal( surf.normal );
3032
+ surf.normalInvBasis = inverse( surf.normalBasis );
3033
+
3034
+ surf.clearcoatBasis = getBasisFromNormal( surf.clearcoatNormal );
3035
+ surf.clearcoatInvBasis = inverse( surf.clearcoatBasis );
3036
+
3037
+ return HIT_SURFACE;
3038
+
3039
+ }
3040
+ `;var Sr=`
3041
+
3042
+ struct Ray {
3043
+
3044
+ vec3 origin;
3045
+ vec3 direction;
3046
+
3047
+ };
3048
+
3049
+ struct SurfaceHit {
3050
+
3051
+ uvec4 faceIndices;
3052
+ vec3 barycoord;
3053
+ vec3 faceNormal;
3054
+ float side;
3055
+ float dist;
3056
+
3057
+ };
3058
+
3059
+ struct RenderState {
3060
+
3061
+ bool firstRay;
3062
+ bool transmissiveRay;
3063
+ bool isShadowRay;
3064
+ float accumulatedRoughness;
3065
+ int transmissiveTraversals;
3066
+ int traversals;
3067
+ uint depth;
3068
+ vec3 throughputColor;
3069
+ Material fogMaterial;
3070
+
3071
+ };
3072
+
3073
+ RenderState initRenderState() {
3074
+
3075
+ RenderState result;
3076
+ result.firstRay = true;
3077
+ result.transmissiveRay = true;
3078
+ result.isShadowRay = false;
3079
+ result.accumulatedRoughness = 0.0;
3080
+ result.transmissiveTraversals = 0;
3081
+ result.traversals = 0;
3082
+ result.throughputColor = vec3( 1.0 );
3083
+ result.depth = 0u;
3084
+ result.fogMaterial.fogVolume = false;
3085
+ return result;
3086
+
3087
+ }
3088
+
3089
+ `;var _r=`
3090
+
3091
+ #define NO_HIT 0
3092
+ #define SURFACE_HIT 1
3093
+ #define LIGHT_HIT 2
3094
+ #define FOG_HIT 3
3095
+
3096
+ // Passing the global variable 'lights' into this function caused shader program errors.
3097
+ // So global variables like 'lights' and 'bvh' were moved out of the function parameters.
3098
+ // For more information, refer to: https://github.com/gkjohnson/three-gpu-pathtracer/pull/457
3099
+ int traceScene(
3100
+ Ray ray, Material fogMaterial, inout SurfaceHit surfaceHit
3101
+ ) {
3102
+
3103
+ int result = NO_HIT;
3104
+ bool hit = bvhIntersectFirstHit( bvh, ray.origin, ray.direction, surfaceHit.faceIndices, surfaceHit.faceNormal, surfaceHit.barycoord, surfaceHit.side, surfaceHit.dist );
3105
+
3106
+ #if FEATURE_FOG
3107
+
3108
+ if ( fogMaterial.fogVolume ) {
3109
+
3110
+ // offset the distance so we don't run into issues with particles on the same surface
3111
+ // as other objects
3112
+ float particleDist = intersectFogVolume( fogMaterial, rand( 1 ) );
3113
+ if ( particleDist + RAY_OFFSET < surfaceHit.dist ) {
3114
+
3115
+ surfaceHit.side = 1.0;
3116
+ surfaceHit.faceNormal = normalize( - ray.direction );
3117
+ surfaceHit.dist = particleDist;
3118
+ return FOG_HIT;
3119
+
3120
+ }
3121
+
3122
+ }
3123
+
3124
+ #endif
3125
+
3126
+ if ( hit ) {
3127
+
3128
+ result = SURFACE_HIT;
3129
+
3130
+ }
3131
+
3132
+ return result;
3133
+
3134
+ }
3135
+
3136
+ `;var Fe=class extends _{static{a(this,"PhysicalPathTracingMaterial");}onBeforeRender(){this.setDefine("FEATURE_DOF",this.physicalCamera.bokehSize===0?0:1),this.setDefine("FEATURE_BACKGROUND_MAP",this.backgroundMap?1:0),this.setDefine("FEATURE_FOG",this.materials.features.isUsed("FOG")?1:0);}constructor(e$1){super({transparent:true,depthWrite:false,defines:{FEATURE_MIS:1,FEATURE_RUSSIAN_ROULETTE:1,FEATURE_DOF:1,FEATURE_BACKGROUND_MAP:0,FEATURE_FOG:1,RANDOM_TYPE:2,CAMERA_TYPE:0,DEBUG_MODE:0,ATTR_NORMAL:0,ATTR_TANGENT:1,ATTR_UV:2,ATTR_COLOR:3,MATERIAL_PIXELS:Te},uniforms:{resolution:{value:new Vector2},opacity:{value:1},bounces:{value:10},transmissiveBounces:{value:10},filterGlossyFactor:{value:0},physicalCamera:{value:new me},cameraWorldMatrix:{value:new Matrix4},invProjectionMatrix:{value:new Matrix4},bvh:{value:new d},attributesArray:{value:new xe},materialIndexAttribute:{value:new b},materials:{value:new ye},textures:{value:new j().texture},lights:{value:new ge},iesProfiles:{value:new j(360,180,{type:HalfFloatType,wrapS:ClampToEdgeWrapping,wrapT:ClampToEdgeWrapping}).texture},environmentIntensity:{value:1},environmentRotation:{value:new Matrix4},envMapInfo:{value:new pe},backgroundBlur:{value:0},backgroundMap:{value:null},backgroundAlpha:{value:1},backgroundIntensity:{value:1},backgroundRotation:{value:new Matrix4},seed:{value:0},sobolTexture:{value:null},stratifiedTexture:{value:new _e},stratifiedOffsetTexture:{value:new Ie(64,1)}},vertexShader:`
3137
+
3138
+ varying vec2 vUv;
3139
+ void main() {
3140
+
3141
+ vec4 mvPosition = vec4( position, 1.0 );
3142
+ mvPosition = modelViewMatrix * mvPosition;
3143
+ gl_Position = projectionMatrix * mvPosition;
3144
+
3145
+ vUv = uv;
3146
+
3147
+ }
3148
+
3149
+ `,fragmentShader:`
3150
+ #define RAY_OFFSET 1e-4
3151
+ #define INFINITY 1e20
3152
+
3153
+ precision highp isampler2D;
3154
+ precision highp usampler2D;
3155
+ precision highp sampler2DArray;
3156
+ vec4 envMapTexelToLinear( vec4 a ) { return a; }
3157
+ #include <common>
3158
+
3159
+ // bvh intersection
3160
+ ${e.common_functions}
3161
+ ${e.bvh_struct_definitions}
3162
+ ${e.bvh_ray_functions}
3163
+
3164
+ // uniform structs
3165
+ ${er}
3166
+ ${rr}
3167
+ ${tr}
3168
+ ${ar}
3169
+ ${ir}
3170
+
3171
+ // random
3172
+ #if RANDOM_TYPE == 2 // Stratified List
3173
+
3174
+ ${hr}
3175
+
3176
+ #elif RANDOM_TYPE == 1 // Sobol
3177
+
3178
+ ${Ze}
3179
+ ${ue}
3180
+ ${Pt}
3181
+
3182
+ #define rand(v) sobol(v)
3183
+ #define rand2(v) sobol2(v)
3184
+ #define rand3(v) sobol3(v)
3185
+ #define rand4(v) sobol4(v)
3186
+
3187
+ #else // PCG
3188
+
3189
+ ${Ze}
3190
+
3191
+ // Using the sobol functions seems to break the the compiler on MacOS
3192
+ // - specifically the "sobolReverseBits" function.
3193
+ uint sobolPixelIndex = 0u;
3194
+ uint sobolPathIndex = 0u;
3195
+ uint sobolBounceIndex = 0u;
3196
+
3197
+ #define rand(v) pcgRand()
3198
+ #define rand2(v) pcgRand2()
3199
+ #define rand3(v) pcgRand3()
3200
+ #define rand4(v) pcgRand4()
3201
+
3202
+ #endif
3203
+
3204
+ // common
3205
+ ${fr}
3206
+ ${lr}
3207
+ ${N}
3208
+ ${cr}
3209
+ ${ur}
3210
+
3211
+ // environment
3212
+ uniform EquirectHdrInfo envMapInfo;
3213
+ uniform mat4 environmentRotation;
3214
+ uniform float environmentIntensity;
3215
+
3216
+ // lighting
3217
+ uniform sampler2DArray iesProfiles;
3218
+ uniform LightsInfo lights;
3219
+
3220
+ // background
3221
+ uniform float backgroundBlur;
3222
+ uniform float backgroundAlpha;
3223
+ #if FEATURE_BACKGROUND_MAP
3224
+
3225
+ uniform sampler2D backgroundMap;
3226
+ uniform mat4 backgroundRotation;
3227
+ uniform float backgroundIntensity;
3228
+
3229
+ #endif
3230
+
3231
+ // camera
3232
+ uniform mat4 cameraWorldMatrix;
3233
+ uniform mat4 invProjectionMatrix;
3234
+ #if FEATURE_DOF
3235
+
3236
+ uniform PhysicalCamera physicalCamera;
3237
+
3238
+ #endif
3239
+
3240
+ // geometry
3241
+ uniform sampler2DArray attributesArray;
3242
+ uniform usampler2D materialIndexAttribute;
3243
+ uniform sampler2D materials;
3244
+ uniform sampler2DArray textures;
3245
+ uniform BVH bvh;
3246
+
3247
+ // path tracer
3248
+ uniform int bounces;
3249
+ uniform int transmissiveBounces;
3250
+ uniform float filterGlossyFactor;
3251
+ uniform int seed;
3252
+
3253
+ // image
3254
+ uniform vec2 resolution;
3255
+ uniform float opacity;
3256
+
3257
+ varying vec2 vUv;
3258
+
3259
+ // globals
3260
+ mat3 envRotation3x3;
3261
+ mat3 invEnvRotation3x3;
3262
+ float lightsDenom;
3263
+
3264
+ // sampling
3265
+ ${nr}
3266
+ ${or}
3267
+ ${sr}
3268
+
3269
+ ${xr}
3270
+ ${pr}
3271
+ ${vr}
3272
+ ${gr}
3273
+ ${dr}
3274
+ ${mr}
3275
+
3276
+ float applyFilteredGlossy( float roughness, float accumulatedRoughness ) {
3277
+
3278
+ return clamp(
3279
+ max(
3280
+ roughness,
3281
+ accumulatedRoughness * filterGlossyFactor * 5.0 ),
3282
+ 0.0,
3283
+ 1.0
3284
+ );
3285
+
3286
+ }
3287
+
3288
+ vec3 sampleBackground( vec3 direction, vec2 uv ) {
3289
+
3290
+ vec3 sampleDir = sampleHemisphere( direction, uv ) * 0.5 * backgroundBlur;
3291
+
3292
+ #if FEATURE_BACKGROUND_MAP
3293
+
3294
+ sampleDir = normalize( mat3( backgroundRotation ) * direction + sampleDir );
3295
+ return backgroundIntensity * sampleEquirectColor( backgroundMap, sampleDir );
3296
+
3297
+ #else
3298
+
3299
+ sampleDir = normalize( envRotation3x3 * direction + sampleDir );
3300
+ return environmentIntensity * sampleEquirectColor( envMapInfo.map, sampleDir );
3301
+
3302
+ #endif
3303
+
3304
+ }
3305
+
3306
+ ${Sr}
3307
+ ${yr}
3308
+ ${_r}
3309
+ ${br}
3310
+ ${Tr}
3311
+ ${wr}
3312
+
3313
+ void main() {
3314
+
3315
+ // init
3316
+ rng_initialize( gl_FragCoord.xy, seed );
3317
+ sobolPixelIndex = ( uint( gl_FragCoord.x ) << 16 ) | uint( gl_FragCoord.y );
3318
+ sobolPathIndex = uint( seed );
3319
+
3320
+ // get camera ray
3321
+ Ray ray = getCameraRay();
3322
+
3323
+ // inverse environment rotation
3324
+ envRotation3x3 = mat3( environmentRotation );
3325
+ invEnvRotation3x3 = inverse( envRotation3x3 );
3326
+ lightsDenom =
3327
+ ( environmentIntensity == 0.0 || envMapInfo.totalSum == 0.0 ) && lights.count != 0u ?
3328
+ float( lights.count ) :
3329
+ float( lights.count + 1u );
3330
+
3331
+ // final color
3332
+ gl_FragColor = vec4( 0, 0, 0, 1 );
3333
+
3334
+ // surface results
3335
+ SurfaceHit surfaceHit;
3336
+ ScatterRecord scatterRec;
3337
+
3338
+ // path tracing state
3339
+ RenderState state = initRenderState();
3340
+ state.transmissiveTraversals = transmissiveBounces;
3341
+ #if FEATURE_FOG
3342
+
3343
+ state.fogMaterial.fogVolume = bvhIntersectFogVolumeHit(
3344
+ ray.origin, - ray.direction,
3345
+ materialIndexAttribute, materials,
3346
+ state.fogMaterial
3347
+ );
3348
+
3349
+ #endif
3350
+
3351
+ for ( int i = 0; i < bounces; i ++ ) {
3352
+
3353
+ sobolBounceIndex ++;
3354
+
3355
+ state.depth ++;
3356
+ state.traversals = bounces - i;
3357
+ state.firstRay = i == 0 && state.transmissiveTraversals == transmissiveBounces;
3358
+
3359
+ int hitType = traceScene( ray, state.fogMaterial, surfaceHit );
3360
+
3361
+ // check if we intersect any lights and accumulate the light contribution
3362
+ // TODO: we can add support for light surface rendering in the else condition if we
3363
+ // add the ability to toggle visibility of the the light
3364
+ if ( ! state.firstRay && ! state.transmissiveRay ) {
3365
+
3366
+ LightRecord lightRec;
3367
+ float lightDist = hitType == NO_HIT ? INFINITY : surfaceHit.dist;
3368
+ for ( uint i = 0u; i < lights.count; i ++ ) {
3369
+
3370
+ if (
3371
+ intersectLightAtIndex( lights.tex, ray.origin, ray.direction, i, lightRec ) &&
3372
+ lightRec.dist < lightDist
3373
+ ) {
3374
+
3375
+ #if FEATURE_MIS
3376
+
3377
+ // weight the contribution
3378
+ // NOTE: Only area lights are supported for forward sampling and can be hit
3379
+ float misWeight = misHeuristic( scatterRec.pdf, lightRec.pdf / lightsDenom );
3380
+ gl_FragColor.rgb += lightRec.emission * state.throughputColor * misWeight;
3381
+
3382
+ #else
3383
+
3384
+ gl_FragColor.rgb += lightRec.emission * state.throughputColor;
3385
+
3386
+ #endif
3387
+
3388
+ }
3389
+
3390
+ }
3391
+
3392
+ }
3393
+
3394
+ if ( hitType == NO_HIT ) {
3395
+
3396
+ if ( state.firstRay || state.transmissiveRay ) {
3397
+
3398
+ gl_FragColor.rgb += sampleBackground( ray.direction, rand2( 2 ) ) * state.throughputColor;
3399
+ gl_FragColor.a = backgroundAlpha;
3400
+
3401
+ } else {
3402
+
3403
+ #if FEATURE_MIS
3404
+
3405
+ // get the PDF of the hit envmap point
3406
+ vec3 envColor;
3407
+ float envPdf = sampleEquirect( envRotation3x3 * ray.direction, envColor );
3408
+ envPdf /= lightsDenom;
3409
+
3410
+ // and weight the contribution
3411
+ float misWeight = misHeuristic( scatterRec.pdf, envPdf );
3412
+ gl_FragColor.rgb += environmentIntensity * envColor * state.throughputColor * misWeight;
3413
+
3414
+ #else
3415
+
3416
+ gl_FragColor.rgb +=
3417
+ environmentIntensity *
3418
+ sampleEquirectColor( envMapInfo.map, envRotation3x3 * ray.direction ) *
3419
+ state.throughputColor;
3420
+
3421
+ #endif
3422
+
3423
+ }
3424
+ break;
3425
+
3426
+ }
3427
+
3428
+ uint materialIndex = uTexelFetch1D( materialIndexAttribute, surfaceHit.faceIndices.x ).r;
3429
+ Material material = readMaterialInfo( materials, materialIndex );
3430
+
3431
+ #if FEATURE_FOG
3432
+
3433
+ if ( hitType == FOG_HIT ) {
3434
+
3435
+ material = state.fogMaterial;
3436
+ state.accumulatedRoughness += 0.2;
3437
+
3438
+ } else if ( material.fogVolume ) {
3439
+
3440
+ state.fogMaterial = material;
3441
+ state.fogMaterial.fogVolume = surfaceHit.side == 1.0;
3442
+
3443
+ ray.origin = stepRayOrigin( ray.origin, ray.direction, - surfaceHit.faceNormal, surfaceHit.dist );
3444
+
3445
+ i -= sign( state.transmissiveTraversals );
3446
+ state.transmissiveTraversals -= sign( state.transmissiveTraversals );
3447
+ continue;
3448
+
3449
+ }
3450
+
3451
+ #endif
3452
+
3453
+ // early out if this is a matte material
3454
+ if ( material.matte && state.firstRay ) {
3455
+
3456
+ gl_FragColor = vec4( 0.0 );
3457
+ break;
3458
+
3459
+ }
3460
+
3461
+ // if we've determined that this is a shadow ray and we've hit an item with no shadow casting
3462
+ // then skip it
3463
+ if ( ! material.castShadow && state.isShadowRay ) {
3464
+
3465
+ ray.origin = stepRayOrigin( ray.origin, ray.direction, - surfaceHit.faceNormal, surfaceHit.dist );
3466
+ continue;
3467
+
3468
+ }
3469
+
3470
+ SurfaceRecord surf;
3471
+ if (
3472
+ getSurfaceRecord(
3473
+ material, surfaceHit, attributesArray, state.accumulatedRoughness,
3474
+ surf
3475
+ ) == SKIP_SURFACE
3476
+ ) {
3477
+
3478
+ // only allow a limited number of transparency discards otherwise we could
3479
+ // crash the context with too long a loop.
3480
+ i -= sign( state.transmissiveTraversals );
3481
+ state.transmissiveTraversals -= sign( state.transmissiveTraversals );
3482
+
3483
+ ray.origin = stepRayOrigin( ray.origin, ray.direction, - surfaceHit.faceNormal, surfaceHit.dist );
3484
+ continue;
3485
+
3486
+ }
3487
+
3488
+ scatterRec = bsdfSample( - ray.direction, surf );
3489
+ state.isShadowRay = scatterRec.specularPdf < rand( 4 );
3490
+
3491
+ bool isBelowSurface = ! surf.volumeParticle && dot( scatterRec.direction, surf.faceNormal ) < 0.0;
3492
+ vec3 hitPoint = stepRayOrigin( ray.origin, ray.direction, isBelowSurface ? - surf.faceNormal : surf.faceNormal, surfaceHit.dist );
3493
+
3494
+ // next event estimation
3495
+ #if FEATURE_MIS
3496
+
3497
+ gl_FragColor.rgb += directLightContribution( - ray.direction, surf, state, hitPoint );
3498
+
3499
+ #endif
3500
+
3501
+ // accumulate a roughness value to offset diffuse, specular, diffuse rays that have high contribution
3502
+ // to a single pixel resulting in fireflies
3503
+ // TODO: handle transmissive surfaces
3504
+ if ( ! surf.volumeParticle && ! isBelowSurface ) {
3505
+
3506
+ // determine if this is a rough normal or not by checking how far off straight up it is
3507
+ vec3 halfVector = normalize( - ray.direction + scatterRec.direction );
3508
+ state.accumulatedRoughness += max(
3509
+ sin( acosApprox( dot( halfVector, surf.normal ) ) ),
3510
+ sin( acosApprox( dot( halfVector, surf.clearcoatNormal ) ) )
3511
+ );
3512
+
3513
+ state.transmissiveRay = false;
3514
+
3515
+ }
3516
+
3517
+ // accumulate emissive color
3518
+ gl_FragColor.rgb += ( surf.emission * state.throughputColor );
3519
+
3520
+ // skip the sample if our PDF or ray is impossible
3521
+ if ( scatterRec.pdf <= 0.0 || ! isDirectionValid( scatterRec.direction, surf.normal, surf.faceNormal ) ) {
3522
+
3523
+ break;
3524
+
3525
+ }
3526
+
3527
+ // if we're bouncing around the inside a transmissive material then decrement
3528
+ // perform this separate from a bounce
3529
+ bool isTransmissiveRay = ! surf.volumeParticle && dot( scatterRec.direction, surf.faceNormal * surfaceHit.side ) < 0.0;
3530
+ if ( ( isTransmissiveRay || isBelowSurface ) && state.transmissiveTraversals > 0 ) {
3531
+
3532
+ state.transmissiveTraversals --;
3533
+ i --;
3534
+
3535
+ }
3536
+
3537
+ //
3538
+
3539
+ // handle throughput color transformation
3540
+ // attenuate the throughput color by the medium color
3541
+ if ( ! surf.frontFace ) {
3542
+
3543
+ state.throughputColor *= transmissionAttenuation( surfaceHit.dist, surf.attenuationColor, surf.attenuationDistance );
3544
+
3545
+ }
3546
+
3547
+ #if FEATURE_RUSSIAN_ROULETTE
3548
+
3549
+ // russian roulette path termination
3550
+ // https://www.arnoldrenderer.com/research/physically_based_shader_design_in_arnold.pdf
3551
+ uint minBounces = 3u;
3552
+ float depthProb = float( state.depth < minBounces );
3553
+
3554
+ float rrProb = luminance( state.throughputColor * scatterRec.color / scatterRec.pdf );
3555
+ rrProb /= luminance( state.throughputColor );
3556
+ rrProb = sqrt( rrProb );
3557
+ rrProb = max( rrProb, depthProb );
3558
+ rrProb = min( rrProb, 1.0 );
3559
+ if ( rand( 8 ) > rrProb ) {
3560
+
3561
+ break;
3562
+
3563
+ }
3564
+
3565
+ // perform sample clamping here to avoid bright pixels
3566
+ state.throughputColor *= min( 1.0 / rrProb, 20.0 );
3567
+
3568
+ #endif
3569
+
3570
+ // adjust the throughput and discard and exit if we find discard the sample if there are any NaNs
3571
+ state.throughputColor *= scatterRec.color / scatterRec.pdf;
3572
+ if ( any( isnan( state.throughputColor ) ) || any( isinf( state.throughputColor ) ) ) {
3573
+
3574
+ break;
3575
+
3576
+ }
3577
+
3578
+ //
3579
+
3580
+ // prepare for next ray
3581
+ ray.direction = scatterRec.direction;
3582
+ ray.origin = hitPoint;
3583
+
3584
+ }
3585
+
3586
+ gl_FragColor.a *= opacity;
3587
+
3588
+ #if DEBUG_MODE == 1
3589
+
3590
+ // output the number of rays checked in the path and number of
3591
+ // transmissive rays encountered.
3592
+ gl_FragColor.rgb = vec3(
3593
+ float( state.depth ),
3594
+ transmissiveBounces - state.transmissiveTraversals,
3595
+ 0.0
3596
+ );
3597
+ gl_FragColor.a = 1.0;
3598
+
3599
+ #endif
3600
+
3601
+ }
3602
+
3603
+ `}),this.setValues(e$1);}};function*Si(){let{_renderer:i,_fsQuad:e,_blendQuad:t,_primaryTarget:a,_blendTargets:o,_sobolTarget:s,_subframe:r,alpha:l,material:f}=this,d=new Vector4,m=new Vector4,u=t.material,[n,x]=o;for(;;){l?(u.opacity=this._opacityFactor/(this.samples+1),f.blending=NoBlending,f.opacity=1):(f.opacity=this._opacityFactor/(this.samples+1),f.blending=NormalBlending);let[p,g,c,b]=r,v=a.width,y=a.height;f.resolution.set(v*c,y*b),f.sobolTexture=s.texture,f.stratifiedTexture.init(20,f.bounces+f.transmissiveBounces+5),f.stratifiedTexture.next(),f.seed++;let T=this.tiles.x||1,w=this.tiles.y||1,I=T*w,M=Math.ceil(v*c),ke=Math.ceil(y*b),ot=Math.floor(p*v),st=Math.floor(g*y),Le=Math.ceil(M/T),Oe=Math.ceil(ke/w);for(let K=0;K<w;K++)for(let Z=0;Z<T;Z++){let nt=i.getRenderTarget(),qr=i.autoClear,$r=i.getScissorTest();i.getScissor(d),i.getViewport(m);let ze=Z,lt=K;if(!this.stableTiles){let Be=this._currentTile%(T*w);ze=Be%T,lt=~~(Be/T),this._currentTile=Be+1;}let ct=w-lt-1;a.scissor.set(ot+ze*Le,st+ct*Oe,Math.min(Le,M-ze*Le),Math.min(Oe,ke-ct*Oe)),a.viewport.set(ot,st,M,ke),i.setRenderTarget(a),i.setScissorTest(true),i.autoClear=false,e.render(i),i.setViewport(m),i.setScissor(d),i.setScissorTest($r),i.setRenderTarget(nt),i.autoClear=qr,l&&(u.target1=n.texture,u.target2=a.texture,i.setRenderTarget(x),t.render(i),i.setRenderTarget(nt)),this.samples+=1/I,Z===T-1&&K===w-1&&(this.samples=Math.round(this.samples)),yield;}[n,x]=[x,n];}}a(Si,"renderTask");var Fr=new Color,Q=class{static{a(this,"PathTracingRenderer");}get material(){return this._fsQuad.material}set material(e){this._fsQuad.material.removeEventListener("recompilation",this._compileFunction),e.addEventListener("recompilation",this._compileFunction),this._fsQuad.material=e;}get target(){return this._alpha?this._blendTargets[1]:this._primaryTarget}set alpha(e){this._alpha!==e&&(e||(this._blendTargets[0].dispose(),this._blendTargets[1].dispose()),this._alpha=e,this.reset());}get alpha(){return this._alpha}get isCompiling(){return !!this._compilePromise}constructor(e){this.camera=null,this.tiles=new Vector2(3,3),this.stableNoise=false,this.stableTiles=true,this.samples=0,this._subframe=new Vector4(0,0,1,1),this._opacityFactor=1,this._renderer=e,this._alpha=false,this._fsQuad=new FullScreenQuad(new Fe),this._blendQuad=new FullScreenQuad(new ne),this._task=null,this._currentTile=0,this._compilePromise=null,this._sobolTarget=new fe().generate(e),this._primaryTarget=new WebGLRenderTarget(1,1,{format:RGBAFormat,type:FloatType,magFilter:NearestFilter,minFilter:NearestFilter}),this._blendTargets=[new WebGLRenderTarget(1,1,{format:RGBAFormat,type:FloatType,magFilter:NearestFilter,minFilter:NearestFilter}),new WebGLRenderTarget(1,1,{format:RGBAFormat,type:FloatType,magFilter:NearestFilter,minFilter:NearestFilter})],this._compileFunction=()=>{let t=this.compileMaterial(this._fsQuad._mesh);t.then(()=>{this._compilePromise===t&&(this._compilePromise=null);}),this._compilePromise=t;},this.material.addEventListener("recompilation",this._compileFunction);}compileMaterial(){return this._renderer.compileAsync(this._fsQuad._mesh)}setCamera(e){let{material:t}=this;t.cameraWorldMatrix.copy(e.matrixWorld),t.invProjectionMatrix.copy(e.projectionMatrixInverse),t.physicalCamera.updateFrom(e);let a=0;e.projectionMatrix.elements[15]>0&&(a=1),e.isEquirectCamera&&(a=2),t.setDefine("CAMERA_TYPE",a),this.camera=e;}setSize(e,t){e=Math.ceil(e),t=Math.ceil(t),!(this._primaryTarget.width===e&&this._primaryTarget.height===t)&&(this._primaryTarget.setSize(e,t),this._blendTargets[0].setSize(e,t),this._blendTargets[1].setSize(e,t),this.reset());}getSize(e){e.x=this._primaryTarget.width,e.y=this._primaryTarget.height;}dispose(){this._primaryTarget.dispose(),this._blendTargets[0].dispose(),this._blendTargets[1].dispose(),this._sobolTarget.dispose(),this._fsQuad.dispose(),this._blendQuad.dispose(),this._task=null;}reset(){let{_renderer:e,_primaryTarget:t,_blendTargets:a}=this,o=e.getRenderTarget(),s=e.getClearAlpha();e.getClearColor(Fr),e.setRenderTarget(t),e.setClearColor(0,0),e.clearColor(),e.setRenderTarget(a[0]),e.setClearColor(0,0),e.clearColor(),e.setRenderTarget(a[1]),e.setClearColor(0,0),e.clearColor(),e.setClearColor(Fr,s),e.setRenderTarget(o),this.samples=0,this._task=null,this.material.stratifiedTexture.stableNoise=this.stableNoise,this.stableNoise&&(this.material.seed=0,this.material.stratifiedTexture.reset());}update(){this.material.onBeforeRender(),!this.isCompiling&&(this._task||(this._task=Si.call(this)),this._task.next());}};var L=new Vector2,Ar=new Vector2,Ce=new Spherical,Ae=new Color,Pe=class extends DataTexture{static{a(this,"ProceduralEquirectTexture");}constructor(e=512,t=512){super(new Float32Array(e*t*4),e,t,RGBAFormat,FloatType,EquirectangularReflectionMapping,RepeatWrapping,ClampToEdgeWrapping,LinearFilter,LinearFilter),this.generationCallback=null;}update(){this.dispose(),this.needsUpdate=true;let{data:e,width:t,height:a}=this.image;for(let o=0;o<t;o++)for(let s=0;s<a;s++){Ar.set(t,a),L.set(o/t,s/a),L.x-=.5,L.y=1-L.y,Ce.theta=L.x*2*Math.PI,Ce.phi=L.y*Math.PI,Ce.radius=1,this.generationCallback(Ce,L,Ar,Ae);let l=4*(s*t+o);e[l+0]=Ae.r,e[l+1]=Ae.g,e[l+2]=Ae.b,e[l+3]=1;}}copy(e){return super.copy(e),this.generationCallback=e.generationCallback,this}};var Er=new Vector3,De=class extends Pe{static{a(this,"GradientEquirectTexture");}constructor(e=512){super(e,e),this.topColor=new Color().set(16777215),this.bottomColor=new Color().set(0),this.exponent=2,this.generationCallback=(t,a,o,s)=>{Er.setFromSpherical(t);let r=Er.y*.5+.5;s.lerpColors(this.bottomColor,this.topColor,r**this.exponent);};}copy(e){return super.copy(e),this.topColor.copy(e.topColor),this.bottomColor.copy(e.bottomColor),this}};var Ee=class extends ShaderMaterial{static{a(this,"ClampedInterpolationMaterial");}get map(){return this.uniforms.map.value}set map(e){this.uniforms.map.value=e;}get opacity(){return this.uniforms.opacity.value}set opacity(e){this.uniforms&&(this.uniforms.opacity.value=e);}constructor(e){super({uniforms:{map:{value:null},opacity:{value:1}},vertexShader:`
3604
+ varying vec2 vUv;
3605
+ void main() {
3606
+
3607
+ vUv = uv;
3608
+ gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
3609
+
3610
+ }
3611
+ `,fragmentShader:`
3612
+ uniform sampler2D map;
3613
+ uniform float opacity;
3614
+ varying vec2 vUv;
3615
+
3616
+ vec4 clampedTexelFatch( sampler2D map, ivec2 px, int lod ) {
3617
+
3618
+ vec4 res = texelFetch( map, ivec2( px.x, px.y ), 0 );
3619
+
3620
+ #if defined( TONE_MAPPING )
3621
+
3622
+ res.xyz = toneMapping( res.xyz );
3623
+
3624
+ #endif
3625
+
3626
+ return linearToOutputTexel( res );
3627
+
3628
+ }
3629
+
3630
+ void main() {
3631
+
3632
+ vec2 size = vec2( textureSize( map, 0 ) );
3633
+ vec2 pxUv = vUv * size;
3634
+ vec2 pxCurr = floor( pxUv );
3635
+ vec2 pxFrac = fract( pxUv ) - 0.5;
3636
+ vec2 pxOffset;
3637
+ pxOffset.x = pxFrac.x > 0.0 ? 1.0 : - 1.0;
3638
+ pxOffset.y = pxFrac.y > 0.0 ? 1.0 : - 1.0;
3639
+
3640
+ vec2 pxNext = clamp( pxOffset + pxCurr, vec2( 0.0 ), size - 1.0 );
3641
+ vec2 alpha = abs( pxFrac );
3642
+
3643
+ vec4 p1 = mix(
3644
+ clampedTexelFatch( map, ivec2( pxCurr.x, pxCurr.y ), 0 ),
3645
+ clampedTexelFatch( map, ivec2( pxNext.x, pxCurr.y ), 0 ),
3646
+ alpha.x
3647
+ );
3648
+
3649
+ vec4 p2 = mix(
3650
+ clampedTexelFatch( map, ivec2( pxCurr.x, pxNext.y ), 0 ),
3651
+ clampedTexelFatch( map, ivec2( pxNext.x, pxNext.y ), 0 ),
3652
+ alpha.x
3653
+ );
3654
+
3655
+ gl_FragColor = mix( p1, p2, alpha.y );
3656
+ gl_FragColor.a *= opacity;
3657
+ #include <premultiplied_alpha_fragment>
3658
+
3659
+ }
3660
+ `}),this.setValues(e);}};var at=class extends ShaderMaterial{static{a(this,"CubeToEquirectMaterial");}constructor(){super({uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:`
3661
+ varying vec2 vUv;
3662
+ void main() {
3663
+
3664
+ vUv = uv;
3665
+ gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
3666
+
3667
+ }`,fragmentShader:`
3668
+ #define ENVMAP_TYPE_CUBE_UV
3669
+
3670
+ uniform samplerCube envMap;
3671
+ uniform float flipEnvMap;
3672
+ varying vec2 vUv;
3673
+
3674
+ #include <common>
3675
+ #include <cube_uv_reflection_fragment>
3676
+
3677
+ ${N}
3678
+
3679
+ void main() {
3680
+
3681
+ vec3 rayDirection = equirectUvToDirection( vUv );
3682
+ rayDirection.x *= flipEnvMap;
3683
+ gl_FragColor = textureCube( envMap, rayDirection );
3684
+
3685
+ }`}),this.depthWrite=false,this.depthTest=false;}},X=class{static{a(this,"CubeToEquirectGenerator");}constructor(e){this._renderer=e,this._quad=new FullScreenQuad(new at);}generate(e,t=null,a=null){if(!e.isCubeTexture)throw new Error("CubeToEquirectMaterial: Source can only be cube textures.");let o=e.images[0],s=this._renderer,r=this._quad;t===null&&(t=4*o.height),a===null&&(a=2*o.height);let l=new WebGLRenderTarget(t,a,{type:FloatType,colorSpace:o.colorSpace}),f=o.height,d=Math.log2(f)-2,m=1/f,u=1/(3*Math.max(Math.pow(2,d),112));r.material.defines.CUBEUV_MAX_MIP=`${d}.0`,r.material.defines.CUBEUV_TEXEL_WIDTH=u,r.material.defines.CUBEUV_TEXEL_HEIGHT=m,r.material.uniforms.envMap.value=e,r.material.uniforms.flipEnvMap.value=e.isRenderTargetTexture?1:-1,r.material.needsUpdate=true;let n=s.getRenderTarget(),x=s.autoClear;s.autoClear=true,s.setRenderTarget(l),r.render(s),s.setRenderTarget(n),s.autoClear=x;let p=new Uint16Array(t*a*4),g=new Float32Array(t*a*4);s.readRenderTargetPixels(l,0,0,t,a,g),l.dispose();for(let b=0,v=g.length;b<v;b++)p[b]=DataUtils.toHalfFloat(g[b]);let c=new DataTexture(p,t,a,RGBAFormat,HalfFloatType);return c.minFilter=LinearMipMapLinearFilter,c.magFilter=LinearFilter,c.wrapS=RepeatWrapping,c.wrapT=RepeatWrapping,c.mapping=EquirectangularReflectionMapping,c.needsUpdate=true,c}dispose(){this._quad.dispose();}};function Ki(i){return i.extensions.get("EXT_float_blend")}a(Ki,"supportsFloatBlending");var U=new Vector2,Or=class{static{a(this,"WebGLPathTracer");}get multipleImportanceSampling(){return !!this._pathTracer.material.defines.FEATURE_MIS}set multipleImportanceSampling(e){this._pathTracer.material.setDefine("FEATURE_MIS",e?1:0);}get transmissiveBounces(){return this._pathTracer.material.transmissiveBounces}set transmissiveBounces(e){this._pathTracer.material.transmissiveBounces=e;}get bounces(){return this._pathTracer.material.bounces}set bounces(e){this._pathTracer.material.bounces=e;}get filterGlossyFactor(){return this._pathTracer.material.filterGlossyFactor}set filterGlossyFactor(e){this._pathTracer.material.filterGlossyFactor=e;}get samples(){return this._pathTracer.samples}get target(){return this._pathTracer.target}get tiles(){return this._pathTracer.tiles}get stableNoise(){return this._pathTracer.stableNoise}set stableNoise(e){this._pathTracer.stableNoise=e;}get isCompiling(){return !!this._pathTracer.isCompiling}constructor(e){this._renderer=e,this._generator=new z,this._pathTracer=new Q(e),this._queueReset=false,this._clock=new Clock,this._compilePromise=null,this._lowResPathTracer=new Q(e),this._lowResPathTracer.tiles.set(1,1),this._quad=new FullScreenQuad(new Ee({map:null,transparent:true,blending:NoBlending,premultipliedAlpha:e.getContextAttributes().premultipliedAlpha})),this._materials=null,this._previousEnvironment=null,this._previousBackground=null,this._internalBackground=null,this.renderDelay=100,this.minSamples=5,this.fadeDuration=500,this.enablePathTracing=true,this.pausePathTracing=false,this.dynamicLowRes=false,this.lowResScale=.25,this.renderScale=1,this.synchronizeRenderSize=true,this.rasterizeScene=true,this.renderToCanvas=true,this.textureSize=new Vector2(1024,1024),this.rasterizeSceneCallback=(t,a)=>{this._renderer.render(t,a);},this.renderToCanvasCallback=(t,a,o)=>{let s=a.autoClear;a.autoClear=false,o.render(a),a.autoClear=s;},this.setScene(new Scene,new PerspectiveCamera);}setBVHWorker(e){this._generator.setBVHWorker(e);}setScene(e,t,a={}){e.updateMatrixWorld(true),t.updateMatrixWorld();let o=this._generator;if(o.setObjects(e),this._buildAsync)return o.generateAsync(a.onProgress).then(s=>this._updateFromResults(e,t,s));{let s=o.generate();return this._updateFromResults(e,t,s)}}setSceneAsync(...e){this._buildAsync=true;let t=this.setScene(...e);return this._buildAsync=false,t}setCamera(e){this.camera=e,this.updateCamera();}updateCamera(){let e=this.camera;e.updateMatrixWorld(),this._pathTracer.setCamera(e),this._lowResPathTracer.setCamera(e),this.reset();}updateMaterials(){let e=this._pathTracer.material,t=this._renderer,a=this._materials,o=this.textureSize,s=Nt(a);e.textures.setTextures(t,s,o.x,o.y),e.materials.updateFrom(a,s),this.reset();}updateLights(){let e=this.scene,t=this._renderer,a=this._pathTracer.material,o=Gt(e),s=Ht(o);a.lights.updateFrom(o,s),a.iesProfiles.setTextures(t,s),this.reset();}updateEnvironment(){let e=this.scene,t=this._pathTracer.material;if(this._internalBackground&&(this._internalBackground.dispose(),this._internalBackground=null),t.backgroundBlur=e.backgroundBlurriness,t.backgroundIntensity=e.backgroundIntensity??1,t.backgroundRotation.makeRotationFromEuler(e.backgroundRotation).invert(),e.background===null)t.backgroundMap=null,t.backgroundAlpha=0;else if(e.background.isColor){this._colorBackground=this._colorBackground||new De(16);let a=this._colorBackground;a.topColor.equals(e.background)||(a.topColor.set(e.background),a.bottomColor.set(e.background),a.update()),t.backgroundMap=a,t.backgroundAlpha=1;}else if(e.background.isCubeTexture){if(e.background!==this._previousBackground){let a=new X(this._renderer).generate(e.background);this._internalBackground=a,t.backgroundMap=a,t.backgroundAlpha=1;}}else t.backgroundMap=e.background,t.backgroundAlpha=1;if(t.environmentIntensity=e.environment!==null?e.environmentIntensity??1:0,t.environmentRotation.makeRotationFromEuler(e.environmentRotation).invert(),this._previousEnvironment!==e.environment&&e.environment!==null)if(e.environment.isCubeTexture){let a=new X(this._renderer).generate(e.environment);t.envMapInfo.updateFrom(a);}else t.envMapInfo.updateFrom(e.environment);this._previousEnvironment=e.environment,this._previousBackground=e.background,this.reset();}_updateFromResults(e,t,a){let{materials:o,geometry:s,bvh:r,bvhChanged:l,needsMaterialIndexUpdate:f}=a;this._materials=o;let m=this._pathTracer.material;return l&&(m.bvh.updateFrom(r),m.attributesArray.updateFrom(s.attributes.normal,s.attributes.tangent,s.attributes.uv,s.attributes.color)),f&&m.materialIndexAttribute.updateFrom(s.attributes.materialIndex),this._previousScene=e,this.scene=e,this.camera=t,this.updateCamera(),this.updateMaterials(),this.updateEnvironment(),this.updateLights(),a}renderSample(){let e=this._lowResPathTracer,t=this._pathTracer,a=this._renderer,o=this._clock,s=this._quad;this._updateScale(),this._queueReset&&(t.reset(),e.reset(),this._queueReset=false,s.material.opacity=0,o.start());let r=o.getDelta()*1e3,l=o.getElapsedTime()*1e3;if(!this.pausePathTracing&&this.enablePathTracing&&this.renderDelay<=l&&!this.isCompiling&&t.update(),t.alpha=t.material.backgroundAlpha!==1||!Ki(a),e.alpha=t.alpha,this.renderToCanvas){let f=this._renderer,d=this.minSamples;if(l>=this.renderDelay&&this.samples>=this.minSamples&&(this.fadeDuration!==0?s.material.opacity=Math.min(s.material.opacity+r/this.fadeDuration,1):s.material.opacity=1),!this.enablePathTracing||this.samples<d||s.material.opacity<1){if(this.dynamicLowRes&&!this.isCompiling){e.samples<1&&(e.material=t.material,e.update());let m=s.material.opacity;s.material.opacity=1-s.material.opacity,s.material.map=e.target.texture,s.render(f),s.material.opacity=m;}(!this.dynamicLowRes&&this.rasterizeScene||this.dynamicLowRes&&this.isCompiling)&&this.rasterizeSceneCallback(this.scene,this.camera);}this.enablePathTracing&&s.material.opacity>0&&(s.material.opacity<1&&(s.material.blending=this.dynamicLowRes?AdditiveBlending:NormalBlending),s.material.map=t.target.texture,this.renderToCanvasCallback(t.target,f,s),s.material.blending=NoBlending);}}reset(){this._queueReset=true,this._pathTracer.samples=0;}dispose(){this._quad.dispose(),this._quad.material.dispose(),this._pathTracer.dispose();}_updateScale(){if(this.synchronizeRenderSize){this._renderer.getDrawingBufferSize(U);let e=Math.floor(this.renderScale*U.x),t=Math.floor(this.renderScale*U.y);if(this._pathTracer.getSize(U),U.x!==e||U.y!==t){let a=this.lowResScale;this._pathTracer.setSize(e,t),this._lowResPathTracer.setSize(Math.floor(e*a),Math.floor(t*a));}}}};var Br=class extends Camera{static{a(this,"EquirectCamera");}constructor(){super(),this.isEquirectCamera=true;}};var Wr=class extends SpotLight{static{a(this,"PhysicalSpotLight");}constructor(...e){super(...e),this.iesMap=null,this.radius=0;}copy(e,t){return super.copy(e,t),this.iesMap=e.iesMap,this.radius=e.radius,this}};var Hr=class extends RectAreaLight{static{a(this,"ShapedAreaLight");}constructor(...e){super(...e),this.isCircular=false;}copy(e,t){return super.copy(e,t),this.isCircular=e.isCircular,this}};var it=class extends _{static{a(this,"PMREMCopyMaterial");}constructor(){super({uniforms:{envMap:{value:null},blur:{value:0}},vertexShader:`
3686
+
3687
+ varying vec2 vUv;
3688
+ void main() {
3689
+ vUv = uv;
3690
+ gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
3691
+ }
3692
+
3693
+ `,fragmentShader:`
3694
+
3695
+ #include <common>
3696
+ #include <cube_uv_reflection_fragment>
3697
+
3698
+ ${N}
3699
+
3700
+ uniform sampler2D envMap;
3701
+ uniform float blur;
3702
+ varying vec2 vUv;
3703
+ void main() {
3704
+
3705
+ vec3 rayDirection = equirectUvToDirection( vUv );
3706
+ gl_FragColor = textureCubeUV( envMap, rayDirection, blur );
3707
+
3708
+ }
3709
+
3710
+ `});}},Gr=class{static{a(this,"BlurredEnvMapGenerator");}constructor(e){this.renderer=e,this.pmremGenerator=new PMREMGenerator(e),this.copyQuad=new FullScreenQuad(new it),this.renderTarget=new WebGLRenderTarget(1,1,{type:FloatType,format:RGBAFormat});}dispose(){this.pmremGenerator.dispose(),this.copyQuad.dispose(),this.renderTarget.dispose();}generate(e,t){let{pmremGenerator:a,renderTarget:o,copyQuad:s,renderer:r}=this,l=a.fromEquirectangular(e),{width:f,height:d}=e.image;o.setSize(f,d),s.material.envMap=l.texture,s.material.blur=t;let m=r.getRenderTarget(),u=r.autoClear;r.setRenderTarget(o),r.autoClear=true,s.render(r),r.setRenderTarget(m),r.autoClear=u;let n=new Uint16Array(f*d*4),x=new Float32Array(f*d*4);r.readRenderTargetPixels(o,0,0,f,d,x);for(let g=0,c=x.length;g<c;g++)n[g]=DataUtils.toHalfFloat(x[g]);let p=new DataTexture(n,f,d,RGBAFormat,HalfFloatType);return p.minFilter=e.minFilter,p.magFilter=e.magFilter,p.wrapS=e.wrapS,p.wrapT=e.wrapT,p.mapping=EquirectangularReflectionMapping,p.needsUpdate=true,l.dispose(),p}};var Ur=class extends _{static{a(this,"DenoiseMaterial");}constructor(e){super({blending:NoBlending,transparent:false,depthWrite:false,depthTest:false,defines:{USE_SLIDER:0},uniforms:{sigma:{value:5},threshold:{value:.03},kSigma:{value:1},map:{value:null},opacity:{value:1}},vertexShader:`
3711
+
3712
+ varying vec2 vUv;
3713
+
3714
+ void main() {
3715
+
3716
+ vUv = uv;
3717
+ gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
3718
+
3719
+ }
3720
+
3721
+ `,fragmentShader:`
3722
+
3723
+ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3724
+ // Copyright (c) 2018-2019 Michele Morrone
3725
+ // All rights reserved.
3726
+ //
3727
+ // https://michelemorrone.eu - https://BrutPitt.com
3728
+ //
3729
+ // me@michelemorrone.eu - brutpitt@gmail.com
3730
+ // twitter: @BrutPitt - github: BrutPitt
3731
+ //
3732
+ // https://github.com/BrutPitt/glslSmartDeNoise/
3733
+ //
3734
+ // This software is distributed under the terms of the BSD 2-Clause license
3735
+ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3736
+
3737
+ uniform sampler2D map;
3738
+
3739
+ uniform float sigma;
3740
+ uniform float threshold;
3741
+ uniform float kSigma;
3742
+ uniform float opacity;
3743
+
3744
+ varying vec2 vUv;
3745
+
3746
+ #define INV_SQRT_OF_2PI 0.39894228040143267793994605993439
3747
+ #define INV_PI 0.31830988618379067153776752674503
3748
+
3749
+ // Parameters:
3750
+ // sampler2D tex - sampler image / texture
3751
+ // vec2 uv - actual fragment coord
3752
+ // float sigma > 0 - sigma Standard Deviation
3753
+ // float kSigma >= 0 - sigma coefficient
3754
+ // kSigma * sigma --> radius of the circular kernel
3755
+ // float threshold - edge sharpening threshold
3756
+ vec4 smartDeNoise( sampler2D tex, vec2 uv, float sigma, float kSigma, float threshold ) {
3757
+
3758
+ float radius = round( kSigma * sigma );
3759
+ float radQ = radius * radius;
3760
+
3761
+ float invSigmaQx2 = 0.5 / ( sigma * sigma );
3762
+ float invSigmaQx2PI = INV_PI * invSigmaQx2;
3763
+
3764
+ float invThresholdSqx2 = 0.5 / ( threshold * threshold );
3765
+ float invThresholdSqrt2PI = INV_SQRT_OF_2PI / threshold;
3766
+
3767
+ vec4 centrPx = texture2D( tex, uv );
3768
+ centrPx.rgb *= centrPx.a;
3769
+
3770
+ float zBuff = 0.0;
3771
+ vec4 aBuff = vec4( 0.0 );
3772
+ vec2 size = vec2( textureSize( tex, 0 ) );
3773
+
3774
+ vec2 d;
3775
+ for ( d.x = - radius; d.x <= radius; d.x ++ ) {
3776
+
3777
+ float pt = sqrt( radQ - d.x * d.x );
3778
+
3779
+ for ( d.y = - pt; d.y <= pt; d.y ++ ) {
3780
+
3781
+ float blurFactor = exp( - dot( d, d ) * invSigmaQx2 ) * invSigmaQx2PI;
3782
+
3783
+ vec4 walkPx = texture2D( tex, uv + d / size );
3784
+ walkPx.rgb *= walkPx.a;
3785
+
3786
+ vec4 dC = walkPx - centrPx;
3787
+ float deltaFactor = exp( - dot( dC.rgba, dC.rgba ) * invThresholdSqx2 ) * invThresholdSqrt2PI * blurFactor;
3788
+
3789
+ zBuff += deltaFactor;
3790
+ aBuff += deltaFactor * walkPx;
3791
+
3792
+ }
3793
+
3794
+ }
3795
+
3796
+ return aBuff / zBuff;
3797
+
3798
+ }
3799
+
3800
+ void main() {
3801
+
3802
+ gl_FragColor = smartDeNoise( map, vec2( vUv.x, vUv.y ), sigma, kSigma, threshold );
3803
+ #include <tonemapping_fragment>
3804
+ #include <colorspace_fragment>
3805
+ #include <premultiplied_alpha_fragment>
3806
+
3807
+ gl_FragColor.a *= opacity;
3808
+
3809
+ }
3810
+
3811
+ `}),this.setValues(e);}};var Vr=class extends MeshStandardMaterial{static{a(this,"FogVolumeMaterial");}constructor(e){super(e),this.isFogVolumeMaterial=true,this.density=.015,this.emissive=new Color,this.emissiveIntensity=0,this.opacity=.15,this.transparent=true,this.roughness=1,this.metalness=0,this.setValues(e);}};export{Gr as BlurredEnvMapGenerator,Ur as DenoiseMaterial,Ft as DynamicPathTracingSceneGenerator,Br as EquirectCamera,Vr as FogVolumeMaterial,De as GradientEquirectTexture,Q as PathTracingRenderer,z as PathTracingSceneGenerator,Ct as PathTracingSceneWorker,he as PhysicalCamera,Fe as PhysicalPathTracingMaterial,Wr as PhysicalSpotLight,Pe as ProceduralEquirectTexture,Hr as ShapedAreaLight,Or as WebGLPathTracer};