three-gpu-pathtracer 0.0.6 → 0.0.8

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 (49) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +887 -781
  3. package/build/index.module.js +6070 -5224
  4. package/build/index.module.js.map +1 -1
  5. package/build/index.umd.cjs +6071 -5221
  6. package/build/index.umd.cjs.map +1 -1
  7. package/package.json +69 -68
  8. package/src/core/DynamicPathTracingSceneGenerator.js +119 -119
  9. package/src/core/MaterialReducer.js +256 -256
  10. package/src/core/PathTracingRenderer.js +270 -255
  11. package/src/core/PathTracingSceneGenerator.js +69 -68
  12. package/src/index.js +39 -33
  13. package/src/materials/AlphaDisplayMaterial.js +48 -48
  14. package/src/materials/AmbientOcclusionMaterial.js +197 -197
  15. package/src/materials/BlendMaterial.js +67 -67
  16. package/src/materials/DenoiseMaterial.js +142 -0
  17. package/src/materials/GraphMaterial.js +243 -0
  18. package/src/materials/LambertPathTracingMaterial.js +285 -285
  19. package/src/materials/MaterialBase.js +56 -56
  20. package/src/materials/PhysicalPathTracingMaterial.js +973 -922
  21. package/src/objects/EquirectCamera.js +13 -13
  22. package/src/objects/PhysicalCamera.js +28 -28
  23. package/src/objects/PhysicalSpotLight.js +14 -14
  24. package/src/objects/ShapedAreaLight.js +12 -12
  25. package/src/shader/shaderEnvMapSampling.js +59 -59
  26. package/src/shader/shaderGGXFunctions.js +100 -108
  27. package/src/shader/shaderIridescenceFunctions.js +130 -130
  28. package/src/shader/shaderLayerTexelFetchFunctions.js +25 -0
  29. package/src/shader/shaderLightSampling.js +231 -231
  30. package/src/shader/shaderMaterialSampling.js +504 -546
  31. package/src/shader/shaderSheenFunctions.js +98 -98
  32. package/src/shader/shaderStructs.js +321 -307
  33. package/src/shader/shaderUtils.js +403 -350
  34. package/src/textures/GradientEquirectTexture.js +35 -0
  35. package/src/textures/ProceduralEquirectTexture.js +75 -0
  36. package/src/uniforms/AttributesTextureArray.js +35 -0
  37. package/src/uniforms/EquirectHdrInfoUniform.js +259 -259
  38. package/src/uniforms/FloatAttributeTextureArray.js +169 -0
  39. package/src/uniforms/IESProfilesTexture.js +100 -100
  40. package/src/uniforms/LightsInfoUniformStruct.js +162 -162
  41. package/src/uniforms/MaterialsTexture.js +420 -406
  42. package/src/uniforms/PhysicalCameraUniform.js +36 -36
  43. package/src/uniforms/RenderTarget2DArray.js +97 -93
  44. package/src/uniforms/utils.js +21 -0
  45. package/src/utils/BlurredEnvMapGenerator.js +116 -113
  46. package/src/utils/GeometryPreparationUtils.js +214 -194
  47. package/src/utils/IESLoader.js +325 -325
  48. package/src/utils/UVUnwrapper.js +101 -101
  49. package/src/workers/PathTracingSceneWorker.js +42 -42
