@react-three/drei 9.74.11 → 9.74.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (189) hide show
  1. package/core/CatmullRomLine.js +2 -0
  2. package/core/Cloud.js +3 -0
  3. package/core/CubeCamera.js +1 -0
  4. package/core/CubicBezierLine.js +2 -0
  5. package/core/Environment.js +1 -0
  6. package/core/Example.js +6 -0
  7. package/core/FaceControls.cjs.js +1 -1
  8. package/core/FaceControls.js +2 -0
  9. package/core/FaceLandmarker.cjs.js +1 -1
  10. package/core/FaceLandmarker.js +3 -2
  11. package/core/Facemesh.js +2 -0
  12. package/core/GizmoHelper.js +3 -0
  13. package/core/GizmoViewcube.js +4 -0
  14. package/core/GizmoViewport.js +4 -0
  15. package/core/Gltf.js +4 -0
  16. package/core/MeshDiscardMaterial.js +2 -0
  17. package/core/MeshDistortMaterial.js +2 -1
  18. package/core/MeshReflectorMaterial.js +1 -0
  19. package/core/MeshRefractionMaterial.js +2 -0
  20. package/core/MeshTransmissionMaterial.js +1 -0
  21. package/core/OrthographicCamera.js +1 -0
  22. package/core/PerspectiveCamera.js +1 -0
  23. package/core/QuadraticBezierLine.js +2 -0
  24. package/core/Reflector.js +1 -0
  25. package/core/SpotLight.js +2 -1
  26. package/core/Stage.js +7 -0
  27. package/core/Text3D.js +1 -0
  28. package/core/Wireframe.js +1 -0
  29. package/core/index.cjs.js +1 -1
  30. package/core/index.js +0 -1
  31. package/core/useKTX2.js +1 -0
  32. package/core/useMatcapTexture.js +2 -0
  33. package/core/useNormalTexture.js +1 -0
  34. package/index.cjs.js +1 -1
  35. package/materials/DiscardMaterial.js +1 -0
  36. package/materials/MeshRefractionMaterial.js +1 -1
  37. package/native/index.cjs.js +1 -1
  38. package/native/index.js +0 -1
  39. package/package.json +9 -9
  40. package/src/core/AccumulativeShadows.js +311 -0
  41. package/src/core/AdaptiveDpr.js +28 -0
  42. package/src/core/AdaptiveEvents.js +20 -0
  43. package/src/core/ArcballControls.js +67 -0
  44. package/src/core/AsciiRenderer.js +60 -0
  45. package/src/core/BBAnchor.js +37 -0
  46. package/src/core/Backdrop.js +36 -0
  47. package/src/core/BakeShadows.js +16 -0
  48. package/src/core/Billboard.js +41 -0
  49. package/src/core/Bounds.js +245 -0
  50. package/src/core/CameraControls.js +92 -0
  51. package/src/core/CameraShake.js +61 -0
  52. package/src/core/CatmullRomLine.js +44 -0
  53. package/src/core/Caustics.js +375 -0
  54. package/src/core/Center.js +66 -0
  55. package/src/core/Clone.js +102 -0
  56. package/src/core/Cloud.js +59 -0
  57. package/src/core/ComputedAttribute.js +34 -0
  58. package/src/core/ContactShadows.js +114 -0
  59. package/src/core/CubeCamera.js +43 -0
  60. package/src/core/CubicBezierLine.js +28 -0
  61. package/src/core/CurveModifier.js +34 -0
  62. package/src/core/Decal.js +92 -0
  63. package/src/core/Detailed.js +34 -0
  64. package/src/core/DeviceOrientationControls.js +51 -0
  65. package/src/core/Edges.js +36 -0
  66. package/src/core/Effects.js +93 -0
  67. package/src/core/Environment.js +132 -0
  68. package/src/core/Example.js +42 -0
  69. package/src/core/FaceControls.js +315 -0
  70. package/src/core/FaceLandmarker.js +43 -0
  71. package/src/core/Facemesh.js +4545 -0
  72. package/src/core/FirstPersonControls.js +38 -0
  73. package/src/core/Float.js +36 -0
  74. package/src/core/FlyControls.js +55 -0
  75. package/src/core/GizmoHelper.js +111 -0
  76. package/src/core/GizmoViewcube.js +152 -0
  77. package/src/core/GizmoViewport.js +152 -0
  78. package/src/core/Gltf.js +20 -0
  79. package/src/core/GradientTexture.js +33 -0
  80. package/src/core/Grid.js +112 -0
  81. package/src/core/Hud.js +58 -0
  82. package/src/core/Image.js +119 -0
  83. package/src/core/Instances.js +215 -0
  84. package/src/core/Lightformer.js +51 -0
  85. package/src/core/Line.js +68 -0
  86. package/src/core/MapControls.js +64 -0
  87. package/src/core/MarchingCubes.js +76 -0
  88. package/src/core/Mask.js +42 -0
  89. package/src/core/MeshDiscardMaterial.js +15 -0
  90. package/src/core/MeshDistortMaterial.js +79 -0
  91. package/src/core/MeshPortalMaterial.js +381 -0
  92. package/src/core/MeshReflectorMaterial.js +182 -0
  93. package/src/core/MeshRefractionMaterial.js +79 -0
  94. package/src/core/MeshTransmissionMaterial.js +395 -0
  95. package/src/core/MeshWobbleMaterial.js +65 -0
  96. package/src/core/OrbitControls.js +82 -0
  97. package/src/core/OrthographicCamera.js +77 -0
  98. package/src/core/PerformanceMonitor.js +121 -0
  99. package/src/core/PerspectiveCamera.js +73 -0
  100. package/src/core/PointMaterial.js +36 -0
  101. package/src/core/PointerLockControls.js +90 -0
  102. package/src/core/Points.js +227 -0
  103. package/src/core/PositionalAudio.js +51 -0
  104. package/src/core/Preload.js +45 -0
  105. package/src/core/QuadraticBezierLine.js +44 -0
  106. package/src/core/Reflector.js +182 -0
  107. package/src/core/RenderTexture.js +96 -0
  108. package/src/core/Resize.js +39 -0
  109. package/src/core/RoundedBox.js +52 -0
  110. package/src/core/Sampler.js +85 -0
  111. package/src/core/ScreenQuad.js +24 -0
  112. package/src/core/ScreenSpace.js +25 -0
  113. package/src/core/Segments.js +102 -0
  114. package/src/core/Shadow.js +42 -0
  115. package/src/core/Sky.js +39 -0
  116. package/src/core/Sparkles.js +139 -0
  117. package/src/core/SpotLight.js +231 -0
  118. package/src/core/SpriteAnimator.js +342 -0
  119. package/src/core/Stage.js +135 -0
  120. package/src/core/Stars.js +108 -0
  121. package/src/core/Stats.js +30 -0
  122. package/src/core/Svg.js +59 -0
  123. package/src/core/Text.js +58 -0
  124. package/src/core/Text3D.js +76 -0
  125. package/src/core/TrackballControls.js +72 -0
  126. package/src/core/Trail.js +161 -0
  127. package/src/core/TransformControls.js +106 -0
  128. package/src/core/Wireframe.js +185 -0
  129. package/src/core/meshBounds.js +38 -0
  130. package/src/core/shaderMaterial.js +39 -0
  131. package/src/core/shapes.js +68 -0
  132. package/src/core/softShadows.js +161 -0
  133. package/src/core/useAnimations.js +56 -0
  134. package/src/core/useAspect.js +10 -0
  135. package/src/core/useBVH.js +90 -0
  136. package/src/core/useBoxProjectedEnv.js +98 -0
  137. package/src/core/useCamera.js +27 -0
  138. package/src/core/useContextBridge.js +21 -0
  139. package/src/core/useCubeCamera.js +49 -0
  140. package/src/core/useCubeTexture.js +18 -0
  141. package/src/core/useDepthBuffer.js +38 -0
  142. package/src/core/useDetectGPU.js +6 -0
  143. package/src/core/useEnvironment.js +48 -0
  144. package/src/core/useFBO.js +53 -0
  145. package/src/core/useFBX.js +12 -0
  146. package/src/core/useFont.js +20 -0
  147. package/src/core/useGLTF.js +37 -0
  148. package/src/core/useHelper.js +31 -0
  149. package/src/core/useIntersect.js +39 -0
  150. package/src/core/useKTX2.js +38 -0
  151. package/src/core/useMatcapTexture.js +45 -0
  152. package/src/core/useNormalTexture.js +30 -0
  153. package/src/core/useProgress.js +50 -0
  154. package/src/core/useTexture.js +35 -0
  155. package/src/core/useTrailTexture.js +164 -0
  156. package/src/core/useVideoTexture.js +41 -0
  157. package/src/helpers/environment-assets.js +14 -0
  158. package/src/helpers/useEffectfulState.js +18 -0
  159. package/src/materials/BlurPass.js +75 -0
  160. package/src/materials/ConvolutionMaterial.js +99 -0
  161. package/src/materials/DiscardMaterial.js +5 -0
  162. package/src/materials/MeshReflectorMaterial.js +290 -0
  163. package/src/materials/MeshRefractionMaterial.js +171 -0
  164. package/src/materials/SpotLightMaterial.js +111 -0
  165. package/src/materials/WireframeMaterial.js +235 -0
  166. package/src/web/CycleRaycast.js +97 -0
  167. package/src/web/Html.js +417 -0
  168. package/src/web/KeyboardControls.js +101 -0
  169. package/src/web/Loader.js +98 -0
  170. package/src/web/PresentationControls.js +86 -0
  171. package/src/web/ScrollControls.js +246 -0
  172. package/src/web/Select.js +175 -0
  173. package/src/web/View.js +206 -0
  174. package/src/web/pivotControls/AxisArrow.js +202 -0
  175. package/src/web/pivotControls/AxisRotator.js +235 -0
  176. package/src/web/pivotControls/PlaneSlider.js +211 -0
  177. package/src/web/pivotControls/context.js +5 -0
  178. package/src/web/pivotControls/index.js +223 -0
  179. package/src/web/useCursor.js +12 -0
  180. package/web/Loader.js +2 -0
  181. package/web/index.cjs.js +1 -1
  182. package/web/index.js +0 -1
  183. package/web/pivotControls/AxisArrow.js +3 -0
  184. package/web/pivotControls/AxisRotator.js +3 -0
  185. package/web/pivotControls/PlaneSlider.js +3 -0
  186. package/web/pivotControls/index.js +5 -0
  187. /package/{helpers → src/helpers}/glsl/DefaultSpotlightShadowShadows.glsl.js +0 -0
  188. /package/{helpers → src/helpers}/glsl/distort.vert.glsl.js +0 -0
  189. /package/{index.js → src/index.js} +0 -0
