-
-
Notifications
You must be signed in to change notification settings - Fork 126
/
PhysicalPathTracingMaterial.js
789 lines (551 loc) · 24.2 KB
/
PhysicalPathTracingMaterial.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
import { Matrix4, Matrix3, Color, Vector2 } from 'three';
import { MaterialBase } from './MaterialBase.js';
import {
MeshBVHUniformStruct, FloatVertexAttributeTexture, UIntVertexAttributeTexture,
shaderStructs, shaderIntersectFunction,
} from 'three-mesh-bvh';
import { shaderMaterialStructs, shaderLightStruct } from '../shader/shaderStructs.js';
import { MaterialsTexture } from '../uniforms/MaterialsTexture.js';
import { RenderTarget2DArray } from '../uniforms/RenderTarget2DArray.js';
import { shaderMaterialSampling } from '../shader/shaderMaterialSampling.js';
import { shaderEnvMapSampling } from '../shader/shaderEnvMapSampling.js';
import { shaderLightSampling } from '../shader/shaderLightSampling.js';
import { shaderUtils } from '../shader/shaderUtils.js';
import { PhysicalCameraUniform } from '../uniforms/PhysicalCameraUniform.js';
import { EquirectHdrInfoUniform } from '../uniforms/EquirectHdrInfoUniform.js';
import { LightsTexture } from '../uniforms/LightsTexture.js';
export class PhysicalPathTracingMaterial extends MaterialBase {
onBeforeRender() {
this.setDefine( 'FEATURE_DOF', this.physicalCamera.bokehSize === 0 ? 0 : 1 );
}
constructor( parameters ) {
super( {
transparent: true,
depthWrite: false,
defines: {
FEATURE_MIS: 1,
FEATURE_DOF: 1,
FEATURE_GRADIENT_BG: 0,
TRANSPARENT_TRAVERSALS: 5,
// 0 = Perspective
// 1 = Orthographic
// 2 = Equirectangular
CAMERA_TYPE: 0,
},
uniforms: {
resolution: { value: new Vector2() },
bounces: { value: 3 },
physicalCamera: { value: new PhysicalCameraUniform() },
bvh: { value: new MeshBVHUniformStruct() },
normalAttribute: { value: new FloatVertexAttributeTexture() },
tangentAttribute: { value: new FloatVertexAttributeTexture() },
uvAttribute: { value: new FloatVertexAttributeTexture() },
materialIndexAttribute: { value: new UIntVertexAttributeTexture() },
materials: { value: new MaterialsTexture() },
textures: { value: new RenderTarget2DArray().texture },
lights: { value: new LightsTexture() },
lightCount: { value: 0 },
cameraWorldMatrix: { value: new Matrix4() },
invProjectionMatrix: { value: new Matrix4() },
backgroundBlur: { value: 0.0 },
environmentIntensity: { value: 2.0 },
environmentRotation: { value: new Matrix3() },
envMapInfo: { value: new EquirectHdrInfoUniform() },
seed: { value: 0 },
opacity: { value: 1 },
filterGlossyFactor: { value: 0.0 },
bgGradientTop: { value: new Color( 0x111111 ) },
bgGradientBottom: { value: new Color( 0x000000 ) },
backgroundAlpha: { value: 1.0 },
},
vertexShader: /* glsl */`
varying vec2 vUv;
void main() {
vec4 mvPosition = vec4( position, 1.0 );
mvPosition = modelViewMatrix * mvPosition;
gl_Position = projectionMatrix * mvPosition;
vUv = uv;
}
`,
fragmentShader: /* glsl */`
#define RAY_OFFSET 1e-4
precision highp isampler2D;
precision highp usampler2D;
precision highp sampler2DArray;
vec4 envMapTexelToLinear( vec4 a ) { return a; }
#include <common>
${ shaderStructs }
${ shaderIntersectFunction }
${ shaderMaterialStructs }
${ shaderLightStruct }
${ shaderUtils }
${ shaderMaterialSampling }
${ shaderEnvMapSampling }
${ shaderLightSampling }
uniform mat3 environmentRotation;
uniform float backgroundBlur;
uniform float backgroundAlpha;
#if FEATURE_GRADIENT_BG
uniform vec3 bgGradientTop;
uniform vec3 bgGradientBottom;
#endif
#if FEATURE_DOF
uniform PhysicalCamera physicalCamera;
#endif
uniform vec2 resolution;
uniform int bounces;
uniform mat4 cameraWorldMatrix;
uniform mat4 invProjectionMatrix;
uniform sampler2D normalAttribute;
uniform sampler2D tangentAttribute;
uniform sampler2D uvAttribute;
uniform usampler2D materialIndexAttribute;
uniform BVH bvh;
uniform float environmentIntensity;
uniform float filterGlossyFactor;
uniform int seed;
uniform float opacity;
uniform sampler2D materials;
uniform sampler2D lights;
uniform uint lightCount;
uniform EquirectHdrInfo envMapInfo;
uniform sampler2DArray textures;
varying vec2 vUv;
vec3 sampleBackground( vec3 direction ) {
#if FEATURE_GRADIENT_BG
direction = normalize( direction + randDirection() * 0.05 );
float value = ( direction.y + 1.0 ) / 2.0;
value = pow( value, 2.0 );
return mix( bgGradientBottom, bgGradientTop, value );
#else
vec3 sampleDir = normalize( direction + getHemisphereSample( direction, rand2() ) * 0.5 * backgroundBlur );
return environmentIntensity * sampleEquirectEnvMapColor( sampleDir, envMapInfo.map );
#endif
}
// step through multiple surface hits and accumulate color attenuation based on transmissive surfaces
bool attenuateHit( BVH bvh, vec3 rayOrigin, vec3 rayDirection, int traversals, bool isShadowRay, out vec3 color ) {
// hit results
uvec4 faceIndices = uvec4( 0u );
vec3 faceNormal = vec3( 0.0, 0.0, 1.0 );
vec3 barycoord = vec3( 0.0 );
float side = 1.0;
float dist = 0.0;
color = vec3( 1.0 );
for ( int i = 0; i < traversals; i ++ ) {
if ( bvhIntersectFirstHit( bvh, rayOrigin, rayDirection, faceIndices, faceNormal, barycoord, side, dist ) ) {
// TODO: attenuate the contribution based on the PDF of the resulting ray including refraction values
// Should be able to work using the material BSDF functions which will take into account specularity, etc.
// TODO: should we account for emissive surfaces here?
vec2 uv = textureSampleBarycoord( uvAttribute, barycoord, faceIndices.xyz ).xy;
uint materialIndex = uTexelFetch1D( materialIndexAttribute, faceIndices.x ).r;
Material material = readMaterialInfo( materials, materialIndex );
// adjust the ray to the new surface
bool isBelowSurface = dot( rayDirection, faceNormal ) < 0.0;
vec3 point = rayOrigin + rayDirection * dist;
vec3 absPoint = abs( point );
float maxPoint = max( absPoint.x, max( absPoint.y, absPoint.z ) );
rayOrigin = point + faceNormal * ( maxPoint + 1.0 ) * ( isBelowSurface ? - RAY_OFFSET : RAY_OFFSET );
if ( ! material.castShadow && isShadowRay ) {
continue;
}
// Opacity Test
// albedo
vec4 albedo = vec4( material.color, material.opacity );
if ( material.map != - 1 ) {
vec3 uvPrime = material.mapTransform * vec3( uv, 1 );
albedo *= texture2D( textures, vec3( uvPrime.xy, material.map ) );
}
// alphaMap
if ( material.alphaMap != -1 ) {
albedo.a *= texture2D( textures, vec3( uv, material.alphaMap ) ).x;
}
// transmission
float transmission = material.transmission;
if ( material.transmissionMap != - 1 ) {
vec3 uvPrime = material.transmissionMapTransform * vec3( uv, 1 );
transmission *= texture2D( textures, vec3( uvPrime.xy, material.transmissionMap ) ).r;
}
// metalness
float metalness = material.metalness;
if ( material.metalnessMap != - 1 ) {
vec3 uvPrime = material.metalnessMapTransform * vec3( uv, 1 );
metalness *= texture2D( textures, vec3( uvPrime.xy, material.metalnessMap ) ).b;
}
float alphaTest = material.alphaTest;
bool useAlphaTest = alphaTest != 0.0;
float transmissionFactor = ( 1.0 - metalness ) * transmission;
if (
transmissionFactor < rand() && ! (
// material sidedness
material.side != 0.0 && side == material.side
// alpha test
|| useAlphaTest && albedo.a < alphaTest
// opacity
|| ! useAlphaTest && albedo.a < rand()
)
) {
return true;
}
// only attenuate on the way in
if ( isBelowSurface ) {
color *= mix( vec3( 1.0 ), albedo.rgb, transmissionFactor );
}
} else {
return false;
}
}
return true;
}
// returns whether the ray hit anything before a certain distance, not just the first surface. Could be optimized to not check the full hierarchy.
bool anyCloserHit( BVH bvh, vec3 rayOrigin, vec3 rayDirection, float maxDist ) {
uvec4 faceIndices = uvec4( 0u );
vec3 faceNormal = vec3( 0.0, 0.0, 1.0 );
vec3 barycoord = vec3( 0.0 );
float side = 1.0;
float dist = 0.0;
bool hit = bvhIntersectFirstHit( bvh, rayOrigin, rayDirection, faceIndices, faceNormal, barycoord, side, dist );
return hit && dist < maxDist;
}
// tentFilter from Peter Shirley's 'Realistic Ray Tracing (2nd Edition)' book, pg. 60
// erichlof/THREE.js-PathTracing-Renderer/
float tentFilter( float x ) {
return x < 0.5 ? sqrt( 2.0 * x ) - 1.0 : 1.0 - sqrt( 2.0 - ( 2.0 * x ) );
}
vec3 ndcToRayOrigin( vec2 coord ) {
vec4 rayOrigin4 = cameraWorldMatrix * invProjectionMatrix * vec4( coord, - 1.0, 1.0 );
return rayOrigin4.xyz / rayOrigin4.w;
}
void getCameraRay( out vec3 rayDirection, out vec3 rayOrigin ) {
vec2 ssd = vec2( 1.0 ) / resolution;
// Jitter the camera ray by finding a uv coordinate at a random sample
// around this pixel's UV coordinate
vec2 jitteredUv = vUv + vec2( tentFilter( rand() ) * ssd.x, tentFilter( rand() ) * ssd.y );
#if CAMERA_TYPE == 2
// Equirectangular projection
vec4 rayDirection4 = vec4( equirectUvToDirection( jitteredUv ), 0.0 );
vec4 rayOrigin4 = vec4( 0.0, 0.0, 0.0, 1.0 );
rayDirection4 = cameraWorldMatrix * rayDirection4;
rayOrigin4 = cameraWorldMatrix * rayOrigin4;
rayDirection = normalize( rayDirection4.xyz );
rayOrigin = rayOrigin4.xyz / rayOrigin4.w;
#else
// get [-1, 1] normalized device coordinates
vec2 ndc = 2.0 * jitteredUv - vec2( 1.0 );
rayOrigin = ndcToRayOrigin( ndc );
#if CAMERA_TYPE == 1
// Orthographic projection
rayDirection = ( cameraWorldMatrix * vec4( 0.0, 0.0, -1.0, 0.0 ) ).xyz;
rayDirection = normalize( rayDirection );
#else
// Perspective projection
vec3 cameraOrigin = ( cameraWorldMatrix * vec4( 0.0, 0.0, 0.0, 1.0 ) ).xyz;
rayDirection = normalize( rayOrigin - cameraOrigin );
#endif
#endif
#if FEATURE_DOF
{
// depth of field
vec3 focalPoint = rayOrigin + normalize( rayDirection ) * physicalCamera.focusDistance;
// get the aperture sample
vec2 apertureSample = sampleAperture( physicalCamera.apertureBlades ) * physicalCamera.bokehSize * 0.5 * 1e-3;
// rotate the aperture shape
float ac = cos( physicalCamera.apertureRotation );
float as = sin( physicalCamera.apertureRotation );
apertureSample = vec2(
apertureSample.x * ac - apertureSample.y * as,
apertureSample.x * as + apertureSample.y * ac
);
apertureSample.x *= saturate( physicalCamera.anamorphicRatio );
apertureSample.y *= saturate( 1.0 / physicalCamera.anamorphicRatio );
// create the new ray
rayOrigin += ( cameraWorldMatrix * vec4( apertureSample, 0.0, 0.0 ) ).xyz;
rayDirection = focalPoint - rayOrigin;
}
#endif
rayDirection = normalize( rayDirection );
}
void main() {
rng_initialize( gl_FragCoord.xy, seed );
vec3 rayDirection;
vec3 rayOrigin;
getCameraRay( rayDirection, rayOrigin );
// inverse environment rotation
mat3 invEnvironmentRotation = inverse( environmentRotation );
// final color
gl_FragColor = vec4( 0.0 );
gl_FragColor.a = 1.0;
// hit results
uvec4 faceIndices = uvec4( 0u );
vec3 faceNormal = vec3( 0.0, 0.0, 1.0 );
vec3 barycoord = vec3( 0.0 );
float side = 1.0;
float dist = 0.0;
// path tracing state
float accumulatedRoughness = 0.0;
bool transmissiveRay = true;
int transparentTraversals = TRANSPARENT_TRAVERSALS;
vec3 throughputColor = vec3( 1.0 );
SampleRec sampleRec;
int i;
bool isShadowRay = false;
for ( i = 0; i < bounces; i ++ ) {
bool hit = bvhIntersectFirstHit( bvh, rayOrigin, rayDirection, faceIndices, faceNormal, barycoord, side, dist );
LightSampleRec lightHit = lightsClosestHit( lights, lightCount, rayOrigin, rayDirection );
if ( lightHit.hit && ( lightHit.dist < dist || !hit ) ) {
if ( i == 0 || transmissiveRay ) {
gl_FragColor.rgb += lightHit.emission * throughputColor;
} else {
#if FEATURE_MIS
// weight the contribution
float misWeight = misHeuristic( sampleRec.pdf, lightHit.pdf / float( lightCount + 1u ) );
gl_FragColor.rgb += lightHit.emission * throughputColor * misWeight;
#else
gl_FragColor.rgb +=
lightHit.emission *
throughputColor;
#endif
}
break;
}
if ( ! hit ) {
if ( i == 0 || transmissiveRay ) {
gl_FragColor.rgb += sampleBackground( environmentRotation * rayDirection ) * throughputColor;
gl_FragColor.a = backgroundAlpha;
} else {
#if FEATURE_MIS
// get the PDF of the hit envmap point
vec3 envColor;
float envPdf = envMapSample( environmentRotation * rayDirection, envMapInfo, envColor );
envPdf /= float( lightCount + 1u );
// and weight the contribution
float misWeight = misHeuristic( sampleRec.pdf, envPdf );
gl_FragColor.rgb += environmentIntensity * envColor * throughputColor * misWeight;
#else
gl_FragColor.rgb +=
environmentIntensity *
sampleEquirectEnvMapColor( environmentRotation * rayDirection, envMapInfo.map ) *
throughputColor;
#endif
}
break;
}
uint materialIndex = uTexelFetch1D( materialIndexAttribute, faceIndices.x ).r;
Material material = readMaterialInfo( materials, materialIndex );
if ( material.matte && i == 0 ) {
gl_FragColor = vec4( 0.0 );
break;
}
// if we've determined that this is a shadow ray and we've hit an item with no shadow casting
// then skip it
if ( ! material.castShadow && isShadowRay ) {
vec3 point = rayOrigin + rayDirection * dist;
vec3 absPoint = abs( point );
float maxPoint = max( absPoint.x, max( absPoint.y, absPoint.z ) );
rayOrigin = point - ( maxPoint + 1.0 ) * faceNormal * RAY_OFFSET;
continue;
}
vec2 uv = textureSampleBarycoord( uvAttribute, barycoord, faceIndices.xyz ).xy;
// albedo
vec4 albedo = vec4( material.color, material.opacity );
if ( material.map != - 1 ) {
vec3 uvPrime = material.mapTransform * vec3( uv, 1 );
albedo *= texture2D( textures, vec3( uvPrime.xy, material.map ) );
}
// alphaMap
if ( material.alphaMap != -1 ) {
albedo.a *= texture2D( textures, vec3( uv, material.alphaMap ) ).x;
}
// possibly skip this sample if it's transparent, alpha test is enabled, or we hit the wrong material side
// and it's single sided.
// - alpha test is disabled when it === 0
// - the material sidedness test is complicated because we want light to pass through the back side but still
// be able to see the front side. This boolean checks if the side we hit is the front side on the first ray
// and we're rendering the other then we skip it. Do the opposite on subsequent bounces to get incoming light.
float alphaTest = material.alphaTest;
bool useAlphaTest = alphaTest != 0.0;
bool isFirstHit = i == 0;
if (
// material sidedness
material.side != 0.0 && ( side != material.side ) == isFirstHit
// alpha test
|| useAlphaTest && albedo.a < alphaTest
// opacity
|| ! useAlphaTest && albedo.a < rand()
) {
vec3 point = rayOrigin + rayDirection * dist;
vec3 absPoint = abs( point );
float maxPoint = max( absPoint.x, max( absPoint.y, absPoint.z ) );
rayOrigin = point - ( maxPoint + 1.0 ) * faceNormal * RAY_OFFSET;
// only allow a limited number of transparency discards otherwise we could
// crash the context with too long a loop.
i -= sign( transparentTraversals );
transparentTraversals -= sign( transparentTraversals );
continue;
}
// fetch the interpolated smooth normal
vec3 normal = normalize( textureSampleBarycoord(
normalAttribute,
barycoord,
faceIndices.xyz
).xyz );
// roughness
float roughness = material.roughness;
if ( material.roughnessMap != - 1 ) {
vec3 uvPrime = material.roughnessMapTransform * vec3( uv, 1 );
roughness *= texture2D( textures, vec3( uvPrime.xy, material.roughnessMap ) ).g;
}
// metalness
float metalness = material.metalness;
if ( material.metalnessMap != - 1 ) {
vec3 uvPrime = material.metalnessMapTransform * vec3( uv, 1 );
metalness *= texture2D( textures, vec3( uvPrime.xy, material.metalnessMap ) ).b;
}
// emission
vec3 emission = material.emissiveIntensity * material.emissive;
if ( material.emissiveMap != - 1 ) {
vec3 uvPrime = material.emissiveMapTransform * vec3( uv, 1 );
emission *= texture2D( textures, vec3( uvPrime.xy, material.emissiveMap ) ).xyz;
}
// transmission
float transmission = material.transmission;
if ( material.transmissionMap != - 1 ) {
vec3 uvPrime = material.transmissionMapTransform * vec3( uv, 1 );
transmission *= texture2D( textures, vec3( uvPrime.xy, material.transmissionMap ) ).r;
}
// normal
if ( material.normalMap != - 1 ) {
vec4 tangentSample = textureSampleBarycoord(
tangentAttribute,
barycoord,
faceIndices.xyz
);
// some provided tangents can be malformed (0, 0, 0) causing the normal to be degenerate
// resulting in NaNs and slow path tracing.
if ( length( tangentSample.xyz ) > 0.0 ) {
vec3 tangent = normalize( tangentSample.xyz );
vec3 bitangent = normalize( cross( normal, tangent ) * tangentSample.w );
mat3 vTBN = mat3( tangent, bitangent, normal );
vec3 uvPrime = material.normalMapTransform * vec3( uv, 1 );
vec3 texNormal = texture2D( textures, vec3( uvPrime.xy, material.normalMap ) ).xyz * 2.0 - 1.0;
texNormal.xy *= material.normalScale;
normal = vTBN * texNormal;
}
}
normal *= side;
SurfaceRec surfaceRec;
surfaceRec.normal = normal;
surfaceRec.faceNormal = faceNormal;
surfaceRec.transmission = transmission;
surfaceRec.ior = material.ior;
surfaceRec.emission = emission;
surfaceRec.metalness = metalness;
surfaceRec.color = albedo.rgb;
surfaceRec.roughness = roughness;
// frontFace is used to determine transmissive properties and PDF. If no transmission is used
// then we can just always assume this is a front face.
surfaceRec.frontFace = side == 1.0 || transmission == 0.0;
// Compute the filtered roughness value to use during specular reflection computations.
// The accumulated roughness value is scaled by a user setting and a "magic value" of 5.0.
// If we're exiting something transmissive then scale the factor down significantly so we can retain
// sharp internal reflections
surfaceRec.filteredRoughness = clamp( max( surfaceRec.roughness, accumulatedRoughness * filterGlossyFactor * 5.0 ), 0.0, 1.0 );
mat3 normalBasis = getBasisFromNormal( surfaceRec.normal );
mat3 invBasis = inverse( normalBasis );
vec3 outgoing = - normalize( invBasis * rayDirection );
sampleRec = bsdfSample( outgoing, surfaceRec );
isShadowRay = sampleRec.specularPdf < rand();
// adjust the hit point by the surface normal by a factor of some offset and the
// maximum component-wise value of the current point to accommodate floating point
// error as values increase.
vec3 point = rayOrigin + rayDirection * dist;
vec3 absPoint = abs( point );
float maxPoint = max( absPoint.x, max( absPoint.y, absPoint.z ) );
rayDirection = normalize( normalBasis * sampleRec.direction );
bool isBelowSurface = dot( rayDirection, faceNormal ) < 0.0;
rayOrigin = point + faceNormal * ( maxPoint + 1.0 ) * ( isBelowSurface ? - RAY_OFFSET : RAY_OFFSET );
// direct env map sampling
#if FEATURE_MIS
// uniformly pick a light or environment map
if( rand() > 1.0 / float( lightCount + 1u ) ) {
// sample a light or environment
LightSampleRec lightSampleRec = randomLightSample( lights, lightCount, rayOrigin );
bool isSampleBelowSurface = dot( faceNormal, lightSampleRec.direction ) < 0.0;
if ( isSampleBelowSurface ) {
lightSampleRec.pdf = 0.0;
}
// check if a ray could even reach the light area
if (
lightSampleRec.pdf > 0.0 &&
isDirectionValid( lightSampleRec.direction, normal, faceNormal ) &&
! anyCloserHit( bvh, rayOrigin, lightSampleRec.direction, lightSampleRec.dist )
) {
// get the material pdf
vec3 sampleColor;
float lightMaterialPdf = bsdfResult( outgoing, normalize( invBasis * lightSampleRec.direction ), surfaceRec, sampleColor );
bool isValidSampleColor = all( greaterThanEqual( sampleColor, vec3( 0.0 ) ) );
if ( lightMaterialPdf > 0.0 && isValidSampleColor ) {
// weight the direct light contribution
float lightPdf = lightSampleRec.pdf / float( lightCount + 1u );
float misWeight = misHeuristic( lightPdf, lightMaterialPdf );
gl_FragColor.rgb += lightSampleRec.emission * throughputColor * sampleColor * misWeight / lightPdf;
}
}
} else {
// find a sample in the environment map to include in the contribution
vec3 envColor, envDirection;
float envPdf = randomEnvMapSample( envMapInfo, envColor, envDirection );
envDirection = invEnvironmentRotation * envDirection;
// this env sampling is not set up for transmissive sampling and yields overly bright
// results so we ignore the sample in this case.
// TODO: this should be improved but how? The env samples could traverse a few layers?
bool isSampleBelowSurface = dot( faceNormal, envDirection ) < 0.0;
if ( isSampleBelowSurface ) {
envPdf = 0.0;
}
// check if a ray could even reach the surface
vec3 attenuatedColor;
if (
envPdf > 0.0 &&
isDirectionValid( envDirection, normal, faceNormal ) &&
! attenuateHit( bvh, rayOrigin, envDirection, bounces - i, isShadowRay, attenuatedColor )
) {
// get the material pdf
vec3 sampleColor;
float envMaterialPdf = bsdfResult( outgoing, normalize( invBasis * envDirection ), surfaceRec, sampleColor );
bool isValidSampleColor = all( greaterThanEqual( sampleColor, vec3( 0.0 ) ) );
if ( envMaterialPdf > 0.0 && isValidSampleColor ) {
// weight the direct light contribution
envPdf /= float( lightCount + 1u );
float misWeight = misHeuristic( envPdf, envMaterialPdf );
gl_FragColor.rgb += attenuatedColor * environmentIntensity * envColor * throughputColor * sampleColor * misWeight / envPdf;
}
}
}
#endif
// accumulate a roughness value to offset diffuse, specular, diffuse rays that have high contribution
// to a single pixel resulting in fireflies
if ( ! isBelowSurface ) {
// determine if this is a rough normal or not by checking how far off straight up it is
vec3 halfVector = normalize( outgoing + sampleRec.direction );
accumulatedRoughness += sin( acosApprox( halfVector.z ) );
transmissiveRay = false;
}
// accumulate color
gl_FragColor.rgb += ( emission * throughputColor );
// skip the sample if our PDF or ray is impossible
if ( sampleRec.pdf <= 0.0 || ! isDirectionValid( rayDirection, normal, faceNormal) ) {
break;
}
throughputColor *= sampleRec.color / sampleRec.pdf;
// discard the sample if there are any NaNs
if ( any( isnan( throughputColor ) ) || any( isinf( throughputColor ) ) ) {
break;
}
}
gl_FragColor.a *= opacity;
}
`
} );
this.setValues( parameters );
}
}