forked from NVIDIA-RTX/RTXDI
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathResamplingFunctions.hlsli
2208 lines (1792 loc) · 86.5 KB
/
ResamplingFunctions.hlsli
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
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/***************************************************************************
# Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
**************************************************************************/
#ifndef RESAMPLING_FUNCTIONS_HLSLI
#define RESAMPLING_FUNCTIONS_HLSLI
#include "Reservoir.hlsli"
// This macro can be defined in the including shader file to reduce code bloat
// and/or remove ray tracing calls from temporal and spatial resampling shaders
// if bias correction is not necessary.
#ifndef RTXDI_ALLOWED_BIAS_CORRECTION
#define RTXDI_ALLOWED_BIAS_CORRECTION RTXDI_BIAS_CORRECTION_RAY_TRACED
#endif
// This macro enables the functions that deal with the RIS buffer and presampling.
#ifndef RTXDI_ENABLE_PRESAMPLING
#define RTXDI_ENABLE_PRESAMPLING 1
#endif
#if !RTXDI_ENABLE_PRESAMPLING && (RTXDI_REGIR_MODE != RTXDI_REGIR_DISABLED)
#error "ReGIR requires presampling to be enabled"
#endif
#if RTXDI_ENABLE_PRESAMPLING && !defined(RTXDI_RIS_BUFFER)
#error "RTXDI_RIS_BUFFER must be defined to point to a RWBuffer<uint2> type resource"
#endif
#ifndef RTXDI_NEIGHBOR_OFFSETS_BUFFER
#error "RTXDI_NEIGHBOR_OFFSETS_BUFFER must be defined to point to a Buffer<float2> type resource"
#endif
#define RTXDI_NAIVE_SAMPLING_M_THRESHOLD 2
struct RTXDI_SampleParameters
{
uint numRegirSamples;
uint numLocalLightSamples;
uint numInfiniteLightSamples;
uint numEnvironmentMapSamples;
uint numBrdfSamples;
uint numMisSamples;
float localLightMisWeight;
float environmentMapMisWeight;
float brdfMisWeight;
float brdfCutoff;
float brdfRayMinT;
};
// Sample parameters struct
// Defined so that so these can be compile time constants as defined by the user
// brdfCutoff Value in range [0,1] to determine how much to shorten BRDF rays. 0 to disable shortening
RTXDI_SampleParameters RTXDI_InitSampleParameters(
uint numRegirSamples,
uint numLocalLightSamples,
uint numInfiniteLightSamples,
uint numEnvironmentMapSamples,
uint numBrdfSamples,
float brdfCutoff RTXDI_DEFAULT(0.0),
float brdfRayMinT RTXDI_DEFAULT(0.001f))
{
RTXDI_SampleParameters result;
result.numRegirSamples = numRegirSamples;
result.numLocalLightSamples = numLocalLightSamples;
result.numInfiniteLightSamples = numInfiniteLightSamples;
result.numEnvironmentMapSamples = numEnvironmentMapSamples;
result.numBrdfSamples = numBrdfSamples;
result.numMisSamples = numLocalLightSamples + numEnvironmentMapSamples + numBrdfSamples;
result.localLightMisWeight = float(numLocalLightSamples) / result.numMisSamples;
result.environmentMapMisWeight = float(numEnvironmentMapSamples) / result.numMisSamples;
result.brdfMisWeight = float(numBrdfSamples) / result.numMisSamples;
result.brdfCutoff = brdfCutoff;
result.brdfRayMinT = brdfRayMinT;
return result;
}
// Heuristic to determine a max visibility ray length from a PDF wrt. solid angle.
float RTXDI_BrdfMaxDistanceFromPdf(float brdfCutoff, float pdf)
{
const float kRayTMax = 3.402823466e+38F; // FLT_MAX
return brdfCutoff > 0.f ? sqrt((1.f / brdfCutoff - 1.f) * pdf) : kRayTMax;
}
// Computes the multi importance sampling pdf for brdf and light sample.
// For light and BRDF PDFs wrt solid angle, blend between the two.
// lightSelectionPdf is a dimensionless selection pdf
float RTXDI_LightBrdfMisWeight(RAB_Surface surface, RAB_LightSample lightSample,
float lightSelectionPdf, float lightMisWeight, bool isEnvironmentMap,
RTXDI_SampleParameters sampleParams)
{
float lightSolidAnglePdf = RAB_LightSampleSolidAnglePdf(lightSample);
if (sampleParams.brdfMisWeight == 0 || RAB_IsAnalyticLightSample(lightSample) ||
lightSolidAnglePdf <= 0 || isinf(lightSolidAnglePdf) || isnan(lightSolidAnglePdf))
{
// BRDF samples disabled or we can't trace BRDF rays MIS with analytical lights
return lightMisWeight * lightSelectionPdf;
}
float3 lightDir;
float lightDistance;
RAB_GetLightDirDistance(surface, lightSample, lightDir, lightDistance);
// Compensate for ray shortening due to brdf cutoff, does not apply to environment map sampling
float brdfPdf = RAB_GetSurfaceBrdfPdf(surface, lightDir);
float maxDistance = RTXDI_BrdfMaxDistanceFromPdf(sampleParams.brdfCutoff, brdfPdf);
if (!isEnvironmentMap && lightDistance > maxDistance)
brdfPdf = 0.f;
// Convert light selection pdf (unitless) to a solid angle measurement
float sourcePdfWrtSolidAngle = lightSelectionPdf * lightSolidAnglePdf;
// MIS blending against solid angle pdfs.
float blendedPdfWrtSolidangle = lightMisWeight * sourcePdfWrtSolidAngle + sampleParams.brdfMisWeight * brdfPdf;
// Convert back, RTXDI divides shading again by this term later
return blendedPdfWrtSolidangle / lightSolidAnglePdf;
}
// Adds a new, non-reservoir light sample into the reservoir, returns true if this sample was selected.
// Algorithm (3) from the ReSTIR paper, Streaming RIS using weighted reservoir sampling.
bool RTXDI_StreamSample(
inout RTXDI_Reservoir reservoir,
uint lightIndex,
float2 uv,
float random,
float targetPdf,
float invSourcePdf)
{
// What's the current weight
float risWeight = targetPdf * invSourcePdf;
// Add one sample to the counter
reservoir.M += 1;
// Update the weight sum
reservoir.weightSum += risWeight;
// Decide if we will randomly pick this sample
bool selectSample = (random * reservoir.weightSum < risWeight);
// If we did select this sample, update the relevant data.
// New samples don't have visibility or age information, we can skip that.
if (selectSample)
{
reservoir.lightData = lightIndex | RTXDI_Reservoir_LightValidBit;
reservoir.uvData = uint(saturate(uv.x) * 0xffff) | (uint(saturate(uv.y) * 0xffff) << 16);
reservoir.targetPdf = targetPdf;
}
return selectSample;
}
// Adds `newReservoir` into `reservoir`, returns true if the new reservoir's sample was selected.
// This is a very general form, allowing input parameters to specfiy normalization and targetPdf
// rather than computing them from `newReservoir`. Named "internal" since these parameters take
// different meanings (e.g., in RTXDI_CombineReservoirs() or RTXDI_StreamNeighborWithPairwiseMIS())
bool RTXDI_InternalSimpleResample(
inout RTXDI_Reservoir reservoir,
const RTXDI_Reservoir newReservoir,
float random,
float targetPdf RTXDI_DEFAULT(1.0f), // Usually closely related to the sample normalization,
float sampleNormalization RTXDI_DEFAULT(1.0f), // typically off by some multiplicative factor
float sampleM RTXDI_DEFAULT(1.0f) // In its most basic form, should be newReservoir.M
)
{
// What's the current weight (times any prior-step RIS normalization factor)
float risWeight = targetPdf * sampleNormalization;
// Our *effective* candidate pool is the sum of our candidates plus those of our neighbors
reservoir.M += sampleM;
// Update the weight sum
reservoir.weightSum += risWeight;
// Decide if we will randomly pick this sample
bool selectSample = (random * reservoir.weightSum < risWeight);
// If we did select this sample, update the relevant data
if (selectSample)
{
reservoir.lightData = newReservoir.lightData;
reservoir.uvData = newReservoir.uvData;
reservoir.targetPdf = targetPdf;
reservoir.packedVisibility = newReservoir.packedVisibility;
reservoir.spatialDistance = newReservoir.spatialDistance;
reservoir.age = newReservoir.age;
}
return selectSample;
}
// Adds `newReservoir` into `reservoir`, returns true if the new reservoir's sample was selected.
// Algorithm (4) from the ReSTIR paper, Combining the streams of multiple reservoirs.
// Normalization - Equation (6) - is postponed until all reservoirs are combined.
bool RTXDI_CombineReservoirs(
inout RTXDI_Reservoir reservoir,
const RTXDI_Reservoir newReservoir,
float random,
float targetPdf)
{
return RTXDI_InternalSimpleResample(
reservoir,
newReservoir,
random,
targetPdf,
newReservoir.weightSum * newReservoir.M,
newReservoir.M
);
}
// Performs normalization of the reservoir after streaming. Equation (6) from the ReSTIR paper.
void RTXDI_FinalizeResampling(
inout RTXDI_Reservoir reservoir,
float normalizationNumerator,
float normalizationDenominator)
{
float denominator = reservoir.targetPdf * normalizationDenominator;
reservoir.weightSum = (denominator == 0.0) ? 0.0 : (reservoir.weightSum * normalizationNumerator) / denominator;
}
// A helper used for pairwise MIS computations. This might be able to simplify code elsewhere, too.
float RTXDI_TargetPdfHelper(const RTXDI_Reservoir lightReservoir, const RAB_Surface surface, bool priorFrame RTXDI_DEFAULT(false))
{
RAB_LightSample lightSample = RAB_SamplePolymorphicLight(
RAB_LoadLightInfo(RTXDI_GetReservoirLightIndex(lightReservoir), priorFrame),
surface, RTXDI_GetReservoirSampleUV(lightReservoir));
return RAB_GetLightSampleTargetPdfForSurface(lightSample, surface);
}
// "Pairwise MIS" is a MIS approach that is O(N) instead of O(N^2) for N estimators. The idea is you know
// a canonical sample which is a known (pretty-)good estimator, but you'd still like to improve the result
// given multiple other candidate estimators. You can do this in a pairwise fashion, MIS'ing between each
// candidate and the canonical sample. RTXDI_StreamNeighborWithPairwiseMIS() is executed once for each
// candidate, after which the MIS is completed by calling RTXDI_StreamCanonicalWithPairwiseStep() once for
// the canonical sample.
// See Chapter 9.1 of https://digitalcommons.dartmouth.edu/dissertations/77/, especially Eq 9.10 & Algo 8
bool RTXDI_StreamNeighborWithPairwiseMIS(inout RTXDI_Reservoir reservoir,
float random,
const RTXDI_Reservoir neighborReservoir,
const RAB_Surface neighborSurface,
const RTXDI_Reservoir canonicalReservor,
const RAB_Surface canonicalSurface,
const uint numberOfNeighborsInStream) // # neighbors streamed via pairwise MIS before streaming the canonical sample
{
// Compute PDFs of the neighbor and cannonical light samples and surfaces in all permutations.
// Note: First two must be computed this way. Last two *should* be replacable by neighborReservoir.targetPdf
// and canonicalReservor.targetPdf to reduce redundant computations, but there's a bug in that naive reuse.
float neighborWeightAtCanonical = max(0.0f, RTXDI_TargetPdfHelper(neighborReservoir, canonicalSurface, false));
float canonicalWeightAtNeighbor = max(0.0f, RTXDI_TargetPdfHelper(canonicalReservor, neighborSurface, false));
float neighborWeightAtNeighbor = max(0.0f, RTXDI_TargetPdfHelper(neighborReservoir, neighborSurface, false));
float canonicalWeightAtCanonical = max(0.0f, RTXDI_TargetPdfHelper(canonicalReservor, canonicalSurface, false));
// Compute two pairwise MIS weights
float w0 = RTXDI_PairwiseMisWeight(neighborWeightAtNeighbor, neighborWeightAtCanonical,
neighborReservoir.M * numberOfNeighborsInStream, canonicalReservor.M);
float w1 = RTXDI_PairwiseMisWeight(canonicalWeightAtNeighbor, canonicalWeightAtCanonical,
neighborReservoir.M * numberOfNeighborsInStream, canonicalReservor.M);
// Determine the effective M value when using pairwise MIS
float M = neighborReservoir.M * min(
RTXDI_MFactor(neighborWeightAtNeighbor, neighborWeightAtCanonical),
RTXDI_MFactor(canonicalWeightAtNeighbor, canonicalWeightAtCanonical));
// With pairwise MIS, we touch the canonical sample multiple times (but every other sample only once). This
// with overweight the canonical sample; we track how much it is overweighted so we can renormalize to account
// for this in the function RTXDI_StreamCanonicalWithPairwiseStep()
reservoir.canonicalWeight += (1.0f - w1);
// Go ahead and stream the neighbor sample through via RIS, appropriately weighted
return RTXDI_InternalSimpleResample(reservoir, neighborReservoir, random,
neighborWeightAtCanonical,
neighborReservoir.weightSum * w0,
M);
}
// Called to finish the process of doing pairwise MIS. This function must be called after all required calls to
// RTXDI_StreamNeighborWithPairwiseMIS(), since pairwise MIS overweighs the canonical sample. This function
// compensates for this overweighting, but it can only happen after all neighbors have been processed.
bool RTXDI_StreamCanonicalWithPairwiseStep(inout RTXDI_Reservoir reservoir,
float random,
const RTXDI_Reservoir canonicalReservoir,
const RAB_Surface canonicalSurface)
{
return RTXDI_InternalSimpleResample(reservoir, canonicalReservoir, random,
canonicalReservoir.targetPdf,
canonicalReservoir.weightSum * reservoir.canonicalWeight,
canonicalReservoir.M);
}
void RTXDI_SamplePdfMipmap(
inout RAB_RandomSamplerState rng,
RTXDI_TEX2D pdfTexture, // full mip chain starting from unnormalized sampling pdf in mip 0
uint2 pdfTextureSize, // dimensions of pdfTexture at mip 0; must be 16k or less
out uint2 position,
out float pdf)
{
int lastMipLevel = max(0, int(floor(log2(max(pdfTextureSize.x, pdfTextureSize.y)))) - 1);
position = uint2(0, 0);
pdf = 1.0;
for (int mipLevel = lastMipLevel; mipLevel >= 0; mipLevel--)
{
position *= 2;
float4 samples;
samples.x = max(0, RTXDI_TEX2D_LOAD(pdfTexture, int2(position.x + 0, position.y + 0), mipLevel).x);
samples.y = max(0, RTXDI_TEX2D_LOAD(pdfTexture, int2(position.x + 0, position.y + 1), mipLevel).x);
samples.z = max(0, RTXDI_TEX2D_LOAD(pdfTexture, int2(position.x + 1, position.y + 0), mipLevel).x);
samples.w = max(0, RTXDI_TEX2D_LOAD(pdfTexture, int2(position.x + 1, position.y + 1), mipLevel).x);
float weightSum = samples.x + samples.y + samples.z + samples.w;
if (weightSum <= 0)
{
pdf = 0;
return;
}
samples /= weightSum;
float rnd = RAB_GetNextRandom(rng);
int2 selectedOffset;
if (rnd < samples.x)
{
pdf *= samples.x;
}
else
{
rnd -= samples.x;
if (rnd < samples.y)
{
position += uint2(0, 1);
pdf *= samples.y;
}
else
{
rnd -= samples.y;
if (rnd < samples.z)
{
position += uint2(1, 0);
pdf *= samples.z;
}
else
{
position += uint2(1, 1);
pdf *= samples.w;
}
}
}
}
}
#if RTXDI_ENABLE_PRESAMPLING
void RTXDI_PresampleLocalLights(
inout RAB_RandomSamplerState rng,
RTXDI_TEX2D pdfTexture,
uint2 pdfTextureSize,
uint tileIndex,
uint sampleInTile,
RTXDI_ResamplingRuntimeParameters params)
{
uint2 texelPosition;
float pdf;
RTXDI_SamplePdfMipmap(rng, pdfTexture, pdfTextureSize, texelPosition, pdf);
uint lightIndex = RTXDI_ZCurveToLinearIndex(texelPosition);
uint risBufferPtr = sampleInTile + tileIndex * params.risBufferParams.tileSize;
bool compact = false;
float invSourcePdf = 0;
if (pdf > 0)
{
invSourcePdf = 1.0 / pdf;
RAB_LightInfo lightInfo = RAB_LoadLightInfo(lightIndex + params.localLightParams.firstLocalLight, false);
compact = RAB_StoreCompactLightInfo(risBufferPtr, lightInfo);
}
lightIndex += params.localLightParams.firstLocalLight;
if(compact) {
lightIndex |= RTXDI_LIGHT_COMPACT_BIT;
}
// Store the index of the light that we found and its inverse pdf.
// Or zero and zero if we somehow found nothing.
RTXDI_RIS_BUFFER[risBufferPtr] = uint2(lightIndex, asuint(invSourcePdf));
}
void RTXDI_PresampleEnvironmentMap(
inout RAB_RandomSamplerState rng,
RTXDI_TEX2D pdfTexture,
uint2 pdfTextureSize,
uint tileIndex,
uint sampleInTile,
RTXDI_EnvironmentLightRuntimeParameters params)
{
uint2 texelPosition;
float pdf;
RTXDI_SamplePdfMipmap(rng, pdfTexture, pdfTextureSize, texelPosition, pdf);
// Uniform sampling inside the pixels
float2 fPos = float2(texelPosition);
fPos.x += RAB_GetNextRandom(rng);
fPos.y += RAB_GetNextRandom(rng);
// Convert texel position to UV and pack it
float2 uv = fPos / float2(pdfTextureSize);
uint packedUv = uint(saturate(uv.x) * 0xffff) | (uint(saturate(uv.y) * 0xffff) << 16);
// Compute the inverse PDF if we found something
float invSourcePdf = (pdf > 0) ? (1.0 / pdf) : 0;
// Store the result
uint risBufferPtr = params.environmentRisBufferOffset + sampleInTile + tileIndex * params.environmentTileSize;
RTXDI_RIS_BUFFER[risBufferPtr] = uint2(packedUv, asuint(invSourcePdf));
}
#endif // RTXDI_ENABLE_PRESAMPLING
#ifndef RTXDI_TILE_SIZE_IN_PIXELS
#define RTXDI_TILE_SIZE_IN_PIXELS 16
#endif
void RTXDI_RandomlySelectLocalLight(
inout RAB_RandomSamplerState rng,
uint firstLocalLight,
uint numLocalLights,
#if RTXDI_ENABLE_PRESAMPLING
bool useRisBuffer,
uint risBufferBase,
uint risBufferCount,
#endif
out RAB_LightInfo lightInfo,
out uint lightIndex,
out float invSourcePdf
)
{
float rnd = RAB_GetNextRandom(rng);
lightInfo = RAB_EmptyLightInfo();
bool lightLoaded = false;
#if RTXDI_ENABLE_PRESAMPLING
if (useRisBuffer)
{
uint risSample = min(uint(floor(rnd * risBufferCount)), risBufferCount - 1);
uint risBufferPtr = risSample + risBufferBase;
uint2 tileData = RTXDI_RIS_BUFFER[risBufferPtr];
lightIndex = tileData.x & RTXDI_LIGHT_INDEX_MASK;
invSourcePdf = asfloat(tileData.y);
if ((tileData.x & RTXDI_LIGHT_COMPACT_BIT) != 0)
{
lightInfo = RAB_LoadCompactLightInfo(risBufferPtr);
lightLoaded = true;
}
}
else
#endif
{
lightIndex = min(uint(floor(rnd * numLocalLights)), numLocalLights - 1) + firstLocalLight;
invSourcePdf = float(numLocalLights);
}
if (!lightLoaded) {
lightInfo = RAB_LoadLightInfo(lightIndex, false);
}
}
float2 RTXDI_RandomlySelectLocalLightUV(inout RAB_RandomSamplerState rng)
{
float2 uv;
uv.x = RAB_GetNextRandom(rng);
uv.y = RAB_GetNextRandom(rng);
return uv;
}
// Returns false if the blended source PDF == 0, true otherwise
bool RTXDI_StreamLocalLightAtUVIntoReservoir(
inout RAB_RandomSamplerState rng,
RTXDI_SampleParameters sampleParams,
RAB_Surface surface,
uint lightIndex,
float2 uv,
float invSourcePdf,
RAB_LightInfo lightInfo,
inout RTXDI_Reservoir state,
inout RAB_LightSample o_selectedSample)
{
RAB_LightSample candidateSample = RAB_SamplePolymorphicLight(lightInfo, surface, uv);
float blendedSourcePdf = RTXDI_LightBrdfMisWeight(surface, candidateSample, 1.0 / invSourcePdf,
sampleParams.localLightMisWeight, false, sampleParams);
float targetPdf = RAB_GetLightSampleTargetPdfForSurface(candidateSample, surface);
float risRnd = RAB_GetNextRandom(rng);
if (blendedSourcePdf == 0)
{
return false;
}
bool selected = RTXDI_StreamSample(state, lightIndex, uv, risRnd, targetPdf, 1.0 / blendedSourcePdf);
if (selected) {
o_selectedSample = candidateSample;
}
return true;
}
// SDK internal function that samples the given set of lights generated by RIS
// or the local light pool. The RIS set can come from local light importance presampling or from ReGIR.
RTXDI_Reservoir RTXDI_SampleLocalLightsInternal(
inout RAB_RandomSamplerState rng,
RAB_Surface surface,
RTXDI_SampleParameters sampleParams,
RTXDI_LocalLightRuntimeParameters params,
#if RTXDI_ENABLE_PRESAMPLING
bool useRisBuffer,
uint risBufferBase,
uint risBufferCount,
#endif
out RAB_LightSample o_selectedSample)
{
RTXDI_Reservoir state = RTXDI_EmptyReservoir();
o_selectedSample = RAB_EmptyLightSample();
if (params.numLocalLights == 0)
return state;
if (sampleParams.numLocalLightSamples == 0)
return state;
for (uint i = 0; i < sampleParams.numLocalLightSamples; i++)
{
uint lightIndex;
RAB_LightInfo lightInfo;
float invSourcePdf;
RTXDI_RandomlySelectLocalLight(rng, params.firstLocalLight, params.numLocalLights,
#if RTXDI_ENABLE_PRESAMPLING
useRisBuffer, risBufferBase, risBufferCount,
#endif
lightInfo, lightIndex, invSourcePdf);
float2 uv = RTXDI_RandomlySelectLocalLightUV(rng);
bool zeroPdf = RTXDI_StreamLocalLightAtUVIntoReservoir(rng, sampleParams, surface, lightIndex, uv, invSourcePdf, lightInfo, state, o_selectedSample);
if (zeroPdf)
continue;
}
RTXDI_FinalizeResampling(state, 1.0, sampleParams.numMisSamples);
state.M = 1;
return state;
}
// Samples the local light pool for the given surface.
RTXDI_Reservoir RTXDI_SampleLocalLights(
inout RAB_RandomSamplerState rng,
inout RAB_RandomSamplerState coherentRng,
RAB_Surface surface,
RTXDI_SampleParameters sampleParams,
RTXDI_ResamplingRuntimeParameters params,
out RAB_LightSample o_selectedSample)
{
float tileRnd = RAB_GetNextRandom(coherentRng);
uint tileIndex = uint(tileRnd * params.risBufferParams.tileCount);
uint risBufferBase = tileIndex * params.risBufferParams.tileSize;
return RTXDI_SampleLocalLightsInternal(rng, surface, sampleParams, params.localLightParams,
#if RTXDI_ENABLE_PRESAMPLING
params.localLightParams.enableLocalLightImportanceSampling != 0, risBufferBase, params.risBufferParams.tileSize,
#endif
o_selectedSample);
}
void RTXDI_RandomlySelectInfiniteLight(
inout RAB_RandomSamplerState rng,
RTXDI_InfiniteLightRuntimeParameters params,
out RAB_LightInfo lightInfo,
out uint lightIndex,
out float invSourcePdf)
{
float rnd = RAB_GetNextRandom(rng);
invSourcePdf = float(params.numInfiniteLights);
lightIndex = params.firstInfiniteLight + min(uint(floor(rnd * params.numInfiniteLights)), params.numInfiniteLights - 1);
lightInfo = RAB_LoadLightInfo(lightIndex, false);
}
float2 RTXDI_RandomlySelectInfiniteLightUV(RAB_RandomSamplerState rng)
{
float2 uv;
uv.x = RAB_GetNextRandom(rng);
uv.y = RAB_GetNextRandom(rng);
return uv;
}
void RTXDI_StreamInfiniteLightAtUVIntoReservoir(
inout RAB_RandomSamplerState rng,
RAB_LightInfo lightInfo,
RAB_Surface surface,
uint lightIndex,
float2 uv,
float invSourcePdf,
inout RTXDI_Reservoir state,
inout RAB_LightSample o_selectedSample)
{
RAB_LightSample candidateSample = RAB_SamplePolymorphicLight(lightInfo, surface, uv);
float targetPdf = RAB_GetLightSampleTargetPdfForSurface(candidateSample, surface);
float risRnd = RAB_GetNextRandom(rng);
bool selected = RTXDI_StreamSample(state, lightIndex, uv, risRnd, targetPdf, invSourcePdf);
if (selected)
{
o_selectedSample = candidateSample;
}
}
// Samples the infinite light pool for the given surface.
RTXDI_Reservoir RTXDI_SampleInfiniteLights(
inout RAB_RandomSamplerState rng,
RAB_Surface surface,
uint numSamples,
RTXDI_InfiniteLightRuntimeParameters params,
inout RAB_LightSample o_selectedSample)
{
RTXDI_Reservoir state = RTXDI_EmptyReservoir();
o_selectedSample = RAB_EmptyLightSample();
if (params.numInfiniteLights == 0)
return state;
if (numSamples == 0)
return state;
uint stride = (params.numInfiniteLights + numSamples - 1) / numSamples;
uint randStart = uint(RAB_GetNextRandom(rng) * params.numInfiniteLights);
for(uint i = 0; i < numSamples; i++)
{
float invSourcePdf;
uint lightIndex;
RAB_LightInfo lightInfo;
RTXDI_RandomlySelectInfiniteLight(rng, params, lightInfo, lightIndex, invSourcePdf);
float2 uv = RTXDI_RandomlySelectInfiniteLightUV(rng);
RTXDI_StreamInfiniteLightAtUVIntoReservoir(rng, lightInfo, surface, lightIndex, uv, invSourcePdf, state, o_selectedSample);
}
RTXDI_FinalizeResampling(state, 1.0, state.M);
state.M = 1;
return state;
}
#if RTXDI_ENABLE_PRESAMPLING
void RTXDI_ComputeRISBufferBaseAndCount(
inout RAB_RandomSamplerState coherentRng,
RTXDI_EnvironmentLightRuntimeParameters params,
out uint risBufferBase,
out uint risBufferCount)
{
float tileRnd = RAB_GetNextRandom(coherentRng);
uint tileIndex = uint(tileRnd * params.environmentTileCount);
risBufferBase = tileIndex * params.environmentTileSize + params.environmentRisBufferOffset;
risBufferCount = params.environmentTileSize;
}
void RTXDI_SelectEnvironmentLightUV(
inout RAB_RandomSamplerState rng,
uint risBufferCount,
uint risBufferBase,
out float2 uv,
out float invSourcePdf
)
{
float rnd = RAB_GetNextRandom(rng);
uint risSample = min(uint(floor(rnd * risBufferCount)), risBufferCount - 1);
uint risBufferPtr = risSample + risBufferBase;
uint2 tileData = RTXDI_RIS_BUFFER[risBufferPtr];
uint packedUv = tileData.x;
invSourcePdf = asfloat(tileData.y);
uv = float2(packedUv & 0xffff, packedUv >> 16) / float(0xffff);
}
void RTXDI_StreamEnvironmentLightAtUVIntoReservoir(
inout RAB_RandomSamplerState rng,
RTXDI_SampleParameters sampleParams,
RAB_Surface surface,
RAB_LightInfo lightInfo,
uint environmentLightIndex,
float2 uv,
float invSourcePdf,
inout RTXDI_Reservoir state,
inout RAB_LightSample o_selectedSample)
{
RAB_LightSample candidateSample = RAB_SamplePolymorphicLight(lightInfo, surface, uv);
float blendedSourcePdf = RTXDI_LightBrdfMisWeight(surface, candidateSample, 1.0 / invSourcePdf,
sampleParams.environmentMapMisWeight, true, sampleParams);
float targetPdf = RAB_GetLightSampleTargetPdfForSurface(candidateSample, surface);
float risRnd = RAB_GetNextRandom(rng);
bool selected = RTXDI_StreamSample(state, environmentLightIndex, uv, risRnd, targetPdf, 1.0 / blendedSourcePdf);
if (selected) {
o_selectedSample = candidateSample;
}
}
RTXDI_Reservoir RTXDI_SampleEnvironmentMap(
inout RAB_RandomSamplerState rng,
inout RAB_RandomSamplerState coherentRng,
RAB_Surface surface,
RTXDI_SampleParameters sampleParams,
RTXDI_EnvironmentLightRuntimeParameters params,
out RAB_LightSample o_selectedSample)
{
RTXDI_Reservoir state = RTXDI_EmptyReservoir();
o_selectedSample = RAB_EmptyLightSample();
if (params.environmentLightPresent == 0)
return state;
if (sampleParams.numEnvironmentMapSamples == 0)
return state;
float tileRnd = RAB_GetNextRandom(coherentRng);
uint tileIndex = uint(tileRnd * params.environmentTileCount);
uint risBufferBase;
uint risBufferCount;
RTXDI_ComputeRISBufferBaseAndCount(coherentRng, params, risBufferBase, risBufferCount);
RAB_LightInfo lightInfo = RAB_LoadLightInfo(params.environmentLightIndex, false);
for (uint i = 0; i < sampleParams.numEnvironmentMapSamples; i++)
{
float2 uv;
float invSourcePdf;
RTXDI_SelectEnvironmentLightUV(rng, risBufferCount, risBufferBase, uv, invSourcePdf);
RTXDI_StreamEnvironmentLightAtUVIntoReservoir(rng, sampleParams, surface, lightInfo, params.environmentLightIndex, uv, invSourcePdf, state, o_selectedSample);
}
RTXDI_FinalizeResampling(state, 1.0, sampleParams.numMisSamples);
state.M = 1;
return state;
}
#endif // RTXDI_ENABLE_PRESAMPLING
#if RTXDI_REGIR_MODE != RTXDI_REGIR_DISABLED
// ReGIR grid build pass.
// Each thread populates one light slot in a grid cell.
void RTXDI_PresampleLocalLightsForReGIR(
inout RAB_RandomSamplerState rng,
inout RAB_RandomSamplerState coherentRng,
uint lightSlot,
uint numSamples,
RTXDI_ResamplingRuntimeParameters params)
{
uint risBufferPtr = params.regirCommon.risBufferOffset + lightSlot;
if (numSamples == 0)
{
RTXDI_RIS_BUFFER[risBufferPtr] = uint2(0, 0);
return;
}
uint lightInCell = lightSlot % params.regirCommon.lightsPerCell;
uint cellIndex = lightSlot / params.regirCommon.lightsPerCell;
float3 cellCenter;
float cellRadius;
if (!RTXDI_ReGIR_CellIndexToWorldPos(params, int(cellIndex), cellCenter, cellRadius))
{
RTXDI_RIS_BUFFER[risBufferPtr] = uint2(0, 0);
return;
}
cellRadius *= (params.regirCommon.samplingJitter + 1.0);
RAB_LightInfo selectedLightInfo = RAB_EmptyLightInfo();
uint selectedLight = 0;
float selectedTargetPdf = 0;
float weightSum = 0;
float rndTileSample = RAB_GetNextRandom(coherentRng);
uint tileIndex = uint(rndTileSample * params.risBufferParams.tileCount);
float invNumSamples = 1.0 / float(numSamples);
for (uint i = 0; i < numSamples; i++)
{
uint rndLight;
RAB_LightInfo lightInfo = RAB_EmptyLightInfo();
float invSourcePdf;
float rand = RAB_GetNextRandom(rng);
bool lightLoaded = false;
if (params.localLightParams.enableLocalLightImportanceSampling != 0)
{
uint tileSample = uint(min(rand * params.risBufferParams.tileSize, params.risBufferParams.tileSize - 1));
uint tilePtr = tileSample + tileIndex * params.risBufferParams.tileSize;
uint2 tileData = RTXDI_RIS_BUFFER[tilePtr];
rndLight = tileData.x & RTXDI_LIGHT_INDEX_MASK;
invSourcePdf = asfloat(tileData.y) * invNumSamples;
if ((tileData.x & RTXDI_LIGHT_COMPACT_BIT) != 0)
{
lightInfo = RAB_LoadCompactLightInfo(tilePtr);
lightLoaded = true;
}
}
else
{
rndLight = uint(min(rand * params.localLightParams.numLocalLights, params.localLightParams.numLocalLights - 1)) + params.localLightParams.firstLocalLight;
invSourcePdf = float(params.localLightParams.numLocalLights) * invNumSamples;
}
if (!lightLoaded) {
lightInfo = RAB_LoadLightInfo(rndLight, false);
}
float targetPdf = RAB_GetLightTargetPdfForVolume(lightInfo, cellCenter, cellRadius);
float risRnd = RAB_GetNextRandom(rng);
float risWeight = targetPdf * invSourcePdf;
weightSum += risWeight;
if (risRnd * weightSum < risWeight)
{
selectedLightInfo = lightInfo;
selectedLight = rndLight;
selectedTargetPdf = targetPdf;
}
}
float weight = (selectedTargetPdf > 0) ? weightSum / selectedTargetPdf : 0;
bool compact = false;
if (weight > 0) {
compact = RAB_StoreCompactLightInfo(risBufferPtr, selectedLightInfo);
}
if(compact) {
selectedLight |= RTXDI_LIGHT_COMPACT_BIT;
}
RTXDI_RIS_BUFFER[risBufferPtr] = uint2(selectedLight, asuint(weight));
}
// Sampling lights for a surface from the ReGIR structure or the local light pool.
// If the surface is inside the ReGIR structure, and ReGIR is enabled, and
// numRegirSamples is nonzero, then this function will sample the ReGIR structure.
// Otherwise, it samples the local light pool.
RTXDI_Reservoir RTXDI_SampleLocalLightsFromReGIR(
inout RAB_RandomSamplerState rng,
inout RAB_RandomSamplerState coherentRng,
RAB_Surface surface,
RTXDI_SampleParameters sampleParams,
RTXDI_ResamplingRuntimeParameters params,
out RAB_LightSample o_selectedSample)
{
RTXDI_Reservoir reservoir = RTXDI_EmptyReservoir();
o_selectedSample = RAB_EmptyLightSample();
if (sampleParams.numRegirSamples == 0 && sampleParams.numLocalLightSamples == 0)
return reservoir;
int cellIndex = -1;
if (params.regirCommon.enable != 0 && sampleParams.numRegirSamples > 0)
{
float3 cellJitter = float3(
RAB_GetNextRandom(coherentRng),
RAB_GetNextRandom(coherentRng),
RAB_GetNextRandom(coherentRng));
cellJitter -= 0.5;
float3 samplingPos = RAB_GetSurfaceWorldPos(surface);
float jitterScale = RTXDI_ReGIR_GetJitterScale(params, samplingPos);
samplingPos += cellJitter * jitterScale;
cellIndex = RTXDI_ReGIR_WorldPosToCellIndex(params, samplingPos);
}
uint risBufferBase, risBufferCount, numSamples;
bool useRisBuffer;
if (cellIndex < 0)
{
float tileRnd = RAB_GetNextRandom(coherentRng);
uint tileIndex = uint(tileRnd * params.risBufferParams.tileCount);
risBufferBase = tileIndex * params.risBufferParams.tileSize;
risBufferCount = params.risBufferParams.tileSize;
numSamples = sampleParams.numLocalLightSamples;
useRisBuffer = params.localLightParams.enableLocalLightImportanceSampling != 0;
}
else
{
uint cellBase = uint(cellIndex) * params.regirCommon.lightsPerCell;
risBufferBase = cellBase + params.regirCommon.risBufferOffset;
risBufferCount = params.regirCommon.lightsPerCell;
numSamples = sampleParams.numRegirSamples;
useRisBuffer = true;
}
reservoir = RTXDI_SampleLocalLightsInternal(rng, surface, sampleParams, params.localLightParams,
useRisBuffer, risBufferBase, risBufferCount, o_selectedSample);
return reservoir;
}
#endif // (RTXDI_REGIR_MODE != RTXDI_REGIR_DISABLED)
// Samples from the BRDF defined by the given surface
RTXDI_Reservoir RTXDI_SampleBrdf(
inout RAB_RandomSamplerState rng,
RAB_Surface surface,
RTXDI_SampleParameters sampleParams,
RTXDI_ResamplingRuntimeParameters params,
out RAB_LightSample o_selectedSample)
{
RTXDI_Reservoir state = RTXDI_EmptyReservoir();
for (uint i = 0; i < sampleParams.numBrdfSamples; ++i)
{
float lightSourcePdf = 0;
float3 sampleDir;
uint lightIndex = RTXDI_InvalidLightIndex;
float2 randXY = float2(0, 0);
RAB_LightSample candidateSample = RAB_EmptyLightSample();
if (RAB_GetSurfaceBrdfSample(surface, rng, sampleDir))
{
float brdfPdf = RAB_GetSurfaceBrdfPdf(surface, sampleDir);
float maxDistance = RTXDI_BrdfMaxDistanceFromPdf(sampleParams.brdfCutoff, brdfPdf);
bool hitAnything = RAB_TraceRayForLocalLight(RAB_GetSurfaceWorldPos(surface), sampleDir,
sampleParams.brdfRayMinT, maxDistance, lightIndex, randXY);
if (lightIndex != RTXDI_InvalidLightIndex)
{
RAB_LightInfo lightInfo = RAB_LoadLightInfo(lightIndex, false);
candidateSample = RAB_SamplePolymorphicLight(lightInfo, surface, randXY);
if (sampleParams.brdfCutoff > 0.f)
{
// If Mis cutoff is used, we need to evaluate the sample and make sure it actually could have been
// generated by the area sampling technique. This is due to numerical precision.
float3 lightDir;
float lightDistance;
RAB_GetLightDirDistance(surface, candidateSample, lightDir, lightDistance);
float brdfPdf = RAB_GetSurfaceBrdfPdf(surface, lightDir);
float maxDistance = RTXDI_BrdfMaxDistanceFromPdf(sampleParams.brdfCutoff, brdfPdf);
if (lightDistance > maxDistance)
lightIndex = RTXDI_InvalidLightIndex;
}
if (lightIndex != RTXDI_InvalidLightIndex)
{
lightSourcePdf = RAB_EvaluateLocalLightSourcePdf(params, lightIndex);
}
}
else if (!hitAnything && params.environmentLightParams.environmentLightPresent != 0)
{
// sample environment light
lightIndex = params.environmentLightParams.environmentLightIndex;
RAB_LightInfo lightInfo = RAB_LoadLightInfo(lightIndex, false);
randXY = RAB_GetEnvironmentMapRandXYFromDir(sampleDir);
candidateSample = RAB_SamplePolymorphicLight(lightInfo, surface, randXY);
lightSourcePdf = RAB_EvaluateEnvironmentMapSamplingPdf(sampleDir);
}
}