@@ -0,0 +1,182 @@
1
+ import _extends from '@babel/runtime/helpers/esm/extends';
2
+ import * as React from 'react';
3
+ import { Plane, Vector3, Matrix4, Vector4, PerspectiveCamera, WebGLRenderTarget, DepthTexture, DepthFormat, UnsignedShortType, LinearFilter, HalfFloatType } from 'three';
4
+ import { extend, useThree, useFrame } from '@react-three/fiber';
5
+ import mergeRefs from 'react-merge-refs';
6
+ import { BlurPass } from '../materials/BlurPass.js';
7
+ import { MeshReflectorMaterial as MeshReflectorMaterial$1 } from '../materials/MeshReflectorMaterial.js';
8
+
9
+ extend({
10
+ MeshReflectorMaterialImpl: MeshReflectorMaterial$1
11
+ });
12
+ const MeshReflectorMaterial = /*#__PURE__*/React.forwardRef(({
13
+ mixBlur = 0,
14
+ mixStrength = 1,
15
+ resolution = 256,
16
+ blur = [0, 0],
17
+ minDepthThreshold = 0.9,
18
+ maxDepthThreshold = 1,
19
+ depthScale = 0,
20
+ depthToBlurRatioBias = 0.25,
21
+ mirror = 0,
22
+ distortion = 1,
23
+ mixContrast = 1,
24
+ distortionMap,
25
+ reflectorOffset = 0,
26
+ ...props
27
+ }, ref) => {
28
+ const gl = useThree(({
29
+ gl
30
+ }) => gl);
31
+ const camera = useThree(({
32
+ camera
33
+ }) => camera);
34
+ const scene = useThree(({
35
+ scene
36
+ }) => scene);
37
+ blur = Array.isArray(blur) ? blur : [blur, blur];
38
+ const hasBlur = blur[0] + blur[1] > 0;
39
+ const materialRef = React.useRef(null);
40
+ const [reflectorPlane] = React.useState(() => new Plane());
41
+ const [normal] = React.useState(() => new Vector3());
42
+ const [reflectorWorldPosition] = React.useState(() => new Vector3());
43
+ const [cameraWorldPosition] = React.useState(() => new Vector3());
44
+ const [rotationMatrix] = React.useState(() => new Matrix4());
45
+ const [lookAtPosition] = React.useState(() => new Vector3(0, 0, -1));
46
+ const [clipPlane] = React.useState(() => new Vector4());
47
+ const [view] = React.useState(() => new Vector3());
48
+ const [target] = React.useState(() => new Vector3());
49
+ const [q] = React.useState(() => new Vector4());
50
+ const [textureMatrix] = React.useState(() => new Matrix4());
51
+ const [virtualCamera] = React.useState(() => new PerspectiveCamera());
52
+ const beforeRender = React.useCallback(() => {
53
+ var _materialRef$current;
54
+
55
+ // TODO: As of R3f 7-8 this should be __r3f.parent
56
+ const parent = materialRef.current.parent || ((_materialRef$current = materialRef.current) == null ? void 0 : _materialRef$current.__r3f.parent);
57
+ if (!parent) return;
58
+ reflectorWorldPosition.setFromMatrixPosition(parent.matrixWorld);
59
+ cameraWorldPosition.setFromMatrixPosition(camera.matrixWorld);
60
+ rotationMatrix.extractRotation(parent.matrixWorld);
61
+ normal.set(0, 0, 1);
62
+ normal.applyMatrix4(rotationMatrix);
63
+ reflectorWorldPosition.addScaledVector(normal, reflectorOffset);
64
+ view.subVectors(reflectorWorldPosition, cameraWorldPosition); // Avoid rendering when reflector is facing away
65
+
66
+ if (view.dot(normal) > 0) return;
67
+ view.reflect(normal).negate();
68
+ view.add(reflectorWorldPosition);
69
+ rotationMatrix.extractRotation(camera.matrixWorld);
70
+ lookAtPosition.set(0, 0, -1);
71
+ lookAtPosition.applyMatrix4(rotationMatrix);
72
+ lookAtPosition.add(cameraWorldPosition);
73
+ target.subVectors(reflectorWorldPosition, lookAtPosition);
74
+ target.reflect(normal).negate();
75
+ target.add(reflectorWorldPosition);
76
+ virtualCamera.position.copy(view);
77
+ virtualCamera.up.set(0, 1, 0);
78
+ virtualCamera.up.applyMatrix4(rotationMatrix);
79
+ virtualCamera.up.reflect(normal);
80
+ virtualCamera.lookAt(target);
81
+ virtualCamera.far = camera.far; // Used in WebGLBackground
82
+
83
+ virtualCamera.updateMatrixWorld();
84
+ virtualCamera.projectionMatrix.copy(camera.projectionMatrix); // Update the texture matrix
85
+
86
+ textureMatrix.set(0.5, 0.0, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0);
87
+ textureMatrix.multiply(virtualCamera.projectionMatrix);
88
+ textureMatrix.multiply(virtualCamera.matrixWorldInverse);
89
+ textureMatrix.multiply(parent.matrixWorld); // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
90
+ // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
91
+
92
+ reflectorPlane.setFromNormalAndCoplanarPoint(normal, reflectorWorldPosition);
93
+ reflectorPlane.applyMatrix4(virtualCamera.matrixWorldInverse);
94
+ clipPlane.set(reflectorPlane.normal.x, reflectorPlane.normal.y, reflectorPlane.normal.z, reflectorPlane.constant);
95
+ const projectionMatrix = virtualCamera.projectionMatrix;
96
+ q.x = (Math.sign(clipPlane.x) + projectionMatrix.elements[8]) / projectionMatrix.elements[0];
97
+ q.y = (Math.sign(clipPlane.y) + projectionMatrix.elements[9]) / projectionMatrix.elements[5];
98
+ q.z = -1.0;
99
+ q.w = (1.0 + projectionMatrix.elements[10]) / projectionMatrix.elements[14]; // Calculate the scaled plane vector
100
+
101
+ clipPlane.multiplyScalar(2.0 / clipPlane.dot(q)); // Replacing the third row of the projection matrix
102
+
103
+ projectionMatrix.elements[2] = clipPlane.x;
104
+ projectionMatrix.elements[6] = clipPlane.y;
105
+ projectionMatrix.elements[10] = clipPlane.z + 1.0;
106
+ projectionMatrix.elements[14] = clipPlane.w;
107
+ }, [camera, reflectorOffset]);
108
+ const [fbo1, fbo2, blurpass, reflectorProps] = React.useMemo(() => {
109
+ const parameters = {
110
+ minFilter: LinearFilter,
111
+ magFilter: LinearFilter,
112
+ type: HalfFloatType
113
+ };
114
+ const fbo1 = new WebGLRenderTarget(resolution, resolution, parameters);
115
+ fbo1.depthBuffer = true;
116
+ fbo1.depthTexture = new DepthTexture(resolution, resolution);
117
+ fbo1.depthTexture.format = DepthFormat;
118
+ fbo1.depthTexture.type = UnsignedShortType;
119
+ const fbo2 = new WebGLRenderTarget(resolution, resolution, parameters);
120
+ const blurpass = new BlurPass({
121
+ gl,
122
+ resolution,
123
+ width: blur[0],
124
+ height: blur[1],
125
+ minDepthThreshold,
126
+ maxDepthThreshold,
127
+ depthScale,
128
+ depthToBlurRatioBias
129
+ });
130
+ const reflectorProps = {
131
+ mirror,
132
+ textureMatrix,
133
+ mixBlur,
134
+ tDiffuse: fbo1.texture,
135
+ tDepth: fbo1.depthTexture,
136
+ tDiffuseBlur: fbo2.texture,
137
+ hasBlur,
138
+ mixStrength,
139
+ minDepthThreshold,
140
+ maxDepthThreshold,
141
+ depthScale,
142
+ depthToBlurRatioBias,
143
+ distortion,
144
+ distortionMap,
145
+ mixContrast,
146
+ 'defines-USE_BLUR': hasBlur ? '' : undefined,
147
+ 'defines-USE_DEPTH': depthScale > 0 ? '' : undefined,
148
+ 'defines-USE_DISTORTION': distortionMap ? '' : undefined
149
+ };
150
+ return [fbo1, fbo2, blurpass, reflectorProps];
151
+ }, [gl, blur, textureMatrix, resolution, mirror, hasBlur, mixBlur, mixStrength, minDepthThreshold, maxDepthThreshold, depthScale, depthToBlurRatioBias, distortion, distortionMap, mixContrast]);
152
+ useFrame(() => {
153
+ var _materialRef$current2;
154
+
155
+ // TODO: As of R3f 7-8 this should be __r3f.parent
156
+ const parent = materialRef.current.parent || ((_materialRef$current2 = materialRef.current) == null ? void 0 : _materialRef$current2.__r3f.parent);
157
+ if (!parent) return;
158
+ parent.visible = false;
159
+ const currentXrEnabled = gl.xr.enabled;
160
+ const currentShadowAutoUpdate = gl.shadowMap.autoUpdate;
161
+ beforeRender();
162
+ gl.xr.enabled = false;
163
+ gl.shadowMap.autoUpdate = false;
164
+ gl.setRenderTarget(fbo1);
165
+ gl.state.buffers.depth.setMask(true);
166
+ if (!gl.autoClear) gl.clear();
167
+ gl.render(scene, virtualCamera);
168
+ if (hasBlur) blurpass.render(gl, fbo1, fbo2);
169
+ gl.xr.enabled = currentXrEnabled;
170
+ gl.shadowMap.autoUpdate = currentShadowAutoUpdate;
171
+ parent.visible = true;
172
+ gl.setRenderTarget(null);
173
+ });
174
+ return /*#__PURE__*/React.createElement("meshReflectorMaterialImpl", _extends({
175
+ attach: "material" // Defines can't be updated dynamically, so we need to recreate the material
176
+ ,
177
+ key: 'key' + reflectorProps['defines-USE_BLUR'] + reflectorProps['defines-USE_DEPTH'] + reflectorProps['defines-USE_DISTORTION'],
178
+ ref: mergeRefs([materialRef, ref])
179
+ }, reflectorProps, props));
180
+ });
181
+
182
+ export { MeshReflectorMaterial };
@@ -0,0 +1,79 @@
1
+ import _extends from '@babel/runtime/helpers/esm/extends';
2
+ import * as React from 'react';
3
+ import { useRef, useMemo, useLayoutEffect } from 'react';
4
+ import { extend, useThree, useFrame } from '@react-three/fiber';
5
+ import { MeshBVHUniformStruct, MeshBVH, SAH } from 'three-mesh-bvh';
6
+ import { MeshRefractionMaterial as MeshRefractionMaterial$1 } from '../materials/MeshRefractionMaterial.js';
7
+
8
+ const isCubeTexture = def => def && def.isCubeTexture;
9
+
10
+ function MeshRefractionMaterial({
11
+ aberrationStrength = 0,
12
+ fastChroma = true,
13
+ envMap,
14
+ ...props
15
+ }) {
16
+ extend({
17
+ MeshRefractionMaterial: MeshRefractionMaterial$1
18
+ });
19
+ const material = useRef();
20
+ const {
21
+ size
22
+ } = useThree();
23
+ const defines = useMemo(() => {
24
+ var _ref, _envMap$image$;
25
+
26
+ const temp = {}; // Sampler2D and SamplerCube need different defines
27
+
28
+ const isCubeMap = isCubeTexture(envMap);
29
+ const w = (_ref = isCubeMap ? (_envMap$image$ = envMap.image[0]) == null ? void 0 : _envMap$image$.width : envMap.image.width) !== null && _ref !== void 0 ? _ref : 1024;
30
+ const cubeSize = w / 4;
31
+
32
+ const _lodMax = Math.floor(Math.log2(cubeSize));
33
+
34
+ const _cubeSize = Math.pow(2, _lodMax);
35
+
36
+ const width = 3 * Math.max(_cubeSize, 16 * 7);
37
+ const height = 4 * _cubeSize;
38
+ if (isCubeMap) temp.ENVMAP_TYPE_CUBEM = '';
39
+ temp.CUBEUV_TEXEL_WIDTH = `${1.0 / width}`;
40
+ temp.CUBEUV_TEXEL_HEIGHT = `${1.0 / height}`;
41
+ temp.CUBEUV_MAX_MIP = `${_lodMax}.0`; // Add defines from chromatic aberration
42
+
43
+ if (aberrationStrength > 0) temp.CHROMATIC_ABERRATIONS = '';
44
+ if (fastChroma) temp.FAST_CHROMA = '';
45
+ return temp;
46
+ }, [aberrationStrength, fastChroma]);
47
+ useLayoutEffect(() => {
48
+ var _material$current, _material$current$__r, _material$current$__r2;
49
+
50
+ // Get the geometry of this materials parent
51
+ const geometry = (_material$current = material.current) == null ? void 0 : (_material$current$__r = _material$current.__r3f) == null ? void 0 : (_material$current$__r2 = _material$current$__r.parent) == null ? void 0 : _material$current$__r2.geometry; // Update the BVH
52
+
53
+ if (geometry) {
54
+ material.current.bvh = new MeshBVHUniformStruct();
55
+ material.current.bvh.updateFrom(new MeshBVH(geometry.clone().toNonIndexed(), {
56
+ lazyGeneration: false,
57
+ strategy: SAH
58
+ }));
59
+ }
60
+ }, []);
61
+ useFrame(({
62
+ camera
63
+ }) => {
64
+ material.current.viewMatrixInverse = camera.matrixWorld;
65
+ material.current.projectionMatrixInverse = camera.projectionMatrixInverse;
66
+ });
67
+ return /*#__PURE__*/React.createElement("meshRefractionMaterial", _extends({
68
+ // @ts-ignore
69
+ key: JSON.stringify(defines) // @ts-ignore
70
+ ,
71
+ defines: defines,
72
+ ref: material,
73
+ resolution: [size.width, size.height],
74
+ aberrationStrength: aberrationStrength,
75
+ envMap: envMap
76
+ }, props));
77
+ }
78
+
79
+ export { MeshRefractionMaterial };
@@ -0,0 +1,395 @@
1
+ import _extends from '@babel/runtime/helpers/esm/extends';
2
+ import * as THREE from 'three';
3
+ import * as React from 'react';
4
+ import { extend, useFrame } from '@react-three/fiber';
5
+ import { useFBO } from './useFBO.js';
6
+ import { DiscardMaterial } from '../materials/DiscardMaterial.js';
7
+
8
+ class MeshTransmissionMaterialImpl extends THREE.MeshPhysicalMaterial {
9
+ constructor(samples = 6, transmissionSampler = false) {
10
+ super();
11
+ this.uniforms = {
12
+ chromaticAberration: {
13
+ value: 0.05
14
+ },
15
+ // Transmission must always be 0, unless transmissionSampler is being used
16
+ transmission: {
17
+ value: 0
18
+ },
19
+ // Instead a workaround is used, see below for reasons why
20
+ _transmission: {
21
+ value: 1
22
+ },
23
+ transmissionMap: {
24
+ value: null
25
+ },
26
+ // Roughness is 1 in THREE.MeshPhysicalMaterial but it makes little sense in a transmission material
27
+ roughness: {
28
+ value: 0
29
+ },
30
+ thickness: {
31
+ value: 0
32
+ },
33
+ thicknessMap: {
34
+ value: null
35
+ },
36
+ attenuationDistance: {
37
+ value: Infinity
38
+ },
39
+ attenuationColor: {
40
+ value: new THREE.Color('white')
41
+ },
42
+ anisotropicBlur: {
43
+ value: 0.1
44
+ },
45
+ time: {
46
+ value: 0
47
+ },
48
+ distortion: {
49
+ value: 0.0
50
+ },
51
+ distortionScale: {
52
+ value: 0.5
53
+ },
54
+ temporalDistortion: {
55
+ value: 0.0
56
+ },
57
+ buffer: {
58
+ value: null
59
+ }
60
+ };
61
+
62
+ this.onBeforeCompile = shader => {
63
+ shader.uniforms = { ...shader.uniforms,
64
+ ...this.uniforms
65
+ }; // If the transmission sampler is active inject a flag
66
+
67
+ if (transmissionSampler) shader.defines.USE_SAMPLER = ''; // Otherwise we do use use .transmission and must therefore force USE_TRANSMISSION
68
+ // because threejs won't inject it for us
69
+ else shader.defines.USE_TRANSMISSION = ''; // Head
70
+
71
+ shader.fragmentShader =
72
+ /*glsl*/
73
+ `
74
+ uniform float chromaticAberration;
75
+ uniform float anisotropicBlur;
76
+ uniform float time;
77
+ uniform float distortion;
78
+ uniform float distortionScale;
79
+ uniform float temporalDistortion;
80
+ uniform sampler2D buffer;
81
+
82
+ vec3 random3(vec3 c) {
83
+ float j = 4096.0*sin(dot(c,vec3(17.0, 59.4, 15.0)));
84
+ vec3 r;
85
+ r.z = fract(512.0*j);
86
+ j *= .125;
87
+ r.x = fract(512.0*j);
88
+ j *= .125;
89
+ r.y = fract(512.0*j);
90
+ return r-0.5;
91
+ }
92
+
93
+ float seed = 0.0;
94
+ uint hash( uint x ) {
95
+ x += ( x << 10u );
96
+ x ^= ( x >> 6u );
97
+ x += ( x << 3u );
98
+ x ^= ( x >> 11u );
99
+ x += ( x << 15u );
100
+ return x;
101
+ }
102
+
103
+ // Compound versions of the hashing algorithm I whipped together.
104
+ uint hash( uvec2 v ) { return hash( v.x ^ hash(v.y) ); }
105
+ uint hash( uvec3 v ) { return hash( v.x ^ hash(v.y) ^ hash(v.z) ); }
106
+ uint hash( uvec4 v ) { return hash( v.x ^ hash(v.y) ^ hash(v.z) ^ hash(v.w) ); }
107
+
108
+ // Construct a float with half-open range [0:1] using low 23 bits.
109
+ // All zeroes yields 0.0, all ones yields the next smallest representable value below 1.0.
110
+ float floatConstruct( uint m ) {
111
+ const uint ieeeMantissa = 0x007FFFFFu; // binary32 mantissa bitmask
112
+ const uint ieeeOne = 0x3F800000u; // 1.0 in IEEE binary32
113
+ m &= ieeeMantissa; // Keep only mantissa bits (fractional part)
114
+ m |= ieeeOne; // Add fractional part to 1.0
115
+ float f = uintBitsToFloat( m ); // Range [1:2]
116
+ return f - 1.0; // Range [0:1]
117
+ }
118
+
119
+ // Pseudo-random value in half-open range [0:1].
120
+ float random( float x ) { return floatConstruct(hash(floatBitsToUint(x))); }
121
+ float random( vec2 v ) { return floatConstruct(hash(floatBitsToUint(v))); }
122
+ float random( vec3 v ) { return floatConstruct(hash(floatBitsToUint(v))); }
123
+ float random( vec4 v ) { return floatConstruct(hash(floatBitsToUint(v))); }
124
+
125
+ float rand() {
126
+ float result = random(vec3(gl_FragCoord.xy, seed));
127
+ seed += 1.0;
128
+ return result;
129
+ }
130
+
131
+ const float F3 = 0.3333333;
132
+ const float G3 = 0.1666667;
133
+
134
+ float snoise(vec3 p) {
135
+ vec3 s = floor(p + dot(p, vec3(F3)));
136
+ vec3 x = p - s + dot(s, vec3(G3));
137
+ vec3 e = step(vec3(0.0), x - x.yzx);
138
+ vec3 i1 = e*(1.0 - e.zxy);
139
+ vec3 i2 = 1.0 - e.zxy*(1.0 - e);
140
+ vec3 x1 = x - i1 + G3;
141
+ vec3 x2 = x - i2 + 2.0*G3;
142
+ vec3 x3 = x - 1.0 + 3.0*G3;
143
+ vec4 w, d;
144
+ w.x = dot(x, x);
145
+ w.y = dot(x1, x1);
146
+ w.z = dot(x2, x2);
147
+ w.w = dot(x3, x3);
148
+ w = max(0.6 - w, 0.0);
149
+ d.x = dot(random3(s), x);
150
+ d.y = dot(random3(s + i1), x1);
151
+ d.z = dot(random3(s + i2), x2);
152
+ d.w = dot(random3(s + 1.0), x3);
153
+ w *= w;
154
+ w *= w;
155
+ d *= w;
156
+ return dot(d, vec4(52.0));
157
+ }
158
+
159
+ float snoiseFractal(vec3 m) {
160
+ return 0.5333333* snoise(m)
161
+ +0.2666667* snoise(2.0*m)
162
+ +0.1333333* snoise(4.0*m)
163
+ +0.0666667* snoise(8.0*m);
164
+ }\n` + shader.fragmentShader; // Remove transmission
165
+
166
+ shader.fragmentShader = shader.fragmentShader.replace('#include <transmission_pars_fragment>',
167
+ /*glsl*/
168
+ `
169
+ #ifdef USE_TRANSMISSION
170
+ // Transmission code is based on glTF-Sampler-Viewer
171
+ // https://github.com/KhronosGroup/glTF-Sample-Viewer
172
+ uniform float _transmission;
173
+ uniform float thickness;
174
+ uniform float attenuationDistance;
175
+ uniform vec3 attenuationColor;
176
+ #ifdef USE_TRANSMISSIONMAP
177
+ uniform sampler2D transmissionMap;
178
+ #endif
179
+ #ifdef USE_THICKNESSMAP
180
+ uniform sampler2D thicknessMap;
181
+ #endif
182
+ uniform vec2 transmissionSamplerSize;
183
+ uniform sampler2D transmissionSamplerMap;
184
+ uniform mat4 modelMatrix;
185
+ uniform mat4 projectionMatrix;
186
+ varying vec3 vWorldPosition;
187
+ vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {
188
+ // Direction of refracted light.
189
+ vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );
190
+ // Compute rotation-independant scaling of the model matrix.
191
+ vec3 modelScale;
192
+ modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );
193
+ modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );
194
+ modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );
195
+ // The thickness is specified in local space.
196
+ return normalize( refractionVector ) * thickness * modelScale;
197
+ }
198
+ float applyIorToRoughness( const in float roughness, const in float ior ) {
199
+ // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
200
+ // an IOR of 1.5 results in the default amount of microfacet refraction.
201
+ return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );
202
+ }
203
+ vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {
204
+ float framebufferLod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );
205
+ #ifdef USE_SAMPLER
206
+ #ifdef texture2DLodEXT
207
+ return texture2DLodEXT(transmissionSamplerMap, fragCoord.xy, framebufferLod);
208
+ #else
209
+ return texture2D(transmissionSamplerMap, fragCoord.xy, framebufferLod);
210
+ #endif
211
+ #else
212
+ return texture2D(buffer, fragCoord.xy);
213
+ #endif
214
+ }
215
+ vec3 applyVolumeAttenuation( const in vec3 radiance, const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {
216
+ if ( isinf( attenuationDistance ) ) {
217
+ // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
218
+ return radiance;
219
+ } else {
220
+ // Compute light attenuation using Beer's law.
221
+ vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;
222
+ vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); // Beer's law
223
+ return transmittance * radiance;
224
+ }
225
+ }
226
+ vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,
227
+ const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,
228
+ const in mat4 viewMatrix, const in mat4 projMatrix, const in float ior, const in float thickness,
229
+ const in vec3 attenuationColor, const in float attenuationDistance ) {
230
+ vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
231
+ vec3 refractedRayExit = position + transmissionRay;
232
+ // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
233
+ vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );
234
+ vec2 refractionCoords = ndcPos.xy / ndcPos.w;
235
+ refractionCoords += 1.0;
236
+ refractionCoords /= 2.0;
237
+ // Sample framebuffer to get pixel the refracted ray hits.
238
+ vec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
239
+ vec3 attenuatedColor = applyVolumeAttenuation( transmittedLight.rgb, length( transmissionRay ), attenuationColor, attenuationDistance );
240
+ // Get the specular component.
241
+ vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );
242
+ return vec4( ( 1.0 - F ) * attenuatedColor * diffuseColor, transmittedLight.a );
243
+ }
244
+ #endif\n`); // Add refraction
245
+
246
+ shader.fragmentShader = shader.fragmentShader.replace('#include <transmission_fragment>',
247
+ /*glsl*/
248
+ `
249
+ // Improve the refraction to use the world pos
250
+ material.transmission = _transmission;
251
+ material.transmissionAlpha = 1.0;
252
+ material.thickness = thickness;
253
+ material.attenuationDistance = attenuationDistance;
254
+ material.attenuationColor = attenuationColor;
255
+ #ifdef USE_TRANSMISSIONMAP
256
+ material.transmission *= texture2D( transmissionMap, vUv ).r;
257
+ #endif
258
+ #ifdef USE_THICKNESSMAP
259
+ material.thickness *= texture2D( thicknessMap, vUv ).g;
260
+ #endif
261
+
262
+ vec3 pos = vWorldPosition;
263
+ vec3 v = normalize( cameraPosition - pos );
264
+ vec3 n = inverseTransformDirection( normal, viewMatrix );
265
+ vec3 transmission = vec3(0.0);
266
+ float transmissionR, transmissionB, transmissionG;
267
+ float randomCoords = rand();
268
+ float thickness_smear = thickness * max(pow(roughnessFactor, 0.33), anisotropicBlur);
269
+ vec3 distortionNormal = vec3(0.0);
270
+ vec3 temporalOffset = vec3(time, -time, -time) * temporalDistortion;
271
+ if (distortion > 0.0) {
272
+ distortionNormal = distortion * vec3(snoiseFractal(vec3((pos * distortionScale + temporalOffset))), snoiseFractal(vec3(pos.zxy * distortionScale - temporalOffset)), snoiseFractal(vec3(pos.yxz * distortionScale + temporalOffset)));
273
+ }
274
+ for (float i = 0.0; i < ${samples}.0; i ++) {
275
+ vec3 sampleNorm = normalize(n + roughnessFactor * roughnessFactor * 2.0 * normalize(vec3(rand() - 0.5, rand() - 0.5, rand() - 0.5)) * pow(rand(), 0.33) + distortionNormal);
276
+ transmissionR = getIBLVolumeRefraction(
277
+ sampleNorm, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,
278
+ pos, modelMatrix, viewMatrix, projectionMatrix, material.ior, material.thickness + thickness_smear * (i + randomCoords) / float(${samples}),
279
+ material.attenuationColor, material.attenuationDistance
280
+ ).r;
281
+ transmissionG = getIBLVolumeRefraction(
282
+ sampleNorm, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,
283
+ pos, modelMatrix, viewMatrix, projectionMatrix, material.ior * (1.0 + chromaticAberration * (i + randomCoords) / float(${samples})) , material.thickness + thickness_smear * (i + randomCoords) / float(${samples}),
284
+ material.attenuationColor, material.attenuationDistance
285
+ ).g;
286
+ transmissionB = getIBLVolumeRefraction(
287
+ sampleNorm, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,
288
+ pos, modelMatrix, viewMatrix, projectionMatrix, material.ior * (1.0 + 2.0 * chromaticAberration * (i + randomCoords) / float(${samples})), material.thickness + thickness_smear * (i + randomCoords) / float(${samples}),
289
+ material.attenuationColor, material.attenuationDistance
290
+ ).b;
291
+ transmission.r += transmissionR;
292
+ transmission.g += transmissionG;
293
+ transmission.b += transmissionB;
294
+ }
295
+ transmission /= ${samples}.0;
296
+ totalDiffuse = mix( totalDiffuse, transmission.rgb, material.transmission );\n`);
297
+ };
298
+
299
+ Object.keys(this.uniforms).forEach(name => Object.defineProperty(this, name, {
300
+ get: () => this.uniforms[name].value,
301
+ set: v => this.uniforms[name].value = v
302
+ }));
303
+ }
304
+
305
+ }
306
+
307
+ const MeshTransmissionMaterial = /*#__PURE__*/React.forwardRef(({
308
+ buffer,
309
+ transmissionSampler = false,
310
+ backside = false,
311
+ side = THREE.FrontSide,
312
+ transmission = 1,
313
+ thickness = 0,
314
+ backsideThickness = 0,
315
+ samples = 10,
316
+ resolution,
317
+ backsideResolution,
318
+ background,
319
+ anisotropy,
320
+ anisotropicBlur,
321
+ ...props
322
+ }, fref) => {
323
+ extend({
324
+ MeshTransmissionMaterial: MeshTransmissionMaterialImpl
325
+ });
326
+ const ref = React.useRef(null);
327
+ const [discardMaterial] = React.useState(() => new DiscardMaterial());
328
+ const fboBack = useFBO(backsideResolution || resolution);
329
+ const fboMain = useFBO(resolution);
330
+ let oldBg;
331
+ let oldTone;
332
+ let parent;
333
+ useFrame(state => {
334
+ ref.current.time = state.clock.getElapsedTime(); // Render only if the buffer matches the built-in and no transmission sampler is set
335
+
336
+ if (ref.current.buffer === fboMain.texture && !transmissionSampler) {
337
+ parent = ref.current.__r3f.parent;
338
+
339
+ if (parent) {
340
+ // Save defaults
341
+ oldTone = state.gl.toneMapping;
342
+ oldBg = state.scene.background; // Switch off tonemapping lest it double tone maps
343
+ // Save the current background and set the HDR as the new BG
344
+ // Use discardmaterial, the parent will be invisible, but it's shadows will still be cast
345
+
346
+ state.gl.toneMapping = THREE.NoToneMapping;
347
+ if (background) state.scene.background = background;
348
+ parent.material = discardMaterial;
349
+
350
+ if (backside) {
351
+ // Render into the backside buffer
352
+ state.gl.setRenderTarget(fboBack);
353
+ state.gl.render(state.scene, state.camera); // And now prepare the material for the main render using the backside buffer
354
+
355
+ parent.material = ref.current;
356
+ parent.material.buffer = fboBack.texture;
357
+ parent.material.thickness = backsideThickness;
358
+ parent.material.side = THREE.BackSide;
359
+ } // Render into the main buffer
360
+
361
+
362
+ state.gl.setRenderTarget(fboMain);
363
+ state.gl.render(state.scene, state.camera);
364
+ parent.material.thickness = thickness;
365
+ parent.material.side = side;
366
+ parent.material.buffer = fboMain.texture; // Set old state back
367
+
368
+ state.scene.background = oldBg;
369
+ state.gl.setRenderTarget(null);
370
+ parent.material = ref.current;
371
+ state.gl.toneMapping = oldTone;
372
+ }
373
+ }
374
+ }); // Forward ref
375
+
376
+ React.useImperativeHandle(fref, () => ref.current, []);
377
+ return /*#__PURE__*/React.createElement("meshTransmissionMaterial", _extends({
378
+ // Samples must re-compile the shader so we memoize it
379
+ args: [samples, transmissionSampler],
380
+ ref: ref
381
+ }, props, {
382
+ buffer: buffer || fboMain.texture // @ts-ignore
383
+ ,
384
+ _transmission: transmission // In order for this to not incur extra cost "transmission" must be set to 0 and treated as a reserved prop.
385
+ // This is because THREE.WebGLRenderer will check for transmission > 0 and execute extra renders.
386
+ // The exception is when transmissionSampler is set, in which case we are using three's built in sampler.
387
+ ,
388
+ anisotropicBlur: anisotropicBlur !== null && anisotropicBlur !== void 0 ? anisotropicBlur : anisotropy,
389
+ transmission: transmissionSampler ? transmission : 0,
390
+ thickness: thickness,
391
+ side: side
392
+ }));
393
+ });
394
+
395
+ export { MeshTransmissionMaterial };