-
Notifications
You must be signed in to change notification settings - Fork 7
/
Caustics.cpp
1279 lines (1177 loc) · 61.6 KB
/
Caustics.cpp
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) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of NVIDIA CORPORATION nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
***************************************************************************/
#include "Caustics.h"
#include "Scene/Model/Model.h"
static const glm::vec4 kClearColor(0.f, 0.f, 0.f, 1);
static const std::string kDefaultScene = "Caustics/ring.fscene";
std::string to_string(const vec3& v)
{
std::string s;
s += "(" + std::to_string(v.x) + ", " + std::to_string(v.y) + ", " + std::to_string(v.z) + ")";
return s;
}
const FileDialogFilterVec settingFilter = { {"ini", "Scene Setting File"} };
void Caustics::onGuiRender(Gui* pGui)
{
pGui->addCheckBox("Ray Trace", mRayTrace);
if (pGui->addButton("Load Scene"))
{
std::string filename;
if (openFileDialog(Scene::kFileExtensionFilters, filename))
{
loadScene(filename, gpFramework->getTargetFbo().get());
loadShader();
}
}
if (pGui->addButton("Load Scene Settings"))
{
std::string filename;
if (openFileDialog(settingFilter, filename))
{
loadSceneSetting(filename);
}
}
if (pGui->addButton("Save Scene Settings"))
{
std::string filename;
if (saveFileDialog(settingFilter, filename))
{
saveSceneSetting(filename);
}
}
if (pGui->addButton("Update Shader"))
{
loadShader();
}
if (pGui->beginGroup("Display", true))
{
{
Gui::DropdownList debugModeList;
debugModeList.push_back({ 0, "Rasterize" });
debugModeList.push_back({ 1, "Depth" });
debugModeList.push_back({ 2, "Normal" });
debugModeList.push_back({ 3, "Diffuse" });
debugModeList.push_back({ 4, "Specular" });
debugModeList.push_back({ 5, "Photon" });
debugModeList.push_back({ 6, "World" });
debugModeList.push_back({ 7, "Roughness" });
debugModeList.push_back({ 8, "Ray Info" });
debugModeList.push_back({ 9, "Raytrace" });
debugModeList.push_back({ 10, "Avg. Screen Area" });
debugModeList.push_back({ 11, "Screen Area Std. Variance" });
debugModeList.push_back({ 12, "Photon Count" });
debugModeList.push_back({ 13, "Photon Total Count" });
debugModeList.push_back({ 14, "Ray count Mipmap" });
debugModeList.push_back({ 15, "Photon Density" });
debugModeList.push_back({ 16, "Small Photon Color" });
debugModeList.push_back({ 17, "Small Photon Count" });
pGui->addDropdown("Composite mode", debugModeList, (uint32_t&)mDebugMode);
}
pGui->addFloatVar("Max Pixel Value", mMaxPixelArea, 0, 1000000000, 5.f);
pGui->addFloatVar("Max Photon Count", mMaxPhotonCount, 0, 1000000000, 5.f);
pGui->addIntVar("Ray Count Mipmap", mRayCountMipIdx, 0, 11);
{
Gui::DropdownList debugModeList;
debugModeList.push_back({ 1, "x1" });
debugModeList.push_back({ 2, "x2" });
debugModeList.push_back({ 4, "x4" });
debugModeList.push_back({ 8, "x8" });
debugModeList.push_back({ 16, "x16" });
pGui->addDropdown("Ray Tex Scale", debugModeList, (uint32_t&)mRayTexScaleFactor);
}
pGui->endGroup();
}
if (pGui->beginGroup("Photon Trace", true))
{
{
Gui::DropdownList debugModeList;
debugModeList.push_back({ 0, "Fixed Resolution" });
debugModeList.push_back({ 1, "Adaptive Resolution" });
debugModeList.push_back({ 3, "Fast Adaptive Resolution" });
debugModeList.push_back({ 2, "None" });
pGui->addDropdown("Trace Type", debugModeList, (uint32_t&)mTraceType);
}
{
Gui::DropdownList debugModeList;
debugModeList.push_back({ 0, "Ray Differential" });
debugModeList.push_back({ 1, "Ray Cone" });
debugModeList.push_back({ 2, "None" });
pGui->addDropdown("Ray Type", debugModeList, (uint32_t&)mPhotonTraceMacro);
}
{
Gui::DropdownList debugModeList;
debugModeList.push_back({ 64, "64" });
debugModeList.push_back({ 128, "128" });
debugModeList.push_back({ 256, "256" });
debugModeList.push_back({ 512, "512" });
debugModeList.push_back({ 1024, "1024" });
debugModeList.push_back({ 2048, "2048" });
pGui->addDropdown("Dispatch Size", debugModeList, (uint32_t&)mDispatchSize);
}
{
Gui::DropdownList debugModeList;
debugModeList.push_back({ 0, "Avg Square" });
debugModeList.push_back({ 1, "Avg Length" });
debugModeList.push_back({ 2, "Max Square" });
debugModeList.push_back({ 3, "Exact Area" });
pGui->addDropdown("Area Type", debugModeList, (uint32_t&)mAreaType);
}
pGui->addFloatVar("Intensity", mIntensity, 0, 10, 0.1f);
pGui->addFloatVar("Emit size", mEmitSize, 0, 1000, 1);
pGui->addFloatVar("Rough Threshold", mRoughThreshold, 0, 1, 0.01f);
pGui->addIntVar("Max Trace Depth", mMaxTraceDepth, 0, 30);
pGui->addFloatVar("IOR Override", mIOROveride, 0, 3, 0.01f);
pGui->addCheckBox("ID As Color", mColorPhoton);
pGui->addIntVar("Photon ID Scale", mPhotonIDScale);
pGui->addFloatVar("Min Trace Luminance", mTraceColorThreshold, 0, 10,0.005f);
pGui->addFloatVar("Min Cull Luminance", mCullColorThreshold, 0, 10000, 0.01f);
pGui->addCheckBox("Fast Photon Path", mFastPhotonPath);
pGui->addFloatVar("Max Pixel Radius", mMaxPhotonPixelRadius, 0, 5000, 1.f);
pGui->addFloatVar("Fast Pixel Radius", mFastPhotonPixelRadius, 0, 5000, 1.f);
pGui->addFloatVar("Fast Draw Count", mFastPhotonDrawCount, 0, 50000, 0.1f);
pGui->addFloatVar("Color Compress Scale", mSmallPhotonCompressScale, 0, 5000, 1.f);
pGui->addCheckBox("Shrink Color Payload", mShrinkColorPayload);
pGui->addCheckBox("Shrink Ray Diff Payload", mShrinkRayDiffPayload);
pGui->addCheckBox("Update Photon", mUpdatePhoton);
pGui->endGroup();
}
if (pGui->beginGroup("Adaptive Resolution", true))
{
{
Gui::DropdownList debugModeList;
debugModeList.push_back({ 0, "Random" });
debugModeList.push_back({ 1, "Grid" });
pGui->addDropdown("Sample Placement", debugModeList, (uint32_t&)mSamplePlacement);
}
pGui->addFloatVar("Luminance Threshold", mPixelLuminanceThreshold, 0.01f, 10.0, 0.01f);
pGui->addFloatVar("Photon Size Threshold", mMinPhotonPixelSize, 1.f, 1000.0f, 0.1f);
pGui->addFloatVar("Smooth Weight", mSmoothWeight, 0, 10.0f, 0.001f);
pGui->addFloatVar("Proportional Gain", mUpdateSpeed, 0, 1, 0.01f);
pGui->addFloatVar("Variance Gain", mVarianceGain, 0, 10, 0.0001f);
pGui->addFloatVar("Derivative Gain", mDerivativeGain, -10, 10, 0.1f);
pGui->addFloatVar("Max Task Per Pixel", mMaxTaskCountPerPixel, 1.0, 1000000, 5);
pGui->endGroup();
}
if (pGui->beginGroup("Smooth Photon", false))
{
pGui->addCheckBox("Remove Isolated Photon", mRemoveIsolatedPhoton);
pGui->addCheckBox("Enable Median Filter", mMedianFilter);
pGui->addFloatVar("Normal Threshold", mNormalThreshold, 0.01f, 1.0, 0.01f);
pGui->addFloatVar("Distance Threshold", mDistanceThreshold, 0.1f, 100.0f, 0.1f);
pGui->addFloatVar("Planar Threshold", mPlanarThreshold, 0.01f, 10.0, 0.1f);
pGui->addFloatVar("Trim Direction Threshold", trimDirectionThreshold, 0, 1);
pGui->addIntVar("Min Neighbour Count", mMinNeighbourCount, 0, 8);
pGui->endGroup();
}
if (pGui->beginGroup("Photon Splatting", true))
{
{
Gui::DropdownList debugModeList;
debugModeList.push_back({ 0, "Scatter" });
debugModeList.push_back({ 1, "Gather" });
debugModeList.push_back({ 2, "None" });
pGui->addDropdown("Density Estimation", debugModeList, (uint32_t&)mScatterOrGather);
}
pGui->addFloatVar("Splat size", mSplatSize, 0, 100, 0.01f);
pGui->addFloatVar("Kernel Power", mKernelPower, 0.01f, 10.f, 0.01f);
if(pGui->beginGroup("Scatter Parameters", false))
{
pGui->addFloatVar("Z Tolerance", mZTolerance, 0.001f, 1, 0.001f);
pGui->addFloatVar("Scatter Normal Threshold", mScatterNormalThreshold, 0.01f, 1.0, 0.01f);
pGui->addFloatVar("Scatter Distance Threshold", mScatterDistanceThreshold, 0.1f, 10.0f, 0.1f);
pGui->addFloatVar("Scatter Planar Threshold", mScatterPlanarThreshold, 0.01f, 10.0, 0.1f);
pGui->addFloatVar("Max Anisotropy", mMaxAnisotropy, 1, 100, 0.1f);
{
Gui::DropdownList debugModeList;
debugModeList.push_back({ 0, "Quad" });
debugModeList.push_back({ 1, "Sphere" });
pGui->addDropdown("Photon Geometry", debugModeList, (uint32_t&)mScatterGeometry);
}
{
Gui::DropdownList debugModeList;
debugModeList.push_back({ 0, "Kernel" });
debugModeList.push_back({ 1, "Solid" });
debugModeList.push_back({ 2, "Shaded" });
pGui->addDropdown("Photon Display Mode", debugModeList, (uint32_t&)mPhotonDisplayMode);
}
{
Gui::DropdownList debugModeList;
debugModeList.push_back({ 0, "Anisotropic" });
debugModeList.push_back({ 1, "Isotropic" });
debugModeList.push_back({ 2, "Photon Mesh" });
debugModeList.push_back({ 3, "Screen Dot" });
debugModeList.push_back({ 4, "Screen Dot With Color" });
pGui->addDropdown("Photon mode", debugModeList, (uint32_t&)mPhotonMode);
}
pGui->endGroup();
}
if(pGui->beginGroup("Gather Parameters", false))
{
pGui->addFloatVar("Gather Depth Radius", mDepthRadius, 0, 10, 0.01f);
pGui->addFloatVar("Gather Min Color", mMinGatherColor, 0, 2, 0.001f);
pGui->addCheckBox("Gather Show Tile Count", mShowTileCount);
pGui->addIntVar("Gather Tile Count Scale", mTileCountScale, 0, 1000);
pGui->endGroup();
}
pGui->endGroup();
}
if (pGui->beginGroup("Temporal Filter", true))
{
pGui->addCheckBox("Enable Temporal Filter", mTemporalFilter);
pGui->addFloatVar("Filter Weight", mFilterWeight, 0.0f, 1.0f, 0.001f);
pGui->addFloatVar("Jitter", mJitter, 0, 10, 0.01f);
pGui->addFloatVar("Jitter Power", mJitterPower, 0, 200, 0.01f);
pGui->addFloatVar("Temporal Normal Strength", mTemporalNormalKernel, 0.0001f, 1000, 0.01f);
pGui->addFloatVar("Temporal Depth Strength", mTemporalDepthKernel, 0.0001f, 1000, 0.01f);
pGui->addFloatVar("Temporal Color Strength", mTemporalColorKernel, 0.0001f, 1000, 0.01f);
pGui->endGroup();
}
if (pGui->beginGroup("Spacial Filter", true))
{
pGui->addCheckBox("Enable Spatial Filter", mSpacialFilter);
pGui->addIntVar("A trous Pass", mSpacialPasses, 0, 10);
pGui->addFloatVar("Spacial Normal Strength", mSpacialNormalKernel, 0.0001f, 100, 0.01f);
pGui->addFloatVar("Spacial Depth Strength", mSpacialDepthKernel, 0.0001f, 100, 0.01f);
pGui->addFloatVar("Spacial Color Strength", mSpacialColorKernel, 0.0001f, 100, 0.01f);
pGui->addFloatVar("Spacial Screen Kernel", mSpacialScreenKernel, 0.0001f, 100, 0.01f);
pGui->endGroup();
}
if (pGui->beginGroup("Composite", true))
{
{
int oldResRatio = mCausticsMapResRatio;
Gui::DropdownList debugModeList;
debugModeList.push_back({ 1, "x 1" });
debugModeList.push_back({ 2, "x 1/2" });
debugModeList.push_back({ 4, "x 1/4" });
debugModeList.push_back({ 8, "x 1/8" });
pGui->addDropdown("Caustics Resolution", debugModeList, (uint32_t&)mCausticsMapResRatio);
if (oldResRatio != mCausticsMapResRatio)
{
createCausticsMap();
}
}
pGui->addCheckBox("Filter Caustics Map", mFilterCausticsMap);
pGui->addFloatVar("UV Kernel", mUVKernel, 0.0f, 1000.f, 0.1f);
pGui->addFloatVar("Depth Kernel", mZKernel, 0.0f, 1000.f, 0.1f);
pGui->addFloatVar("Normal Kernel", mNormalKernel, 0.0f, 1000.f, 0.1f);
pGui->endGroup();
}
mLightDirection = vec3(
cos(mLightAngle.x) * sin(mLightAngle.y),
cos(mLightAngle.y),
sin(mLightAngle.x) * sin(mLightAngle.y));
if (pGui->beginGroup("Light", true))
{
pGui->addFloat2Var("Light Angle", mLightAngle, -FLT_MAX, FLT_MAX, 0.01f);
if (mpScene)
{
auto light0 = dynamic_cast<DirectionalLight*>(mpScene->getLight(0).get());
light0->setWorldDirection(mLightDirection);
}
pGui->addFloat2Var("Light Angle Speed", mLightAngleSpeed, -FLT_MAX, FLT_MAX, 0.001f);
mLightAngle += mLightAngleSpeed*0.01f;
pGui->endGroup();
}
if (pGui->beginGroup("Camera"))
{
mpCamera->renderUI(pGui);
pGui->endGroup();
}
}
void Caustics::loadScene(const std::string& filename, const Fbo* pTargetFbo)
{
mpScene = RtScene::loadFromFile(filename, RtBuildFlags::None, Model::LoadFlags::None);
if (!mpScene) return;
mpQuad = Model::createFromFile("Caustics/quad.obj");
mpSphere = Model::createFromFile("Caustics/sphere.obj");
Model::SharedPtr pModel = mpScene->getModel(0);
float radius = pModel->getRadius();
mpCamera = mpScene->getActiveCamera();
assert(mpCamera);
mCamController.attachCamera(mpCamera);
Sampler::Desc samplerDesc;
samplerDesc.setFilterMode(Sampler::Filter::Linear, Sampler::Filter::Linear, Sampler::Filter::Linear);
Sampler::SharedPtr pSampler = Sampler::create(samplerDesc);
pModel->bindSamplerToMaterials(pSampler);
// Update the controllers
mCamController.setCameraSpeed(radius * 0.2f);
auto sceneBBox = mpScene->getBoundingBox();
float sceneRadius = sceneBBox.getSize().length() * 0.5f;
//mCamController.setModelParams(mpScene->getCenter(), sceneRadius, sceneRadius);
float nearZ = std::max(0.1f, pModel->getRadius() / 750.0f);
float farZ = radius * 10;
mpCamera->setDepthRange(nearZ, farZ);
mpCamera->setAspectRatio((float)pTargetFbo->getWidth() / (float)pTargetFbo->getHeight());
mpGaussianKernel = Texture::createFromFile("Caustics/gaussian.png", true, false);
mpUniformNoise = Texture::createFromFile("Caustics/uniform.png", true, false);
}
Caustics::PhotonTraceShader Caustics::getPhotonTraceShader()
{
uint flag = photonMacroToFlags();
auto pIter = mPhotonTraceShaderList.find(flag);
if (pIter == mPhotonTraceShaderList.end())
{
RtProgram::Desc desc;
desc.addShaderLibrary("PhotonTrace.rt.hlsl");
desc.setRayGen("rayGen");
desc.addHitGroup(0, "primaryClosestHit", "");
desc.addMiss(0, "primaryMiss");
switch (mPhotonTraceMacro)
{
case Caustics::RAY_DIFFERENTIAL:
desc.addDefine("RAY_DIFFERENTIAL", "1");
break;
case Caustics::RAY_CONE:
desc.addDefine("RAY_CONE", "1");
break;
case Caustics::RAY_NONE:
desc.addDefine("RAY_NONE", "1");
break;
default:
break;
}
switch (mTraceType)
{
case Caustics::TRACE_FIXED:
desc.addDefine("TRACE_FIXED", "1");
break;
case Caustics::TRACE_ADAPTIVE:
desc.addDefine("TRACE_ADAPTIVE", "1");
break;
case Caustics::TRACE_NONE:
desc.addDefine("TRACE_NONE", "1");
break;
case Caustics::TRACE_ADAPTIVE_RAY_MIP_MAP:
desc.addDefine("TRACE_ADAPTIVE_RAY_MIP_MAP", "1");
break;
default:
break;
}
if (mFastPhotonPath)
{
desc.addDefine("FAST_PHOTON_PATH", "1");
}
if (mShrinkColorPayload)
{
desc.addDefine("SMALL_COLOR", "1");
}
if (mShrinkRayDiffPayload)
{
desc.addDefine("SMALL_RAY_DIFFERENTIAL", "1");
}
if (mUpdatePhoton)
{
desc.addDefine("UPDATE_PHOTON", "1");
}
uint payLoadSize = 80U;
if (mShrinkColorPayload)
payLoadSize -= 12U;
if (mShrinkRayDiffPayload)
payLoadSize -= 24U;
auto pPhotonTraceProgram = RtProgram::create(desc, payLoadSize, 8U);
auto pPhotonTraceState = RtState::create();
pPhotonTraceState->setProgram(pPhotonTraceProgram);
auto pPhotonTraceVars = RtProgramVars::create(pPhotonTraceProgram, mpScene);
mPhotonTraceShaderList[flag] = { pPhotonTraceProgram , pPhotonTraceVars ,pPhotonTraceState };
}
return mPhotonTraceShaderList[flag];
}
void Caustics::loadSceneSetting(std::string path)
{
std::ifstream file(path, std::ios::in);
if (!file)
{
return;
}
file >> mLightAngle.x >> mLightAngle.y;
float3 camOri, camTarget;
file >> camOri.x >> camOri.y >> camOri.z;
file >> camTarget.x >> camTarget.y >> camTarget.z;
mpCamera->setPosition(camOri);
mpCamera->setTarget(camTarget);
}
void Caustics::saveSceneSetting(std::string path)
{
if (path.find(".ini") == std::string::npos)
{
path += ".ini";
}
std::ofstream file(path, std::ios::out);
if (!file)
{
return;
}
file << mLightAngle.x << " " << mLightAngle.y << std::endl;
float3 camOri = mpCamera->getPosition();
float3 camTarget = mpCamera->getTarget();
file << camOri.x << " " << camOri.y << " " << camOri.z << std::endl;
file << camTarget.x << " " << camTarget.y << " " << camTarget.z << std::endl;
}
void Caustics::createCausticsMap()
{
uint32_t width = mpRtOut->getWidth();
uint32_t height = mpRtOut->getHeight();
uint2 dim(width / mCausticsMapResRatio, height / mCausticsMapResRatio);
mpSmallPhotonTex = Texture::create2D(dim.x, dim.y, ResourceFormat::R32Uint, 1, 1, nullptr, Resource::BindFlags::RenderTarget | Resource::BindFlags::ShaderResource | Resource::BindFlags::UnorderedAccess);
auto pPhotonMapTex = Texture::create2D(dim.x, dim.y, ResourceFormat::RGBA16Float, 1, 1, nullptr, Resource::BindFlags::RenderTarget | Resource::BindFlags::ShaderResource | Resource::BindFlags::UnorderedAccess);
auto depthTex = Texture::create2D(dim.x, dim.y, ResourceFormat::D24UnormS8, 1, 1, nullptr, Resource::BindFlags::DepthStencil);
mpCausticsFbo[0] = Fbo::create({ pPhotonMapTex }, depthTex);
pPhotonMapTex = Texture::create2D(dim.x, dim.y, ResourceFormat::RGBA16Float, 1, 1, nullptr, Resource::BindFlags::RenderTarget | Resource::BindFlags::ShaderResource | Resource::BindFlags::UnorderedAccess);
mpCausticsFbo[1] = Fbo::create({ pPhotonMapTex }, depthTex);
}
void Caustics::createGBuffer(int width, int height, GBuffer& gbuffer)
{
gbuffer.mpDepthTex = Texture::create2D(width, height, ResourceFormat::D24UnormS8, 1, 1, nullptr, Resource::BindFlags::DepthStencil | Resource::BindFlags::ShaderResource);
gbuffer.mpNormalTex = Texture::create2D(width, height, ResourceFormat::RGBA16Float, 1, 1, nullptr, Resource::BindFlags::RenderTarget | Resource::BindFlags::ShaderResource);
gbuffer.mpDiffuseTex = Texture::create2D(width, height, ResourceFormat::RGBA16Float, 1, 1, nullptr, Resource::BindFlags::RenderTarget | Resource::BindFlags::ShaderResource);
gbuffer.mpSpecularTex = Texture::create2D(width, height, ResourceFormat::RGBA16Float, 1, 1, nullptr, Resource::BindFlags::RenderTarget | Resource::BindFlags::ShaderResource);
gbuffer.mpGPassFbo = Fbo::create({ gbuffer.mpNormalTex , gbuffer.mpDiffuseTex ,gbuffer.mpSpecularTex }, gbuffer.mpDepthTex);//Fbo::create2D(width, height, ResourceFormat::RGBA16Float, ResourceFormat::D24UnormS8);
}
int2 Caustics::getTileDim() const
{
int2 tileDim;
tileDim.x = (mpRtOut->getWidth() / mCausticsMapResRatio + mTileSize.x - 1) / mTileSize.x;
tileDim.y = (mpRtOut->getHeight() / mCausticsMapResRatio + mTileSize.y - 1) / mTileSize.y;
return tileDim;
}
float Caustics::resolutionFactor()
{
float2 res(mpRtOut->getWidth(), mpRtOut->getHeight());
float2 refRes(1920, 1080);
return glm::length(res) / glm::length(refRes);
}
uint Caustics::photonMacroToFlags()
{
uint flags = 0;
flags |= (1 << mPhotonTraceMacro); // 3 bits
flags |= ((1 << mTraceType) << 3); // 4 bits
if (mFastPhotonPath)
flags |= (1 << 7); // 1 bits
if (mShrinkColorPayload)
flags |= (1 << 8); // 1 bits
if (mShrinkRayDiffPayload)
flags |= (1 << 9); // 1 bits
if (mUpdatePhoton)
flags |= (1 << 10); // 1 bits
return flags;
}
void Caustics::loadShader()
{
// raytrace
RtProgram::Desc rtProgDesc;
rtProgDesc.addShaderLibrary("Caustics.rt.hlsl");
rtProgDesc.setRayGen("rayGen");
rtProgDesc.addHitGroup(0, "primaryClosestHit", "");
rtProgDesc.addMiss(0, "primaryMiss");
rtProgDesc.addHitGroup(1, "", "shadowAnyHit");
rtProgDesc.addMiss(1, "shadowMiss");
mpRaytraceProgram = RtProgram::create(rtProgDesc);
mpRtState = RtState::create();
mpRtState->setProgram(mpRaytraceProgram);
mpRtState->setMaxTraceRecursionDepth(3);
mpRtVars = RtProgramVars::create(mpRaytraceProgram, mpScene);
// clear draw argument program
mpDrawArgumentProgram = ComputeProgram::createFromFile("ResetDrawArgument.cs.hlsl", "main");
mpDrawArgumentState = ComputeState::create();
mpDrawArgumentState->setProgram(mpDrawArgumentProgram);
mpDrawArgumentVars = ComputeVars::create(mpDrawArgumentProgram.get());
// photon trace
mPhotonTraceShaderList.clear();
getPhotonTraceShader();
// composite rt
{
RtProgram::Desc desc;
desc.addShaderLibrary("CompositeRT.rt.hlsl");
desc.setRayGen("rayGen");
desc.addHitGroup(0, "primaryClosestHit", "");
desc.addHitGroup(1, "", "shadowAnyHit").addMiss(1, "shadowMiss");
desc.addMiss(0, "primaryMiss");
desc.addMiss(1, "shadowMiss");
mpCompositeRTProgram = RtProgram::create(desc,48);
mpCompositeRTState = RtState::create();
mpCompositeRTState->setProgram(mpCompositeRTProgram);
mpCompositeRTVars = RtProgramVars::create(mpCompositeRTProgram, mpScene);
}
// update ray density texture
mpUpdateRayDensityProgram = ComputeProgram::createFromFile("UpdateRayDensity.cs.hlsl", "updateRayDensityTex");
mpUpdateRayDensityState = ComputeState::create();
mpUpdateRayDensityState->setProgram(mpUpdateRayDensityProgram);
mpUpdateRayDensityVars = ComputeVars::create(mpUpdateRayDensityProgram.get());
// analyse trace result
mpAnalyseProgram = ComputeProgram::createFromFile("AnalyseTraceResult.cs.hlsl", "addPhotonTaskFromTexture");
mpAnalyseState = ComputeState::create();
mpAnalyseState->setProgram(mpAnalyseProgram);
mpAnalyseVars = ComputeVars::create(mpAnalyseProgram.get());
// generate ray count tex
mpGenerateRayCountProgram = ComputeProgram::createFromFile("GenerateRayCountMipmap.cs.hlsl", "generateMip0");
mpGenerateRayCountState = ComputeState::create();
mpGenerateRayCountState->setProgram(mpGenerateRayCountProgram);
mpGenerateRayCountVars = ComputeVars::create(mpGenerateRayCountProgram.get());
// generate ray count mip tex
mpGenerateRayCountMipProgram = ComputeProgram::createFromFile("GenerateRayCountMipmap.cs.hlsl", "generateMipLevel");
mpGenerateRayCountMipState = ComputeState::create();
mpGenerateRayCountMipState->setProgram(mpGenerateRayCountMipProgram);
mpGenerateRayCountMipVars = ComputeVars::create(mpGenerateRayCountMipProgram.get());
// smooth photon
mpSmoothProgram = ComputeProgram::createFromFile("SmoothPhoton.cs.hlsl", "main");
mpSmoothState = ComputeState::create();
mpSmoothState->setProgram(mpSmoothProgram);
mpSmoothVars = ComputeVars::create(mpSmoothProgram.get());
// allocate tile
const char* shaderEntries[] = { "OrthogonalizePhoton", "CountTilePhoton","AllocateMemory","StoreTilePhoton" };
for (int i = 0; i < GATHER_PROCESSING_SHADER_COUNT; i++)
{
mpAllocateTileProgram[i] = ComputeProgram::createFromFile("AllocateTilePhoton.cs.hlsl", shaderEntries[i]);
mpAllocateTileState[i] = ComputeState::create();
mpAllocateTileState[i]->setProgram(mpAllocateTileProgram[i]);
mpAllocateTileVars[i] = ComputeVars::create(mpAllocateTileProgram[i].get());
}
// photon gather
mpPhotonGatherProgram = ComputeProgram::createFromFile("PhotonGather.cs.hlsl", "main");
mpPhotonGatherState = ComputeState::create();
mpPhotonGatherState->setProgram(mpPhotonGatherProgram);
mpPhotonGatherVars = ComputeVars::create(mpPhotonGatherProgram.get());
// photon scatter
{
BlendState::Desc blendDesc;
blendDesc.setRtBlend(0, true);
blendDesc.setRtParams(0, BlendState::BlendOp::Add, BlendState::BlendOp::Add, BlendState::BlendFunc::One, BlendState::BlendFunc::One, BlendState::BlendFunc::One, BlendState::BlendFunc::One);
BlendState::SharedPtr scatterBlendState = BlendState::create(blendDesc);
mpPhotonScatterProgram = GraphicsProgram::createFromFile("PhotonScatter.ps.hlsl", "photonScatterVS", "photonScatterPS");
DepthStencilState::Desc dsDesc;
dsDesc.setDepthEnabled(false);
dsDesc.setDepthWriteMask(false);
auto depthStencilState = DepthStencilState::create(dsDesc);
RasterizerState::Desc rasterDesc;
rasterDesc.setCullMode(RasterizerState::CullMode::None);
static int32_t depthBias = -8;
static float slopeBias = -16;
rasterDesc.setDepthBias(depthBias, slopeBias);
auto rasterState = RasterizerState::create(rasterDesc);
mpPhotonScatterBlendState = GraphicsState::create();
mpPhotonScatterBlendState->setProgram(mpPhotonScatterProgram);
mpPhotonScatterBlendState->setBlendState(scatterBlendState);
mpPhotonScatterBlendState->setDepthStencilState(depthStencilState);
mpPhotonScatterBlendState->setRasterizerState(rasterState);
mpPhotonScatterNoBlendState = GraphicsState::create();
mpPhotonScatterNoBlendState->setProgram(mpPhotonScatterProgram);
mpPhotonScatterBlendState->setDepthStencilState(depthStencilState);
mpPhotonScatterNoBlendState->setRasterizerState(rasterState);
mpPhotonScatterVars = GraphicsVars::create(mpPhotonScatterProgram->getReflector());
}
// temporal filter
mpFilterProgram = ComputeProgram::createFromFile("TemporalFilter.cs.hlsl", "main");
mpFilterState = ComputeState::create();
mpFilterState->setProgram(mpFilterProgram);
mpFilterVars = ComputeVars::create(mpFilterProgram.get());
// spacial filter
mpSpacialFilterProgram = ComputeProgram::createFromFile("SpacialFilter.cs.hlsl", "main");
mpSpacialFilterState = ComputeState::create();
mpSpacialFilterState->setProgram(mpSpacialFilterProgram);
mpSpacialFilterVars = ComputeVars::create(mpSpacialFilterProgram.get());
mpRtRenderer = RtSceneRenderer::create(mpScene);
mpRasterPass = RasterScenePass::create(mpScene, "Caustics.ps.hlsl", "", "main");
mpGPass = RasterScenePass::create(mpScene, "GPass.ps.hlsl", "", "gpassPS");
mpCompositePass = FullScreenPass::create("Composite.ps.hlsl");
Sampler::Desc samplerDesc;
samplerDesc.setFilterMode(Sampler::Filter::Linear, Sampler::Filter::Linear, Sampler::Filter::Linear);
samplerDesc.setAddressingMode(Sampler::AddressMode::Border, Sampler::AddressMode::Border, Sampler::AddressMode::Border);
mpLinearSampler = Sampler::create(samplerDesc);
samplerDesc.setFilterMode(Sampler::Filter::Point, Sampler::Filter::Point, Sampler::Filter::Point);
mpPointSampler = Sampler::create(samplerDesc);
}
Caustics::Caustics() {}
void Caustics::onLoad(RenderContext* pRenderContext)
{
if (gpDevice->isFeatureSupported(Device::SupportedFeatures::Raytracing) == false)
{
logErrorAndExit("Device does not support raytracing!");
}
loadScene(kDefaultScene, gpFramework->getTargetFbo().get());
loadSceneSetting("Data/init.ini");
loadShader();
}
void Caustics::setCommonVars(GraphicsVars* pVars, const Fbo* pTargetFbo)
{
ConstantBuffer::SharedPtr pCB = pVars->getConstantBuffer("PerFrameCB");
//pCB["invView"] = glm::inverse(mpCamera->getViewMatrix());
//pCB["viewportDims"] = vec2(pTargetFbo->getWidth(), pTargetFbo->getHeight());
//pCB["emitSize"] = mEmitSize;
//float fovY = focalLengthToFovY(mpCamera->getFocalLength(), Camera::kDefaultFrameHeight);
//pCB["tanHalfFovY"] = tanf(fovY * 0.5f);
//pCB["sampleIndex"] = mSampleIndex;
//pCB["useDOF"] = false;// mUseDOF;
}
void Caustics::setPerFrameVars(const Fbo* pTargetFbo)
{
PROFILE("setPerFrameVars");
{
GraphicsVars* pVars = mpRtVars->getGlobalVars().get();
ConstantBuffer::SharedPtr pCB = pVars->getConstantBuffer("PerFrameCB");
pCB["invView"] = glm::inverse(mpCamera->getViewMatrix());
pCB["viewportDims"] = vec2(pTargetFbo->getWidth(), pTargetFbo->getHeight());
float fovY = focalLengthToFovY(mpCamera->getFocalLength(), Camera::kDefaultFrameHeight);
pCB["tanHalfFovY"] = tanf(fovY * 0.5f);
pCB["sampleIndex"] = mSampleIndex;
pCB["useDOF"] = mUseDOF;
}
//setCommonVars(mpRtVars->getGlobalVars().get(), pTargetFbo);
mSampleIndex++;
}
float2 getRandomPoint(int i)
{
const double g = 1.32471795724474602596;
const double a1 = 1.0 / g;
const double a2 = 1.0 / (g * g);
double x = 0.5 + a1 * (i + 1);
double y = 0.5 + a2 * (i + 1);
float xF = float(x - floor(x));
float yF = float(y - floor(y));
return float2(xF, yF);
}
void Caustics::setPhotonTracingCommonVariable(Caustics::PhotonTraceShader& shader)
{
}
void Caustics::renderRT(RenderContext* pContext, Fbo::SharedPtr pTargetFbo)
{
PROFILE("renderRT");
//setPerFrameVars(pTargetFbo.get());
// reset data
uint32_t statisticsOffset = uint32_t(mFrameCounter % mpPhotonCountTex->getWidth());
int thisIdx = mFrameCounter % 2;
int lastIdx = 1- thisIdx;
GBuffer* gBuffer = mGBuffer + thisIdx;
GBuffer* gBufferLast = mGBuffer + lastIdx;
Fbo::SharedPtr causticsFbo = mpCausticsFbo[thisIdx];
Fbo::SharedPtr causticsFboLast = mpCausticsFbo[lastIdx];
if (mUpdatePhoton)
{
ConstantBuffer::SharedPtr pPerFrameCB = mpDrawArgumentVars["PerFrameCB"];
pPerFrameCB["initRayCount"] = uint(mDispatchSize * mDispatchSize);
pPerFrameCB["coarseDim"] = uint2(mDispatchSize, mDispatchSize);
pPerFrameCB["textureOffset"] = statisticsOffset;
pPerFrameCB["scatterGeoIdxCount"] = mScatterGeometry == SCATTER_GEOMETRY_QUAD ? 6U : 12U;
mpDrawArgumentVars->setStructuredBuffer("gDrawArgument", mpDrawArgumentBuffer);
mpDrawArgumentVars->setStructuredBuffer("gRayArgument", mpRayArgumentBuffer);
//mpDrawArgumentVars->setStructuredBuffer("gPhotonBuffer", mpPhotonBuffer);
mpDrawArgumentVars->setStructuredBuffer("gPixelInfo", mpPixelInfoBuffer);
mpDrawArgumentVars->setTexture("gPhotonCountTexture", mpPhotonCountTex);
pContext->dispatch(mpDrawArgumentState.get(), mpDrawArgumentVars.get(), uvec3(mDispatchSize/16, mDispatchSize / 16, 1));
}
// gpass
{
pContext->clearFbo(gBuffer->mpGPassFbo.get(), vec4(0, 0, 0, 1), 1.0, 0);
mpGPass->renderScene(pContext, gBuffer->mpGPassFbo);
}
// photon tracing
if (mTraceType != TRACE_NONE)
{
pContext->clearUAV(mpSmallPhotonTex->getUAV().get(), uvec4(0, 0, 0, 0));
auto photonTraceShader = getPhotonTraceShader();
//setPhotonTracingCommonVariable(photonTraceShader);
GraphicsVars* pVars = photonTraceShader.mpPhotonTraceVars->getGlobalVars().get();
ConstantBuffer::SharedPtr pCB = pVars->getConstantBuffer("PerFrameCB");
float2 r = getRandomPoint(mFrameCounter) * 2.0f - 1.0f;
float2 sign(r.x > 0 ? 1 : -1, r.y > 0 ? 1 : -1);
float2 randomOffset = sign * float2(pow(abs(r.x), mJitterPower), pow(abs(r.y), mJitterPower)) * mJitter;
pCB["invView"] = glm::inverse(mpCamera->getViewMatrix());
pCB["viewportDims"] = vec2(mpRtOut->getWidth(), mpRtOut->getHeight());
pCB["emitSize"] = mEmitSize;
pCB["roughThreshold"] = mRoughThreshold;
pCB["randomOffset"] = mTemporalFilter ? randomOffset : float2(0, 0);
pCB["rayTaskOffset"] = mDispatchSize * mDispatchSize;
pCB["coarseDim"] = uint2(mDispatchSize, mDispatchSize);
pCB["maxDepth"] = mMaxTraceDepth;
pCB["iorOverride"] = mIOROveride;
pCB["colorPhotonID"] = (uint32_t)mColorPhoton;
pCB["photonIDScale"] = mPhotonIDScale;
pCB["traceColorThreshold"] = mTraceColorThreshold * (512 * 512) / (mDispatchSize * mDispatchSize);
pCB["cullColorThreshold"] = mCullColorThreshold / 255;
pCB["gAreaType"] = (uint32_t)mAreaType;
pCB["gIntensity"] = mIntensity / 1000;
pCB["gSplatSize"] = mSplatSize;
pCB["updatePhoton"] = (uint32_t)mUpdatePhoton;
pCB["gMinDrawCount"] = mFastPhotonDrawCount;
pCB["gMinScreenRadius"] = mFastPhotonPixelRadius * resolutionFactor();
pCB["gMaxScreenRadius"] = mMaxPhotonPixelRadius * resolutionFactor();
pCB["gMipmap"] = int(log(mDispatchSize) / log(2));
pCB["gSmallPhotonColorScale"] = mSmallPhotonCompressScale;
pCB["cameraPos"] = mpCamera->getPosition();
auto rayGenVars = photonTraceShader.mpPhotonTraceVars->getRayGenVars();
rayGenVars->setStructuredBuffer("gPhotonBuffer", mpPhotonBuffer);
rayGenVars->setStructuredBuffer("gRayTask", mpRayTaskBuffer);
rayGenVars->setStructuredBuffer("gRayArgument", mpRayArgumentBuffer);
rayGenVars->setStructuredBuffer("gPixelInfo", mpPixelInfoBuffer);
rayGenVars->setTexture("gUniformNoise", mpUniformNoise);
rayGenVars->setStructuredBuffer("gDrawArgument", mpDrawArgumentBuffer);
rayGenVars->setStructuredBuffer("gRayCountQuadTree", mpRayCountQuadTree);
rayGenVars->setTexture("gRayDensityTex", mpRayDensityTex);
rayGenVars->setTexture("gSmallPhotonBuffer", mpSmallPhotonTex);
rayGenVars->setTexture("gPhotonTexture", causticsFboLast->getColorTexture(0));
auto hitVars = photonTraceShader.mpPhotonTraceVars->getHitVars(0);
for (auto& hitVar : hitVars)
{
hitVar->setStructuredBuffer("gPixelInfo", mpPixelInfoBuffer);
hitVar->setStructuredBuffer("gPhotonBuffer", mpPhotonBuffer);
hitVar->setStructuredBuffer("gDrawArgument", mpDrawArgumentBuffer);
hitVar->setStructuredBuffer("gRayTask", mpRayTaskBuffer);
}
photonTraceShader.mpPhotonTraceState->setMaxTraceRecursionDepth(1);
uvec3 resolution = mTraceType == TRACE_FIXED ? uvec3(mDispatchSize, mDispatchSize, 1) : uvec3(2048, 4096, 1);
mpRtRenderer->renderScene(pContext, photonTraceShader.mpPhotonTraceVars, photonTraceShader.mpPhotonTraceState, resolution, mpCamera.get());
}
// analysis output
if ( mUpdatePhoton)
{
if(mTraceType == TRACE_ADAPTIVE || mTraceType == TRACE_ADAPTIVE_RAY_MIP_MAP)
{
ConstantBuffer::SharedPtr pPerFrameCB = mpUpdateRayDensityVars["PerFrameCB"];
pPerFrameCB["coarseDim"] = int2(mDispatchSize, mDispatchSize);
pPerFrameCB["minPhotonPixelSize"] = mMinPhotonPixelSize * resolutionFactor();
pPerFrameCB["smoothWeight"] = mSmoothWeight;
pPerFrameCB["maxTaskPerPixel"] = (int)mMaxTaskCountPerPixel;
pPerFrameCB["updateSpeed"] = mUpdateSpeed;
pPerFrameCB["varianceGain"] = mVarianceGain;
pPerFrameCB["derivativeGain"] = mDerivativeGain;
mpUpdateRayDensityVars->setStructuredBuffer("gPixelInfo", mpPixelInfoBuffer);
mpUpdateRayDensityVars->setStructuredBuffer("gRayArgument", mpRayArgumentBuffer);
mpUpdateRayDensityVars->setTexture("gRayDensityTex", mpRayDensityTex);
static int groupSize = 16;
pContext->dispatch(mpUpdateRayDensityState.get(), mpUpdateRayDensityVars.get(), uvec3(mDispatchSize / groupSize, mDispatchSize / groupSize, 1));
}
if (mTraceType == TRACE_ADAPTIVE)
{
ConstantBuffer::SharedPtr pPerFrameCB = mpAnalyseVars["PerFrameCB"];
glm::mat4 wvp = mpCamera->getProjMatrix() * mpCamera->getViewMatrix();
pPerFrameCB["viewProjMat"] = wvp;// mpCamera->getViewProjMatrix();
pPerFrameCB["taskDim"] = int2(mDispatchSize, mDispatchSize);
pPerFrameCB["screenDim"] = int2(mpRtOut->getWidth(), mpRtOut->getHeight());
pPerFrameCB["normalThreshold"] = mNormalThreshold;
pPerFrameCB["distanceThreshold"] = mDistanceThreshold;
pPerFrameCB["planarThreshold"] = mPlanarThreshold;
pPerFrameCB["samplePlacement"] = (uint32_t)mSamplePlacement;
pPerFrameCB["pixelLuminanceThreshold"] = mPixelLuminanceThreshold;
pPerFrameCB["minPhotonPixelSize"] = mMinPhotonPixelSize * resolutionFactor();
static float2 offset(0.5, 0.5);
static float speed = 0.0f;
pPerFrameCB["randomOffset"] = offset;
offset += speed;
mpAnalyseVars->setStructuredBuffer("gPhotonBuffer", mpPhotonBuffer);
mpAnalyseVars->setStructuredBuffer("gRayArgument", mpRayArgumentBuffer);
mpAnalyseVars->setStructuredBuffer("gRayTask", mpRayTaskBuffer);
mpAnalyseVars->setStructuredBuffer("gPixelInfo", mpPixelInfoBuffer);
mpAnalyseVars->setTexture("gDepthTex", gBuffer->mpGPassFbo->getDepthStencilTexture());
mpAnalyseVars->setTexture("gRayDensityTex", mpRayDensityTex);
int2 groupSize(32, 16);
pContext->dispatch(mpAnalyseState.get(), mpAnalyseVars.get(), uvec3(mDispatchSize / groupSize.x, mDispatchSize / groupSize.y, 1));
}
else if (mTraceType == TRACE_ADAPTIVE_RAY_MIP_MAP)
{
int startMipLevel = int(log(mDispatchSize) / log(2)) - 1;
{
ConstantBuffer::SharedPtr pPerFrameCB = mpGenerateRayCountVars["PerFrameCB"];
pPerFrameCB["taskDim"] = int2(mDispatchSize, mDispatchSize);
pPerFrameCB["screenDim"] = int2(mpRtOut->getWidth(), mpRtOut->getHeight());
pPerFrameCB["mipLevel"] = startMipLevel;
mpGenerateRayCountVars->setStructuredBuffer("gRayArgument", mpRayArgumentBuffer);
mpGenerateRayCountVars->setTexture("gRayDensityTex", mpRayDensityTex);
mpGenerateRayCountVars->setStructuredBuffer("gRayCountQuadTree", mpRayCountQuadTree);
int2 groupSize(8, 8);
uvec3 blockCount(mDispatchSize / groupSize.x / 2, mDispatchSize / groupSize.y / 2, 1);
pContext->dispatch(mpGenerateRayCountState.get(), mpGenerateRayCountVars.get(), blockCount);
}
for (int mipLevel = startMipLevel - 1, dispatchSize = mDispatchSize / 4; mipLevel >= 0; mipLevel--, dispatchSize >>= 1)
{
ConstantBuffer::SharedPtr pPerFrameCB = mpGenerateRayCountMipVars["PerFrameCB"];
pPerFrameCB["taskDim"] = int2(mDispatchSize, mDispatchSize);
pPerFrameCB["screenDim"] = int2(mpRtOut->getWidth(), mpRtOut->getHeight());
pPerFrameCB["mipLevel"] = mipLevel;
mpGenerateRayCountMipVars->setStructuredBuffer("gRayArgument", mpRayArgumentBuffer);
mpGenerateRayCountMipVars->setTexture("gRayDensityTex", mpRayDensityTex);
mpGenerateRayCountMipVars->setStructuredBuffer("gRayCountQuadTree", mpRayCountQuadTree);
int2 groupSize(8, 8);
uvec3 blockCount((dispatchSize + groupSize.x - 1) / groupSize.x, (dispatchSize + groupSize.y - 1) / groupSize.y, 1);
pContext->dispatch(mpGenerateRayCountMipState.get(), mpGenerateRayCountMipVars.get(), blockCount);
}
}
}
// smooth photon
StructuredBuffer::SharedPtr photonBuffer = mpPhotonBuffer;
if (mRemoveIsolatedPhoton || mMedianFilter)
{
ConstantBuffer::SharedPtr pPerFrameCB = mpSmoothVars["PerFrameCB"];
glm::mat4 wvp = mpCamera->getProjMatrix() * mpCamera->getViewMatrix();
pPerFrameCB["viewProjMat"] = wvp;// mpCamera->getViewProjMatrix();
pPerFrameCB["taskDim"] = int2(mDispatchSize, mDispatchSize);
pPerFrameCB["screenDim"] = int2(mpRtOut->getWidth(), mpRtOut->getHeight());
pPerFrameCB["normalThreshold"] = mNormalThreshold;
pPerFrameCB["distanceThreshold"] = mDistanceThreshold;
pPerFrameCB["planarThreshold"] = mPlanarThreshold;
pPerFrameCB["pixelLuminanceThreshold"] = mPixelLuminanceThreshold;
pPerFrameCB["minPhotonPixelSize"] = mMinPhotonPixelSize * resolutionFactor();
pPerFrameCB["trimDirectionThreshold"] = trimDirectionThreshold;
pPerFrameCB["enableMedianFilter"] = uint32_t(mMedianFilter);
pPerFrameCB["removeIsolatedPhoton"] = uint32_t(mRemoveIsolatedPhoton);
pPerFrameCB["minNeighbourCount"] = mMinNeighbourCount;
mpSmoothVars->setStructuredBuffer("gSrcPhotonBuffer", mpPhotonBuffer);
mpSmoothVars->setStructuredBuffer("gDstPhotonBuffer", mpPhotonBuffer2);
mpSmoothVars->setStructuredBuffer("gRayArgument", mpRayArgumentBuffer);
mpSmoothVars->setStructuredBuffer("gRayTask", mpPixelInfoBuffer);
mpSmoothVars->setTexture("gDepthTex", gBuffer->mpGPassFbo->getDepthStencilTexture());
static int groupSize = 16;
pContext->dispatch(mpSmoothState.get(), mpSmoothVars.get(), uvec3(mDispatchSize / groupSize, mDispatchSize / groupSize, 1));
photonBuffer = mpPhotonBuffer2;
}
// photon scattering
if(mScatterOrGather == DENSITY_ESTIMATION_SCATTER)
{
pContext->clearRtv(causticsFbo->getColorTexture(0)->getRTV().get(), vec4(0, 0, 0, 0));
glm::mat4 wvp = mpCamera->getProjMatrix() * mpCamera->getViewMatrix();
glm::mat4 invP = glm::inverse(mpCamera->getProjMatrix());
ConstantBuffer::SharedPtr pPerFrameCB = mpPhotonScatterVars["PerFrameCB"];
pPerFrameCB["gWorldMat"] = glm::mat4();
pPerFrameCB["gWvpMat"] = wvp;
pPerFrameCB["gInvProjMat"] = invP;
pPerFrameCB["gEyePosW"] = mpCamera->getPosition();
pPerFrameCB["gSplatSize"] = mSplatSize;
pPerFrameCB["gPhotonMode"] = (uint)mPhotonMode;
pPerFrameCB["gKernelPower"] = mKernelPower;
pPerFrameCB["gShowPhoton"] = uint32_t(mPhotonDisplayMode);
pPerFrameCB["gLightDir"] = mLightDirection;
pPerFrameCB["taskDim"] = int2(mDispatchSize, mDispatchSize);
pPerFrameCB["screenDim"] = int2(mpRtOut->getWidth(), mpRtOut->getHeight());
pPerFrameCB["normalThreshold"] = mScatterNormalThreshold;
pPerFrameCB["distanceThreshold"] = mScatterDistanceThreshold;
pPerFrameCB["planarThreshold"] = mScatterPlanarThreshold;
pPerFrameCB["gMaxAnisotropy"] = mMaxAnisotropy;
pPerFrameCB["gCameraPos"] = mpCamera->getPosition();
pPerFrameCB["gZTolerance"] = mZTolerance;
pPerFrameCB["gResRatio"] = mCausticsMapResRatio;
mpPhotonScatterVars["gLinearSampler"] = mpLinearSampler;
mpPhotonScatterVars->setStructuredBuffer("gPhotonBuffer", photonBuffer);
mpPhotonScatterVars->setStructuredBuffer("gRayTask", mpPixelInfoBuffer);
mpPhotonScatterVars->setTexture("gDepthTex", gBuffer->mpGPassFbo->getDepthStencilTexture());
mpPhotonScatterVars->setTexture("gNormalTex", gBuffer->mpGPassFbo->getColorTexture(0));
mpPhotonScatterVars->setTexture("gDiffuseTex", gBuffer->mpGPassFbo->getColorTexture(1));
mpPhotonScatterVars->setTexture("gSpecularTex", gBuffer->mpGPassFbo->getColorTexture(2));
mpPhotonScatterVars->setTexture("gGaussianTex", mpGaussianKernel);
int instanceCount = mDispatchSize * mDispatchSize;
GraphicsState::SharedPtr scatterState;
if (mPhotonDisplayMode == 2)
{
scatterState = mpPhotonScatterNoBlendState;
}
else
{
scatterState = mpPhotonScatterBlendState;
}
if (mScatterGeometry == SCATTER_GEOMETRY_QUAD)
scatterState->setVao(mpQuad->getMesh(0)->getVao());
else
scatterState->setVao(mpSphere->getMesh(0)->getVao());
scatterState->setFbo(causticsFbo);
if (mPhotonMode == PHOTON_MODE_PHOTON_MESH)
{
pContext->drawIndexedInstanced(scatterState.get(), mpPhotonScatterVars.get(), 6, mDispatchSize* mDispatchSize, 0, 0, 0);
}
else
{
pContext->drawIndexedIndirect(scatterState.get(), mpPhotonScatterVars.get(), mpDrawArgumentBuffer.get(), 0);
}
}
else if (mScatterOrGather == DENSITY_ESTIMATION_GATHER)
{
int2 tileDim = getTileDim();
int dimX, dimY;
if (mTraceType == TRACE_FIXED)
{
dimX = mDispatchSize;
dimY = mDispatchSize;
}