@react-three/drei 10.7.7 → 10.7.9

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.
package/README.md CHANGED
@@ -1,4 +1,5 @@
1
1
  [![Storybook](https://img.shields.io/static/v1?message=Storybook&style=flat&colorA=000000&colorB=000000&label=&logo=storybook&logoColor=ffffff)](https://drei.pmnd.rs/)
2
+ [![](https://img.shields.io/badge/chromatic-171c23.svg?style=flat&colorA=000000&colorB=000000&logo=chromatic&logoColor=ffffff)](https://www.chromatic.com/library?appId=64a019f36ecd3751d0ada612&branch=master)
2
3
  [![Version](https://img.shields.io/npm/v/@react-three/drei?style=flat&colorA=000000&colorB=000000)](https://www.npmjs.com/package/@react-three/drei)
3
4
  [![Downloads](https://img.shields.io/npm/dt/@react-three/drei.svg?style=flat&colorA=000000&colorB=000000)](https://www.npmjs.com/package/@react-three/drei)
4
5
  [![Discord Shield](https://img.shields.io/discord/740090768164651008?style=flat&colorA=000000&colorB=000000&label=discord&logo=discord&logoColor=ffffff)](https://discord.com/channels/740090768164651008/741751532592038022)
@@ -801,8 +802,23 @@ https://pmndrs.github.io/drei
801
802
 
802
803
  ### INSTALL
803
804
 
805
+ Pre-requisites:
806
+
807
+ - Install [nvm](https://github.com/nvm-sh/nvm), then:
808
+ ```sh
809
+ $ nvm install
810
+ $ nvm use
811
+ $ node -v # make sure your version satisfies package.json#engines.node
812
+ ```
813
+ nb: if you want this node version to be your default nvm's one: `nvm alias default node`
814
+ - Install yarn, with:
815
+ ```sh
816
+ $ corepack enable
817
+ $ corepack prepare --activate # it reads "packageManager"
818
+ $ yarn -v # make sure your version satisfies package.json#engines.yarn
819
+ ```
820
+
804
821
  ```sh
805
- $ corepack enable
806
822
  $ yarn install
807
823
  ```
808
824
 
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("@babel/runtime/helpers/extends"),t=require("three"),r=require("react"),a=require("@react-three/fiber"),i=require("./shaderMaterial.cjs.js"),s=require("../materials/DiscardMaterial.cjs.js"),n=require("../helpers/constants.cjs.js");function o(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function l(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(r){if("default"!==r){var a=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,a.get?a:{enumerable:!0,get:function(){return e[r]}})}})),t.default=e,Object.freeze(t)}var h=o(e),c=l(t),u=l(r);const d=u.createContext(null),p=i.shaderMaterial({color:new c.Color,blend:2,alphaTest:.75,opacity:0,map:null},"varying vec2 vUv;\n void main() {\n gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4(position, 1.);\n vUv = uv;\n }",`varying vec2 vUv;\n uniform sampler2D map;\n uniform vec3 color;\n uniform float opacity;\n uniform float alphaTest;\n uniform float blend;\n void main() {\n vec4 sampledDiffuseColor = texture2D(map, vUv);\n gl_FragColor = vec4(color * sampledDiffuseColor.r * blend, max(0.0, (1.0 - (sampledDiffuseColor.r + sampledDiffuseColor.g + sampledDiffuseColor.b) / alphaTest)) * opacity);\n #include <tonemapping_fragment>\n #include <${n.version>=154?"colorspace_fragment":"encodings_fragment"}>\n }`),f=u.forwardRef((({children:e,temporal:t,frames:r=40,limit:i=1/0,blend:s=20,scale:n=10,opacity:o=1,alphaTest:l=.75,color:h="black",colorBlend:c=2,resolution:f=1024,toneMapped:g=!0,...v},M)=>{a.extend({SoftShadowMaterial:p});const b=a.useThree((e=>e.gl)),w=a.useThree((e=>e.scene)),y=a.useThree((e=>e.camera)),x=a.useThree((e=>e.invalidate)),C=u.useRef(null),S=u.useRef(null),[j]=u.useState((()=>new m(b,w,f)));u.useLayoutEffect((()=>{j.configure(C.current)}),[]);const T=u.useMemo((()=>({lights:new Map,temporal:!!t,frames:Math.max(2,r),blend:Math.max(2,r===1/0?s:r),count:0,getMesh:()=>C.current,reset:()=>{j.clear();const e=C.current.material;e.opacity=0,e.alphaTest=0,T.count=0},update:(e=1)=>{const t=C.current.material;T.temporal?(t.opacity=Math.min(o,t.opacity+o/T.blend),t.alphaTest=Math.min(l,t.alphaTest+l/T.blend)):(t.opacity=o,t.alphaTest=l),S.current.visible=!0,j.prepare();for(let t=0;t<e;t++)T.lights.forEach((e=>e.update())),j.update(y,T.blend);S.current.visible=!1,j.finish()}})),[j,y,w,t,r,s,o,l]);return u.useLayoutEffect((()=>{T.reset(),T.temporal||T.frames===1/0||T.update(T.blend)})),u.useImperativeHandle(M,(()=>T),[T]),a.useFrame((()=>{(T.temporal||T.frames===1/0)&&T.count<T.frames&&T.count<i&&(x(),T.update(),T.count++)})),u.createElement("group",v,u.createElement("group",{traverse:()=>null,ref:S},u.createElement(d.Provider,{value:T},e)),u.createElement("mesh",{receiveShadow:!0,ref:C,scale:n,rotation:[-Math.PI/2,0,0]},u.createElement("planeGeometry",null),u.createElement("softShadowMaterial",{transparent:!0,depthWrite:!1,toneMapped:g,color:h,blend:c,map:j.progressiveLightMap2.texture})))})),g=u.forwardRef((({castShadow:e=!0,bias:t=.001,mapSize:r=512,size:a=5,near:i=.5,far:s=500,frames:o=1,position:l=[0,0,0],radius:p=1,amount:f=8,intensity:g=(n.version>=155?Math.PI:1),ambient:m=.5,...v},M)=>{const b=u.useRef(null),w=new c.Vector3(...l).length(),y=u.useContext(d),x=u.useCallback((()=>{let e;if(b.current)for(let t=0;t<b.current.children.length;t++)if(e=b.current.children[t],Math.random()>m)e.position.set(l[0]+c.MathUtils.randFloatSpread(p),l[1]+c.MathUtils.randFloatSpread(p),l[2]+c.MathUtils.randFloatSpread(p));else{let t=Math.acos(2*Math.random()-1)-Math.PI/2,r=2*Math.PI*Math.random();e.position.set(Math.cos(t)*Math.cos(r)*w,Math.abs(Math.cos(t)*Math.sin(r)*w),Math.sin(t)*w)}}),[p,m,w,...l]),C=u.useMemo((()=>({update:x})),[x]);return u.useImperativeHandle(M,(()=>C),[C]),u.useLayoutEffect((()=>{var e;const t=b.current;return y&&(null==(e=y.lights)||e.set(t.uuid,C)),()=>{var e;null==y||null==(e=y.lights)||e.delete(t.uuid)}}),[y,C]),u.createElement("group",h.default({ref:b},v),Array.from({length:f},((n,o)=>u.createElement("directionalLight",{key:o,castShadow:e,"shadow-bias":t,"shadow-mapSize":[r,r],intensity:g/f},u.createElement("orthographicCamera",{attach:"shadow-camera",args:[-a,a,a,-a,i,s]})))))}));class m{constructor(e,t,r=1024){this.renderer=e,this.res=r,this.scene=t,this.buffer1Active=!1,this.lights=[],this.meshes=[],this.object=null,this.clearColor=new c.Color,this.clearAlpha=0;const a={type:c.HalfFloatType,magFilter:c.NearestFilter,minFilter:c.NearestFilter};this.progressiveLightMap1=new c.WebGLRenderTarget(this.res,this.res,a),this.progressiveLightMap2=new c.WebGLRenderTarget(this.res,this.res,a),this.discardMat=new s.DiscardMaterial,this.targetMat=new c.MeshLambertMaterial({fog:!1}),this.previousShadowMap={value:this.progressiveLightMap1.texture},this.averagingWindow={value:100},this.targetMat.onBeforeCompile=e=>{e.vertexShader="varying vec2 vUv;\n"+e.vertexShader.slice(0,-1)+"vUv = uv; gl_Position = vec4((uv - 0.5) * 2.0, 1.0, 1.0); }";const t=e.fragmentShader.indexOf("void main() {");e.fragmentShader="varying vec2 vUv;\n"+e.fragmentShader.slice(0,t)+"uniform sampler2D previousShadowMap;\n\tuniform float averagingWindow;\n"+e.fragmentShader.slice(t-1,-1)+"\nvec3 texelOld = texture2D(previousShadowMap, vUv).rgb;\n gl_FragColor.rgb = mix(texelOld, gl_FragColor.rgb, 1.0/ averagingWindow);\n }",e.uniforms.previousShadowMap=this.previousShadowMap,e.uniforms.averagingWindow=this.averagingWindow}}clear(){this.renderer.getClearColor(this.clearColor),this.clearAlpha=this.renderer.getClearAlpha(),this.renderer.setClearColor("black",1),this.renderer.setRenderTarget(this.progressiveLightMap1),this.renderer.clear(),this.renderer.setRenderTarget(this.progressiveLightMap2),this.renderer.clear(),this.renderer.setRenderTarget(null),this.renderer.setClearColor(this.clearColor,this.clearAlpha),this.lights=[],this.meshes=[],this.scene.traverse((e=>{!function(e){return!!e.geometry}(e)?function(e){return e.isLight}(e)&&this.lights.push({object:e,intensity:e.intensity}):this.meshes.push({object:e,material:e.material})}))}prepare(){this.lights.forEach((e=>e.object.intensity=0)),this.meshes.forEach((e=>e.object.material=this.discardMat))}finish(){this.lights.forEach((e=>e.object.intensity=e.intensity)),this.meshes.forEach((e=>e.object.material=e.material))}configure(e){this.object=e}update(e,t=100){if(!this.object)return;this.averagingWindow.value=t,this.object.material=this.targetMat;const r=this.buffer1Active?this.progressiveLightMap1:this.progressiveLightMap2,a=this.buffer1Active?this.progressiveLightMap2:this.progressiveLightMap1,i=this.scene.background;this.scene.background=null,this.renderer.setRenderTarget(r),this.previousShadowMap.value=a.texture,this.buffer1Active=!this.buffer1Active,this.renderer.render(this.scene,e),this.renderer.setRenderTarget(null),this.scene.background=i}}exports.AccumulativeShadows=f,exports.RandomizedLight=g,exports.accumulativeContext=d;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("@babel/runtime/helpers/extends"),t=require("three"),r=require("react"),a=require("@react-three/fiber"),i=require("./shaderMaterial.cjs.js"),s=require("../materials/DiscardMaterial.cjs.js"),n=require("../helpers/constants.cjs.js");function o(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function l(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(r){if("default"!==r){var a=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,a.get?a:{enumerable:!0,get:function(){return e[r]}})}})),t.default=e,Object.freeze(t)}var h=o(e),c=l(t),u=l(r);const d=u.createContext(null),p=i.shaderMaterial({color:new c.Color,blend:2,alphaTest:.75,opacity:0,map:null},"varying vec2 vUv;\n void main() {\n gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4(position, 1.);\n vUv = uv;\n }",`varying vec2 vUv;\n uniform sampler2D map;\n uniform vec3 color;\n uniform float opacity;\n uniform float alphaTest;\n uniform float blend;\n void main() {\n vec4 sampledDiffuseColor = texture2D(map, vUv);\n gl_FragColor = vec4(color * sampledDiffuseColor.r * blend, max(0.0, (1.0 - (sampledDiffuseColor.r + sampledDiffuseColor.g + sampledDiffuseColor.b) / alphaTest)) * opacity);\n #include <tonemapping_fragment>\n #include <${n.version>=154?"colorspace_fragment":"encodings_fragment"}>\n }`),m=u.forwardRef((({children:e,temporal:t,frames:r=40,limit:i=1/0,blend:s=20,scale:n=10,opacity:o=1,alphaTest:l=.75,color:h="black",colorBlend:c=2,resolution:m=1024,toneMapped:f=!0,...v},M)=>{a.extend({SoftShadowMaterial:p});const b=a.useThree((e=>e.gl)),w=a.useThree((e=>e.scene)),y=a.useThree((e=>e.camera)),x=a.useThree((e=>e.invalidate)),C=u.useRef(null),S=u.useRef(null),[j]=u.useState((()=>new g(b,w,m)));u.useLayoutEffect((()=>{j.configure(C.current)}),[]);const T=u.useMemo((()=>({lights:new Map,temporal:!!t,frames:Math.max(2,r),blend:Math.max(2,r===1/0?s:r),count:0,getMesh:()=>C.current,reset:()=>{j.clear();const e=C.current.material;e.opacity=0,e.alphaTest=0,T.count=0},update:(e=1)=>{const t=C.current.material;T.temporal?(t.opacity=Math.min(o,t.opacity+o/T.blend),t.alphaTest=Math.min(l,t.alphaTest+l/T.blend)):(t.opacity=o,t.alphaTest=l),S.current.visible=!0,j.prepare();for(let t=0;t<e;t++)T.lights.forEach((e=>e.update())),j.update(y,T.blend);S.current.visible=!1,j.finish()}})),[j,y,w,t,r,s,o,l]);return u.useLayoutEffect((()=>{T.reset(),T.temporal||T.frames===1/0||T.update(T.blend)})),u.useImperativeHandle(M,(()=>T),[T]),a.useFrame((()=>{(T.temporal||T.frames===1/0)&&T.count<T.frames&&T.count<i&&(x(),T.update(),T.count++)})),u.createElement("group",v,u.createElement("group",{traverse:()=>null,ref:S},u.createElement(d.Provider,{value:T},e)),u.createElement("mesh",{receiveShadow:!0,ref:C,scale:n,rotation:[-Math.PI/2,0,0]},u.createElement("planeGeometry",null),u.createElement("softShadowMaterial",{transparent:!0,depthWrite:!1,toneMapped:f,color:h,blend:c,map:j.progressiveLightMap2.texture})))})),f=u.forwardRef((({castShadow:e=!0,bias:t=.001,mapSize:r=512,size:a=5,near:i=.5,far:s=500,frames:o=1,position:l=[0,0,0],radius:p=1,amount:m=8,intensity:f=(n.version>=155?Math.PI:1),ambient:g=.5,...v},M)=>{const b=u.useRef(null),w=new c.Vector3(...l).length(),y=u.useContext(d),x=u.useCallback((()=>{let e;if(b.current)for(let t=0;t<b.current.children.length;t++)if(e=b.current.children[t],Math.random()>g)e.position.set(l[0]+c.MathUtils.randFloatSpread(p),l[1]+c.MathUtils.randFloatSpread(p),l[2]+c.MathUtils.randFloatSpread(p));else{let t=Math.acos(2*Math.random()-1)-Math.PI/2,r=2*Math.PI*Math.random();e.position.set(Math.cos(t)*Math.cos(r)*w,Math.abs(Math.cos(t)*Math.sin(r)*w),Math.sin(t)*w)}}),[p,g,w,...l]),C=u.useMemo((()=>({update:x})),[x]);return u.useImperativeHandle(M,(()=>C),[C]),u.useLayoutEffect((()=>{var e;const t=b.current;return y&&(null==(e=y.lights)||e.set(t.uuid,C)),()=>{var e;null==y||null==(e=y.lights)||e.delete(t.uuid)}}),[y,C]),u.createElement("group",h.default({ref:b},v),Array.from({length:m},((n,o)=>u.createElement("directionalLight",{key:o,castShadow:e,"shadow-bias":t,"shadow-mapSize":[r,r],intensity:f/m},u.createElement("orthographicCamera",{attach:"shadow-camera",args:[-a,a,a,-a,i,s]})))))}));class g{constructor(e,t,r=1024){this.renderer=e,this.res=r,this.scene=t,this.buffer1Active=!1,this.lights=[],this.meshes=[],this.object=null,this.clearColor=new c.Color,this.clearAlpha=0;const a={type:c.HalfFloatType,magFilter:c.NearestFilter,minFilter:c.NearestFilter};this.progressiveLightMap1=new c.WebGLRenderTarget(this.res,this.res,a),this.progressiveLightMap2=new c.WebGLRenderTarget(this.res,this.res,a),this.discardMat=new s.DiscardMaterial,this.targetMat=new c.MeshLambertMaterial({fog:!1}),this.previousShadowMap={value:this.progressiveLightMap1.texture},this.averagingWindow={value:100},this.targetMat.onBeforeCompile=e=>{e.vertexShader="varying vec2 vUv;\n"+e.vertexShader.slice(0,-1)+"vUv = uv; gl_Position = vec4((uv - 0.5) * 2.0, 1.0, 1.0); }";const t=e.fragmentShader.indexOf("void main() {");e.fragmentShader="varying vec2 vUv;\n"+e.fragmentShader.slice(0,t)+"uniform sampler2D previousShadowMap;\n\tuniform float averagingWindow;\n"+e.fragmentShader.slice(t-1,-1)+"\nvec3 texelOld = texture2D(previousShadowMap, vUv).rgb;\n gl_FragColor.rgb = mix(texelOld, gl_FragColor.rgb, 1.0/ averagingWindow);\n }",e.uniforms.previousShadowMap=this.previousShadowMap,e.uniforms.averagingWindow=this.averagingWindow}}clear(){this.renderer.getClearColor(this.clearColor),this.clearAlpha=this.renderer.getClearAlpha(),this.renderer.setClearColor("black",1),this.renderer.setRenderTarget(this.progressiveLightMap1),this.renderer.clear(),this.renderer.setRenderTarget(this.progressiveLightMap2),this.renderer.clear(),this.renderer.setRenderTarget(null),this.renderer.setClearColor(this.clearColor,this.clearAlpha),this.lights=[],this.meshes=[],this.scene.traverse((e=>{!function(e){return!!e.geometry}(e)?function(e){return e.isLight}(e)&&this.lights.push({object:e,intensity:e.intensity}):this.meshes.push({object:e,material:e.material})}))}prepare(){this.lights.forEach((e=>e.object.intensity=0)),this.meshes.forEach((e=>e.object.material=this.discardMat))}finish(){this.lights.forEach((e=>e.object.intensity=e.intensity)),this.meshes.forEach((e=>e.object.material=e.material))}configure(e){this.object=e}update(e,t=100){if(!this.object)return;this.averagingWindow.value=t,this.object.material=this.targetMat;const r=this.buffer1Active?this.progressiveLightMap1:this.progressiveLightMap2,a=this.buffer1Active?this.progressiveLightMap2:this.progressiveLightMap1,i=this.scene.background,s=this.scene.environment;this.scene.background=null,this.scene.environment=null,this.renderer.setRenderTarget(r),this.previousShadowMap.value=a.texture,this.buffer1Active=!this.buffer1Active,this.renderer.render(this.scene,e),this.renderer.setRenderTarget(null),this.scene.background=i,this.scene.environment=s}}exports.AccumulativeShadows=m,exports.RandomizedLight=f,exports.accumulativeContext=d;
@@ -295,15 +295,19 @@ class ProgressiveLightMap {
295
295
  // Ping-pong two surface buffers for reading/writing
296
296
  const activeMap = this.buffer1Active ? this.progressiveLightMap1 : this.progressiveLightMap2;
297
297
  const inactiveMap = this.buffer1Active ? this.progressiveLightMap2 : this.progressiveLightMap1;
298
- // Render the object's surface maps
298
+ // Render the object's surface maps with direct light only: since three r182
299
+ // scene.environment also lights MeshLambertMaterial, so clear it like the background
299
300
  const oldBg = this.scene.background;
301
+ const oldEnv = this.scene.environment;
300
302
  this.scene.background = null;
303
+ this.scene.environment = null;
301
304
  this.renderer.setRenderTarget(activeMap);
302
305
  this.previousShadowMap.value = inactiveMap.texture;
303
306
  this.buffer1Active = !this.buffer1Active;
304
307
  this.renderer.render(this.scene, camera);
305
308
  this.renderer.setRenderTarget(null);
306
309
  this.scene.background = oldBg;
310
+ this.scene.environment = oldEnv;
307
311
  }
308
312
  }
309
313
 
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var n=require("@babel/runtime/helpers/extends"),e=require("three"),t=require("react"),a=require("@react-three/fiber"),r=require("./Fbo.cjs.js"),o=require("../materials/DiscardMaterial.cjs.js");function i(n){return n&&"object"==typeof n&&"default"in n?n:{default:n}}function s(n){if(n&&n.__esModule)return n;var e=Object.create(null);return n&&Object.keys(n).forEach((function(t){if("default"!==t){var a=Object.getOwnPropertyDescriptor(n,t);Object.defineProperty(e,t,a.get?a:{enumerable:!0,get:function(){return n[t]}})}})),e.default=n,Object.freeze(e)}require("./shaderMaterial.cjs.js");var l=i(n),c=s(e),m=s(t);class u extends c.MeshPhysicalMaterial{constructor(n=6,e=!1){super(),this.uniforms={chromaticAberration:{value:.05},transmission:{value:0},_transmission:{value:1},transmissionMap:{value:null},roughness:{value:0},thickness:{value:0},thicknessMap:{value:null},attenuationDistance:{value:1/0},attenuationColor:{value:new c.Color("white")},anisotropicBlur:{value:.1},time:{value:0},distortion:{value:0},distortionScale:{value:.5},temporalDistortion:{value:0},buffer:{value:null}},this.onBeforeCompile=t=>{t.uniforms={...t.uniforms,...this.uniforms},this.anisotropy>0&&(t.defines.USE_ANISOTROPY=""),e?t.defines.USE_SAMPLER="":t.defines.USE_TRANSMISSION="",t.fragmentShader="\n uniform float chromaticAberration; \n uniform float anisotropicBlur; \n uniform float time;\n uniform float distortion;\n uniform float distortionScale;\n uniform float temporalDistortion;\n uniform sampler2D buffer;\n\n vec3 random3(vec3 c) {\n float j = 4096.0*sin(dot(c,vec3(17.0, 59.4, 15.0)));\n vec3 r;\n r.z = fract(512.0*j);\n j *= .125;\n r.x = fract(512.0*j);\n j *= .125;\n r.y = fract(512.0*j);\n return r-0.5;\n }\n\n uint hash( uint x ) {\n x += ( x << 10u );\n x ^= ( x >> 6u );\n x += ( x << 3u );\n x ^= ( x >> 11u );\n x += ( x << 15u );\n return x;\n }\n\n // Compound versions of the hashing algorithm I whipped together.\n uint hash( uvec2 v ) { return hash( v.x ^ hash(v.y) ); }\n uint hash( uvec3 v ) { return hash( v.x ^ hash(v.y) ^ hash(v.z) ); }\n uint hash( uvec4 v ) { return hash( v.x ^ hash(v.y) ^ hash(v.z) ^ hash(v.w) ); }\n\n // Construct a float with half-open range [0:1] using low 23 bits.\n // All zeroes yields 0.0, all ones yields the next smallest representable value below 1.0.\n float floatConstruct( uint m ) {\n const uint ieeeMantissa = 0x007FFFFFu; // binary32 mantissa bitmask\n const uint ieeeOne = 0x3F800000u; // 1.0 in IEEE binary32\n m &= ieeeMantissa; // Keep only mantissa bits (fractional part)\n m |= ieeeOne; // Add fractional part to 1.0\n float f = uintBitsToFloat( m ); // Range [1:2]\n return f - 1.0; // Range [0:1]\n }\n\n // Pseudo-random value in half-open range [0:1].\n float randomBase( float x ) { return floatConstruct(hash(floatBitsToUint(x))); }\n float randomBase( vec2 v ) { return floatConstruct(hash(floatBitsToUint(v))); }\n float randomBase( vec3 v ) { return floatConstruct(hash(floatBitsToUint(v))); }\n float randomBase( vec4 v ) { return floatConstruct(hash(floatBitsToUint(v))); }\n float rand(float seed) {\n float result = randomBase(vec3(gl_FragCoord.xy, seed));\n return result;\n }\n\n const float F3 = 0.3333333;\n const float G3 = 0.1666667;\n\n float snoise(vec3 p) {\n vec3 s = floor(p + dot(p, vec3(F3)));\n vec3 x = p - s + dot(s, vec3(G3));\n vec3 e = step(vec3(0.0), x - x.yzx);\n vec3 i1 = e*(1.0 - e.zxy);\n vec3 i2 = 1.0 - e.zxy*(1.0 - e);\n vec3 x1 = x - i1 + G3;\n vec3 x2 = x - i2 + 2.0*G3;\n vec3 x3 = x - 1.0 + 3.0*G3;\n vec4 w, d;\n w.x = dot(x, x);\n w.y = dot(x1, x1);\n w.z = dot(x2, x2);\n w.w = dot(x3, x3);\n w = max(0.6 - w, 0.0);\n d.x = dot(random3(s), x);\n d.y = dot(random3(s + i1), x1);\n d.z = dot(random3(s + i2), x2);\n d.w = dot(random3(s + 1.0), x3);\n w *= w;\n w *= w;\n d *= w;\n return dot(d, vec4(52.0));\n }\n\n float snoiseFractal(vec3 m) {\n return 0.5333333* snoise(m)\n +0.2666667* snoise(2.0*m)\n +0.1333333* snoise(4.0*m)\n +0.0666667* snoise(8.0*m);\n }\n"+t.fragmentShader,t.fragmentShader=t.fragmentShader.replace("#include <transmission_pars_fragment>","\n #ifdef USE_TRANSMISSION\n // Transmission code is based on glTF-Sampler-Viewer\n // https://github.com/KhronosGroup/glTF-Sample-Viewer\n uniform float _transmission;\n uniform float thickness;\n uniform float attenuationDistance;\n uniform vec3 attenuationColor;\n #ifdef USE_TRANSMISSIONMAP\n uniform sampler2D transmissionMap;\n #endif\n #ifdef USE_THICKNESSMAP\n uniform sampler2D thicknessMap;\n #endif\n uniform vec2 transmissionSamplerSize;\n uniform sampler2D transmissionSamplerMap;\n uniform mat4 modelMatrix;\n uniform mat4 projectionMatrix;\n varying vec3 vWorldPosition;\n vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {\n // Direction of refracted light.\n vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n // Compute rotation-independant scaling of the model matrix.\n vec3 modelScale;\n modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n // The thickness is specified in local space.\n return normalize( refractionVector ) * thickness * modelScale;\n }\n float applyIorToRoughness( const in float roughness, const in float ior ) {\n // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and\n // an IOR of 1.5 results in the default amount of microfacet refraction.\n return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n }\n vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {\n float framebufferLod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior ); \n #ifdef USE_SAMPLER\n #ifdef texture2DLodEXT\n return texture2DLodEXT(transmissionSamplerMap, fragCoord.xy, framebufferLod);\n #else\n return texture2D(transmissionSamplerMap, fragCoord.xy, framebufferLod);\n #endif\n #else\n return texture2D(buffer, fragCoord.xy);\n #endif\n }\n vec3 applyVolumeAttenuation( const in vec3 radiance, const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n if ( isinf( attenuationDistance ) ) {\n // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.\n return radiance;\n } else {\n // Compute light attenuation using Beer's law.\n vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); // Beer's law\n return transmittance * radiance;\n }\n }\n vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,\n const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,\n const in mat4 viewMatrix, const in mat4 projMatrix, const in float ior, const in float thickness,\n const in vec3 attenuationColor, const in float attenuationDistance ) {\n vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n vec3 refractedRayExit = position + transmissionRay;\n // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.\n vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n vec2 refractionCoords = ndcPos.xy / ndcPos.w;\n refractionCoords += 1.0;\n refractionCoords /= 2.0;\n // Sample framebuffer to get pixel the refracted ray hits.\n vec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n vec3 attenuatedColor = applyVolumeAttenuation( transmittedLight.rgb, length( transmissionRay ), attenuationColor, attenuationDistance );\n // Get the specular component.\n vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n return vec4( ( 1.0 - F ) * attenuatedColor * diffuseColor, transmittedLight.a );\n }\n #endif\n"),t.fragmentShader=t.fragmentShader.replace("#include <transmission_fragment>",` \n // Improve the refraction to use the world pos\n material.transmission = _transmission;\n material.transmissionAlpha = 1.0;\n material.thickness = thickness;\n material.attenuationDistance = attenuationDistance;\n material.attenuationColor = attenuationColor;\n #ifdef USE_TRANSMISSIONMAP\n material.transmission *= texture2D( transmissionMap, vUv ).r;\n #endif\n #ifdef USE_THICKNESSMAP\n material.thickness *= texture2D( thicknessMap, vUv ).g;\n #endif\n \n vec3 pos = vWorldPosition;\n float runningSeed = 0.0;\n vec3 v = normalize( cameraPosition - pos );\n vec3 n = inverseTransformDirection( normal, viewMatrix );\n vec3 transmission = vec3(0.0);\n float transmissionR, transmissionB, transmissionG;\n float randomCoords = rand(runningSeed++);\n float thickness_smear = thickness * max(pow(roughnessFactor, 0.33), anisotropicBlur);\n vec3 distortionNormal = vec3(0.0);\n vec3 temporalOffset = vec3(time, -time, -time) * temporalDistortion;\n if (distortion > 0.0) {\n distortionNormal = distortion * vec3(snoiseFractal(vec3((pos * distortionScale + temporalOffset))), snoiseFractal(vec3(pos.zxy * distortionScale - temporalOffset)), snoiseFractal(vec3(pos.yxz * distortionScale + temporalOffset)));\n }\n for (float i = 0.0; i < ${n}.0; i ++) {\n vec3 sampleNorm = normalize(n + roughnessFactor * roughnessFactor * 2.0 * normalize(vec3(rand(runningSeed++) - 0.5, rand(runningSeed++) - 0.5, rand(runningSeed++) - 0.5)) * pow(rand(runningSeed++), 0.33) + distortionNormal);\n transmissionR = getIBLVolumeRefraction(\n sampleNorm, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,\n pos, modelMatrix, viewMatrix, projectionMatrix, material.ior, material.thickness + thickness_smear * (i + randomCoords) / float(${n}),\n material.attenuationColor, material.attenuationDistance\n ).r;\n transmissionG = getIBLVolumeRefraction(\n sampleNorm, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,\n pos, modelMatrix, viewMatrix, projectionMatrix, material.ior * (1.0 + chromaticAberration * (i + randomCoords) / float(${n})) , material.thickness + thickness_smear * (i + randomCoords) / float(${n}),\n material.attenuationColor, material.attenuationDistance\n ).g;\n transmissionB = getIBLVolumeRefraction(\n sampleNorm, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,\n pos, modelMatrix, viewMatrix, projectionMatrix, material.ior * (1.0 + 2.0 * chromaticAberration * (i + randomCoords) / float(${n})), material.thickness + thickness_smear * (i + randomCoords) / float(${n}),\n material.attenuationColor, material.attenuationDistance\n ).b;\n transmission.r += transmissionR;\n transmission.g += transmissionG;\n transmission.b += transmissionB;\n }\n transmission /= ${n}.0;\n totalDiffuse = mix( totalDiffuse, transmission.rgb, material.transmission );\n`)},Object.keys(this.uniforms).forEach((n=>Object.defineProperty(this,n,{get:()=>this.uniforms[n].value,set:e=>this.uniforms[n].value=e})))}}const f=m.forwardRef((({buffer:n,transmissionSampler:e=!1,backside:t=!1,side:i=c.FrontSide,transmission:s=1,thickness:f=0,backsideThickness:d=0,backsideEnvMapIntensity:v=1,samples:h=10,resolution:p,backsideResolution:x,background:g,anisotropy:S,anisotropicBlur:M,...b},C)=>{a.extend({MeshTransmissionMaterial:u});const y=m.useRef(null),[w]=m.useState((()=>new o.DiscardMaterial)),k=r.useFBO(x||p),D=r.useFBO(p);let R,T,F,j;return a.useFrame((n=>{var a;(y.current.time=n.clock.elapsedTime,y.current.buffer!==D.texture||e)||(j=null==(a=y.current.__r3f.parent)?void 0:a.object,j&&(F=n.gl.toneMapping,R=n.scene.background,T=y.current.envMapIntensity,n.gl.toneMapping=c.NoToneMapping,g&&(n.scene.background=g),j.material=w,t&&(n.gl.setRenderTarget(k),n.gl.render(n.scene,n.camera),j.material=y.current,j.material.buffer=k.texture,j.material.thickness=d,j.material.side=c.BackSide,j.material.envMapIntensity=v),n.gl.setRenderTarget(D),n.gl.render(n.scene,n.camera),j.material=y.current,j.material.thickness=f,j.material.side=i,j.material.buffer=D.texture,j.material.envMapIntensity=T,n.scene.background=R,n.gl.setRenderTarget(null),n.gl.toneMapping=F))})),m.useImperativeHandle(C,(()=>y.current),[]),m.createElement("meshTransmissionMaterial",l.default({args:[h,e],ref:y},b,{buffer:n||D.texture,_transmission:s,anisotropicBlur:null!=M?M:S,transmission:e?s:0,thickness:f,side:i}))}));exports.MeshTransmissionMaterial=f;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("@babel/runtime/helpers/extends"),n=require("three"),t=require("react"),a=require("@react-three/fiber"),r=require("./Fbo.cjs.js"),i=require("../materials/DiscardMaterial.cjs.js");function o(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function s(e){if(e&&e.__esModule)return e;var n=Object.create(null);return e&&Object.keys(e).forEach((function(t){if("default"!==t){var a=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(n,t,a.get?a:{enumerable:!0,get:function(){return e[t]}})}})),n.default=e,Object.freeze(n)}require("./shaderMaterial.cjs.js");var l=o(e),c=s(n),m=s(t);class f extends c.MeshPhysicalMaterial{constructor(e=6,n=!1){super(),this.uniforms={chromaticAberration:{value:.05},transmission:{value:0},_transmission:{value:1},transmissionMap:{value:null},roughness:{value:0},thickness:{value:0},thicknessMap:{value:null},attenuationDistance:{value:1/0},attenuationColor:{value:new c.Color("white")},anisotropicBlur:{value:.1},time:{value:0},distortion:{value:0},distortionScale:{value:.5},temporalDistortion:{value:0},buffer:{value:null}},this.onBeforeCompile=t=>{var a;t.uniforms={...t.uniforms,...this.uniforms},(null!==(a=this.anisotropy)&&void 0!==a?a:0)>0&&(t.defines.USE_ANISOTROPY=""),n?t.defines.USE_SAMPLER="":t.defines.USE_TRANSMISSION="",t.fragmentShader="\n uniform float chromaticAberration; \n uniform float anisotropicBlur; \n uniform float time;\n uniform float distortion;\n uniform float distortionScale;\n uniform float temporalDistortion;\n uniform sampler2D buffer;\n\n vec3 random3(vec3 c) {\n float j = 4096.0*sin(dot(c,vec3(17.0, 59.4, 15.0)));\n vec3 r;\n r.z = fract(512.0*j);\n j *= .125;\n r.x = fract(512.0*j);\n j *= .125;\n r.y = fract(512.0*j);\n return r-0.5;\n }\n\n uint hash( uint x ) {\n x += ( x << 10u );\n x ^= ( x >> 6u );\n x += ( x << 3u );\n x ^= ( x >> 11u );\n x += ( x << 15u );\n return x;\n }\n\n // Compound versions of the hashing algorithm I whipped together.\n uint hash( uvec2 v ) { return hash( v.x ^ hash(v.y) ); }\n uint hash( uvec3 v ) { return hash( v.x ^ hash(v.y) ^ hash(v.z) ); }\n uint hash( uvec4 v ) { return hash( v.x ^ hash(v.y) ^ hash(v.z) ^ hash(v.w) ); }\n\n // Construct a float with half-open range [0:1] using low 23 bits.\n // All zeroes yields 0.0, all ones yields the next smallest representable value below 1.0.\n float floatConstruct( uint m ) {\n const uint ieeeMantissa = 0x007FFFFFu; // binary32 mantissa bitmask\n const uint ieeeOne = 0x3F800000u; // 1.0 in IEEE binary32\n m &= ieeeMantissa; // Keep only mantissa bits (fractional part)\n m |= ieeeOne; // Add fractional part to 1.0\n float f = uintBitsToFloat( m ); // Range [1:2]\n return f - 1.0; // Range [0:1]\n }\n\n // Pseudo-random value in half-open range [0:1].\n float randomBase( float x ) { return floatConstruct(hash(floatBitsToUint(x))); }\n float randomBase( vec2 v ) { return floatConstruct(hash(floatBitsToUint(v))); }\n float randomBase( vec3 v ) { return floatConstruct(hash(floatBitsToUint(v))); }\n float randomBase( vec4 v ) { return floatConstruct(hash(floatBitsToUint(v))); }\n float rand(float seed) {\n float result = randomBase(vec3(gl_FragCoord.xy, seed));\n return result;\n }\n\n const float F3 = 0.3333333;\n const float G3 = 0.1666667;\n\n float snoise(vec3 p) {\n vec3 s = floor(p + dot(p, vec3(F3)));\n vec3 x = p - s + dot(s, vec3(G3));\n vec3 e = step(vec3(0.0), x - x.yzx);\n vec3 i1 = e*(1.0 - e.zxy);\n vec3 i2 = 1.0 - e.zxy*(1.0 - e);\n vec3 x1 = x - i1 + G3;\n vec3 x2 = x - i2 + 2.0*G3;\n vec3 x3 = x - 1.0 + 3.0*G3;\n vec4 w, d;\n w.x = dot(x, x);\n w.y = dot(x1, x1);\n w.z = dot(x2, x2);\n w.w = dot(x3, x3);\n w = max(0.6 - w, 0.0);\n d.x = dot(random3(s), x);\n d.y = dot(random3(s + i1), x1);\n d.z = dot(random3(s + i2), x2);\n d.w = dot(random3(s + 1.0), x3);\n w *= w;\n w *= w;\n d *= w;\n return dot(d, vec4(52.0));\n }\n\n float snoiseFractal(vec3 m) {\n return 0.5333333* snoise(m)\n +0.2666667* snoise(2.0*m)\n +0.1333333* snoise(4.0*m)\n +0.0666667* snoise(8.0*m);\n }\n"+t.fragmentShader,t.fragmentShader=t.fragmentShader.replace("#include <transmission_pars_fragment>","\n #ifdef USE_TRANSMISSION\n // Transmission code is based on glTF-Sampler-Viewer\n // https://github.com/KhronosGroup/glTF-Sample-Viewer\n uniform float _transmission;\n uniform float thickness;\n uniform float attenuationDistance;\n uniform vec3 attenuationColor;\n #ifdef USE_TRANSMISSIONMAP\n uniform sampler2D transmissionMap;\n #endif\n #ifdef USE_THICKNESSMAP\n uniform sampler2D thicknessMap;\n #endif\n uniform vec2 transmissionSamplerSize;\n uniform sampler2D transmissionSamplerMap;\n uniform mat4 modelMatrix;\n uniform mat4 projectionMatrix;\n varying vec3 vWorldPosition;\n vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in vec3 modelScale ) {\n // Direction of refracted light.\n // n is normalized once when the sample normal is built.\n vec3 refractionVector = refract( - v, n, 1.0 / ior );\n // The thickness is specified in local space.\n return normalize( refractionVector ) * thickness * modelScale;\n }\n float applyIorToRoughness( const in float roughness, const in float ior ) {\n // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and\n // an IOR of 1.5 results in the default amount of microfacet refraction.\n return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n }\n vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {\n float framebufferLod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior ); \n #ifdef USE_SAMPLER\n #ifdef texture2DLodEXT\n return texture2DLodEXT(transmissionSamplerMap, fragCoord.xy, framebufferLod);\n #else\n return texture2D(transmissionSamplerMap, fragCoord.xy, framebufferLod);\n #endif\n #else\n return texture2D(buffer, fragCoord.xy);\n #endif\n }\n vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,\n const in vec3 position, const in vec3 modelScale, const in vec3 attenuationCoefficient, const in vec3 F,\n const in mat4 viewMatrix, const in mat4 projMatrix, const in float ior, const in float thickness,\n const in float attenuationDistance ) {\n vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelScale );\n vec3 refractedRayExit = position + transmissionRay;\n // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.\n vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n vec2 refractionCoords = ndcPos.xy / ndcPos.w;\n refractionCoords += 1.0;\n refractionCoords /= 2.0;\n // Sample framebuffer to get pixel the refracted ray hits.\n vec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n vec3 attenuatedColor = transmittedLight.rgb;\n if ( !isinf( attenuationDistance ) ) {\n // Apply Beer's law.\n attenuatedColor *= exp( - attenuationCoefficient * length( transmissionRay ) );\n }\n return vec4( ( 1.0 - F ) * attenuatedColor * diffuseColor, transmittedLight.a );\n }\n #endif\n"),t.fragmentShader=t.fragmentShader.replace("#include <transmission_fragment>",` \n // Improve the refraction to use the world pos\n material.transmission = _transmission;\n material.transmissionAlpha = 1.0;\n material.thickness = thickness;\n material.attenuationDistance = attenuationDistance;\n material.attenuationColor = attenuationColor;\n #ifdef USE_TRANSMISSIONMAP\n material.transmission *= texture2D( transmissionMap, vUv ).r;\n #endif\n #ifdef USE_THICKNESSMAP\n material.thickness *= texture2D( thicknessMap, vUv ).g;\n #endif\n \n if (material.transmission != 0.0) {\n vec3 pos = vWorldPosition;\n float runningSeed = 0.0;\n vec3 v = normalize( cameraPosition - pos );\n vec3 n = inverseTransformDirection( normal, viewMatrix );\n vec3 transmission = vec3(0.0);\n float randomCoords = rand(runningSeed++);\n float thickness_smear = thickness * max(pow(roughnessFactor, 0.33), anisotropicBlur);\n vec3 distortionNormal = vec3(0.0);\n vec3 temporalOffset = vec3(time, -time, -time) * temporalDistortion;\n\n vec3 modelScale = vec3(\n length( vec3( modelMatrix[ 0 ].xyz ) ),\n length( vec3( modelMatrix[ 1 ].xyz ) ),\n length( vec3( modelMatrix[ 2 ].xyz ) )\n );\n\n // Beer's-law coefficient\n vec3 attenuationCoefficient = vec3(0.0);\n if ( !isinf( material.attenuationDistance ) ) {\n attenuationCoefficient = -log( material.attenuationColor ) / material.attenuationDistance;\n }\n\n if (distortion > 0.0) {\n distortionNormal = distortion * vec3(snoiseFractal(vec3((pos * distortionScale + temporalOffset))), snoiseFractal(vec3(pos.zxy * distortionScale - temporalOffset)), snoiseFractal(vec3(pos.yxz * distortionScale + temporalOffset)));\n }\n for (float i = 0.0; i < ${e}.0; i ++) {\n vec3 sampleNorm;\n if (roughnessFactor > 0.0) {\n sampleNorm = normalize(n + roughnessFactor * roughnessFactor * 2.0 * normalize(vec3(rand(runningSeed++) - 0.5, rand(runningSeed++) - 0.5, rand(runningSeed++) - 0.5)) * pow(rand(runningSeed++), 0.33) + distortionNormal);\n } else {\n // Smooth surfaces skip four hashes, a pow, and a normalization per sample\n sampleNorm = normalize(n + distortionNormal);\n }\n float sampleProgress = (i + randomCoords) / float(${e});\n float sampleThickness = material.thickness + thickness_smear * sampleProgress;\n // Fresnel is identical for RGB; only the refracted IOR changes.\n vec3 F = EnvironmentBRDF( sampleNorm, v, material.specularColor, material.specularF90, material.roughness );\n if (chromaticAberration == 0.0) {\n // With one IOR, a single framebuffer sample supplies all RGB channels\n transmission += getIBLVolumeRefraction(\n sampleNorm, v, material.roughness, material.diffuseColor, pos, modelScale, attenuationCoefficient, F,\n viewMatrix, projectionMatrix, material.ior, sampleThickness, material.attenuationDistance\n ).rgb;\n } else {\n float aberration = chromaticAberration * sampleProgress;\n transmission.r += getIBLVolumeRefraction(\n sampleNorm, v, material.roughness, material.diffuseColor, pos, modelScale, attenuationCoefficient, F,\n viewMatrix, projectionMatrix, material.ior, sampleThickness, material.attenuationDistance\n ).r;\n transmission.g += getIBLVolumeRefraction(\n sampleNorm, v, material.roughness, material.diffuseColor, pos, modelScale, attenuationCoefficient, F,\n viewMatrix, projectionMatrix, material.ior * (1.0 + aberration), sampleThickness, material.attenuationDistance\n ).g;\n transmission.b += getIBLVolumeRefraction(\n sampleNorm, v, material.roughness, material.diffuseColor, pos, modelScale, attenuationCoefficient, F,\n viewMatrix, projectionMatrix, material.ior * (1.0 + 2.0 * aberration), sampleThickness, material.attenuationDistance\n ).b;\n }\n }\n transmission /= ${e}.0;\n totalDiffuse = mix( totalDiffuse, transmission, material.transmission );\n }\n`)},Object.keys(this.uniforms).forEach((e=>Object.defineProperty(this,e,{get:()=>this.uniforms[e].value,set:n=>this.uniforms[e].value=n})))}}const u=m.forwardRef((({buffer:e,transmissionSampler:n=!1,backside:t=!1,side:o=c.FrontSide,transmission:s=1,thickness:u=0,backsideThickness:d=0,backsideEnvMapIntensity:v=1,samples:h=10,resolution:p,backsideResolution:g,background:x,anisotropy:S,anisotropicBlur:b,...M},y)=>{a.extend({MeshTransmissionMaterial:f});const C=m.useRef(null),[k]=m.useState((()=>new i.DiscardMaterial)),w=null!=g?g:p,T=r.useFBO(w,w),R=r.useFBO(p,p);let F,D,B,I;return a.useFrame((e=>{const a=C.current;var r;(a.uniforms.time.value=e.clock.elapsedTime,a.uniforms.buffer.value!==R.texture||n)||(I=null==(r=a.__r3f)||null==(r=r.parent)?void 0:r.object,I&&a.visible&&0!==a.uniforms._transmission.value&&(B=e.gl.toneMapping,F=e.scene.background,D=a.envMapIntensity,e.gl.toneMapping=c.NoToneMapping,x&&(e.scene.background=x),I.material=k,t&&(e.gl.setRenderTarget(T),e.gl.render(e.scene,e.camera),I.material=a,a.uniforms.buffer.value=T.texture,a.uniforms.thickness.value=d,a.side=c.BackSide,o!==c.BackSide&&(a.needsUpdate=!0),a.envMapIntensity=v),e.gl.setRenderTarget(R),e.gl.render(e.scene,e.camera),I.material=a,a.uniforms.thickness.value=u,a.side=o,t&&o!==c.BackSide&&(a.needsUpdate=!0),a.uniforms.buffer.value=R.texture,a.envMapIntensity=D,e.scene.background=F,e.gl.setRenderTarget(null),e.gl.toneMapping=B))})),m.useImperativeHandle(y,(()=>C.current),[]),m.createElement("meshTransmissionMaterial",l.default({args:[h,n],ref:C},M,{buffer:e||R.texture,_transmission:s,anisotropicBlur:null!=b?b:S,transmission:n?s:0,thickness:u,side:o}))}));exports.MeshTransmissionMaterial=u;
@@ -13,6 +13,7 @@ type MeshTransmissionMaterialType = Omit<ThreeElements['meshPhysicalMaterial'],
13
13
  temporalDistortion?: number;
14
14
  buffer?: THREE.Texture;
15
15
  time?: number;
16
+ _transmission?: number;
16
17
  args?: [samples: number, transmissionSampler: boolean];
17
18
  };
18
19
  export type MeshTransmissionMaterialProps = Omit<MeshTransmissionMaterialType, 'ref' | 'args'> & {
@@ -6,6 +6,8 @@ import { useFBO } from './Fbo.js';
6
6
  import { DiscardMaterial } from '../materials/DiscardMaterial.js';
7
7
 
8
8
  class MeshTransmissionMaterialImpl extends THREE.MeshPhysicalMaterial {
9
+ /** Set by the R3F reconciler */
10
+
9
11
  constructor(samples = 6, transmissionSampler = false) {
10
12
  super();
11
13
  this.uniforms = {
@@ -59,6 +61,7 @@ class MeshTransmissionMaterialImpl extends THREE.MeshPhysicalMaterial {
59
61
  }
60
62
  };
61
63
  this.onBeforeCompile = shader => {
64
+ var _this$anisotropy;
62
65
  shader.uniforms = {
63
66
  ...shader.uniforms,
64
67
  ...this.uniforms
@@ -66,7 +69,7 @@ class MeshTransmissionMaterialImpl extends THREE.MeshPhysicalMaterial {
66
69
 
67
70
  // Fix for r153-r156 anisotropy chunks
68
71
  // https://github.com/mrdoob/three.js/pull/26716
69
- if (this.anisotropy > 0) shader.defines.USE_ANISOTROPY = '';
72
+ if (((_this$anisotropy = this.anisotropy) !== null && _this$anisotropy !== void 0 ? _this$anisotropy : 0) > 0) shader.defines.USE_ANISOTROPY = '';
70
73
 
71
74
  // If the transmission sampler is active inject a flag
72
75
  if (transmissionSampler) shader.defines.USE_SAMPLER = '';
@@ -185,14 +188,10 @@ class MeshTransmissionMaterialImpl extends THREE.MeshPhysicalMaterial {
185
188
  uniform mat4 modelMatrix;
186
189
  uniform mat4 projectionMatrix;
187
190
  varying vec3 vWorldPosition;
188
- vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {
191
+ vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in vec3 modelScale ) {
189
192
  // Direction of refracted light.
190
- vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );
191
- // Compute rotation-independant scaling of the model matrix.
192
- vec3 modelScale;
193
- modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );
194
- modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );
195
- modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );
193
+ // n is normalized once when the sample normal is built.
194
+ vec3 refractionVector = refract( - v, n, 1.0 / ior );
196
195
  // The thickness is specified in local space.
197
196
  return normalize( refractionVector ) * thickness * modelScale;
198
197
  }
@@ -213,22 +212,11 @@ class MeshTransmissionMaterialImpl extends THREE.MeshPhysicalMaterial {
213
212
  return texture2D(buffer, fragCoord.xy);
214
213
  #endif
215
214
  }
216
- vec3 applyVolumeAttenuation( const in vec3 radiance, const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {
217
- if ( isinf( attenuationDistance ) ) {
218
- // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
219
- return radiance;
220
- } else {
221
- // Compute light attenuation using Beer's law.
222
- vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;
223
- vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); // Beer's law
224
- return transmittance * radiance;
225
- }
226
- }
227
215
  vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,
228
- const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,
216
+ const in vec3 position, const in vec3 modelScale, const in vec3 attenuationCoefficient, const in vec3 F,
229
217
  const in mat4 viewMatrix, const in mat4 projMatrix, const in float ior, const in float thickness,
230
- const in vec3 attenuationColor, const in float attenuationDistance ) {
231
- vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
218
+ const in float attenuationDistance ) {
219
+ vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelScale );
232
220
  vec3 refractedRayExit = position + transmissionRay;
233
221
  // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
234
222
  vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );
@@ -237,9 +225,11 @@ class MeshTransmissionMaterialImpl extends THREE.MeshPhysicalMaterial {
237
225
  refractionCoords /= 2.0;
238
226
  // Sample framebuffer to get pixel the refracted ray hits.
239
227
  vec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
240
- vec3 attenuatedColor = applyVolumeAttenuation( transmittedLight.rgb, length( transmissionRay ), attenuationColor, attenuationDistance );
241
- // Get the specular component.
242
- vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );
228
+ vec3 attenuatedColor = transmittedLight.rgb;
229
+ if ( !isinf( attenuationDistance ) ) {
230
+ // Apply Beer's law.
231
+ attenuatedColor *= exp( - attenuationCoefficient * length( transmissionRay ) );
232
+ }
243
233
  return vec4( ( 1.0 - F ) * attenuatedColor * diffuseColor, transmittedLight.a );
244
234
  }
245
235
  #endif\n`);
@@ -259,42 +249,69 @@ class MeshTransmissionMaterialImpl extends THREE.MeshPhysicalMaterial {
259
249
  material.thickness *= texture2D( thicknessMap, vUv ).g;
260
250
  #endif
261
251
 
262
- vec3 pos = vWorldPosition;
263
- float runningSeed = 0.0;
264
- vec3 v = normalize( cameraPosition - pos );
265
- vec3 n = inverseTransformDirection( normal, viewMatrix );
266
- vec3 transmission = vec3(0.0);
267
- float transmissionR, transmissionB, transmissionG;
268
- float randomCoords = rand(runningSeed++);
269
- float thickness_smear = thickness * max(pow(roughnessFactor, 0.33), anisotropicBlur);
270
- vec3 distortionNormal = vec3(0.0);
271
- vec3 temporalOffset = vec3(time, -time, -time) * temporalDistortion;
272
- if (distortion > 0.0) {
273
- distortionNormal = distortion * vec3(snoiseFractal(vec3((pos * distortionScale + temporalOffset))), snoiseFractal(vec3(pos.zxy * distortionScale - temporalOffset)), snoiseFractal(vec3(pos.yxz * distortionScale + temporalOffset)));
274
- }
275
- for (float i = 0.0; i < ${samples}.0; i ++) {
276
- vec3 sampleNorm = normalize(n + roughnessFactor * roughnessFactor * 2.0 * normalize(vec3(rand(runningSeed++) - 0.5, rand(runningSeed++) - 0.5, rand(runningSeed++) - 0.5)) * pow(rand(runningSeed++), 0.33) + distortionNormal);
277
- transmissionR = getIBLVolumeRefraction(
278
- sampleNorm, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,
279
- pos, modelMatrix, viewMatrix, projectionMatrix, material.ior, material.thickness + thickness_smear * (i + randomCoords) / float(${samples}),
280
- material.attenuationColor, material.attenuationDistance
281
- ).r;
282
- transmissionG = getIBLVolumeRefraction(
283
- sampleNorm, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,
284
- pos, modelMatrix, viewMatrix, projectionMatrix, material.ior * (1.0 + chromaticAberration * (i + randomCoords) / float(${samples})) , material.thickness + thickness_smear * (i + randomCoords) / float(${samples}),
285
- material.attenuationColor, material.attenuationDistance
286
- ).g;
287
- transmissionB = getIBLVolumeRefraction(
288
- sampleNorm, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,
289
- pos, modelMatrix, viewMatrix, projectionMatrix, material.ior * (1.0 + 2.0 * chromaticAberration * (i + randomCoords) / float(${samples})), material.thickness + thickness_smear * (i + randomCoords) / float(${samples}),
290
- material.attenuationColor, material.attenuationDistance
291
- ).b;
292
- transmission.r += transmissionR;
293
- transmission.g += transmissionG;
294
- transmission.b += transmissionB;
295
- }
296
- transmission /= ${samples}.0;
297
- totalDiffuse = mix( totalDiffuse, transmission.rgb, material.transmission );\n`);
252
+ if (material.transmission != 0.0) {
253
+ vec3 pos = vWorldPosition;
254
+ float runningSeed = 0.0;
255
+ vec3 v = normalize( cameraPosition - pos );
256
+ vec3 n = inverseTransformDirection( normal, viewMatrix );
257
+ vec3 transmission = vec3(0.0);
258
+ float randomCoords = rand(runningSeed++);
259
+ float thickness_smear = thickness * max(pow(roughnessFactor, 0.33), anisotropicBlur);
260
+ vec3 distortionNormal = vec3(0.0);
261
+ vec3 temporalOffset = vec3(time, -time, -time) * temporalDistortion;
262
+
263
+ vec3 modelScale = vec3(
264
+ length( vec3( modelMatrix[ 0 ].xyz ) ),
265
+ length( vec3( modelMatrix[ 1 ].xyz ) ),
266
+ length( vec3( modelMatrix[ 2 ].xyz ) )
267
+ );
268
+
269
+ // Beer's-law coefficient
270
+ vec3 attenuationCoefficient = vec3(0.0);
271
+ if ( !isinf( material.attenuationDistance ) ) {
272
+ attenuationCoefficient = -log( material.attenuationColor ) / material.attenuationDistance;
273
+ }
274
+
275
+ if (distortion > 0.0) {
276
+ distortionNormal = distortion * vec3(snoiseFractal(vec3((pos * distortionScale + temporalOffset))), snoiseFractal(vec3(pos.zxy * distortionScale - temporalOffset)), snoiseFractal(vec3(pos.yxz * distortionScale + temporalOffset)));
277
+ }
278
+ for (float i = 0.0; i < ${samples}.0; i ++) {
279
+ vec3 sampleNorm;
280
+ if (roughnessFactor > 0.0) {
281
+ sampleNorm = normalize(n + roughnessFactor * roughnessFactor * 2.0 * normalize(vec3(rand(runningSeed++) - 0.5, rand(runningSeed++) - 0.5, rand(runningSeed++) - 0.5)) * pow(rand(runningSeed++), 0.33) + distortionNormal);
282
+ } else {
283
+ // Smooth surfaces skip four hashes, a pow, and a normalization per sample
284
+ sampleNorm = normalize(n + distortionNormal);
285
+ }
286
+ float sampleProgress = (i + randomCoords) / float(${samples});
287
+ float sampleThickness = material.thickness + thickness_smear * sampleProgress;
288
+ // Fresnel is identical for RGB; only the refracted IOR changes.
289
+ vec3 F = EnvironmentBRDF( sampleNorm, v, material.specularColor, material.specularF90, material.roughness );
290
+ if (chromaticAberration == 0.0) {
291
+ // With one IOR, a single framebuffer sample supplies all RGB channels
292
+ transmission += getIBLVolumeRefraction(
293
+ sampleNorm, v, material.roughness, material.diffuseColor, pos, modelScale, attenuationCoefficient, F,
294
+ viewMatrix, projectionMatrix, material.ior, sampleThickness, material.attenuationDistance
295
+ ).rgb;
296
+ } else {
297
+ float aberration = chromaticAberration * sampleProgress;
298
+ transmission.r += getIBLVolumeRefraction(
299
+ sampleNorm, v, material.roughness, material.diffuseColor, pos, modelScale, attenuationCoefficient, F,
300
+ viewMatrix, projectionMatrix, material.ior, sampleThickness, material.attenuationDistance
301
+ ).r;
302
+ transmission.g += getIBLVolumeRefraction(
303
+ sampleNorm, v, material.roughness, material.diffuseColor, pos, modelScale, attenuationCoefficient, F,
304
+ viewMatrix, projectionMatrix, material.ior * (1.0 + aberration), sampleThickness, material.attenuationDistance
305
+ ).g;
306
+ transmission.b += getIBLVolumeRefraction(
307
+ sampleNorm, v, material.roughness, material.diffuseColor, pos, modelScale, attenuationCoefficient, F,
308
+ viewMatrix, projectionMatrix, material.ior * (1.0 + 2.0 * aberration), sampleThickness, material.attenuationDistance
309
+ ).b;
310
+ }
311
+ }
312
+ transmission /= ${samples}.0;
313
+ totalDiffuse = mix( totalDiffuse, transmission, material.transmission );
314
+ }\n`);
298
315
  };
299
316
  Object.keys(this.uniforms).forEach(name => Object.defineProperty(this, name, {
300
317
  get: () => this.uniforms[name].value,
@@ -324,23 +341,27 @@ const MeshTransmissionMaterial = /* @__PURE__ */React.forwardRef(({
324
341
  });
325
342
  const ref = React.useRef(null);
326
343
  const [discardMaterial] = React.useState(() => new DiscardMaterial());
327
- const fboBack = useFBO(backsideResolution || resolution);
328
- const fboMain = useFBO(resolution);
344
+ const backsideSize = backsideResolution !== null && backsideResolution !== void 0 ? backsideResolution : resolution;
345
+ const fboBack = useFBO(backsideSize, backsideSize);
346
+ const fboMain = useFBO(resolution, resolution);
329
347
  let oldBg;
330
348
  let oldEnvMapIntensity;
331
349
  let oldTone;
332
350
  let parent;
333
351
  useFrame(state => {
334
- ref.current.time = state.clock.elapsedTime;
352
+ const material = ref.current;
353
+ material.uniforms.time.value = state.clock.elapsedTime;
335
354
  // Render only if the buffer matches the built-in and no transmission sampler is set
336
- if (ref.current.buffer === fboMain.texture && !transmissionSampler) {
337
- var _r3f$parent;
338
- parent = (_r3f$parent = ref.current.__r3f.parent) == null ? void 0 : _r3f$parent.object;
339
- if (parent) {
355
+ if (material.uniforms.buffer.value === fboMain.texture && !transmissionSampler) {
356
+ var _material$__r3f;
357
+ parent = (_material$__r3f = material.__r3f) == null || (_material$__r3f = _material$__r3f.parent) == null ? void 0 : _material$__r3f.object;
358
+ // The buffers cannot be observed while the material is invisible or has zero
359
+ // transmission, so the extra render passes can be skipped
360
+ if (parent && material.visible && material.uniforms._transmission.value !== 0) {
340
361
  // Save defaults
341
362
  oldTone = state.gl.toneMapping;
342
363
  oldBg = state.scene.background;
343
- oldEnvMapIntensity = ref.current.envMapIntensity;
364
+ oldEnvMapIntensity = material.envMapIntensity;
344
365
 
345
366
  // Switch off tonemapping lest it double tone maps
346
367
  // Save the current background and set the HDR as the new BG
@@ -353,21 +374,25 @@ const MeshTransmissionMaterial = /* @__PURE__ */React.forwardRef(({
353
374
  state.gl.setRenderTarget(fboBack);
354
375
  state.gl.render(state.scene, state.camera);
355
376
  // And now prepare the material for the main render using the backside buffer
356
- parent.material = ref.current;
357
- parent.material.buffer = fboBack.texture;
358
- parent.material.thickness = backsideThickness;
359
- parent.material.side = THREE.BackSide;
360
- parent.material.envMapIntensity = backsideEnvMapIntensity;
377
+ parent.material = material;
378
+ material.uniforms.buffer.value = fboBack.texture;
379
+ material.uniforms.thickness.value = backsideThickness;
380
+ // Side is part of three's program cache key, so select the cached BackSide variant
381
+ material.side = THREE.BackSide;
382
+ if (side !== THREE.BackSide) material.needsUpdate = true;
383
+ material.envMapIntensity = backsideEnvMapIntensity;
361
384
  }
362
385
 
363
386
  // Render into the main buffer
364
387
  state.gl.setRenderTarget(fboMain);
365
388
  state.gl.render(state.scene, state.camera);
366
- parent.material = ref.current;
367
- parent.material.thickness = thickness;
368
- parent.material.side = side;
369
- parent.material.buffer = fboMain.texture;
370
- parent.material.envMapIntensity = oldEnvMapIntensity;
389
+ parent.material = material;
390
+ material.uniforms.thickness.value = thickness;
391
+ material.side = side;
392
+ // The backside pass selected another program, so restore the configured variant
393
+ if (backside && side !== THREE.BackSide) material.needsUpdate = true;
394
+ material.uniforms.buffer.value = fboMain.texture;
395
+ material.envMapIntensity = oldEnvMapIntensity;
371
396
 
372
397
  // Set old state back
373
398
  state.scene.background = oldBg;
@@ -384,9 +409,7 @@ const MeshTransmissionMaterial = /* @__PURE__ */React.forwardRef(({
384
409
  args: [samples, transmissionSampler],
385
410
  ref: ref
386
411
  }, props, {
387
- buffer: buffer || fboMain.texture
388
- // @ts-ignore
389
- ,
412
+ buffer: buffer || fboMain.texture,
390
413
  _transmission: transmission
391
414
  // In order for this to not incur extra cost "transmission" must be set to 0 and treated as a reserved prop.
392
415
  // This is because THREE.WebGLRenderer will check for transmission > 0 and execute extra renders.
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react"),n=require("three"),a=require("@react-three/fiber");function t(e){if(e&&e.__esModule)return e;var n=Object.create(null);return e&&Object.keys(e).forEach((function(a){if("default"!==a){var t=Object.getOwnPropertyDescriptor(e,a);Object.defineProperty(n,a,t.get?t:{enumerable:!0,get:function(){return e[a]}})}})),n.default=e,Object.freeze(n)}var r=t(e),o=t(n);function l(e,n,a){n.traverse((n=>{n.material&&(e.properties.remove(n.material),null==n.material.dispose||n.material.dispose())})),e.info.programs.length=0,e.compile(n,a)}exports.SoftShadows=function({focus:e=0,samples:n=10,size:t=25}){const s=a.useThree((e=>e.gl)),i=a.useThree((e=>e.scene)),u=a.useThree((e=>e.camera));return r.useEffect((()=>{const a=o.ShaderChunk.shadowmap_pars_fragment;return o.ShaderChunk.shadowmap_pars_fragment=o.ShaderChunk.shadowmap_pars_fragment.replace("#ifdef USE_SHADOWMAP","#ifdef USE_SHADOWMAP\n"+(({focus:e=0,size:n=25,samples:a=10}={})=>`\n#define PENUMBRA_FILTER_SIZE float(${n})\n#define RGB_NOISE_FUNCTION(uv) (randRGB(uv))\nvec3 randRGB(vec2 uv) {\n return vec3(\n fract(sin(dot(uv, vec2(12.75613, 38.12123))) * 13234.76575),\n fract(sin(dot(uv, vec2(19.45531, 58.46547))) * 43678.23431),\n fract(sin(dot(uv, vec2(23.67817, 78.23121))) * 93567.23423)\n );\n}\n\nvec3 lowPassRandRGB(vec2 uv) {\n // 3x3 convolution (average)\n // can be implemented as separable with an extra buffer for a total of 6 samples instead of 9\n vec3 result = vec3(0);\n result += RGB_NOISE_FUNCTION(uv + vec2(-1.0, -1.0));\n result += RGB_NOISE_FUNCTION(uv + vec2(-1.0, 0.0));\n result += RGB_NOISE_FUNCTION(uv + vec2(-1.0, +1.0));\n result += RGB_NOISE_FUNCTION(uv + vec2( 0.0, -1.0));\n result += RGB_NOISE_FUNCTION(uv + vec2( 0.0, 0.0));\n result += RGB_NOISE_FUNCTION(uv + vec2( 0.0, +1.0));\n result += RGB_NOISE_FUNCTION(uv + vec2(+1.0, -1.0));\n result += RGB_NOISE_FUNCTION(uv + vec2(+1.0, 0.0));\n result += RGB_NOISE_FUNCTION(uv + vec2(+1.0, +1.0));\n result *= 0.111111111; // 1.0 / 9.0\n return result;\n}\nvec3 highPassRandRGB(vec2 uv) {\n // by subtracting the low-pass signal from the original signal, we're being left with the high-pass signal\n // hp(x) = x - lp(x)\n return RGB_NOISE_FUNCTION(uv) - lowPassRandRGB(uv) + 0.5;\n}\n\n\nvec2 vogelDiskSample(int sampleIndex, int sampleCount, float angle) {\n const float goldenAngle = 2.399963f; // radians\n float r = sqrt(float(sampleIndex) + 0.5f) / sqrt(float(sampleCount));\n float theta = float(sampleIndex) * goldenAngle + angle;\n float sine = sin(theta);\n float cosine = cos(theta);\n return vec2(cosine, sine) * r;\n}\nfloat penumbraSize( const in float zReceiver, const in float zBlocker ) { // Parallel plane estimation\n return (zReceiver - zBlocker) / zBlocker;\n}\nfloat findBlocker(sampler2D shadowMap, vec2 uv, float compare, float angle) {\n float texelSize = 1.0 / float(textureSize(shadowMap, 0).x);\n float blockerDepthSum = float(${e});\n float blockers = 0.0;\n\n int j = 0;\n vec2 offset = vec2(0.);\n float depth = 0.;\n\n #pragma unroll_loop_start\n for(int i = 0; i < ${a}; i ++) {\n offset = (vogelDiskSample(j, ${a}, angle) * texelSize) * 2.0 * PENUMBRA_FILTER_SIZE;\n depth = unpackRGBAToDepth( texture2D( shadowMap, uv + offset));\n if (depth < compare) {\n blockerDepthSum += depth;\n blockers++;\n }\n j++;\n }\n #pragma unroll_loop_end\n\n if (blockers > 0.0) {\n return blockerDepthSum / blockers;\n }\n return -1.0;\n}\n\n \nfloat vogelFilter(sampler2D shadowMap, vec2 uv, float zReceiver, float filterRadius, float angle) {\n float texelSize = 1.0 / float(textureSize(shadowMap, 0).x);\n float shadow = 0.0f;\n int j = 0;\n vec2 vogelSample = vec2(0.0);\n vec2 offset = vec2(0.0);\n #pragma unroll_loop_start\n for (int i = 0; i < ${a}; i++) {\n vogelSample = vogelDiskSample(j, ${a}, angle) * texelSize;\n offset = vogelSample * (1.0 + filterRadius * float(${n}));\n shadow += step( zReceiver, unpackRGBAToDepth( texture2D( shadowMap, uv + offset ) ) );\n j++;\n }\n #pragma unroll_loop_end\n return shadow * 1.0 / ${a}.0;\n}\n\nfloat PCSS (sampler2D shadowMap, vec4 coords) {\n vec2 uv = coords.xy;\n float zReceiver = coords.z; // Assumed to be eye-space z in this code\n float angle = highPassRandRGB(gl_FragCoord.xy).r * PI2;\n float avgBlockerDepth = findBlocker(shadowMap, uv, zReceiver, angle);\n if (avgBlockerDepth == -1.0) {\n return 1.0;\n }\n float penumbraRatio = penumbraSize(zReceiver, avgBlockerDepth);\n return vogelFilter(shadowMap, uv, zReceiver, 1.25 * penumbraRatio, angle);\n}`)({size:t,samples:n,focus:e})).replace("#if defined( SHADOWMAP_TYPE_PCF )","\nreturn PCSS(shadowMap, shadowCoord);\n#if defined( SHADOWMAP_TYPE_PCF )"),l(s,i,u),()=>{o.ShaderChunk.shadowmap_pars_fragment=a,l(s,i,u)}}),[e,t,n]),null};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react"),n=require("three"),a=require("@react-three/fiber");function t(e){if(e&&e.__esModule)return e;var n=Object.create(null);return e&&Object.keys(e).forEach((function(a){if("default"!==a){var t=Object.getOwnPropertyDescriptor(e,a);Object.defineProperty(n,a,t.get?t:{enumerable:!0,get:function(){return e[a]}})}})),n.default=e,Object.freeze(n)}var r=t(e),o=t(n);function s(e,n,a){n.traverse((n=>{if(n.material){(Array.isArray(n.material)?n.material:[n.material]).forEach((n=>{e.properties.remove(n),null==n.dispose||n.dispose(),n.needsUpdate=!0}))}})),e.info.programs.length=0,e.compile(n,a)}exports.SoftShadows=function({focus:e=0,samples:n=10,size:t=25}){const l=a.useThree((e=>e.gl)),i=a.useThree((e=>e.scene)),c=a.useThree((e=>e.camera));return r.useEffect((()=>{const a=o.ShaderChunk.shadowmap_pars_fragment,r=!a.includes("sampler2DShadow"),u=a.lastIndexOf("float getShadow( sampler2D shadowMap"),f=a.indexOf("if ( frustumTest ) {",u)+20;if(u<0||f<20)return void console.warn("[SoftShadows] Could not find injection point in shadow shader");const p=l.shadowMap.type;r||(l.shadowMap.type=o.BasicShadowMap);const d=a.slice(u,f).includes("shadowIntensity")?"return mix( 1.0, PCSS( shadowMap, shadowCoord ), shadowIntensity );":"return PCSS( shadowMap, shadowCoord );",v=(a.slice(0,f)+"\n"+d+a.slice(f)).replace("#ifdef USE_SHADOWMAP","#ifdef USE_SHADOWMAP\n"+(({focus:e=0,size:n=25,samples:a=10},t)=>{const r=t?"unpackRGBAToDepth( texture2D( shadowMap, uv + offset ) )":"texture2D( shadowMap, uv + offset ).r";return`\n#define PENUMBRA_FILTER_SIZE float(${n})\n#define RGB_NOISE_FUNCTION(uv) (randRGB(uv))\nvec3 randRGB(vec2 uv) {\n return vec3(\n fract(sin(dot(uv, vec2(12.75613, 38.12123))) * 13234.76575),\n fract(sin(dot(uv, vec2(19.45531, 58.46547))) * 43678.23431),\n fract(sin(dot(uv, vec2(23.67817, 78.23121))) * 93567.23423)\n );\n}\n\nvec3 lowPassRandRGB(vec2 uv) {\n // 3x3 convolution (average)\n // can be implemented as separable with an extra buffer for a total of 6 samples instead of 9\n vec3 result = vec3(0);\n result += RGB_NOISE_FUNCTION(uv + vec2(-1.0, -1.0));\n result += RGB_NOISE_FUNCTION(uv + vec2(-1.0, 0.0));\n result += RGB_NOISE_FUNCTION(uv + vec2(-1.0, +1.0));\n result += RGB_NOISE_FUNCTION(uv + vec2( 0.0, -1.0));\n result += RGB_NOISE_FUNCTION(uv + vec2( 0.0, 0.0));\n result += RGB_NOISE_FUNCTION(uv + vec2( 0.0, +1.0));\n result += RGB_NOISE_FUNCTION(uv + vec2(+1.0, -1.0));\n result += RGB_NOISE_FUNCTION(uv + vec2(+1.0, 0.0));\n result += RGB_NOISE_FUNCTION(uv + vec2(+1.0, +1.0));\n result *= 0.111111111; // 1.0 / 9.0\n return result;\n}\nvec3 highPassRandRGB(vec2 uv) {\n // by subtracting the low-pass signal from the original signal, we're being left with the high-pass signal\n // hp(x) = x - lp(x)\n return RGB_NOISE_FUNCTION(uv) - lowPassRandRGB(uv) + 0.5;\n}\n\n\nvec2 pcssVogelDiskSample(int sampleIndex, int sampleCount, float angle) {\n const float goldenAngle = 2.399963f; // radians\n float r = sqrt(float(sampleIndex) + 0.5f) / sqrt(float(sampleCount));\n float theta = float(sampleIndex) * goldenAngle + angle;\n float sine = sin(theta);\n float cosine = cos(theta);\n return vec2(cosine, sine) * r;\n}\nfloat penumbraSize( const in float zReceiver, const in float zBlocker ) { // Parallel plane estimation\n return (zReceiver - zBlocker) / zBlocker;\n}\nfloat findBlocker(sampler2D shadowMap, vec2 uv, float compare, float angle) {\n float texelSize = 1.0 / float(textureSize(shadowMap, 0).x);\n float blockerDepthSum = float(${e});\n float blockers = 0.0;\n\n int j = 0;\n vec2 offset = vec2(0.);\n float depth = 0.;\n\n #pragma unroll_loop_start\n for(int i = 0; i < ${a}; i ++) {\n offset = (pcssVogelDiskSample(j, ${a}, angle) * texelSize) * 2.0 * PENUMBRA_FILTER_SIZE;\n depth = ${r};\n if (depth < compare) {\n blockerDepthSum += depth;\n blockers++;\n }\n j++;\n }\n #pragma unroll_loop_end\n\n if (blockers > 0.0) {\n return blockerDepthSum / blockers;\n }\n return -1.0;\n}\n\n \nfloat vogelFilter(sampler2D shadowMap, vec2 uv, float zReceiver, float filterRadius, float angle) {\n float texelSize = 1.0 / float(textureSize(shadowMap, 0).x);\n float shadow = 0.0f;\n int j = 0;\n vec2 vogelSample = vec2(0.0);\n vec2 offset = vec2(0.0);\n #pragma unroll_loop_start\n for (int i = 0; i < ${a}; i++) {\n vogelSample = pcssVogelDiskSample(j, ${a}, angle) * texelSize;\n offset = vogelSample * (1.0 + filterRadius * float(${n}));\n shadow += step( zReceiver, ${r} );\n j++;\n }\n #pragma unroll_loop_end\n return shadow * 1.0 / ${a}.0;\n}\n\nfloat PCSS (sampler2D shadowMap, vec4 coords) {\n vec2 uv = coords.xy;\n float zReceiver = coords.z; // Assumed to be eye-space z in this code\n float angle = highPassRandRGB(gl_FragCoord.xy).r * PI2;\n float avgBlockerDepth = findBlocker(shadowMap, uv, zReceiver, angle);\n if (avgBlockerDepth == -1.0) {\n return 1.0;\n }\n float penumbraRatio = penumbraSize(zReceiver, avgBlockerDepth);\n return vogelFilter(shadowMap, uv, zReceiver, 1.25 * penumbraRatio, angle);\n}`})({size:t,samples:n,focus:e},r));return o.ShaderChunk.shadowmap_pars_fragment=v,s(l,i,c),()=>{o.ShaderChunk.shadowmap_pars_fragment=a,l.shadowMap.type=p,s(l,i,c)}}),[e,t,n]),null};
@@ -20,7 +20,9 @@ const pcss = ({
20
20
  focus = 0,
21
21
  size = 25,
22
22
  samples = 10
23
- } = {}) => `
23
+ }, packedDepth) => {
24
+ const depthSample = packedDepth ? 'unpackRGBAToDepth( texture2D( shadowMap, uv + offset ) )' : 'texture2D( shadowMap, uv + offset ).r';
25
+ return `
24
26
  #define PENUMBRA_FILTER_SIZE float(${size})
25
27
  #define RGB_NOISE_FUNCTION(uv) (randRGB(uv))
26
28
  vec3 randRGB(vec2 uv) {
@@ -54,7 +56,7 @@ vec3 highPassRandRGB(vec2 uv) {
54
56
  }
55
57
 
56
58
 
57
- vec2 vogelDiskSample(int sampleIndex, int sampleCount, float angle) {
59
+ vec2 pcssVogelDiskSample(int sampleIndex, int sampleCount, float angle) {
58
60
  const float goldenAngle = 2.399963f; // radians
59
61
  float r = sqrt(float(sampleIndex) + 0.5f) / sqrt(float(sampleCount));
60
62
  float theta = float(sampleIndex) * goldenAngle + angle;
@@ -76,8 +78,8 @@ float findBlocker(sampler2D shadowMap, vec2 uv, float compare, float angle) {
76
78
 
77
79
  #pragma unroll_loop_start
78
80
  for(int i = 0; i < ${samples}; i ++) {
79
- offset = (vogelDiskSample(j, ${samples}, angle) * texelSize) * 2.0 * PENUMBRA_FILTER_SIZE;
80
- depth = unpackRGBAToDepth( texture2D( shadowMap, uv + offset));
81
+ offset = (pcssVogelDiskSample(j, ${samples}, angle) * texelSize) * 2.0 * PENUMBRA_FILTER_SIZE;
82
+ depth = ${depthSample};
81
83
  if (depth < compare) {
82
84
  blockerDepthSum += depth;
83
85
  blockers++;
@@ -101,9 +103,9 @@ float vogelFilter(sampler2D shadowMap, vec2 uv, float zReceiver, float filterRad
101
103
  vec2 offset = vec2(0.0);
102
104
  #pragma unroll_loop_start
103
105
  for (int i = 0; i < ${samples}; i++) {
104
- vogelSample = vogelDiskSample(j, ${samples}, angle) * texelSize;
106
+ vogelSample = pcssVogelDiskSample(j, ${samples}, angle) * texelSize;
105
107
  offset = vogelSample * (1.0 + filterRadius * float(${size}));
106
- shadow += step( zReceiver, unpackRGBAToDepth( texture2D( shadowMap, uv + offset ) ) );
108
+ shadow += step( zReceiver, ${depthSample} );
107
109
  j++;
108
110
  }
109
111
  #pragma unroll_loop_end
@@ -121,11 +123,16 @@ float PCSS (sampler2D shadowMap, vec4 coords) {
121
123
  float penumbraRatio = penumbraSize(zReceiver, avgBlockerDepth);
122
124
  return vogelFilter(shadowMap, uv, zReceiver, 1.25 * penumbraRatio, angle);
123
125
  }`;
126
+ };
124
127
  function reset(gl, scene, camera) {
125
128
  scene.traverse(object => {
126
129
  if (object.material) {
127
- gl.properties.remove(object.material);
128
- object.material.dispose == null || object.material.dispose();
130
+ const materials = Array.isArray(object.material) ? object.material : [object.material];
131
+ materials.forEach(material => {
132
+ gl.properties.remove(material);
133
+ material.dispose == null || material.dispose();
134
+ material.needsUpdate = true;
135
+ });
129
136
  }
130
137
  });
131
138
  gl.info.programs.length = 0;
@@ -141,14 +148,32 @@ function SoftShadows({
141
148
  const camera = useThree(state => state.camera);
142
149
  React.useEffect(() => {
143
150
  const original = THREE.ShaderChunk.shadowmap_pars_fragment;
144
- THREE.ShaderChunk.shadowmap_pars_fragment = THREE.ShaderChunk.shadowmap_pars_fragment.replace('#ifdef USE_SHADOWMAP', '#ifdef USE_SHADOWMAP\n' + pcss({
151
+ // PCF shadows use a comparison sampler in newer three.js versions.
152
+ // That sampler cannot expose the raw depth needed for blocker search.
153
+ const packedDepth = !original.includes('sampler2DShadow');
154
+ // In newer three.js the final sampler2D overload is the Basic shadow path.
155
+ const getShadowStart = original.lastIndexOf('float getShadow( sampler2D shadowMap');
156
+ const frustumEnd = original.indexOf('if ( frustumTest ) {', getShadowStart) + 'if ( frustumTest ) {'.length;
157
+ if (getShadowStart < 0 || frustumEnd < 'if ( frustumTest ) {'.length) {
158
+ console.warn('[SoftShadows] Could not find injection point in shadow shader');
159
+ return;
160
+ }
161
+ const originalType = gl.shadowMap.type;
162
+ // Newer three.js uses sampler2DShadow for PCF. PCSS needs the raw depth,
163
+ // which is available through the Basic shadow map's sampler2D instead.
164
+ if (!packedDepth) gl.shadowMap.type = THREE.BasicShadowMap;
165
+ const hasIntensity = original.slice(getShadowStart, frustumEnd).includes('shadowIntensity');
166
+ const pcssReturn = hasIntensity ? 'return mix( 1.0, PCSS( shadowMap, shadowCoord ), shadowIntensity );' : 'return PCSS( shadowMap, shadowCoord );';
167
+ const shader = (original.slice(0, frustumEnd) + '\n' + pcssReturn + original.slice(frustumEnd)).replace('#ifdef USE_SHADOWMAP', '#ifdef USE_SHADOWMAP\n' + pcss({
145
168
  size,
146
169
  samples,
147
170
  focus
148
- })).replace('#if defined( SHADOWMAP_TYPE_PCF )', '\nreturn PCSS(shadowMap, shadowCoord);\n#if defined( SHADOWMAP_TYPE_PCF )');
171
+ }, packedDepth));
172
+ THREE.ShaderChunk.shadowmap_pars_fragment = shader;
149
173
  reset(gl, scene, camera);
150
174
  return () => {
151
175
  THREE.ShaderChunk.shadowmap_pars_fragment = original;
176
+ gl.shadowMap.type = originalType;
152
177
  reset(gl, scene, camera);
153
178
  };
154
179
  }, [focus, size, samples]);