@@ -1,922 +1,973 @@
1
- import { Matrix4, Matrix3, Color, Vector2 } from 'three';
2
- import { MaterialBase } from './MaterialBase.js';
3
- import {
4
- MeshBVHUniformStruct, FloatVertexAttributeTexture, UIntVertexAttributeTexture,
5
- shaderStructs, shaderIntersectFunction,
6
- } from 'three-mesh-bvh';
7
- import { shaderMaterialStructs, shaderLightStruct } from '../shader/shaderStructs.js';
8
- import { MaterialsTexture } from '../uniforms/MaterialsTexture.js';
9
- import { RenderTarget2DArray } from '../uniforms/RenderTarget2DArray.js';
10
- import { shaderMaterialSampling } from '../shader/shaderMaterialSampling.js';
11
- import { shaderEnvMapSampling } from '../shader/shaderEnvMapSampling.js';
12
- import { shaderLightSampling } from '../shader/shaderLightSampling.js';
13
- import { shaderUtils } from '../shader/shaderUtils.js';
14
- import { PhysicalCameraUniform } from '../uniforms/PhysicalCameraUniform.js';
15
- import { EquirectHdrInfoUniform } from '../uniforms/EquirectHdrInfoUniform.js';
16
- import { LightsInfoUniformStruct } from '../uniforms/LightsInfoUniformStruct.js';
17
- import { IESProfilesTexture } from '../uniforms/IESProfilesTexture.js';
18
-
19
- export class PhysicalPathTracingMaterial extends MaterialBase {
20
-
21
- onBeforeRender() {
22
-
23
- this.setDefine( 'FEATURE_DOF', this.physicalCamera.bokehSize === 0 ? 0 : 1 );
24
-
25
- }
26
-
27
- constructor( parameters ) {
28
-
29
- super( {
30
-
31
- transparent: true,
32
- depthWrite: false,
33
-
34
- defines: {
35
- FEATURE_MIS: 1,
36
- FEATURE_DOF: 1,
37
- FEATURE_GRADIENT_BG: 0,
38
- TRANSPARENT_TRAVERSALS: 5,
39
- // 0 = Perspective
40
- // 1 = Orthographic
41
- // 2 = Equirectangular
42
- CAMERA_TYPE: 0,
43
- },
44
-
45
- uniforms: {
46
- resolution: { value: new Vector2() },
47
-
48
- bounces: { value: 3 },
49
- physicalCamera: { value: new PhysicalCameraUniform() },
50
-
51
- bvh: { value: new MeshBVHUniformStruct() },
52
- normalAttribute: { value: new FloatVertexAttributeTexture() },
53
- tangentAttribute: { value: new FloatVertexAttributeTexture() },
54
- uvAttribute: { value: new FloatVertexAttributeTexture() },
55
- materialIndexAttribute: { value: new UIntVertexAttributeTexture() },
56
- materials: { value: new MaterialsTexture() },
57
- textures: { value: new RenderTarget2DArray().texture },
58
- lights: { value: new LightsInfoUniformStruct() },
59
- iesProfiles: { value: new IESProfilesTexture().texture },
60
- cameraWorldMatrix: { value: new Matrix4() },
61
- invProjectionMatrix: { value: new Matrix4() },
62
- backgroundBlur: { value: 0.0 },
63
- environmentIntensity: { value: 1.0 },
64
- environmentRotation: { value: new Matrix3() },
65
- envMapInfo: { value: new EquirectHdrInfoUniform() },
66
-
67
- seed: { value: 0 },
68
- opacity: { value: 1 },
69
- filterGlossyFactor: { value: 0.0 },
70
-
71
- bgGradientTop: { value: new Color( 0x111111 ) },
72
- bgGradientBottom: { value: new Color( 0x000000 ) },
73
- backgroundAlpha: { value: 1.0 },
74
- },
75
-
76
- vertexShader: /* glsl */`
77
-
78
- varying vec2 vUv;
79
- void main() {
80
-
81
- vec4 mvPosition = vec4( position, 1.0 );
82
- mvPosition = modelViewMatrix * mvPosition;
83
- gl_Position = projectionMatrix * mvPosition;
84
-
85
- vUv = uv;
86
-
87
- }
88
-
89
- `,
90
-
91
- fragmentShader: /* glsl */`
92
- #define RAY_OFFSET 1e-4
93
-
94
- precision highp isampler2D;
95
- precision highp usampler2D;
96
- precision highp sampler2DArray;
97
- vec4 envMapTexelToLinear( vec4 a ) { return a; }
98
- #include <common>
99
-
100
- ${ shaderStructs }
101
- ${ shaderIntersectFunction }
102
- ${ shaderMaterialStructs }
103
- ${ shaderLightStruct }
104
-
105
- ${ shaderUtils }
106
- ${ shaderMaterialSampling }
107
- ${ shaderEnvMapSampling }
108
-
109
- uniform mat3 environmentRotation;
110
- uniform float backgroundBlur;
111
- uniform float backgroundAlpha;
112
-
113
- #if FEATURE_GRADIENT_BG
114
-
115
- uniform vec3 bgGradientTop;
116
- uniform vec3 bgGradientBottom;
117
-
118
- #endif
119
-
120
- #if FEATURE_DOF
121
-
122
- uniform PhysicalCamera physicalCamera;
123
-
124
- #endif
125
-
126
- uniform vec2 resolution;
127
- uniform int bounces;
128
- uniform mat4 cameraWorldMatrix;
129
- uniform mat4 invProjectionMatrix;
130
- uniform sampler2D normalAttribute;
131
- uniform sampler2D tangentAttribute;
132
- uniform sampler2D uvAttribute;
133
- uniform usampler2D materialIndexAttribute;
134
- uniform BVH bvh;
135
- uniform float environmentIntensity;
136
- uniform float filterGlossyFactor;
137
- uniform int seed;
138
- uniform float opacity;
139
- uniform sampler2D materials;
140
- uniform LightsInfo lights;
141
- uniform sampler2DArray iesProfiles;
142
-
143
- ${ shaderLightSampling }
144
-
145
- uniform EquirectHdrInfo envMapInfo;
146
-
147
- uniform sampler2DArray textures;
148
- varying vec2 vUv;
149
-
150
- vec3 sampleBackground( vec3 direction ) {
151
-
152
- #if FEATURE_GRADIENT_BG
153
-
154
- direction = normalize( direction + randDirection() * 0.05 );
155
-
156
- float value = ( direction.y + 1.0 ) / 2.0;
157
- value = pow( value, 2.0 );
158
-
159
- return mix( bgGradientBottom, bgGradientTop, value );
160
-
161
- #else
162
-
163
- vec3 sampleDir = normalize( direction + getHemisphereSample( direction, rand2() ) * 0.5 * backgroundBlur );
164
- return environmentIntensity * sampleEquirectEnvMapColor( sampleDir, envMapInfo.map );
165
-
166
- #endif
167
-
168
- }
169
-
170
- // step through multiple surface hits and accumulate color attenuation based on transmissive surfaces
171
- bool attenuateHit( BVH bvh, vec3 rayOrigin, vec3 rayDirection, int traversals, bool isShadowRay, out vec3 color ) {
172
-
173
- // hit results
174
- uvec4 faceIndices = uvec4( 0u );
175
- vec3 faceNormal = vec3( 0.0, 0.0, 1.0 );
176
- vec3 barycoord = vec3( 0.0 );
177
- float side = 1.0;
178
- float dist = 0.0;
179
-
180
- color = vec3( 1.0 );
181
-
182
- for ( int i = 0; i < traversals; i ++ ) {
183
-
184
- if ( bvhIntersectFirstHit( bvh, rayOrigin, rayDirection, faceIndices, faceNormal, barycoord, side, dist ) ) {
185
-
186
- // TODO: attenuate the contribution based on the PDF of the resulting ray including refraction values
187
- // Should be able to work using the material BSDF functions which will take into account specularity, etc.
188
- // TODO: should we account for emissive surfaces here?
189
-
190
- vec2 uv = textureSampleBarycoord( uvAttribute, barycoord, faceIndices.xyz ).xy;
191
- uint materialIndex = uTexelFetch1D( materialIndexAttribute, faceIndices.x ).r;
192
- Material material = readMaterialInfo( materials, materialIndex );
193
-
194
- // adjust the ray to the new surface
195
- bool isBelowSurface = dot( rayDirection, faceNormal ) < 0.0;
196
- vec3 point = rayOrigin + rayDirection * dist;
197
- vec3 absPoint = abs( point );
198
- float maxPoint = max( absPoint.x, max( absPoint.y, absPoint.z ) );
199
- rayOrigin = point + faceNormal * ( maxPoint + 1.0 ) * ( isBelowSurface ? - RAY_OFFSET : RAY_OFFSET );
200
-
201
- if ( ! material.castShadow && isShadowRay ) {
202
-
203
- continue;
204
-
205
- }
206
-
207
- // Opacity Test
208
-
209
- // albedo
210
- vec4 albedo = vec4( material.color, material.opacity );
211
- if ( material.map != - 1 ) {
212
-
213
- vec3 uvPrime = material.mapTransform * vec3( uv, 1 );
214
- albedo *= texture2D( textures, vec3( uvPrime.xy, material.map ) );
215
-
216
- }
217
-
218
- // alphaMap
219
- if ( material.alphaMap != -1 ) {
220
-
221
- albedo.a *= texture2D( textures, vec3( uv, material.alphaMap ) ).x;
222
-
223
- }
224
-
225
- // transmission
226
- float transmission = material.transmission;
227
- if ( material.transmissionMap != - 1 ) {
228
-
229
- vec3 uvPrime = material.transmissionMapTransform * vec3( uv, 1 );
230
- transmission *= texture2D( textures, vec3( uvPrime.xy, material.transmissionMap ) ).r;
231
-
232
- }
233
-
234
- // metalness
235
- float metalness = material.metalness;
236
- if ( material.metalnessMap != - 1 ) {
237
-
238
- vec3 uvPrime = material.metalnessMapTransform * vec3( uv, 1 );
239
- metalness *= texture2D( textures, vec3( uvPrime.xy, material.metalnessMap ) ).b;
240
-
241
- }
242
-
243
- float alphaTest = material.alphaTest;
244
- bool useAlphaTest = alphaTest != 0.0;
245
- float transmissionFactor = ( 1.0 - metalness ) * transmission;
246
- if (
247
- transmissionFactor < rand() && ! (
248
- // material sidedness
249
- material.side != 0.0 && side == material.side
250
-
251
- // alpha test
252
- || useAlphaTest && albedo.a < alphaTest
253
-
254
- // opacity
255
- || ! useAlphaTest && albedo.a < rand()
256
- )
257
- ) {
258
-
259
- return true;
260
-
261
- }
262
-
263
- // only attenuate on the way in
264
- if ( isBelowSurface ) {
265
-
266
- color *= mix( vec3( 1.0 ), albedo.rgb, transmissionFactor );
267
-
268
- }
269
-
270
- } else {
271
-
272
- return false;
273
-
274
- }
275
-
276
- }
277
-
278
- return true;
279
-
280
- }
281
-
282
- // returns whether the ray hit anything before a certain distance, not just the first surface. Could be optimized to not check the full hierarchy.
283
- bool anyCloserHit( BVH bvh, vec3 rayOrigin, vec3 rayDirection, float maxDist ) {
284
-
285
- uvec4 faceIndices = uvec4( 0u );
286
- vec3 faceNormal = vec3( 0.0, 0.0, 1.0 );
287
- vec3 barycoord = vec3( 0.0 );
288
- float side = 1.0;
289
- float dist = 0.0;
290
- bool hit = bvhIntersectFirstHit( bvh, rayOrigin, rayDirection, faceIndices, faceNormal, barycoord, side, dist );
291
- return hit && dist < maxDist;
292
-
293
- }
294
-
295
- // tentFilter from Peter Shirley's 'Realistic Ray Tracing (2nd Edition)' book, pg. 60
296
- // erichlof/THREE.js-PathTracing-Renderer/
297
- float tentFilter( float x ) {
298
-
299
- return x < 0.5 ? sqrt( 2.0 * x ) - 1.0 : 1.0 - sqrt( 2.0 - ( 2.0 * x ) );
300
-
301
- }
302
-
303
- vec3 ndcToRayOrigin( vec2 coord ) {
304
-
305
- vec4 rayOrigin4 = cameraWorldMatrix * invProjectionMatrix * vec4( coord, - 1.0, 1.0 );
306
- return rayOrigin4.xyz / rayOrigin4.w;
307
- }
308
-
309
- void getCameraRay( out vec3 rayDirection, out vec3 rayOrigin ) {
310
-
311
- vec2 ssd = vec2( 1.0 ) / resolution;
312
-
313
- // Jitter the camera ray by finding a uv coordinate at a random sample
314
- // around this pixel's UV coordinate
315
- vec2 jitteredUv = vUv + vec2( tentFilter( rand() ) * ssd.x, tentFilter( rand() ) * ssd.y );
316
-
317
- #if CAMERA_TYPE == 2
318
-
319
- // Equirectangular projection
320
-
321
- vec4 rayDirection4 = vec4( equirectUvToDirection( jitteredUv ), 0.0 );
322
- vec4 rayOrigin4 = vec4( 0.0, 0.0, 0.0, 1.0 );
323
-
324
- rayDirection4 = cameraWorldMatrix * rayDirection4;
325
- rayOrigin4 = cameraWorldMatrix * rayOrigin4;
326
-
327
- rayDirection = normalize( rayDirection4.xyz );
328
- rayOrigin = rayOrigin4.xyz / rayOrigin4.w;
329
-
330
- #else
331
-
332
- // get [-1, 1] normalized device coordinates
333
- vec2 ndc = 2.0 * jitteredUv - vec2( 1.0 );
334
-
335
- rayOrigin = ndcToRayOrigin( ndc );
336
-
337
- #if CAMERA_TYPE == 1
338
-
339
- // Orthographic projection
340
-
341
- rayDirection = ( cameraWorldMatrix * vec4( 0.0, 0.0, -1.0, 0.0 ) ).xyz;
342
- rayDirection = normalize( rayDirection );
343
-
344
- #else
345
-
346
- // Perspective projection
347
-
348
- rayDirection = normalize( mat3(cameraWorldMatrix) * ( invProjectionMatrix * vec4( ndc, 0.0, 1.0 ) ).xyz );
349
-
350
- #endif
351
-
352
- #endif
353
-
354
- #if FEATURE_DOF
355
- {
356
-
357
- // depth of field
358
- vec3 focalPoint = rayOrigin + normalize( rayDirection ) * physicalCamera.focusDistance;
359
-
360
- // get the aperture sample
361
- vec2 apertureSample = sampleAperture( physicalCamera.apertureBlades ) * physicalCamera.bokehSize * 0.5 * 1e-3;
362
-
363
- // rotate the aperture shape
364
- float ac = cos( physicalCamera.apertureRotation );
365
- float as = sin( physicalCamera.apertureRotation );
366
- apertureSample = vec2(
367
- apertureSample.x * ac - apertureSample.y * as,
368
- apertureSample.x * as + apertureSample.y * ac
369
- );
370
- apertureSample.x *= saturate( physicalCamera.anamorphicRatio );
371
- apertureSample.y *= saturate( 1.0 / physicalCamera.anamorphicRatio );
372
-
373
- // create the new ray
374
- rayOrigin += ( cameraWorldMatrix * vec4( apertureSample, 0.0, 0.0 ) ).xyz;
375
- rayDirection = focalPoint - rayOrigin;
376
-
377
- }
378
- #endif
379
-
380
- rayDirection = normalize( rayDirection );
381
-
382
- }
383
-
384
- void main() {
385
-
386
- rng_initialize( gl_FragCoord.xy, seed );
387
-
388
- vec3 rayDirection;
389
- vec3 rayOrigin;
390
-
391
- getCameraRay( rayDirection, rayOrigin );
392
-
393
- // inverse environment rotation
394
- mat3 invEnvironmentRotation = inverse( environmentRotation );
395
-
396
- // final color
397
- gl_FragColor = vec4( 0.0 );
398
- gl_FragColor.a = 1.0;
399
-
400
- // hit results
401
- uvec4 faceIndices = uvec4( 0u );
402
- vec3 faceNormal = vec3( 0.0, 0.0, 1.0 );
403
- vec3 barycoord = vec3( 0.0 );
404
- float side = 1.0;
405
- float dist = 0.0;
406
-
407
- // path tracing state
408
- float accumulatedRoughness = 0.0;
409
- float accumulatedClearcoatRoughness = 0.0;
410
- bool transmissiveRay = true;
411
- int transparentTraversals = TRANSPARENT_TRAVERSALS;
412
- vec3 throughputColor = vec3( 1.0 );
413
- SampleRec sampleRec;
414
- int i;
415
- bool isShadowRay = false;
416
-
417
- for ( i = 0; i < bounces; i ++ ) {
418
-
419
- bool hit = bvhIntersectFirstHit( bvh, rayOrigin, rayDirection, faceIndices, faceNormal, barycoord, side, dist );
420
-
421
- LightSampleRec lightHit = lightsClosestHit( lights.tex, lights.count, rayOrigin, rayDirection );
422
-
423
- if ( lightHit.hit && ( lightHit.dist < dist || !hit ) ) {
424
-
425
- if ( i == 0 || transmissiveRay ) {
426
-
427
- gl_FragColor.rgb += lightHit.emission * throughputColor;
428
-
429
- } else {
430
-
431
- #if FEATURE_MIS
432
-
433
- // NOTE: we skip MIS for spotlights since we haven't fixed the forward
434
- // path tracing code path, yet
435
- if ( lightHit.type == SPOT_LIGHT_TYPE ) {
436
-
437
- gl_FragColor.rgb += lightHit.emission * throughputColor;
438
-
439
- } else {
440
-
441
- // weight the contribution
442
- float misWeight = misHeuristic( sampleRec.pdf, lightHit.pdf / float( lights.count + 1u ) );
443
- gl_FragColor.rgb += lightHit.emission * throughputColor * misWeight;
444
-
445
- }
446
-
447
- #else
448
-
449
- gl_FragColor.rgb += lightHit.emission * throughputColor;
450
-
451
- #endif
452
-
453
- }
454
- break;
455
-
456
- }
457
-
458
- if ( ! hit ) {
459
-
460
- if ( i == 0 || transmissiveRay ) {
461
-
462
- gl_FragColor.rgb += sampleBackground( environmentRotation * rayDirection ) * throughputColor;
463
- gl_FragColor.a = backgroundAlpha;
464
-
465
- } else {
466
-
467
- #if FEATURE_MIS
468
-
469
- // get the PDF of the hit envmap point
470
- vec3 envColor;
471
- float envPdf = envMapSample( environmentRotation * rayDirection, envMapInfo, envColor );
472
- envPdf /= float( lights.count + 1u );
473
-
474
- // and weight the contribution
475
- float misWeight = misHeuristic( sampleRec.pdf, envPdf );
476
- gl_FragColor.rgb += environmentIntensity * envColor * throughputColor * misWeight;
477
-
478
- #else
479
-
480
- gl_FragColor.rgb +=
481
- environmentIntensity *
482
- sampleEquirectEnvMapColor( environmentRotation * rayDirection, envMapInfo.map ) *
483
- throughputColor;
484
-
485
- #endif
486
-
487
- }
488
- break;
489
-
490
- }
491
-
492
- uint materialIndex = uTexelFetch1D( materialIndexAttribute, faceIndices.x ).r;
493
- Material material = readMaterialInfo( materials, materialIndex );
494
-
495
- if ( material.matte && i == 0 ) {
496
-
497
- gl_FragColor = vec4( 0.0 );
498
- break;
499
-
500
- }
501
-
502
- // if we've determined that this is a shadow ray and we've hit an item with no shadow casting
503
- // then skip it
504
- if ( ! material.castShadow && isShadowRay ) {
505
-
506
- vec3 point = rayOrigin + rayDirection * dist;
507
- vec3 absPoint = abs( point );
508
- float maxPoint = max( absPoint.x, max( absPoint.y, absPoint.z ) );
509
- rayOrigin = point - ( maxPoint + 1.0 ) * faceNormal * RAY_OFFSET;
510
-
511
- continue;
512
-
513
- }
514
-
515
- vec2 uv = textureSampleBarycoord( uvAttribute, barycoord, faceIndices.xyz ).xy;
516
- // albedo
517
- vec4 albedo = vec4( material.color, material.opacity );
518
- if ( material.map != - 1 ) {
519
-
520
- vec3 uvPrime = material.mapTransform * vec3( uv, 1 );
521
- albedo *= texture2D( textures, vec3( uvPrime.xy, material.map ) );
522
- }
523
-
524
- // alphaMap
525
- if ( material.alphaMap != -1 ) {
526
-
527
- albedo.a *= texture2D( textures, vec3( uv, material.alphaMap ) ).x;
528
-
529
- }
530
-
531
- // possibly skip this sample if it's transparent, alpha test is enabled, or we hit the wrong material side
532
- // and it's single sided.
533
- // - alpha test is disabled when it === 0
534
- // - the material sidedness test is complicated because we want light to pass through the back side but still
535
- // be able to see the front side. This boolean checks if the side we hit is the front side on the first ray
536
- // and we're rendering the other then we skip it. Do the opposite on subsequent bounces to get incoming light.
537
- float alphaTest = material.alphaTest;
538
- bool useAlphaTest = alphaTest != 0.0;
539
- bool isFirstHit = i == 0;
540
- if (
541
- // material sidedness
542
- material.side != 0.0 && ( side != material.side ) == isFirstHit
543
-
544
- // alpha test
545
- || useAlphaTest && albedo.a < alphaTest
546
-
547
- // opacity
548
- || ! useAlphaTest && albedo.a < rand()
549
- ) {
550
-
551
- vec3 point = rayOrigin + rayDirection * dist;
552
- vec3 absPoint = abs( point );
553
- float maxPoint = max( absPoint.x, max( absPoint.y, absPoint.z ) );
554
- rayOrigin = point - ( maxPoint + 1.0 ) * faceNormal * RAY_OFFSET;
555
-
556
- // only allow a limited number of transparency discards otherwise we could
557
- // crash the context with too long a loop.
558
- i -= sign( transparentTraversals );
559
- transparentTraversals -= sign( transparentTraversals );
560
- continue;
561
-
562
- }
563
-
564
- // fetch the interpolated smooth normal
565
- vec3 normal = normalize( textureSampleBarycoord(
566
- normalAttribute,
567
- barycoord,
568
- faceIndices.xyz
569
- ).xyz );
570
-
571
- // roughness
572
- float roughness = material.roughness;
573
- if ( material.roughnessMap != - 1 ) {
574
-
575
- vec3 uvPrime = material.roughnessMapTransform * vec3( uv, 1 );
576
- roughness *= texture2D( textures, vec3( uvPrime.xy, material.roughnessMap ) ).g;
577
-
578
- }
579
-
580
- // metalness
581
- float metalness = material.metalness;
582
- if ( material.metalnessMap != - 1 ) {
583
-
584
- vec3 uvPrime = material.metalnessMapTransform * vec3( uv, 1 );
585
- metalness *= texture2D( textures, vec3( uvPrime.xy, material.metalnessMap ) ).b;
586
-
587
- }
588
-
589
- // emission
590
- vec3 emission = material.emissiveIntensity * material.emissive;
591
- if ( material.emissiveMap != - 1 ) {
592
-
593
- vec3 uvPrime = material.emissiveMapTransform * vec3( uv, 1 );
594
- emission *= texture2D( textures, vec3( uvPrime.xy, material.emissiveMap ) ).xyz;
595
-
596
- }
597
-
598
- // transmission
599
- float transmission = material.transmission;
600
- if ( material.transmissionMap != - 1 ) {
601
-
602
- vec3 uvPrime = material.transmissionMapTransform * vec3( uv, 1 );
603
- transmission *= texture2D( textures, vec3( uvPrime.xy, material.transmissionMap ) ).r;
604
-
605
- }
606
-
607
- // normal
608
- vec3 baseNormal = normal;
609
- if ( material.normalMap != - 1 ) {
610
-
611
- vec4 tangentSample = textureSampleBarycoord(
612
- tangentAttribute,
613
- barycoord,
614
- faceIndices.xyz
615
- );
616
-
617
- // some provided tangents can be malformed (0, 0, 0) causing the normal to be degenerate
618
- // resulting in NaNs and slow path tracing.
619
- if ( length( tangentSample.xyz ) > 0.0 ) {
620
-
621
- vec3 tangent = normalize( tangentSample.xyz );
622
- vec3 bitangent = normalize( cross( normal, tangent ) * tangentSample.w );
623
- mat3 vTBN = mat3( tangent, bitangent, normal );
624
-
625
- vec3 uvPrime = material.normalMapTransform * vec3( uv, 1 );
626
- vec3 texNormal = texture2D( textures, vec3( uvPrime.xy, material.normalMap ) ).xyz * 2.0 - 1.0;
627
- texNormal.xy *= material.normalScale;
628
- normal = vTBN * texNormal;
629
-
630
- }
631
-
632
- }
633
-
634
- normal *= side;
635
-
636
- // clearcoat
637
- float clearcoat = material.clearcoat;
638
- if ( material.clearcoatMap != - 1 ) {
639
-
640
- vec3 uvPrime = material.clearcoatMapTransform * vec3( uv, 1 );
641
- clearcoat *= texture2D( textures, vec3( uvPrime.xy, material.clearcoatMap ) ).r;
642
-
643
- }
644
-
645
- // clearcoatRoughness
646
- float clearcoatRoughness = material.clearcoatRoughness;
647
- if ( material.clearcoatRoughnessMap != - 1 ) {
648
-
649
- vec3 uvPrime = material.clearcoatRoughnessMapTransform * vec3( uv, 1 );
650
- clearcoat *= texture2D( textures, vec3( uvPrime.xy, material.clearcoatRoughnessMap ) ).g;
651
-
652
- }
653
-
654
- // clearcoatNormal
655
- vec3 clearcoatNormal = baseNormal;
656
- if ( material.clearcoatNormalMap != - 1 ) {
657
-
658
- vec4 tangentSample = textureSampleBarycoord(
659
- tangentAttribute,
660
- barycoord,
661
- faceIndices.xyz
662
- );
663
-
664
- // some provided tangents can be malformed (0, 0, 0) causing the normal to be degenerate
665
- // resulting in NaNs and slow path tracing.
666
- if ( length( tangentSample.xyz ) > 0.0 ) {
667
-
668
- vec3 tangent = normalize( tangentSample.xyz );
669
- vec3 bitangent = normalize( cross( clearcoatNormal, tangent ) * tangentSample.w );
670
- mat3 vTBN = mat3( tangent, bitangent, clearcoatNormal );
671
-
672
- vec3 uvPrime = material.clearcoatNormalMapTransform * vec3( uv, 1 );
673
- vec3 texNormal = texture2D( textures, vec3( uvPrime.xy, material.clearcoatNormalMap ) ).xyz * 2.0 - 1.0;
674
- texNormal.xy *= material.clearcoatNormalScale;
675
- clearcoatNormal = vTBN * texNormal;
676
-
677
- }
678
-
679
- }
680
-
681
- clearcoatNormal *= side;
682
-
683
- // sheenColor
684
- vec3 sheenColor = material.sheenColor;
685
- if ( material.sheenColorMap != - 1 ) {
686
-
687
- vec3 uvPrime = material.sheenColorMapTransform * vec3( uv, 1 );
688
- sheenColor *= texture2D( textures, vec3( uvPrime.xy, material.sheenColorMap ) ).rgb;
689
-
690
- }
691
-
692
- // sheenRoughness
693
- float sheenRoughness = material.sheenRoughness;
694
- if ( material.sheenRoughnessMap != - 1 ) {
695
-
696
- vec3 uvPrime = material.sheenRoughnessMapTransform * vec3( uv, 1 );
697
- sheenRoughness *= texture2D( textures, vec3( uvPrime.xy, material.sheenRoughnessMap ) ).a;
698
-
699
- }
700
-
701
- // iridescence
702
- float iridescence = material.iridescence;
703
- if ( material.iridescenceMap != - 1 ) {
704
-
705
- vec3 uvPrime = material.iridescenceMapTransform * vec3( uv, 1 );
706
- iridescence *= texture2D( textures, vec3( uvPrime.xy, material.iridescenceMap ) ).r;
707
-
708
- }
709
-
710
- // iridescence thickness
711
- float iridescenceThickness = material.iridescenceThicknessMaximum;
712
- if ( material.iridescenceThicknessMap != - 1 ) {
713
-
714
- vec3 uvPrime = material.iridescenceThicknessMapTransform * vec3( uv, 1 );
715
- float iridescenceThicknessSampled = texture2D( textures, vec3( uvPrime.xy, material.iridescenceThicknessMap ) ).g;
716
- iridescenceThickness = mix( material.iridescenceThicknessMinimum, material.iridescenceThicknessMaximum, iridescenceThicknessSampled );
717
-
718
- }
719
-
720
- iridescence = iridescenceThickness == 0.0 ? 0.0 : iridescence;
721
-
722
- // specular color
723
- vec3 specularColor = material.specularColor;
724
- if ( material.specularColorMap != - 1 ) {
725
-
726
- vec3 uvPrime = material.specularColorMapTransform * vec3( uv, 1 );
727
- specularColor *= texture2D( textures, vec3( uvPrime.xy, material.specularColorMap ) ).rgb;
728
-
729
- }
730
-
731
- // specular intensity
732
- float specularIntensity = material.specularIntensity;
733
- if ( material.specularIntensityMap != - 1 ) {
734
-
735
- vec3 uvPrime = material.specularIntensityMapTransform * vec3( uv, 1 );
736
- specularIntensity *= texture2D( textures, vec3( uvPrime.xy, material.specularIntensityMap ) ).a;
737
-
738
- }
739
-
740
- SurfaceRec surfaceRec;
741
- surfaceRec.normal = normal;
742
- surfaceRec.faceNormal = faceNormal;
743
- surfaceRec.transmission = transmission;
744
- surfaceRec.ior = material.ior;
745
- surfaceRec.emission = emission;
746
- surfaceRec.metalness = metalness;
747
- surfaceRec.color = albedo.rgb;
748
- surfaceRec.roughness = roughness;
749
- surfaceRec.clearcoat = clearcoat;
750
- surfaceRec.clearcoatRoughness = clearcoatRoughness;
751
- surfaceRec.sheenColor = sheenColor;
752
- surfaceRec.sheenRoughness = sheenRoughness;
753
- surfaceRec.iridescence = iridescence;
754
- surfaceRec.iridescenceIor = material.iridescenceIor;
755
- surfaceRec.iridescenceThickness = iridescenceThickness;
756
- surfaceRec.specularColor = specularColor;
757
- surfaceRec.specularIntensity = specularIntensity;
758
-
759
- // frontFace is used to determine transmissive properties and PDF. If no transmission is used
760
- // then we can just always assume this is a front face.
761
- surfaceRec.frontFace = side == 1.0 || transmission == 0.0;
762
-
763
- // Compute the filtered roughness value to use during specular reflection computations.
764
- // The accumulated roughness value is scaled by a user setting and a "magic value" of 5.0.
765
- // If we're exiting something transmissive then scale the factor down significantly so we can retain
766
- // sharp internal reflections
767
- surfaceRec.filteredRoughness = clamp( max( surfaceRec.roughness, accumulatedRoughness * filterGlossyFactor * 5.0 ), 0.0, 1.0 );
768
- surfaceRec.filteredClearcoatRoughness = clamp( max( surfaceRec.clearcoatRoughness, accumulatedClearcoatRoughness * filterGlossyFactor * 5.0 ), 0.0, 1.0 );
769
-
770
- mat3 normalBasis = getBasisFromNormal( surfaceRec.normal );
771
- mat3 invBasis = inverse( normalBasis );
772
-
773
- mat3 clearcoatNormalBasis = getBasisFromNormal( clearcoatNormal );
774
- mat3 clearcoatInvBasis = inverse( clearcoatNormalBasis );
775
-
776
- vec3 outgoing = - normalize( invBasis * rayDirection );
777
- vec3 clearcoatOutgoing = - normalize( clearcoatInvBasis * rayDirection );
778
- sampleRec = bsdfSample( outgoing, clearcoatOutgoing, normalBasis, invBasis, clearcoatNormalBasis, clearcoatInvBasis, surfaceRec );
779
-
780
- isShadowRay = sampleRec.specularPdf < rand();
781
-
782
- // adjust the hit point by the surface normal by a factor of some offset and the
783
- // maximum component-wise value of the current point to accommodate floating point
784
- // error as values increase.
785
- vec3 point = rayOrigin + rayDirection * dist;
786
- vec3 absPoint = abs( point );
787
- float maxPoint = max( absPoint.x, max( absPoint.y, absPoint.z ) );
788
- rayDirection = normalize( normalBasis * sampleRec.direction );
789
-
790
- bool isBelowSurface = dot( rayDirection, faceNormal ) < 0.0;
791
- rayOrigin = point + faceNormal * ( maxPoint + 1.0 ) * ( isBelowSurface ? - RAY_OFFSET : RAY_OFFSET );
792
-
793
- // direct env map sampling
794
- #if FEATURE_MIS
795
-
796
- // uniformly pick a light or environment map
797
- if( rand() > 1.0 / float( lights.count + 1u ) ) {
798
-
799
- // sample a light or environment
800
- LightSampleRec lightSampleRec = randomLightSample( lights.tex, iesProfiles, lights.count, rayOrigin );
801
-
802
- bool isSampleBelowSurface = dot( faceNormal, lightSampleRec.direction ) < 0.0;
803
- if ( isSampleBelowSurface ) {
804
-
805
- lightSampleRec.pdf = 0.0;
806
-
807
- }
808
-
809
- // check if a ray could even reach the light area
810
- if (
811
- lightSampleRec.pdf > 0.0 &&
812
- isDirectionValid( lightSampleRec.direction, normal, faceNormal ) &&
813
- ! anyCloserHit( bvh, rayOrigin, lightSampleRec.direction, lightSampleRec.dist )
814
- ) {
815
-
816
- // get the material pdf
817
- vec3 sampleColor;
818
- float lightMaterialPdf = bsdfResult( outgoing, clearcoatOutgoing, normalize( invBasis * lightSampleRec.direction ), normalize( clearcoatInvBasis * lightSampleRec.direction ), surfaceRec, sampleColor );
819
- bool isValidSampleColor = all( greaterThanEqual( sampleColor, vec3( 0.0 ) ) );
820
- if ( lightMaterialPdf > 0.0 && isValidSampleColor ) {
821
-
822
- // weight the direct light contribution
823
- float lightPdf = lightSampleRec.pdf / float( lights.count + 1u );
824
- float misWeight = misHeuristic( lightPdf, lightMaterialPdf );
825
- gl_FragColor.rgb += lightSampleRec.emission * throughputColor * sampleColor * misWeight / lightPdf;
826
-
827
- }
828
-
829
- }
830
-
831
- } else {
832
-
833
- // find a sample in the environment map to include in the contribution
834
- vec3 envColor, envDirection;
835
- float envPdf = randomEnvMapSample( envMapInfo, envColor, envDirection );
836
- envDirection = invEnvironmentRotation * envDirection;
837
-
838
- // this env sampling is not set up for transmissive sampling and yields overly bright
839
- // results so we ignore the sample in this case.
840
- // TODO: this should be improved but how? The env samples could traverse a few layers?
841
- bool isSampleBelowSurface = dot( faceNormal, envDirection ) < 0.0;
842
- if ( isSampleBelowSurface ) {
843
-
844
- envPdf = 0.0;
845
-
846
- }
847
-
848
- // check if a ray could even reach the surface
849
- vec3 attenuatedColor;
850
- if (
851
- envPdf > 0.0 &&
852
- isDirectionValid( envDirection, normal, faceNormal ) &&
853
- ! attenuateHit( bvh, rayOrigin, envDirection, bounces - i, isShadowRay, attenuatedColor )
854
- ) {
855
-
856
- // get the material pdf
857
- vec3 sampleColor;
858
- float envMaterialPdf = bsdfResult( outgoing, clearcoatOutgoing, normalize( invBasis * envDirection ), normalize( clearcoatInvBasis * envDirection ), surfaceRec, sampleColor );
859
- bool isValidSampleColor = all( greaterThanEqual( sampleColor, vec3( 0.0 ) ) );
860
- if ( envMaterialPdf > 0.0 && isValidSampleColor ) {
861
-
862
- // weight the direct light contribution
863
- envPdf /= float( lights.count + 1u );
864
- float misWeight = misHeuristic( envPdf, envMaterialPdf );
865
- gl_FragColor.rgb += attenuatedColor * environmentIntensity * envColor * throughputColor * sampleColor * misWeight / envPdf;
866
-
867
- }
868
-
869
- }
870
-
871
- }
872
- #endif
873
-
874
- // accumulate a roughness value to offset diffuse, specular, diffuse rays that have high contribution
875
- // to a single pixel resulting in fireflies
876
- if ( ! isBelowSurface ) {
877
-
878
- // determine if this is a rough normal or not by checking how far off straight up it is
879
- vec3 halfVector = normalize( outgoing + sampleRec.direction );
880
- accumulatedRoughness += sin( acosApprox( halfVector.z ) );
881
-
882
- vec3 clearcoatHalfVector = normalize( clearcoatOutgoing + sampleRec.clearcoatDirection );
883
- accumulatedClearcoatRoughness += sin( acosApprox( clearcoatHalfVector.z ) );
884
-
885
- transmissiveRay = false;
886
-
887
- }
888
-
889
- // accumulate color
890
- gl_FragColor.rgb += ( emission * throughputColor );
891
-
892
- // skip the sample if our PDF or ray is impossible
893
- if ( sampleRec.pdf <= 0.0 || ! isDirectionValid( rayDirection, normal, faceNormal) ) {
894
-
895
- break;
896
-
897
- }
898
-
899
- throughputColor *= sampleRec.color / sampleRec.pdf;
900
-
901
- // discard the sample if there are any NaNs
902
- if ( any( isnan( throughputColor ) ) || any( isinf( throughputColor ) ) ) {
903
-
904
- break;
905
-
906
- }
907
-
908
- }
909
-
910
- gl_FragColor.a *= opacity;
911
-
912
- }
913
-
914
- `
915
-
916
- } );
917
-
918
- this.setValues( parameters );
919
-
920
- }
921
-
922
- }
1
+ import { Matrix4, Vector2 } from 'three';
2
+ import { MaterialBase } from './MaterialBase.js';
3
+ import {
4
+ MeshBVHUniformStruct, UIntVertexAttributeTexture,
5
+ shaderStructs, shaderIntersectFunction,
6
+ } from 'three-mesh-bvh';
7
+ import { shaderMaterialStructs, shaderLightStruct } from '../shader/shaderStructs.js';
8
+ import { MaterialsTexture } from '../uniforms/MaterialsTexture.js';
9
+ import { RenderTarget2DArray } from '../uniforms/RenderTarget2DArray.js';
10
+ import { shaderMaterialSampling } from '../shader/shaderMaterialSampling.js';
11
+ import { shaderEnvMapSampling } from '../shader/shaderEnvMapSampling.js';
12
+ import { shaderLightSampling } from '../shader/shaderLightSampling.js';
13
+ import { shaderUtils } from '../shader/shaderUtils.js';
14
+ import { shaderLayerTexelFetchFunctions } from '../shader/shaderLayerTexelFetchFunctions.js';
15
+ import { PhysicalCameraUniform } from '../uniforms/PhysicalCameraUniform.js';
16
+ import { EquirectHdrInfoUniform } from '../uniforms/EquirectHdrInfoUniform.js';
17
+ import { LightsInfoUniformStruct } from '../uniforms/LightsInfoUniformStruct.js';
18
+ import { IESProfilesTexture } from '../uniforms/IESProfilesTexture.js';
19
+ import { AttributesTextureArray } from '../uniforms/AttributesTextureArray.js';
20
+
21
+ export class PhysicalPathTracingMaterial extends MaterialBase {
22
+
23
+ onBeforeRender() {
24
+
25
+ this.setDefine( 'FEATURE_DOF', this.physicalCamera.bokehSize === 0 ? 0 : 1 );
26
+ this.setDefine( 'FEATURE_BACKGROUND_MAP', this.backgroundMap ? 1 : 0 );
27
+
28
+ }
29
+
30
+ constructor( parameters ) {
31
+
32
+ super( {
33
+
34
+ transparent: true,
35
+ depthWrite: false,
36
+
37
+ defines: {
38
+ FEATURE_MIS: 1,
39
+ FEATURE_DOF: 1,
40
+ FEATURE_BACKGROUND_MAP: 0,
41
+ TRANSPARENT_TRAVERSALS: 5,
42
+ // 0 = Perspective
43
+ // 1 = Orthographic
44
+ // 2 = Equirectangular
45
+ CAMERA_TYPE: 0,
46
+
47
+ ATTR_NORMAL: 0,
48
+ ATTR_TANGENT: 1,
49
+ ATTR_UV: 2,
50
+ ATTR_COLOR: 3,
51
+ },
52
+
53
+ uniforms: {
54
+ resolution: { value: new Vector2() },
55
+
56
+ bounces: { value: 3 },
57
+ physicalCamera: { value: new PhysicalCameraUniform() },
58
+
59
+ bvh: { value: new MeshBVHUniformStruct() },
60
+ attributesArray: { value: new AttributesTextureArray() },
61
+ materialIndexAttribute: { value: new UIntVertexAttributeTexture() },
62
+ materials: { value: new MaterialsTexture() },
63
+ textures: { value: new RenderTarget2DArray().texture },
64
+ lights: { value: new LightsInfoUniformStruct() },
65
+ iesProfiles: { value: new IESProfilesTexture().texture },
66
+ cameraWorldMatrix: { value: new Matrix4() },
67
+ invProjectionMatrix: { value: new Matrix4() },
68
+ backgroundBlur: { value: 0.0 },
69
+ environmentIntensity: { value: 1.0 },
70
+ environmentRotation: { value: new Matrix4() },
71
+ envMapInfo: { value: new EquirectHdrInfoUniform() },
72
+ backgroundMap: { value: null },
73
+
74
+ seed: { value: 0 },
75
+ opacity: { value: 1 },
76
+ filterGlossyFactor: { value: 0.0 },
77
+
78
+ backgroundAlpha: { value: 1.0 },
79
+ },
80
+
81
+ vertexShader: /* glsl */`
82
+
83
+ varying vec2 vUv;
84
+ void main() {
85
+
86
+ vec4 mvPosition = vec4( position, 1.0 );
87
+ mvPosition = modelViewMatrix * mvPosition;
88
+ gl_Position = projectionMatrix * mvPosition;
89
+
90
+ vUv = uv;
91
+
92
+ }
93
+
94
+ `,
95
+
96
+ fragmentShader: /* glsl */`
97
+ #define RAY_OFFSET 1e-4
98
+
99
+ precision highp isampler2D;
100
+ precision highp usampler2D;
101
+ precision highp sampler2DArray;
102
+ vec4 envMapTexelToLinear( vec4 a ) { return a; }
103
+ #include <common>
104
+
105
+ ${ shaderStructs }
106
+ ${ shaderIntersectFunction }
107
+ ${ shaderMaterialStructs }
108
+ ${ shaderLightStruct }
109
+
110
+ ${ shaderLayerTexelFetchFunctions }
111
+ ${ shaderUtils }
112
+ ${ shaderMaterialSampling }
113
+ ${ shaderEnvMapSampling }
114
+
115
+ uniform mat4 environmentRotation;
116
+ uniform float backgroundBlur;
117
+ uniform float backgroundAlpha;
118
+
119
+ #if FEATURE_BACKGROUND_MAP
120
+
121
+ uniform sampler2D backgroundMap;
122
+
123
+ #endif
124
+
125
+ #if FEATURE_DOF
126
+
127
+ uniform PhysicalCamera physicalCamera;
128
+
129
+ #endif
130
+
131
+ uniform vec2 resolution;
132
+ uniform int bounces;
133
+ uniform mat4 cameraWorldMatrix;
134
+ uniform mat4 invProjectionMatrix;
135
+ uniform sampler2DArray attributesArray;
136
+ uniform usampler2D materialIndexAttribute;
137
+ uniform BVH bvh;
138
+ uniform float environmentIntensity;
139
+ uniform float filterGlossyFactor;
140
+ uniform int seed;
141
+ uniform float opacity;
142
+ uniform sampler2D materials;
143
+ uniform LightsInfo lights;
144
+ uniform sampler2DArray iesProfiles;
145
+
146
+ ${ shaderLightSampling }
147
+
148
+ uniform EquirectHdrInfo envMapInfo;
149
+
150
+ uniform sampler2DArray textures;
151
+ varying vec2 vUv;
152
+
153
+ float applyFilteredGlossy( float roughness, float accumulatedRoughness ) {
154
+
155
+ return clamp(
156
+ max(
157
+ roughness,
158
+ accumulatedRoughness * filterGlossyFactor * 5.0 ),
159
+ 0.0,
160
+ 1.0
161
+ );
162
+
163
+ }
164
+
165
+ vec3 sampleBackground( vec3 direction ) {
166
+
167
+ vec3 sampleDir = normalize( direction + getHemisphereSample( direction, rand2() ) * 0.5 * backgroundBlur );
168
+
169
+ #if FEATURE_BACKGROUND_MAP
170
+
171
+ return sampleEquirectEnvMapColor( sampleDir, backgroundMap );
172
+
173
+ #else
174
+
175
+ return environmentIntensity * sampleEquirectEnvMapColor( sampleDir, envMapInfo.map );
176
+
177
+ #endif
178
+
179
+ }
180
+
181
+ // step through multiple surface hits and accumulate color attenuation based on transmissive surfaces
182
+ bool attenuateHit( BVH bvh, vec3 rayOrigin, vec3 rayDirection, int traversals, bool isShadowRay, out vec3 color ) {
183
+
184
+ // hit results
185
+ uvec4 faceIndices = uvec4( 0u );
186
+ vec3 faceNormal = vec3( 0.0, 0.0, 1.0 );
187
+ vec3 barycoord = vec3( 0.0 );
188
+ float side = 1.0;
189
+ float dist = 0.0;
190
+
191
+ color = vec3( 1.0 );
192
+
193
+ for ( int i = 0; i < traversals; i ++ ) {
194
+
195
+ if ( bvhIntersectFirstHit( bvh, rayOrigin, rayDirection, faceIndices, faceNormal, barycoord, side, dist ) ) {
196
+
197
+ // TODO: attenuate the contribution based on the PDF of the resulting ray including refraction values
198
+ // Should be able to work using the material BSDF functions which will take into account specularity, etc.
199
+ // TODO: should we account for emissive surfaces here?
200
+
201
+ vec2 uv = textureSampleBarycoord( attributesArray, ATTR_UV, barycoord, faceIndices.xyz ).xy;
202
+ vec4 vertexColor = textureSampleBarycoord( attributesArray, ATTR_COLOR, barycoord, faceIndices.xyz );
203
+
204
+ uint materialIndex = uTexelFetch1D( materialIndexAttribute, faceIndices.x ).r;
205
+ Material material = readMaterialInfo( materials, materialIndex );
206
+
207
+ // adjust the ray to the new surface
208
+ bool isBelowSurface = dot( rayDirection, faceNormal ) < 0.0;
209
+ vec3 point = rayOrigin + rayDirection * dist;
210
+ vec3 absPoint = abs( point );
211
+ float maxPoint = max( absPoint.x, max( absPoint.y, absPoint.z ) );
212
+ rayOrigin = point + faceNormal * ( maxPoint + 1.0 ) * ( isBelowSurface ? - RAY_OFFSET : RAY_OFFSET );
213
+
214
+ if ( ! material.castShadow && isShadowRay ) {
215
+
216
+ continue;
217
+
218
+ }
219
+
220
+ // Opacity Test
221
+
222
+ // albedo
223
+ vec4 albedo = vec4( material.color, material.opacity );
224
+ if ( material.map != - 1 ) {
225
+
226
+ vec3 uvPrime = material.mapTransform * vec3( uv, 1 );
227
+ albedo *= texture2D( textures, vec3( uvPrime.xy, material.map ) );
228
+
229
+ }
230
+
231
+ if ( material.vertexColors ) {
232
+
233
+ albedo *= vertexColor;
234
+
235
+ }
236
+
237
+ // alphaMap
238
+ if ( material.alphaMap != - 1 ) {
239
+
240
+ albedo.a *= texture2D( textures, vec3( uv, material.alphaMap ) ).x;
241
+
242
+ }
243
+
244
+ // transmission
245
+ float transmission = material.transmission;
246
+ if ( material.transmissionMap != - 1 ) {
247
+
248
+ vec3 uvPrime = material.transmissionMapTransform * vec3( uv, 1 );
249
+ transmission *= texture2D( textures, vec3( uvPrime.xy, material.transmissionMap ) ).r;
250
+
251
+ }
252
+
253
+ // metalness
254
+ float metalness = material.metalness;
255
+ if ( material.metalnessMap != - 1 ) {
256
+
257
+ vec3 uvPrime = material.metalnessMapTransform * vec3( uv, 1 );
258
+ metalness *= texture2D( textures, vec3( uvPrime.xy, material.metalnessMap ) ).b;
259
+
260
+ }
261
+
262
+ float alphaTest = material.alphaTest;
263
+ bool useAlphaTest = alphaTest != 0.0;
264
+ float transmissionFactor = ( 1.0 - metalness ) * transmission;
265
+ if (
266
+ transmissionFactor < rand() && ! (
267
+ // material sidedness
268
+ material.side != 0.0 && side == material.side
269
+
270
+ // alpha test
271
+ || useAlphaTest && albedo.a < alphaTest
272
+
273
+ // opacity
274
+ || material.transparent && ! useAlphaTest && albedo.a < rand()
275
+ )
276
+ ) {
277
+
278
+ return true;
279
+
280
+ }
281
+
282
+ if ( side == 1.0 && isBelowSurface ) {
283
+
284
+ // only attenuate by surface color on the way in
285
+ color *= mix( vec3( 1.0 ), albedo.rgb, transmissionFactor );
286
+
287
+ } else if ( side == - 1.0 ) {
288
+
289
+ // attenuate by medium once we hit the opposite side of the model
290
+ color *= transmissionAttenuation( dist, material.attenuationColor, material.attenuationDistance );
291
+
292
+ }
293
+
294
+ } else {
295
+
296
+ return false;
297
+
298
+ }
299
+
300
+ }
301
+
302
+ return true;
303
+
304
+ }
305
+
306
+ // returns whether the ray hit anything before a certain distance, not just the first surface. Could be optimized to not check the full hierarchy.
307
+ bool anyCloserHit( BVH bvh, vec3 rayOrigin, vec3 rayDirection, float maxDist ) {
308
+
309
+ uvec4 faceIndices = uvec4( 0u );
310
+ vec3 faceNormal = vec3( 0.0, 0.0, 1.0 );
311
+ vec3 barycoord = vec3( 0.0 );
312
+ float side = 1.0;
313
+ float dist = 0.0;
314
+ bool hit = bvhIntersectFirstHit( bvh, rayOrigin, rayDirection, faceIndices, faceNormal, barycoord, side, dist );
315
+ return hit && dist < maxDist;
316
+
317
+ }
318
+
319
+ // tentFilter from Peter Shirley's 'Realistic Ray Tracing (2nd Edition)' book, pg. 60
320
+ // erichlof/THREE.js-PathTracing-Renderer/
321
+ float tentFilter( float x ) {
322
+
323
+ return x < 0.5 ? sqrt( 2.0 * x ) - 1.0 : 1.0 - sqrt( 2.0 - ( 2.0 * x ) );
324
+
325
+ }
326
+
327
+ vec3 ndcToRayOrigin( vec2 coord ) {
328
+
329
+ vec4 rayOrigin4 = cameraWorldMatrix * invProjectionMatrix * vec4( coord, - 1.0, 1.0 );
330
+ return rayOrigin4.xyz / rayOrigin4.w;
331
+ }
332
+
333
+ void getCameraRay( out vec3 rayDirection, out vec3 rayOrigin ) {
334
+
335
+ vec2 ssd = vec2( 1.0 ) / resolution;
336
+
337
+ // Jitter the camera ray by finding a uv coordinate at a random sample
338
+ // around this pixel's UV coordinate
339
+ vec2 jitteredUv = vUv + vec2( tentFilter( rand() ) * ssd.x, tentFilter( rand() ) * ssd.y );
340
+
341
+ #if CAMERA_TYPE == 2
342
+
343
+ // Equirectangular projection
344
+
345
+ vec4 rayDirection4 = vec4( equirectUvToDirection( jitteredUv ), 0.0 );
346
+ vec4 rayOrigin4 = vec4( 0.0, 0.0, 0.0, 1.0 );
347
+
348
+ rayDirection4 = cameraWorldMatrix * rayDirection4;
349
+ rayOrigin4 = cameraWorldMatrix * rayOrigin4;
350
+
351
+ rayDirection = normalize( rayDirection4.xyz );
352
+ rayOrigin = rayOrigin4.xyz / rayOrigin4.w;
353
+
354
+ #else
355
+
356
+ // get [- 1, 1] normalized device coordinates
357
+ vec2 ndc = 2.0 * jitteredUv - vec2( 1.0 );
358
+
359
+ rayOrigin = ndcToRayOrigin( ndc );
360
+
361
+ #if CAMERA_TYPE == 1
362
+
363
+ // Orthographic projection
364
+
365
+ rayDirection = ( cameraWorldMatrix * vec4( 0.0, 0.0, - 1.0, 0.0 ) ).xyz;
366
+ rayDirection = normalize( rayDirection );
367
+
368
+ #else
369
+
370
+ // Perspective projection
371
+
372
+ rayDirection = normalize( mat3(cameraWorldMatrix) * ( invProjectionMatrix * vec4( ndc, 0.0, 1.0 ) ).xyz );
373
+
374
+ #endif
375
+
376
+ #endif
377
+
378
+ #if FEATURE_DOF
379
+ {
380
+
381
+ // depth of field
382
+ vec3 focalPoint = rayOrigin + normalize( rayDirection ) * physicalCamera.focusDistance;
383
+
384
+ // get the aperture sample
385
+ vec2 apertureSample = sampleAperture( physicalCamera.apertureBlades ) * physicalCamera.bokehSize * 0.5 * 1e-3;
386
+
387
+ // rotate the aperture shape
388
+ float ac = cos( physicalCamera.apertureRotation );
389
+ float as = sin( physicalCamera.apertureRotation );
390
+ apertureSample = vec2(
391
+ apertureSample.x * ac - apertureSample.y * as,
392
+ apertureSample.x * as + apertureSample.y * ac
393
+ );
394
+ apertureSample.x *= saturate( physicalCamera.anamorphicRatio );
395
+ apertureSample.y *= saturate( 1.0 / physicalCamera.anamorphicRatio );
396
+
397
+ // create the new ray
398
+ rayOrigin += ( cameraWorldMatrix * vec4( apertureSample, 0.0, 0.0 ) ).xyz;
399
+ rayDirection = focalPoint - rayOrigin;
400
+
401
+ }
402
+ #endif
403
+
404
+ rayDirection = normalize( rayDirection );
405
+
406
+ }
407
+
408
+ void main() {
409
+
410
+ rng_initialize( gl_FragCoord.xy, seed );
411
+
412
+ vec3 rayDirection;
413
+ vec3 rayOrigin;
414
+
415
+ getCameraRay( rayDirection, rayOrigin );
416
+
417
+ // inverse environment rotation
418
+ mat3 envRotation3x3 = mat3( environmentRotation );
419
+ mat3 invEnvRotation3x3 = inverse( envRotation3x3 );
420
+
421
+ // final color
422
+ gl_FragColor = vec4( 0.0 );
423
+ gl_FragColor.a = 1.0;
424
+
425
+ // hit results
426
+ uvec4 faceIndices = uvec4( 0u );
427
+ vec3 faceNormal = vec3( 0.0, 0.0, 1.0 );
428
+ vec3 barycoord = vec3( 0.0 );
429
+ float side = 1.0;
430
+ float dist = 0.0;
431
+
432
+ // path tracing state
433
+ float accumulatedRoughness = 0.0;
434
+ float accumulatedClearcoatRoughness = 0.0;
435
+ bool transmissiveRay = true;
436
+ int transparentTraversals = TRANSPARENT_TRAVERSALS;
437
+ vec3 throughputColor = vec3( 1.0 );
438
+ SampleRec sampleRec;
439
+ int i;
440
+ bool isShadowRay = false;
441
+
442
+ for ( i = 0; i < bounces; i ++ ) {
443
+
444
+ bool hit = bvhIntersectFirstHit( bvh, rayOrigin, rayDirection, faceIndices, faceNormal, barycoord, side, dist );
445
+
446
+ LightSampleRec lightHit = lightsClosestHit( lights.tex, lights.count, rayOrigin, rayDirection );
447
+
448
+ if ( lightHit.hit && ( lightHit.dist < dist || !hit ) ) {
449
+
450
+ if ( i == 0 || transmissiveRay ) {
451
+
452
+ gl_FragColor.rgb += lightHit.emission * throughputColor;
453
+
454
+ } else {
455
+
456
+ #if FEATURE_MIS
457
+
458
+ // NOTE: we skip MIS for spotlights since we haven't fixed the forward
459
+ // path tracing code path, yet
460
+ if ( lightHit.type == SPOT_LIGHT_TYPE ) {
461
+
462
+ gl_FragColor.rgb += lightHit.emission * throughputColor;
463
+
464
+ } else {
465
+
466
+ // weight the contribution
467
+ float misWeight = misHeuristic( sampleRec.pdf, lightHit.pdf / float( lights.count + 1u ) );
468
+ gl_FragColor.rgb += lightHit.emission * throughputColor * misWeight;
469
+
470
+ }
471
+
472
+ #else
473
+
474
+ gl_FragColor.rgb += lightHit.emission * throughputColor;
475
+
476
+ #endif
477
+
478
+ }
479
+ break;
480
+
481
+ }
482
+
483
+ if ( ! hit ) {
484
+
485
+ if ( i == 0 || transmissiveRay ) {
486
+
487
+ gl_FragColor.rgb += sampleBackground( envRotation3x3 * rayDirection ) * throughputColor;
488
+ gl_FragColor.a = backgroundAlpha;
489
+
490
+ } else {
491
+
492
+ #if FEATURE_MIS
493
+
494
+ // get the PDF of the hit envmap point
495
+ vec3 envColor;
496
+ float envPdf = envMapSample( envRotation3x3 * rayDirection, envMapInfo, envColor );
497
+ envPdf /= float( lights.count + 1u );
498
+
499
+ // and weight the contribution
500
+ float misWeight = misHeuristic( sampleRec.pdf, envPdf );
501
+ gl_FragColor.rgb += environmentIntensity * envColor * throughputColor * misWeight;
502
+
503
+ #else
504
+
505
+ gl_FragColor.rgb +=
506
+ environmentIntensity *
507
+ sampleEquirectEnvMapColor( envRotation3x3 * rayDirection, envMapInfo.map ) *
508
+ throughputColor;
509
+
510
+ #endif
511
+
512
+ }
513
+ break;
514
+
515
+ }
516
+
517
+ uint materialIndex = uTexelFetch1D( materialIndexAttribute, faceIndices.x ).r;
518
+ Material material = readMaterialInfo( materials, materialIndex );
519
+
520
+ if ( material.matte && i == 0 ) {
521
+
522
+ gl_FragColor = vec4( 0.0 );
523
+ break;
524
+
525
+ }
526
+
527
+ // if we've determined that this is a shadow ray and we've hit an item with no shadow casting
528
+ // then skip it
529
+ if ( ! material.castShadow && isShadowRay ) {
530
+
531
+ vec3 point = rayOrigin + rayDirection * dist;
532
+ vec3 absPoint = abs( point );
533
+ float maxPoint = max( absPoint.x, max( absPoint.y, absPoint.z ) );
534
+ rayOrigin = point - ( maxPoint + 1.0 ) * faceNormal * RAY_OFFSET;
535
+
536
+ continue;
537
+
538
+ }
539
+
540
+ // uv coord for textures
541
+ vec2 uv = textureSampleBarycoord( attributesArray, ATTR_UV, barycoord, faceIndices.xyz ).xy;
542
+ vec4 vertexColor = textureSampleBarycoord( attributesArray, ATTR_COLOR, barycoord, faceIndices.xyz );
543
+
544
+ // albedo
545
+ vec4 albedo = vec4( material.color, material.opacity );
546
+ if ( material.map != - 1 ) {
547
+
548
+ vec3 uvPrime = material.mapTransform * vec3( uv, 1 );
549
+ albedo *= texture2D( textures, vec3( uvPrime.xy, material.map ) );
550
+ }
551
+
552
+ if ( material.vertexColors ) {
553
+
554
+ albedo *= vertexColor;
555
+
556
+ }
557
+
558
+ // alphaMap
559
+ if ( material.alphaMap != - 1 ) {
560
+
561
+ albedo.a *= texture2D( textures, vec3( uv, material.alphaMap ) ).x;
562
+
563
+ }
564
+
565
+ // possibly skip this sample if it's transparent, alpha test is enabled, or we hit the wrong material side
566
+ // and it's single sided.
567
+ // - alpha test is disabled when it === 0
568
+ // - the material sidedness test is complicated because we want light to pass through the back side but still
569
+ // be able to see the front side. This boolean checks if the side we hit is the front side on the first ray
570
+ // and we're rendering the other then we skip it. Do the opposite on subsequent bounces to get incoming light.
571
+ float alphaTest = material.alphaTest;
572
+ bool useAlphaTest = alphaTest != 0.0;
573
+ if (
574
+ // material sidedness
575
+ material.side != 0.0 && side != material.side
576
+
577
+ // alpha test
578
+ || useAlphaTest && albedo.a < alphaTest
579
+
580
+ // opacity
581
+ || material.transparent && ! useAlphaTest && albedo.a < rand()
582
+ ) {
583
+
584
+ vec3 point = rayOrigin + rayDirection * dist;
585
+ vec3 absPoint = abs( point );
586
+ float maxPoint = max( absPoint.x, max( absPoint.y, absPoint.z ) );
587
+ rayOrigin = point - ( maxPoint + 1.0 ) * faceNormal * RAY_OFFSET;
588
+
589
+ // only allow a limited number of transparency discards otherwise we could
590
+ // crash the context with too long a loop.
591
+ i -= sign( transparentTraversals );
592
+ transparentTraversals -= sign( transparentTraversals );
593
+ continue;
594
+
595
+ }
596
+
597
+ // fetch the interpolated smooth normal
598
+ vec3 normal = normalize( textureSampleBarycoord(
599
+ attributesArray,
600
+ ATTR_NORMAL,
601
+ barycoord,
602
+ faceIndices.xyz
603
+ ).xyz );
604
+
605
+ // roughness
606
+ float roughness = material.roughness;
607
+ if ( material.roughnessMap != - 1 ) {
608
+
609
+ vec3 uvPrime = material.roughnessMapTransform * vec3( uv, 1 );
610
+ roughness *= texture2D( textures, vec3( uvPrime.xy, material.roughnessMap ) ).g;
611
+
612
+ }
613
+
614
+ // metalness
615
+ float metalness = material.metalness;
616
+ if ( material.metalnessMap != - 1 ) {
617
+
618
+ vec3 uvPrime = material.metalnessMapTransform * vec3( uv, 1 );
619
+ metalness *= texture2D( textures, vec3( uvPrime.xy, material.metalnessMap ) ).b;
620
+
621
+ }
622
+
623
+ // emission
624
+ vec3 emission = material.emissiveIntensity * material.emissive;
625
+ if ( material.emissiveMap != - 1 ) {
626
+
627
+ vec3 uvPrime = material.emissiveMapTransform * vec3( uv, 1 );
628
+ emission *= texture2D( textures, vec3( uvPrime.xy, material.emissiveMap ) ).xyz;
629
+
630
+ }
631
+
632
+ // transmission
633
+ float transmission = material.transmission;
634
+ if ( material.transmissionMap != - 1 ) {
635
+
636
+ vec3 uvPrime = material.transmissionMapTransform * vec3( uv, 1 );
637
+ transmission *= texture2D( textures, vec3( uvPrime.xy, material.transmissionMap ) ).r;
638
+
639
+ }
640
+
641
+ // normal
642
+ vec3 baseNormal = normal;
643
+ if ( material.normalMap != - 1 ) {
644
+
645
+ vec4 tangentSample = textureSampleBarycoord(
646
+ attributesArray,
647
+ ATTR_TANGENT,
648
+ barycoord,
649
+ faceIndices.xyz
650
+ );
651
+
652
+ // some provided tangents can be malformed (0, 0, 0) causing the normal to be degenerate
653
+ // resulting in NaNs and slow path tracing.
654
+ if ( length( tangentSample.xyz ) > 0.0 ) {
655
+
656
+ vec3 tangent = normalize( tangentSample.xyz );
657
+ vec3 bitangent = normalize( cross( normal, tangent ) * tangentSample.w );
658
+ mat3 vTBN = mat3( tangent, bitangent, normal );
659
+
660
+ vec3 uvPrime = material.normalMapTransform * vec3( uv, 1 );
661
+ vec3 texNormal = texture2D( textures, vec3( uvPrime.xy, material.normalMap ) ).xyz * 2.0 - 1.0;
662
+ texNormal.xy *= material.normalScale;
663
+ normal = vTBN * texNormal;
664
+
665
+ }
666
+
667
+ }
668
+
669
+ normal *= side;
670
+
671
+ // clearcoat
672
+ float clearcoat = material.clearcoat;
673
+ if ( material.clearcoatMap != - 1 ) {
674
+
675
+ vec3 uvPrime = material.clearcoatMapTransform * vec3( uv, 1 );
676
+ clearcoat *= texture2D( textures, vec3( uvPrime.xy, material.clearcoatMap ) ).r;
677
+
678
+ }
679
+
680
+ // clearcoatRoughness
681
+ float clearcoatRoughness = material.clearcoatRoughness;
682
+ if ( material.clearcoatRoughnessMap != - 1 ) {
683
+
684
+ vec3 uvPrime = material.clearcoatRoughnessMapTransform * vec3( uv, 1 );
685
+ clearcoat *= texture2D( textures, vec3( uvPrime.xy, material.clearcoatRoughnessMap ) ).g;
686
+
687
+ }
688
+
689
+ // clearcoatNormal
690
+ vec3 clearcoatNormal = baseNormal;
691
+ if ( material.clearcoatNormalMap != - 1 ) {
692
+
693
+ vec4 tangentSample = textureSampleBarycoord(
694
+ attributesArray,
695
+ ATTR_TANGENT,
696
+ barycoord,
697
+ faceIndices.xyz
698
+ );
699
+
700
+ // some provided tangents can be malformed (0, 0, 0) causing the normal to be degenerate
701
+ // resulting in NaNs and slow path tracing.
702
+ if ( length( tangentSample.xyz ) > 0.0 ) {
703
+
704
+ vec3 tangent = normalize( tangentSample.xyz );
705
+ vec3 bitangent = normalize( cross( clearcoatNormal, tangent ) * tangentSample.w );
706
+ mat3 vTBN = mat3( tangent, bitangent, clearcoatNormal );
707
+
708
+ vec3 uvPrime = material.clearcoatNormalMapTransform * vec3( uv, 1 );
709
+ vec3 texNormal = texture2D( textures, vec3( uvPrime.xy, material.clearcoatNormalMap ) ).xyz * 2.0 - 1.0;
710
+ texNormal.xy *= material.clearcoatNormalScale;
711
+ clearcoatNormal = vTBN * texNormal;
712
+
713
+ }
714
+
715
+ }
716
+
717
+ clearcoatNormal *= side;
718
+
719
+ // sheenColor
720
+ vec3 sheenColor = material.sheenColor;
721
+ if ( material.sheenColorMap != - 1 ) {
722
+
723
+ vec3 uvPrime = material.sheenColorMapTransform * vec3( uv, 1 );
724
+ sheenColor *= texture2D( textures, vec3( uvPrime.xy, material.sheenColorMap ) ).rgb;
725
+
726
+ }
727
+
728
+ // sheenRoughness
729
+ float sheenRoughness = material.sheenRoughness;
730
+ if ( material.sheenRoughnessMap != - 1 ) {
731
+
732
+ vec3 uvPrime = material.sheenRoughnessMapTransform * vec3( uv, 1 );
733
+ sheenRoughness *= texture2D( textures, vec3( uvPrime.xy, material.sheenRoughnessMap ) ).a;
734
+
735
+ }
736
+
737
+ // iridescence
738
+ float iridescence = material.iridescence;
739
+ if ( material.iridescenceMap != - 1 ) {
740
+
741
+ vec3 uvPrime = material.iridescenceMapTransform * vec3( uv, 1 );
742
+ iridescence *= texture2D( textures, vec3( uvPrime.xy, material.iridescenceMap ) ).r;
743
+
744
+ }
745
+
746
+ // iridescence thickness
747
+ float iridescenceThickness = material.iridescenceThicknessMaximum;
748
+ if ( material.iridescenceThicknessMap != - 1 ) {
749
+
750
+ vec3 uvPrime = material.iridescenceThicknessMapTransform * vec3( uv, 1 );
751
+ float iridescenceThicknessSampled = texture2D( textures, vec3( uvPrime.xy, material.iridescenceThicknessMap ) ).g;
752
+ iridescenceThickness = mix( material.iridescenceThicknessMinimum, material.iridescenceThicknessMaximum, iridescenceThicknessSampled );
753
+
754
+ }
755
+
756
+ iridescence = iridescenceThickness == 0.0 ? 0.0 : iridescence;
757
+
758
+ // specular color
759
+ vec3 specularColor = material.specularColor;
760
+ if ( material.specularColorMap != - 1 ) {
761
+
762
+ vec3 uvPrime = material.specularColorMapTransform * vec3( uv, 1 );
763
+ specularColor *= texture2D( textures, vec3( uvPrime.xy, material.specularColorMap ) ).rgb;
764
+
765
+ }
766
+
767
+ // specular intensity
768
+ float specularIntensity = material.specularIntensity;
769
+ if ( material.specularIntensityMap != - 1 ) {
770
+
771
+ vec3 uvPrime = material.specularIntensityMapTransform * vec3( uv, 1 );
772
+ specularIntensity *= texture2D( textures, vec3( uvPrime.xy, material.specularIntensityMap ) ).a;
773
+
774
+ }
775
+
776
+ SurfaceRec surfaceRec;
777
+ surfaceRec.normal = normal;
778
+ surfaceRec.faceNormal = faceNormal;
779
+ surfaceRec.transmission = transmission;
780
+ surfaceRec.ior = material.ior;
781
+ surfaceRec.emission = emission;
782
+ surfaceRec.metalness = metalness;
783
+ surfaceRec.color = albedo.rgb;
784
+ surfaceRec.clearcoat = clearcoat;
785
+ surfaceRec.sheenColor = sheenColor;
786
+ surfaceRec.iridescence = iridescence;
787
+ surfaceRec.iridescenceIor = material.iridescenceIor;
788
+ surfaceRec.iridescenceThickness = iridescenceThickness;
789
+ surfaceRec.specularColor = specularColor;
790
+ surfaceRec.specularIntensity = specularIntensity;
791
+ surfaceRec.attenuationColor = material.attenuationColor;
792
+ surfaceRec.attenuationDistance = material.attenuationDistance;
793
+
794
+ // apply perceptual roughness factor from gltf
795
+ // https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#microfacet-surfaces
796
+ surfaceRec.roughness = roughness * roughness;
797
+ surfaceRec.clearcoatRoughness = clearcoatRoughness * clearcoatRoughness;
798
+ surfaceRec.sheenRoughness = sheenRoughness * sheenRoughness;
799
+
800
+ // frontFace is used to determine transmissive properties and PDF. If no transmission is used
801
+ // then we can just always assume this is a front face.
802
+ surfaceRec.frontFace = side == 1.0 || transmission == 0.0;
803
+ surfaceRec.eta = material.thinFilm || surfaceRec.frontFace ? 1.0 / material.ior : material.ior;
804
+ surfaceRec.f0 = iorRatioToF0( surfaceRec.eta );
805
+ surfaceRec.thinFilm = material.thinFilm;
806
+
807
+ // Compute the filtered roughness value to use during specular reflection computations.
808
+ // The accumulated roughness value is scaled by a user setting and a "magic value" of 5.0.
809
+ // If we're exiting something transmissive then scale the factor down significantly so we can retain
810
+ // sharp internal reflections
811
+ surfaceRec.filteredRoughness = applyFilteredGlossy( surfaceRec.roughness, accumulatedRoughness );
812
+ surfaceRec.filteredClearcoatRoughness = applyFilteredGlossy( surfaceRec.clearcoatRoughness, accumulatedClearcoatRoughness );
813
+
814
+ mat3 normalBasis = getBasisFromNormal( surfaceRec.normal );
815
+ mat3 invBasis = inverse( normalBasis );
816
+
817
+ mat3 clearcoatNormalBasis = getBasisFromNormal( clearcoatNormal );
818
+ mat3 clearcoatInvBasis = inverse( clearcoatNormalBasis );
819
+
820
+ vec3 outgoing = - normalize( invBasis * rayDirection );
821
+ vec3 clearcoatOutgoing = - normalize( clearcoatInvBasis * rayDirection );
822
+ sampleRec = bsdfSample( outgoing, clearcoatOutgoing, normalBasis, invBasis, clearcoatNormalBasis, clearcoatInvBasis, surfaceRec );
823
+
824
+ isShadowRay = sampleRec.specularPdf < rand();
825
+
826
+ // adjust the hit point by the surface normal by a factor of some offset and the
827
+ // maximum component-wise value of the current point to accommodate floating point
828
+ // error as values increase.
829
+ vec3 point = rayOrigin + rayDirection * dist;
830
+ vec3 absPoint = abs( point );
831
+ float maxPoint = max( absPoint.x, max( absPoint.y, absPoint.z ) );
832
+ rayDirection = normalize( normalBasis * sampleRec.direction );
833
+
834
+ bool isBelowSurface = dot( rayDirection, faceNormal ) < 0.0;
835
+ rayOrigin = point + faceNormal * ( maxPoint + 1.0 ) * ( isBelowSurface ? - RAY_OFFSET : RAY_OFFSET );
836
+
837
+ // direct env map sampling
838
+ #if FEATURE_MIS
839
+
840
+ // uniformly pick a light or environment map
841
+ if( rand() > 1.0 / float( lights.count + 1u ) ) {
842
+
843
+ // sample a light or environment
844
+ LightSampleRec lightSampleRec = randomLightSample( lights.tex, iesProfiles, lights.count, rayOrigin );
845
+
846
+ bool isSampleBelowSurface = dot( faceNormal, lightSampleRec.direction ) < 0.0;
847
+ if ( isSampleBelowSurface ) {
848
+
849
+ lightSampleRec.pdf = 0.0;
850
+
851
+ }
852
+
853
+ // check if a ray could even reach the light area
854
+ if (
855
+ lightSampleRec.pdf > 0.0 &&
856
+ isDirectionValid( lightSampleRec.direction, normal, faceNormal ) &&
857
+ ! anyCloserHit( bvh, rayOrigin, lightSampleRec.direction, lightSampleRec.dist )
858
+ ) {
859
+
860
+ // get the material pdf
861
+ vec3 sampleColor;
862
+ float lightMaterialPdf = bsdfResult( outgoing, clearcoatOutgoing, normalize( invBasis * lightSampleRec.direction ), normalize( clearcoatInvBasis * lightSampleRec.direction ), surfaceRec, sampleColor );
863
+ bool isValidSampleColor = all( greaterThanEqual( sampleColor, vec3( 0.0 ) ) );
864
+ if ( lightMaterialPdf > 0.0 && isValidSampleColor ) {
865
+
866
+ // weight the direct light contribution
867
+ float lightPdf = lightSampleRec.pdf / float( lights.count + 1u );
868
+ float misWeight = misHeuristic( lightPdf, lightMaterialPdf );
869
+ gl_FragColor.rgb += lightSampleRec.emission * throughputColor * sampleColor * misWeight / lightPdf;
870
+
871
+ }
872
+
873
+ }
874
+
875
+ } else {
876
+
877
+ // find a sample in the environment map to include in the contribution
878
+ vec3 envColor, envDirection;
879
+ float envPdf = randomEnvMapSample( envMapInfo, envColor, envDirection );
880
+ envDirection = invEnvRotation3x3 * envDirection;
881
+
882
+ // this env sampling is not set up for transmissive sampling and yields overly bright
883
+ // results so we ignore the sample in this case.
884
+ // TODO: this should be improved but how? The env samples could traverse a few layers?
885
+ bool isSampleBelowSurface = dot( faceNormal, envDirection ) < 0.0;
886
+ if ( isSampleBelowSurface ) {
887
+
888
+ envPdf = 0.0;
889
+
890
+ }
891
+
892
+ // check if a ray could even reach the surface
893
+ vec3 attenuatedColor;
894
+ if (
895
+ envPdf > 0.0 &&
896
+ isDirectionValid( envDirection, normal, faceNormal ) &&
897
+ ! attenuateHit( bvh, rayOrigin, envDirection, bounces - i, isShadowRay, attenuatedColor )
898
+ ) {
899
+
900
+ // get the material pdf
901
+ vec3 sampleColor;
902
+ float envMaterialPdf = bsdfResult( outgoing, clearcoatOutgoing, normalize( invBasis * envDirection ), normalize( clearcoatInvBasis * envDirection ), surfaceRec, sampleColor );
903
+ bool isValidSampleColor = all( greaterThanEqual( sampleColor, vec3( 0.0 ) ) );
904
+ if ( envMaterialPdf > 0.0 && isValidSampleColor ) {
905
+
906
+ // weight the direct light contribution
907
+ envPdf /= float( lights.count + 1u );
908
+ float misWeight = misHeuristic( envPdf, envMaterialPdf );
909
+ gl_FragColor.rgb += attenuatedColor * environmentIntensity * envColor * throughputColor * sampleColor * misWeight / envPdf;
910
+
911
+ }
912
+
913
+ }
914
+
915
+ }
916
+ #endif
917
+
918
+ // accumulate a roughness value to offset diffuse, specular, diffuse rays that have high contribution
919
+ // to a single pixel resulting in fireflies
920
+ if ( ! isBelowSurface ) {
921
+
922
+ // determine if this is a rough normal or not by checking how far off straight up it is
923
+ vec3 halfVector = normalize( outgoing + sampleRec.direction );
924
+ accumulatedRoughness += sin( acosApprox( halfVector.z ) );
925
+
926
+ vec3 clearcoatHalfVector = normalize( clearcoatOutgoing + sampleRec.clearcoatDirection );
927
+ accumulatedClearcoatRoughness += sin( acosApprox( clearcoatHalfVector.z ) );
928
+
929
+ transmissiveRay = false;
930
+
931
+ }
932
+
933
+ // accumulate color
934
+ gl_FragColor.rgb += ( emission * throughputColor );
935
+
936
+ // skip the sample if our PDF or ray is impossible
937
+ if ( sampleRec.pdf <= 0.0 || ! isDirectionValid( rayDirection, normal, faceNormal) ) {
938
+
939
+ break;
940
+
941
+ }
942
+
943
+ throughputColor *= sampleRec.color / sampleRec.pdf;
944
+
945
+ // attenuate the throughput color by the medium color
946
+ if ( side == - 1.0 ) {
947
+
948
+ throughputColor *= transmissionAttenuation( dist, surfaceRec.attenuationColor, surfaceRec.attenuationDistance );
949
+
950
+ }
951
+
952
+ // discard the sample if there are any NaNs
953
+ if ( any( isnan( throughputColor ) ) || any( isinf( throughputColor ) ) ) {
954
+
955
+ break;
956
+
957
+ }
958
+
959
+ }
960
+
961
+ gl_FragColor.a *= opacity;
962
+
963
+ }
964
+
965
+ `
966
+
967
+ } );
968
+
969
+ this.setValues( parameters );
970
+
971
+ }
972
+
973
+ }