@react-three/drei 9.51.9 → 9.51.11

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
@@ -1480,30 +1480,24 @@ return (
1480
1480
  <a href="https://codesandbox.io/s/hmgdjq"><img width="20%" src="https://codesandbox.io/api/v1/sandboxes/hmgdjq/screenshot.png" alt="Demo"/></a>
1481
1481
  </p>
1482
1482
 
1483
- A more convincing transmission shader with RGB shift (based on THREE.MeshPhysicalMaterial). This material can be expensive as it causes an additional render pass of the scene. Low samples and low resolution will make it faster. It will temporarily make the mesh that uses it invisible for that pass, this is better for performance and also improves visuals. If you have other objects that you don't want to see reflected in the material just add them to the parent mesh as children.
1483
+ An improved THREE.MeshPhysicalMaterial. It acts like a normal PhysicalMaterial in terms of transmission support, thickness, ior, roughness, etc., but has chromatic aberration, noise-based roughness blur, (primitive) anisotropy support, and unlike the original it can "see" other transmissive or transparent objects which leads to improved visuals.
1484
+
1485
+ Keep in mind that it can be expensive as it causes an additional render pass of the scene, minus the host mesh which gets removed from the render-stack temporarily. If you have other objects that you don't want to see reflected in the material just add them to the parent mesh as children. Low samples and low resolution will make it faster.
1486
+
1487
+ If you use roughness consider using a tiny resolution, for instance 32x32 pixels, it will still look good but perform much faster.
1484
1488
 
1485
1489
  ```tsx
1486
- type MeshTransmissionMaterialProps = {
1487
- /** Refraction shift, default: 0 */
1488
- refraction?: number
1489
- /** White noise roughness, default: 0 */
1490
- roughness?: number
1491
- /** RGB color shift, default: 0.3 */
1492
- rgbShift?: number
1493
- /** Noise, default: 0.03 */
1494
- noise?: number
1495
- /** Color saturation, default: 1 */
1496
- saturation?: number
1497
- /** Color contrast, default: 1 */
1498
- contrast?: number
1499
- /** Resolution of the local buffer, default: 1024 */
1500
- resolution?: number
1501
- /** Refraction samples, default: 10 */
1502
- samples?: number
1503
- /** Buffer scene background (can be a texture, a cubetexture or a color), default: null */
1504
- background?: THREE.Texture
1505
- /** The scene rendered into a texture (use it to share a texture between materials), default: null */
1506
- buffer?: THREE.Texture
1490
+ type MeshTransmissionMaterialProps = JSX.IntrinsicElements['meshPhysicalMaterial'] & {
1491
+ /* Chromatic aberration, default: 0.03 */
1492
+ chromaticAberration?: number
1493
+ /* Anisotropy, default: 0.1 */
1494
+ anisotropy?: number
1495
+ /* Distortion, default: 0 */
1496
+ distortion?: number
1497
+ /* Distortion scale, default: 0.5 */
1498
+ distortionScale?: number
1499
+ /* Temporal distortion, default: 0.5 */
1500
+ temporalDistortion?: number
1507
1501
  }
1508
1502
  ```
1509
1503
 
@@ -1513,7 +1507,7 @@ return (
1513
1507
  <MeshTransmissionMaterial />
1514
1508
  ```
1515
1509
 
1516
- If each material rendering the scene on its own is too much expensense you can share the buffer, for instance using drei/PerspectiveCamera.
1510
+ If each material rendering the scene on its own is too much expensense you can share a buffer texture, for instance using drei/PerspectiveCamera. This would mimic the default THREE.MeshPhysicalMaterial behaviour, the upside is that it's faster if you have multiple materials, the downside is that one transmissive material now can't "see" the other.
1517
1511
 
1518
1512
  ```jsx
1519
1513
  <PerspectiveCamera makeDefault fov={75} position={[10, 0, 15]} resolution={1024}>
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("@babel/runtime/helpers/extends"),r=require("three"),t=require("react"),n=require("@react-three/fiber"),o=require("./useFBO.cjs.js");function a(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function s(e){if(e&&e.__esModule)return e;var r=Object.create(null);return e&&Object.keys(e).forEach((function(t){if("default"!==t){var n=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(r,t,n.get?n:{enumerable:!0,get:function(){return e[t]}})}})),r.default=e,Object.freeze(r)}var i=a(e),u=s(r),l=s(t);class f extends u.MeshPhysicalMaterial{constructor({samples:e=5,...r}={}){super(r),this.uniforms={refraction:{value:0},rgbShift:{value:.3},noise:{value:.03},saturation:{value:1},contrast:{value:1},buffer:{value:null},resolution:{value:new u.Vector2}},this.onBeforeCompile=r=>{r.uniforms={...r.uniforms,...this.uniforms},r.fragmentShader="uniform float rgbShift;\n uniform vec2 resolution;\n uniform vec3 refractionColor;\n uniform float refraction;\n uniform float noise;\n uniform float saturation;\n uniform float contrast;\n uniform sampler2D buffer;\n \n vec3 sat(vec3 rgb, float adjustment) {\n const vec3 W = vec3(0.2125, 0.7154, 0.0721);\n vec3 intensity = vec3(dot(rgb, W));\n return mix(intensity, rgb, adjustment);\n }\n"+r.fragmentShader,r.fragmentShader=r.fragmentShader.replace("#include <transmission_pars_fragment>",""),r.fragmentShader=r.fragmentShader.replace("#include <transmission_fragment>",""),r.fragmentShader=r.fragmentShader.replace("vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;",`vec2 uv = gl_FragCoord.xy / resolution.xy;\n vec2 refractNormal = vNormal.xy * (1.0 - vNormal.z * 0.85);\n vec3 refractCol = vec3(0.0); \n float randomCoords = rand(uv);\n vec2 randomCoords2;\n float roughBlur = roughness * roughness;\n float slide;\n #pragma unroll_loop_start\n for (int i = 0; i < ${e}; i ++) {\n slide = float(UNROLLED_LOOP_INDEX) / float(${e}) * 0.1 + randomCoords * noise;\n randomCoords2 = vec2(rand(uv + randomCoords + 0.1 * float(UNROLLED_LOOP_INDEX)), rand(uv - randomCoords - 0.1 * float(UNROLLED_LOOP_INDEX))) - 0.5;\n randomCoords2 = normalize(randomCoords2) * sqrt(rand(uv + 0.12 * float(UNROLLED_LOOP_INDEX)));\n refractCol.r += texture2D(buffer, uv - refractNormal * (refraction + slide * 1.0) * rgbShift + randomCoords2 * roughBlur).r;\n refractCol.g += texture2D(buffer, uv - refractNormal * (refraction + slide * 2.0) * rgbShift + randomCoords2 * roughBlur).g;\n refractCol.b += texture2D(buffer, uv - refractNormal * (refraction + slide * 3.0) * rgbShift + randomCoords2 * roughBlur).b;\n refractCol = sat(refractCol, saturation);\n }\n #pragma unroll_loop_end\n refractCol /= float(${e});\n vec3 outgoingLight = (refractCol * totalDiffuse * contrast) + totalSpecular + totalEmissiveRadiance;`)},Object.keys(this.uniforms).forEach((e=>Object.defineProperty(this,e,{get:()=>this.uniforms[e].value,set:r=>this.uniforms[e].value=r})))}}const c=l.forwardRef((({buffer:e,samples:r=10,resolution:t=1024,background:a,...s},u)=>{n.extend({MeshTransmissionMaterial:f});const c=l.useRef(null),{size:d,viewport:m}=n.useThree(),g=o.useFBO(t),v=l.useMemo((()=>({samples:r})),[r]);let h,b,p;return n.useFrame((r=>{e||(p=c.current.__r3f.parent,p&&(b=p.visible,p.visible=!1,r.gl.setRenderTarget(g),h=r.scene.background,a&&(r.scene.background=a),r.gl.render(r.scene,r.camera),r.scene.background=h,r.gl.setRenderTarget(null),p.visible=b))})),l.useImperativeHandle(u,(()=>c.current),[]),l.createElement("meshTransmissionMaterial",i.default({args:[v],ref:c,buffer:e||g.texture,resolution:[d.width*m.dpr,d.height*m.dpr]},s))}));exports.MeshTransmissionMaterial=c;
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"),o=require("./useFBO.cjs.js");function r(n){return n&&"object"==typeof n&&"default"in n?n:{default:n}}function i(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)}var s=r(n),l=i(e),c=i(t);class m extends l.MeshPhysicalMaterial{constructor({samples:n=6,...e}={}){super(e),this.uniforms={chromaticAberration:{value:.05},transmission:{value:0},_transmission:{value:1},transmissionMap:{value:null},thickness:{value:1},thicknessMap:{value:null},attenuationDistance:{value:0},attenuationColor:{value:new l.Color},anisotropy:{value:.1},time:{value:0},distortion:{value:0},distortionScale:{value:.5},temporalDistortion:{value:.5},buffer:{value:null},resolution:{value:new l.Vector2}},this.onBeforeCompile=e=>{e.uniforms={...e.uniforms,...this.uniforms},e.defines.USE_TRANSMISSION="",e.fragmentShader="\n uniform float chromaticAberration;\n uniform vec2 resolution; \n uniform float anisotropy; \n uniform float time;\n uniform float distortion;\n uniform float distortionScale;\n uniform float temporalDistortion;\n uniform sampler2D buffer;\n \n vec3 sat(vec3 rgb, float adjustment) {\n const vec3 W = vec3(0.2125, 0.7154, 0.0721);\n vec3 intensity = vec3(dot(rgb, W));\n return mix(intensity, rgb, adjustment);\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 float seed = 0.0;\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\n m &= ieeeMantissa; // Keep only mantissa bits (fractional part)\n m |= ieeeOne; // Add fractional part to 1.0\n\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 random( float x ) { return floatConstruct(hash(floatBitsToUint(x))); }\n float random( vec2 v ) { return floatConstruct(hash(floatBitsToUint(v))); }\n float random( vec3 v ) { return floatConstruct(hash(floatBitsToUint(v))); }\n float random( vec4 v ) { return floatConstruct(hash(floatBitsToUint(v))); }\n\n float rand() {\n float result = random(vec3(gl_FragCoord.xy, seed));\n seed += 1.0;\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"+e.fragmentShader,e.fragmentShader=e.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 return texture2D(buffer, fragCoord.xy);\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"),e.fragmentShader=e.fragmentShader.replace("#include <transmission_fragment>",`\n vec2 uv = gl_FragCoord.xy / resolution.xy; \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 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();\n float thickness_smear = thickness * max(pow(roughness, 0.33), anisotropy);\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 + roughness * roughness * 2.0 * normalize(vec3(rand() - 0.5, rand() - 0.5, rand() - 0.5)) * pow(rand(), 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 u=c.forwardRef((({buffer:n,transmission:e=1,distortionSpeed:t=1,samples:r=10,resolution:i,background:l,...u},f)=>{a.extend({MeshTransmissionMaterial:m});const d=c.useRef(null),{size:v,viewport:h}=a.useThree(),p=o.useFBO(i);let x,g,C;return a.useFrame((e=>{n||(C=d.current.__r3f.parent,d.current.time=e.clock.getElapsedTime()*t,C&&(g=C.visible,C.visible=!1,e.gl.setRenderTarget(p),x=e.scene.background,l&&(e.scene.background=l),e.gl.render(e.scene,e.camera),e.scene.background=x,e.gl.setRenderTarget(null),C.visible=g))})),c.useImperativeHandle(f,(()=>d.current),[]),c.createElement("meshTransmissionMaterial",s.default({args:[c.useMemo((()=>({samples:r})),[r])],ref:d},u,{buffer:n||p.texture,_transmission:e,transmission:0,resolution:[v.width*h.dpr,v.height*h.dpr]}))}));exports.MeshTransmissionMaterial=u;
@@ -1,19 +1,23 @@
1
1
  import * as THREE from 'three';
2
2
  import * as React from 'react';
3
3
  import { ReactThreeFiber } from '@react-three/fiber';
4
- declare type MeshTransmissionMaterialType = Omit<JSX.IntrinsicElements['meshPhysicalMaterial'], 'args' | 'roughness' | 'transmission' | 'transmissionMap' | 'thickness'> & {
5
- refraction?: number;
6
- roughness?: number;
7
- rgbShift?: number;
8
- noise?: number;
9
- saturation?: number;
10
- contrast?: number;
4
+ declare type MeshTransmissionMaterialType = Omit<JSX.IntrinsicElements['meshPhysicalMaterial'], 'args'> & {
5
+ transmission?: number;
6
+ chromaticAberration?: number;
7
+ anisotropy?: number;
8
+ distortion?: number;
9
+ distortionScale: Uniform<number>;
10
+ temporalDistortion: Uniform<number>;
11
+ time?: number;
11
12
  resolution?: ReactThreeFiber.Vector2;
12
13
  buffer?: THREE.Texture;
13
14
  args?: [{
14
15
  samples: number;
15
16
  }];
16
17
  };
18
+ interface Uniform<T> {
19
+ value: T;
20
+ }
17
21
  declare global {
18
22
  namespace JSX {
19
23
  interface IntrinsicElements {
@@ -22,8 +26,9 @@ declare global {
22
26
  }
23
27
  }
24
28
  export declare const MeshTransmissionMaterial: React.ForwardRefExoticComponent<Pick<Omit<MeshTransmissionMaterialType, "args" | "resolution"> & {
29
+ distortionSpeed?: number | undefined;
25
30
  resolution?: number | undefined;
26
31
  samples?: number | undefined;
27
32
  background?: THREE.Texture | undefined;
28
- }, "visible" | "attach" | "children" | "key" | "onUpdate" | "dispose" | "type" | "id" | "uuid" | "name" | "userData" | "toJSON" | "clone" | "copy" | "addEventListener" | "hasEventListener" | "removeEventListener" | "dispatchEvent" | "color" | "blending" | "map" | "transparent" | "saturation" | "fog" | "alphaTest" | "alphaToCoverage" | "blendDst" | "blendDstAlpha" | "blendEquation" | "blendEquationAlpha" | "blendSrc" | "blendSrcAlpha" | "clipIntersection" | "clippingPlanes" | "clipShadows" | "colorWrite" | "defines" | "depthFunc" | "depthTest" | "depthWrite" | "stencilWrite" | "stencilFunc" | "stencilRef" | "stencilWriteMask" | "stencilFuncMask" | "stencilFail" | "stencilZFail" | "stencilZPass" | "isMaterial" | "needsUpdate" | "opacity" | "polygonOffset" | "polygonOffsetFactor" | "polygonOffsetUnits" | "precision" | "premultipliedAlpha" | "dithering" | "side" | "shadowSide" | "toneMapped" | "vertexColors" | "version" | "onBeforeCompile" | "customProgramCacheKey" | "setValues" | "background" | "buffer" | "alphaMap" | "wireframe" | "wireframeLinewidth" | "clearcoat" | "clearcoatMap" | "clearcoatRoughness" | "clearcoatRoughnessMap" | "clearcoatNormalScale" | "clearcoatNormalMap" | "reflectivity" | "ior" | "sheen" | "sheenColor" | "sheenColorMap" | "sheenRoughness" | "sheenRoughnessMap" | "thicknessMap" | "attenuationDistance" | "attenuationColor" | "specularIntensity" | "specularColor" | "specularIntensityMap" | "specularColorMap" | "roughness" | "metalness" | "lightMap" | "lightMapIntensity" | "aoMap" | "aoMapIntensity" | "emissive" | "emissiveIntensity" | "emissiveMap" | "bumpMap" | "bumpScale" | "normalMap" | "normalMapType" | "normalScale" | "displacementMap" | "displacementScale" | "displacementBias" | "roughnessMap" | "metalnessMap" | "envMap" | "envMapIntensity" | "wireframeLinecap" | "wireframeLinejoin" | "flatShading" | "isMeshStandardMaterial" | "resolution" | "samples" | "refraction" | "rgbShift" | "noise" | "contrast"> & React.RefAttributes<unknown>>;
33
+ }, "attach" | "children" | "key" | "onUpdate" | "time" | "background" | "buffer" | keyof THREE.MeshPhysicalMaterial | "anisotropy" | "resolution" | "samples" | "distortion" | "chromaticAberration" | "distortionScale" | "temporalDistortion" | "distortionSpeed"> & React.RefAttributes<unknown>>;
29
34
  export {};
@@ -6,25 +6,51 @@ import { useFBO } from './useFBO.js';
6
6
 
7
7
  class MeshTransmissionMaterialImpl extends THREE.MeshPhysicalMaterial {
8
8
  constructor({
9
- samples = 5,
9
+ samples = 6,
10
10
  ...args
11
11
  } = {}) {
12
12
  super(args);
13
13
  this.uniforms = {
14
- refraction: {
14
+ chromaticAberration: {
15
+ value: 0.05
16
+ },
17
+ // Transmission must always be 0
18
+ transmission: {
19
+ value: 0
20
+ },
21
+ // Instead a workaround is used, see below for reasons why
22
+ _transmission: {
23
+ value: 1
24
+ },
25
+ transmissionMap: {
26
+ value: null
27
+ },
28
+ thickness: {
29
+ value: 1
30
+ },
31
+ thicknessMap: {
32
+ value: null
33
+ },
34
+ attenuationDistance: {
15
35
  value: 0
16
36
  },
17
- rgbShift: {
18
- value: 0.3
37
+ attenuationColor: {
38
+ value: new THREE.Color()
39
+ },
40
+ anisotropy: {
41
+ value: 0.1
42
+ },
43
+ time: {
44
+ value: 0
19
45
  },
20
- noise: {
21
- value: 0.03
46
+ distortion: {
47
+ value: 0.0
22
48
  },
23
- saturation: {
24
- value: 1.0
49
+ distortionScale: {
50
+ value: 0.5
25
51
  },
26
- contrast: {
27
- value: 1.0
52
+ temporalDistortion: {
53
+ value: 0.5
28
54
  },
29
55
  buffer: {
30
56
  value: null
@@ -37,46 +63,235 @@ class MeshTransmissionMaterialImpl extends THREE.MeshPhysicalMaterial {
37
63
  this.onBeforeCompile = shader => {
38
64
  shader.uniforms = { ...shader.uniforms,
39
65
  ...this.uniforms
40
- }; // Head
41
-
42
- shader.fragmentShader = `uniform float rgbShift;
43
- uniform vec2 resolution;
44
- uniform vec3 refractionColor;
45
- uniform float refraction;
46
- uniform float noise;
47
- uniform float saturation;
48
- uniform float contrast;
66
+ };
67
+ shader.defines.USE_TRANSMISSION = ''; // Head
68
+
69
+ shader.fragmentShader =
70
+ /*glsl*/
71
+ `
72
+ uniform float chromaticAberration;
73
+ uniform vec2 resolution;
74
+ uniform float anisotropy;
75
+ uniform float time;
76
+ uniform float distortion;
77
+ uniform float distortionScale;
78
+ uniform float temporalDistortion;
49
79
  uniform sampler2D buffer;
50
80
 
51
81
  vec3 sat(vec3 rgb, float adjustment) {
52
82
  const vec3 W = vec3(0.2125, 0.7154, 0.0721);
53
83
  vec3 intensity = vec3(dot(rgb, W));
54
84
  return mix(intensity, rgb, adjustment);
85
+ }
86
+ vec3 random3(vec3 c) {
87
+ float j = 4096.0*sin(dot(c,vec3(17.0, 59.4, 15.0)));
88
+ vec3 r;
89
+ r.z = fract(512.0*j);
90
+ j *= .125;
91
+ r.x = fract(512.0*j);
92
+ j *= .125;
93
+ r.y = fract(512.0*j);
94
+ return r-0.5;
95
+ }
96
+
97
+ float seed = 0.0;
98
+ uint hash( uint x ) {
99
+ x += ( x << 10u );
100
+ x ^= ( x >> 6u );
101
+ x += ( x << 3u );
102
+ x ^= ( x >> 11u );
103
+ x += ( x << 15u );
104
+ return x;
105
+ }
106
+
107
+ // Compound versions of the hashing algorithm I whipped together.
108
+ uint hash( uvec2 v ) { return hash( v.x ^ hash(v.y) ); }
109
+ uint hash( uvec3 v ) { return hash( v.x ^ hash(v.y) ^ hash(v.z) ); }
110
+ uint hash( uvec4 v ) { return hash( v.x ^ hash(v.y) ^ hash(v.z) ^ hash(v.w) ); }
111
+
112
+ // Construct a float with half-open range [0:1] using low 23 bits.
113
+ // All zeroes yields 0.0, all ones yields the next smallest representable value below 1.0.
114
+ float floatConstruct( uint m ) {
115
+ const uint ieeeMantissa = 0x007FFFFFu; // binary32 mantissa bitmask
116
+ const uint ieeeOne = 0x3F800000u; // 1.0 in IEEE binary32
117
+
118
+ m &= ieeeMantissa; // Keep only mantissa bits (fractional part)
119
+ m |= ieeeOne; // Add fractional part to 1.0
120
+
121
+ float f = uintBitsToFloat( m ); // Range [1:2]
122
+ return f - 1.0; // Range [0:1]
123
+ }
124
+
125
+ // Pseudo-random value in half-open range [0:1].
126
+ float random( float x ) { return floatConstruct(hash(floatBitsToUint(x))); }
127
+ float random( vec2 v ) { return floatConstruct(hash(floatBitsToUint(v))); }
128
+ float random( vec3 v ) { return floatConstruct(hash(floatBitsToUint(v))); }
129
+ float random( vec4 v ) { return floatConstruct(hash(floatBitsToUint(v))); }
130
+
131
+ float rand() {
132
+ float result = random(vec3(gl_FragCoord.xy, seed));
133
+ seed += 1.0;
134
+ return result;
135
+ }
136
+
137
+ const float F3 = 0.3333333;
138
+ const float G3 = 0.1666667;
139
+
140
+ float snoise(vec3 p) {
141
+ vec3 s = floor(p + dot(p, vec3(F3)));
142
+ vec3 x = p - s + dot(s, vec3(G3));
143
+ vec3 e = step(vec3(0.0), x - x.yzx);
144
+ vec3 i1 = e*(1.0 - e.zxy);
145
+ vec3 i2 = 1.0 - e.zxy*(1.0 - e);
146
+ vec3 x1 = x - i1 + G3;
147
+ vec3 x2 = x - i2 + 2.0*G3;
148
+ vec3 x3 = x - 1.0 + 3.0*G3;
149
+ vec4 w, d;
150
+ w.x = dot(x, x);
151
+ w.y = dot(x1, x1);
152
+ w.z = dot(x2, x2);
153
+ w.w = dot(x3, x3);
154
+ w = max(0.6 - w, 0.0);
155
+ d.x = dot(random3(s), x);
156
+ d.y = dot(random3(s + i1), x1);
157
+ d.z = dot(random3(s + i2), x2);
158
+ d.w = dot(random3(s + 1.0), x3);
159
+ w *= w;
160
+ w *= w;
161
+ d *= w;
162
+ return dot(d, vec4(52.0));
163
+ }
164
+
165
+ float snoiseFractal(vec3 m) {
166
+ return 0.5333333* snoise(m)
167
+ +0.2666667* snoise(2.0*m)
168
+ +0.1333333* snoise(4.0*m)
169
+ +0.0666667* snoise(8.0*m);
55
170
  }\n` + shader.fragmentShader; // Remove transmission
56
171
 
57
- shader.fragmentShader = shader.fragmentShader.replace('#include <transmission_pars_fragment>', '');
58
- shader.fragmentShader = shader.fragmentShader.replace('#include <transmission_fragment>', ''); // Add refraction
59
-
60
- shader.fragmentShader = shader.fragmentShader.replace('vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;', `vec2 uv = gl_FragCoord.xy / resolution.xy;
61
- vec2 refractNormal = vNormal.xy * (1.0 - vNormal.z * 0.85);
62
- vec3 refractCol = vec3(0.0);
63
- float randomCoords = rand(uv);
64
- vec2 randomCoords2;
65
- float roughBlur = roughness * roughness;
66
- float slide;
67
- #pragma unroll_loop_start
68
- for (int i = 0; i < ${samples}; i ++) {
69
- slide = float(UNROLLED_LOOP_INDEX) / float(${samples}) * 0.1 + randomCoords * noise;
70
- randomCoords2 = vec2(rand(uv + randomCoords + 0.1 * float(UNROLLED_LOOP_INDEX)), rand(uv - randomCoords - 0.1 * float(UNROLLED_LOOP_INDEX))) - 0.5;
71
- randomCoords2 = normalize(randomCoords2) * sqrt(rand(uv + 0.12 * float(UNROLLED_LOOP_INDEX)));
72
- refractCol.r += texture2D(buffer, uv - refractNormal * (refraction + slide * 1.0) * rgbShift + randomCoords2 * roughBlur).r;
73
- refractCol.g += texture2D(buffer, uv - refractNormal * (refraction + slide * 2.0) * rgbShift + randomCoords2 * roughBlur).g;
74
- refractCol.b += texture2D(buffer, uv - refractNormal * (refraction + slide * 3.0) * rgbShift + randomCoords2 * roughBlur).b;
75
- refractCol = sat(refractCol, saturation);
172
+ shader.fragmentShader = shader.fragmentShader.replace('#include <transmission_pars_fragment>',
173
+ /*glsl*/
174
+ `
175
+ #ifdef USE_TRANSMISSION
176
+ // Transmission code is based on glTF-Sampler-Viewer
177
+ // https://github.com/KhronosGroup/glTF-Sample-Viewer
178
+ uniform float _transmission;
179
+ uniform float thickness;
180
+ uniform float attenuationDistance;
181
+ uniform vec3 attenuationColor;
182
+ #ifdef USE_TRANSMISSIONMAP
183
+ uniform sampler2D transmissionMap;
184
+ #endif
185
+ #ifdef USE_THICKNESSMAP
186
+ uniform sampler2D thicknessMap;
187
+ #endif
188
+ uniform vec2 transmissionSamplerSize;
189
+ uniform sampler2D transmissionSamplerMap;
190
+ uniform mat4 modelMatrix;
191
+ uniform mat4 projectionMatrix;
192
+ varying vec3 vWorldPosition;
193
+ vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {
194
+ // Direction of refracted light.
195
+ vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );
196
+ // Compute rotation-independant scaling of the model matrix.
197
+ vec3 modelScale;
198
+ modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );
199
+ modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );
200
+ modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );
201
+ // The thickness is specified in local space.
202
+ return normalize( refractionVector ) * thickness * modelScale;
203
+ }
204
+ float applyIorToRoughness( const in float roughness, const in float ior ) {
205
+ // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
206
+ // an IOR of 1.5 results in the default amount of microfacet refraction.
207
+ return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );
208
+ }
209
+ vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {
210
+ return texture2D(buffer, fragCoord.xy);
211
+ }
212
+ vec3 applyVolumeAttenuation( const in vec3 radiance, const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {
213
+ if ( isinf( attenuationDistance ) ) {
214
+ // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
215
+ return radiance;
216
+ } else {
217
+ // Compute light attenuation using Beer's law.
218
+ vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;
219
+ vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); // Beer's law
220
+ return transmittance * radiance;
221
+ }
222
+ }
223
+ vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,
224
+ const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,
225
+ const in mat4 viewMatrix, const in mat4 projMatrix, const in float ior, const in float thickness,
226
+ const in vec3 attenuationColor, const in float attenuationDistance ) {
227
+ vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
228
+ vec3 refractedRayExit = position + transmissionRay;
229
+ // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
230
+ vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );
231
+ vec2 refractionCoords = ndcPos.xy / ndcPos.w;
232
+ refractionCoords += 1.0;
233
+ refractionCoords /= 2.0;
234
+ // Sample framebuffer to get pixel the refracted ray hits.
235
+ vec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
236
+ vec3 attenuatedColor = applyVolumeAttenuation( transmittedLight.rgb, length( transmissionRay ), attenuationColor, attenuationDistance );
237
+ // Get the specular component.
238
+ vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );
239
+ return vec4( ( 1.0 - F ) * attenuatedColor * diffuseColor, transmittedLight.a );
240
+ }
241
+ #endif\n`); // Add refraction
242
+
243
+ shader.fragmentShader = shader.fragmentShader.replace('#include <transmission_fragment>',
244
+ /*glsl*/
245
+ `
246
+ vec2 uv = gl_FragCoord.xy / resolution.xy;
247
+ // Improve the refraction to use the world pos
248
+ material.transmission = _transmission;
249
+ material.transmissionAlpha = 1.0;
250
+ material.thickness = thickness;
251
+ material.attenuationDistance = attenuationDistance;
252
+ material.attenuationColor = attenuationColor;
253
+ #ifdef USE_TRANSMISSIONMAP
254
+ material.transmission *= texture2D( transmissionMap, vUv ).r;
255
+ #endif
256
+ #ifdef USE_THICKNESSMAP
257
+ material.thickness *= texture2D( thicknessMap, vUv ).g;
258
+ #endif
259
+
260
+ vec3 pos = vWorldPosition;
261
+ vec3 v = normalize( cameraPosition - pos );
262
+ vec3 n = inverseTransformDirection( normal, viewMatrix );
263
+ vec3 transmission = vec3(0.0);
264
+ float transmissionR, transmissionB, transmissionG;
265
+ float randomCoords = rand();
266
+ float thickness_smear = thickness * max(pow(roughness, 0.33), anisotropy);
267
+ vec3 distortionNormal = vec3(0.0);
268
+ vec3 temporalOffset = vec3(time, -time, -time) * temporalDistortion;
269
+ if (distortion > 0.0) {
270
+ distortionNormal = distortion * vec3(snoiseFractal(vec3((pos * distortionScale + temporalOffset))), snoiseFractal(vec3(pos.zxy * distortionScale - temporalOffset)), snoiseFractal(vec3(pos.yxz * distortionScale + temporalOffset)));
271
+ }
272
+ for (float i = 0.0; i < ${samples}.0; i ++) {
273
+ vec3 sampleNorm = normalize(n + roughness * roughness * 2.0 * normalize(vec3(rand() - 0.5, rand() - 0.5, rand() - 0.5)) * pow(rand(), 0.33) + distortionNormal);
274
+ transmissionR = getIBLVolumeRefraction(
275
+ sampleNorm, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,
276
+ pos, modelMatrix, viewMatrix, projectionMatrix, material.ior, material.thickness + thickness_smear * (i + randomCoords) / float(${samples}),
277
+ material.attenuationColor, material.attenuationDistance
278
+ ).r;
279
+ transmissionG = getIBLVolumeRefraction(
280
+ sampleNorm, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,
281
+ pos, modelMatrix, viewMatrix, projectionMatrix, material.ior * (1.0 + chromaticAberration * (i + randomCoords) / float(${samples})) , material.thickness + thickness_smear * (i + randomCoords) / float(${samples}),
282
+ material.attenuationColor, material.attenuationDistance
283
+ ).g;
284
+ transmissionB = getIBLVolumeRefraction(
285
+ sampleNorm, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,
286
+ pos, modelMatrix, viewMatrix, projectionMatrix, material.ior * (1.0 + 2.0 * chromaticAberration * (i + randomCoords) / float(${samples})), material.thickness + thickness_smear * (i + randomCoords) / float(${samples}),
287
+ material.attenuationColor, material.attenuationDistance
288
+ ).b;
289
+ transmission.r += transmissionR;
290
+ transmission.g += transmissionG;
291
+ transmission.b += transmissionB;
76
292
  }
77
- #pragma unroll_loop_end
78
- refractCol /= float(${samples});
79
- vec3 outgoingLight = (refractCol * totalDiffuse * contrast) + totalSpecular + totalEmissiveRadiance;`);
293
+ transmission /= ${samples}.0;
294
+ totalDiffuse = mix( totalDiffuse, transmission.rgb, material.transmission );\n`);
80
295
  };
81
296
 
82
297
  Object.keys(this.uniforms).forEach(name => Object.defineProperty(this, name, {
@@ -89,8 +304,10 @@ class MeshTransmissionMaterialImpl extends THREE.MeshPhysicalMaterial {
89
304
 
90
305
  const MeshTransmissionMaterial = /*#__PURE__*/React.forwardRef(({
91
306
  buffer,
307
+ transmission = 1,
308
+ distortionSpeed = 1,
92
309
  samples = 10,
93
- resolution = 1024,
310
+ resolution,
94
311
  background,
95
312
  ...props
96
313
  }, fref) => {
@@ -103,15 +320,13 @@ const MeshTransmissionMaterial = /*#__PURE__*/React.forwardRef(({
103
320
  viewport
104
321
  } = useThree();
105
322
  const fbo = useFBO(resolution);
106
- const config = React.useMemo(() => ({
107
- samples
108
- }), [samples]);
109
323
  let oldBg;
110
324
  let oldVis;
111
325
  let parent;
112
326
  useFrame(state => {
113
327
  if (!buffer) {
114
328
  parent = ref.current.__r3f.parent;
329
+ ref.current.time = state.clock.getElapsedTime() * distortionSpeed;
115
330
 
116
331
  if (parent) {
117
332
  // Hide the outer groups contents
@@ -135,11 +350,19 @@ const MeshTransmissionMaterial = /*#__PURE__*/React.forwardRef(({
135
350
 
136
351
  React.useImperativeHandle(fref, () => ref.current, []);
137
352
  return /*#__PURE__*/React.createElement("meshTransmissionMaterial", _extends({
138
- args: [config],
139
- ref: ref,
140
- buffer: buffer || fbo.texture,
353
+ args: [React.useMemo(() => ({
354
+ samples
355
+ }), [samples])],
356
+ ref: ref
357
+ }, props, {
358
+ buffer: buffer || fbo.texture // @ts-ignore
359
+ ,
360
+ _transmission: transmission // In order for this to not incur extra cost "transmission" must be set to 0 and treated as a reserved prop.
361
+ // This is because THREE.WebGLRenderer will check for transmission > 0 and executed extra renders.
362
+ ,
363
+ transmission: 0,
141
364
  resolution: [size.width * viewport.dpr, size.height * viewport.dpr]
142
- }, props));
365
+ }));
143
366
  });
144
367
 
145
368
  export { MeshTransmissionMaterial };