-
Notifications
You must be signed in to change notification settings - Fork 193
/
VulkanPostProcessing.cpp
4834 lines (4060 loc) · 256 KB
/
VulkanPostProcessing.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
/*!
\brief Shows how to implement post processing in vulkan.
\file VulkanPostProcessing.cpp
\author PowerVR by Imagination, Developer Technology Team
\copyright Copyright (c) Imagination Technologies Limited.
*/
#include "PVRShell/PVRShell.h"
#include "PVRUtils/PVRUtilsVk.h"
#include "PVRCore/cameras/TPSCamera.h"
namespace BufferEntryNames {
namespace PerMesh {
const char* const MVPMatrix = "mvpMatrix";
const char* const WorldMatrix = "worldMatrix";
} // namespace PerMesh
namespace Scene {
const char* const EyePosition = "eyePosition";
const char* const InverseViewProjectionMatrix = "inverseViewProjectionMatrix";
} // namespace Scene
} // namespace BufferEntryNames
// Bloom modes
enum class BloomMode
{
NoBloom = 0,
GaussianOriginal,
GaussianLinear,
Compute,
HybridGaussian,
GaussianLinearTruncated,
Kawase,
DualFilter,
TentFilter,
NumBloomModes,
DefaultMode = GaussianLinearTruncated
};
// Titles for the various bloom modes
const std::string BloomStrings[] = { "Original Image (No Post Processing)", "Gaussian (Reference Implementation)", "Gaussian (Linear Sampling)",
"Gaussian (Compute Sliding Average)", "Hybrid Gaussian", "Truncated Gaussian (Linear Sampling)", "Kawase", "Dual Filter", "Tent Filter" };
// Files used throughout the demo
namespace Files {
// Shader file names
const char Downsample4x4VertSrcFile[] = "Downsample4x4VertShader.vsh.spv";
const char Downsample4x4FragSrcFile[] = "Downsample4x4FragShader.fsh.spv";
// Dual Filter shaders
const char DualFilterDownSampleFragSrcFile[] = "DualFilterDownSampleFragShader.fsh.spv";
const char DualFilterUpSampleFragSrcFile[] = "DualFilterUpSampleFragShader.fsh.spv";
const char DualFilterUpSampleMergedFinalPassFragSrcFile[] = "DualFilterUpSampleMergedFinalPassFragShader.fsh.spv";
const char DualFilterDownVertSrcFile[] = "DualFilterDownVertShader.vsh.spv";
const char DualFilterUpVertSrcFile[] = "DualFilterUpVertShader.vsh.spv";
// Tent Filter shaders
const char TentFilterUpSampleVertSrcFile[] = "TentFilterUpSampleVertShader.vsh.spv";
const char TentFilterFirstUpSampleFragSrcFile[] = "TentFilterFirstUpSampleFragShader.fsh.spv";
const char TentFilterUpSampleFragSrcFile[] = "TentFilterUpSampleFragShader.fsh.spv";
const char TentFilterUpSampleMergedFinalPassFragSrcFile[] = "TentFilterUpSampleMergedFinalPassFragShader.fsh.spv";
// Kawase Blur shaders
const char KawaseVertSrcFile[] = "KawaseVertShader.vsh.spv";
const char KawaseFragSrcFile[] = "KawaseFragShader.fsh.spv";
// Traditional Gaussian Blur shaders
const char GaussianFragSrcFile[] = "GaussianBlurFragmentShader.fsh.template";
const char GaussianVertSrcFile[] = "GaussianVertShader.vsh.spv";
// Linear Sampler Optimised Gaussian Blur shaders
const char LinearGaussianVertSrcFile[] = "LinearGaussianBlurVertexShader.vsh.template";
const char LinearGaussianFragSrcFile[] = "LinearGaussianBlurFragmentShader.fsh.template";
// Compute based sliding average Gaussian Blur shaders
const char GaussianComputeBlurHorizontalSrcFile[] = "ComputeGaussianBlurHorizontalShader.csh.template";
const char GaussianComputeBlurVerticalSrcFile[] = "ComputeGaussianBlurVerticalShader.csh.template";
// Post Bloom Shaders
const char PostBloomVertShaderSrcFile[] = "PostBloomVertShader.vsh.spv";
const char PostBloomFragShaderSrcFile[] = "PostBloomFragShader.fsh.spv";
// Scene Rendering shaders
const char FragShaderSrcFile[] = "FragShader.fsh.spv";
const char VertShaderSrcFile[] = "VertShader.vsh.spv";
const char SkyboxFragShaderSrcFile[] = "SkyboxFragShader.fsh.spv";
const char SkyboxVertShaderSrcFile[] = "SkyboxVertShader.vsh.spv";
} // namespace Files
// POD scene files
const char SceneFile[] = "Satyr.pod";
// Texture files
const std::string StatueTexFile = "Marble";
const std::string StatueNormalMapTexFile = "MarbleNormalMap";
struct EnvironmentTextures
{
std::string skyboxTexture;
std::string diffuseIrradianceMapTexture;
float averageLuminance;
float keyValue;
float threshold;
float getLinearExposure() const { return keyValue / averageLuminance; }
};
float luma(glm::vec3 color) { return glm::max(glm::dot(color, glm::vec3(0.2126f, 0.7152f, 0.0722f)), 0.0001f); }
// The following were taken from the lowest mipmap of each of the corresponding irradiance textures
float sataraNightLuminance = luma((1.0f / 6.0f) *
(glm::vec3(55.0f, 42.0f, 13.0f) + glm::vec3(21.0f, 16.0f, 8.0f) + glm::vec3(7.0f, 5.0f, 6.0f) + glm::vec3(5.0f, 4.0f, 1.0f) + glm::vec3(72.0f, 57.0f, 19.0f) +
glm::vec3(14.0f, 10.0f, 5.0f)));
float pinkSunriseLuminance = luma((1.0f / 6.0f) *
(glm::vec3(104.0f, 76.0f, 106.0f) + glm::vec3(28.0f, 23.0f, 41.0f) + glm::vec3(137.0f, 110.0f, 197.0f) + glm::vec3(9.0f, 6.0f, 7.0f) + glm::vec3(129.0f, 89.0f, 113.0f) +
glm::vec3(28.0f, 27.0f, 54.0f)));
float signalHillSunriseLuminance = luma((1.0f / 6.0f) *
(glm::vec3(10.0f, 10.0f, 10.0f) + glm::vec3(4.0f, 4.0f, 6.0f) + glm::vec3(8.0f, 10.0f, 16.0f) + glm::vec3(4.0f, 2.0f, 0.0f) + glm::vec3(9.0f, 9.0f, 9.0f) +
glm::vec3(4.0f, 4.0f, 5.0f)));
// Textures
EnvironmentTextures SceneTexFileNames[] = { { "satara_night_scale_0.305_rgb9e5.pvr", "satara_night_scale_0.305_rgb9e5_Irradiance.pvr", sataraNightLuminance, 9.0f, 2.6f },
{ "pink_sunrise_rgb9e5.pvr", "pink_sunrise_rgb9e5_Irradiance.pvr", pinkSunriseLuminance, 50.0f, 0.65f },
{ "signal_hill_sunrise_scale_0.312_rgb9e5.pvr", "signal_hill_sunrise_scale_0.312_rgb9e5_Irradiance.pvr", signalHillSunriseLuminance, 23.0f, 0.85f } };
const int NumScenes = sizeof SceneTexFileNames / sizeof SceneTexFileNames[0];
// Various defaults
const float CameraNear = 1.0f;
const float CameraFar = 1000.0f;
const float RotateY = glm::pi<float>() / 150;
const float Fov = 0.80f;
const float MinimumAcceptibleCoefficient = 0.0003f;
const uint8_t MaxFilterIterations = 10;
const uint8_t MaxKawaseIteration = 5;
const uint8_t MaxGaussianKernel = 51;
const uint8_t MaxGaussianHalfKernel = (MaxGaussianKernel - 1) / 2 + 1;
const pvr::utils::VertexBindings VertexAttribBindings[] = {
{ "POSITION", 0 },
{ "NORMAL", 1 },
{ "UV0", 2 },
{ "TANGENT", 3 },
};
// Handles the configurations being used in the demo controlling how the various bloom techniques will operate
namespace DemoConfigurations {
// Wrapper for a Kawase pass including the number of iterations in use and their kernel sizes
struct KawasePass
{
uint32_t numIterations;
uint32_t kernel[MaxKawaseIteration];
};
// A wrapper for the demo configuration at any time
struct DemoConfiguration
{
uint32_t gaussianConfig;
uint32_t linearGaussianConfig;
uint32_t computeGaussianConfig;
uint32_t truncatedLinearGaussianConfig;
KawasePass kawaseConfig;
uint32_t dualFilterConfig;
uint32_t tentFilterConfig;
uint32_t hybridConfig;
};
const uint32_t NumDemoConfigurations = 5;
const uint32_t DefaultDemoConfigurations = 2;
DemoConfiguration Configurations[NumDemoConfigurations]{ // Demo Blur Configurations
DemoConfiguration{
5, // Original Gaussian Blur
5, // Linear Gaussian Blur
5, // Compute Gaussian Blur
5, // Truncated Linear Gaussian Blur
KawasePass{ 2, { 0, 0 } }, // Kawase Blur
2, // Dual Filter Blur
2, // Tent Filter
0, // Hybrid
},
DemoConfiguration{
15, // Original Gaussian Blur
15, // Linear Gaussian Blur
15, // Compute Gaussian Blur
11, // Truncated Linear Gaussian Blur
KawasePass{ 3, { 0, 0, 1 } }, // Kawase Blur
4, // Dual Filter Blur
4, // Tent Filter
0, // Hybrid
},
DemoConfiguration{
25, // Original Gaussian Blur
25, // Linear Gaussian Blur
25, // Compute Gaussian Blur
17, // Truncated Linear Gaussian Blur
KawasePass{ 4, { 0, 0, 1, 1 } }, // Kawase Blur
6, // Dual Filter Blur
6, // Tent Filter
0, // Hybrid
},
DemoConfiguration{
35, // Original Gaussian Blur
35, // Linear Gaussian Blur
35, // Compute Gaussian Blur
21, // Truncated Linear Gaussian Blur
KawasePass{ 4, { 0, 1, 1, 1 } }, // Kawase Blur
8, // Dual Filter Blur
8, // Tent Filter
0, // Hybrid
},
DemoConfiguration{
51, // Original Gaussian Blur
51, // Linear Gaussian Blur
51, // Compute Gaussian Blur
25, // Truncated Linear Gaussian Blur
KawasePass{ 5, { 0, 0, 1, 1, 2 } }, // Kawase Blur
10, // Dual Filter Blur
10, // Tent Filter
0, // Hybrid
}
};
} // namespace DemoConfigurations
/// <summary>Prints the Gaussian weights and offsets provided in the vectors.</summary>
/// <param name="gaussianWeights">The list of Gaussian weights to print.</param>
/// <param name="gaussianOffsets">The list of Gaussian offsets to print.</param>
/// <param name="iterationsString">A string defining the number of iterations.</param>
/// <param name="weightsString">A string defining the iteration set of weights.</param>
/// <param name="offsetsString">A string defining the iteration set of offsets.</param>
void generateGaussianWeightsAndOffsetsStrings(std::vector<double>& gaussianWeights, std::vector<double>& gaussianOffsets, std::string& iterationsString, std::string& weightsString,
std::string& offsetsString, bool duplicateWeightsStrings = false)
{
std::string weights;
for (uint32_t i = 0; i < gaussianWeights.size() - 1; ++i) { weights += pvr::strings::createFormatted("%.15f,", gaussianWeights[i]); }
weights += pvr::strings::createFormatted("%.15f", gaussianWeights[gaussianWeights.size() - 1]);
std::string offsets;
for (uint32_t i = 0; i < gaussianOffsets.size() - 1; ++i) { offsets += pvr::strings::createFormatted("%.15f,", gaussianOffsets[i]); }
offsets += pvr::strings::createFormatted("%.15f", gaussianOffsets[gaussianOffsets.size() - 1]);
if (duplicateWeightsStrings)
{
weights += "," + weights;
weightsString = pvr::strings::createFormatted("const mediump float gWeights[numIterations * 2] = {%s};", weights.c_str());
}
else
{
weightsString = pvr::strings::createFormatted("const mediump float gWeights[numIterations] = {%s};", weights.c_str());
offsetsString = pvr::strings::createFormatted("const mediump float gOffsets[numIterations] = {%s};", offsets.c_str());
}
iterationsString = pvr::strings::createFormatted("const uint numIterations = %uu;", gaussianWeights.size());
}
/// <summary>Updates the Gaussian weights and offsets using the configuration provided.</summary>
/// <param name="kernelSize">The kernel size to generate Gaussian weights and offsets for.</param>
/// <param name="useLinearOptimisation">Specifies whether linear sampling will be used when texture sampling using the given weights and offsets,
/// if linear sampling will be used then the weights and offsets must be adjusted accordingly.</param>
/// <param name="truncateCoefficients">Specifies whether to truncate and ignore coefficients which would provide a negligible change in the resulting blurred image.</param>
/// <param name="gaussianWeights">The returned list of Gaussian weights (as double).</param>
/// <param name="gaussianOffsets">The returned list of Gaussian offsets (as double).</param>
void generateGaussianCoefficients(uint32_t kernelSize, bool useLinearOptimisation, bool truncateCoefficients, std::vector<double>& gaussianWeights, std::vector<double>& gaussianOffsets)
{
// Ensure that the kernel given is odd in size
assertion((kernelSize - 1) % 2 == 0);
assertion(kernelSize <= MaxGaussianKernel);
// generate a new set of weights and offsets based on the given configuration
pvr::math::generateGaussianKernelWeightsAndOffsets(kernelSize, truncateCoefficients, useLinearOptimisation, gaussianWeights, gaussianOffsets, MinimumAcceptibleCoefficient);
}
bool queueFamiliesCompatible(pvrvk::ImageView& imageView, const uint32_t* queueFamilyIndices, uint32_t numQueueFamilyIndices)
{
for (uint32_t i = 0; i < numQueueFamilyIndices; ++i)
{
bool foundMatch = false;
for (uint32_t j = 0; j < imageView->getCreateInfo().getImage()->getNumQueueFamilyIndices(); ++j)
{
if (imageView->getCreateInfo().getImage()->getQueueFamilyIndices()[j] == queueFamilyIndices[i]) { foundMatch = true; }
}
if (!foundMatch) { return false; }
}
return true;
}
bool isCompatibleImageView(pvrvk::ImageView& imageView, pvrvk::ImageType imageType, pvrvk::Format format, const pvrvk::Extent3D& dimension, pvrvk::ImageUsageFlags usage,
const pvrvk::ImageLayersSize& layerSize, pvrvk::SampleCountFlags samples, pvrvk::MemoryPropertyFlags memoryFlags, pvrvk::SharingMode sharingMode, pvrvk::ImageTiling tiling,
const uint32_t* queueFamilyIndices, uint32_t numQueueFamilyIndices)
{
if (imageView)
{
if (imageView->getImage()->getImageType() == imageType && imageView->getImage()->getFormat() == format && imageView->getImage()->getExtent().getWidth() == dimension.getWidth() &&
imageView->getImage()->getExtent().getHeight() == dimension.getHeight() && imageView->getImage()->getExtent().getDepth() == dimension.getDepth() &&
static_cast<uint32_t>(imageView->getImage()->getUsageFlags() & usage) != 0 && imageView->getImage()->getNumArrayLayers() == layerSize.getNumArrayLevels() &&
imageView->getImage()->getNumMipLevels() == layerSize.getNumMipLevels() && imageView->getImage()->getNumSamples() == samples &&
static_cast<uint32_t>(imageView->getImage()->getDeviceMemory()->getMemoryFlags() & memoryFlags) != 0 && imageView->getImage()->getSharingMode() == sharingMode &&
imageView->getImage()->getTiling() == tiling && queueFamiliesCompatible(imageView, queueFamilyIndices, numQueueFamilyIndices))
{
return true;
}
}
return false;
}
void addImageToSharedImages(std::vector<std::vector<pvrvk::ImageView >> &sharedImageViews, pvrvk::ImageView& imageView, uint32_t currentSwapchainIndex)
{
// Naively add a new entry to the back of the shared image list if the swapchain is 0
// This requires that images are added in "swapchain order"
if (currentSwapchainIndex == 0)
{
sharedImageViews.resize(sharedImageViews.size() + 1);
sharedImageViews[sharedImageViews.size() - 1].push_back(imageView);
}
else
{
for (uint32_t i = 0; i < sharedImageViews.size(); ++i)
{
if (isCompatibleImageView(sharedImageViews[i][0], imageView->getImage()->getImageType(), imageView->getImage()->getFormat(), imageView->getImage()->getExtent(),
imageView->getImage()->getUsageFlags(), pvrvk::ImageLayersSize(imageView->getImage()->getNumArrayLayers(), imageView->getImage()->getNumMipLevels()),
imageView->getImage()->getNumSamples(), imageView->getImage()->getDeviceMemory()->getMemoryFlags(), imageView->getImage()->getSharingMode(),
imageView->getImage()->getTiling(), imageView->getImage()->getQueueFamilyIndices(), imageView->getImage()->getNumQueueFamilyIndices()))
{
sharedImageViews[i].push_back(imageView);
}
}
}
}
/// <summary>A simple pass used for rendering our statue object.</summary>
struct StatuePass
{
pvrvk::GraphicsPipeline pipeline;
pvrvk::PipelineLayout pipelineLayout;
pvrvk::ImageView albeoImageView;
pvrvk::ImageView normalMapImageView;
pvrvk::DescriptorSetLayout descriptorSetLayout;
std::vector<pvrvk::DescriptorSet> descriptorSets;
std::vector<pvrvk::SecondaryCommandBuffer> cmdBuffers;
pvr::utils::StructuredBufferView structuredBufferView;
pvrvk::Buffer buffer;
std::vector<pvrvk::Buffer> vbos;
std::vector<pvrvk::Buffer> ibos;
bool isASTCSupported;
// 3D Model
pvr::assets::ModelHandle scene;
/// <summary>Initialises the Statue pass.</summary>
/// <param name="assetProvider">The pvr::IAssetProvider which will be used for loading resources from memory.</param>
/// <param name="device">The device from which the resources will be allocated.</param>
/// <param name="swapchain">The swapchain which will determine the number of per swapchain resources to allocate.</param>
/// <param name="commandPool">The command pool from which to allocate command buffers.</param>
/// <param name="descriptorPool">The descriptor pool from which to allocate descriptor sets.</param>
/// <param name="renderpass">The RenderPass to use.</param>
/// <param name="framebuffers">The framebuffers to use.</param>
/// <param name="vmaAllocator">A VMA allocator to use for allocating images and buffers.</param>
/// <param name="utilityCommandBuffer">A command buffer to use for queueing up all initialisation commands. This command buffer will be submitted later by the main
/// application.</param>
/// <param name="pipelineCache">A pipeline cache object to use when creating pipelines.</param>
void init(pvr::IAssetProvider& assetProvider, pvrvk::Device& device, pvrvk::Swapchain& swapchain, pvrvk::CommandPool& commandPool, pvrvk::DescriptorPool& descriptorPool,
pvrvk::RenderPass& renderpass, pvr::utils::vma::Allocator& vmaAllocator, pvrvk::CommandBuffer& utilityCommandBuffer, pvrvk::PipelineCache& pipelineCache, bool astcSupported)
{
// Load the scene
scene = pvr::assets::loadModel(assetProvider, SceneFile);
isASTCSupported = astcSupported;
bool requiresCommandBufferSubmission = false;
pvr::utils::appendSingleBuffersFromModel(device, *scene, vbos, ibos, utilityCommandBuffer, requiresCommandBufferSubmission, vmaAllocator);
createBuffer(device, swapchain, vmaAllocator);
loadTextures(assetProvider, device, utilityCommandBuffer, vmaAllocator);
createDescriptorSetLayout(device);
createPipeline(assetProvider, device, renderpass, swapchain->getDimension(), pipelineCache);
for (uint32_t i = 0; i < swapchain->getSwapchainLength(); ++i) { descriptorSets.push_back(descriptorPool->allocateDescriptorSet(descriptorSetLayout)); }
for (uint32_t i = 0; i < swapchain->getSwapchainLength(); ++i) {cmdBuffers.push_back(commandPool->allocateSecondaryCommandBuffer()); }
}
/// <summary>Update the object animation.</summary>
/// <param name="angle">The angle to use for rotating the statue.</param>
/// <param name="viewProjectionMatrix">The view projection matrix to use for rendering.</param>
/// <param name="swapchainIndex">The current swapchain index.</param>
void updateAnimation(const float angle, glm::mat4& viewProjectionMatrix, uint32_t swapchainIndex)
{
// Calculate the model matrix
const glm::mat4 mModel = glm::translate(glm::vec3(0.0f, 5.0f, 0.0f)) * glm::rotate(angle, glm::vec3(0.0f, 1.0f, 0.0f)) * glm::scale(glm::vec3(2.2f));
glm::mat4 worldMatrix = mModel * scene->getWorldMatrix(scene->getNode(0).getObjectId());
glm::mat4 mvpMatrix = viewProjectionMatrix * worldMatrix;
structuredBufferView.getElementByName(BufferEntryNames::PerMesh::MVPMatrix, 0, swapchainIndex).setValue(mvpMatrix);
structuredBufferView.getElementByName(BufferEntryNames::PerMesh::WorldMatrix, 0, swapchainIndex).setValue(worldMatrix);
// if the memory property flags used by the buffers' device memory do not contain e_HOST_COHERENT_BIT then we must flush the memory
if (static_cast<uint32_t>(buffer->getDeviceMemory()->getMemoryFlags() & pvrvk::MemoryPropertyFlags::e_HOST_COHERENT_BIT) == 0)
{
buffer->getDeviceMemory()->flushRange(structuredBufferView.getDynamicSliceOffset(swapchainIndex), structuredBufferView.getDynamicSliceSize());
}
}
/// <summary>Creates any required buffers.</summary>
/// <param name="device">The device from which the resources will be allocated.</param>
/// <param name="swapchain">The swapchain which will determine the number of per swapchain resources to allocate.</param>
/// <param name="vmaAllocator">A VMA allocator to use for allocating images and buffers.</param>
void createBuffer(pvrvk::Device device, pvrvk::Swapchain& swapchain, pvr::utils::vma::Allocator& vmaAllocator)
{
pvr::utils::StructuredMemoryDescription desc;
desc.addElement(BufferEntryNames::PerMesh::MVPMatrix, pvr::GpuDatatypes::mat4x4);
desc.addElement(BufferEntryNames::PerMesh::WorldMatrix, pvr::GpuDatatypes::mat4x4);
structuredBufferView.initDynamic(desc, scene->getNumMeshNodes() * swapchain->getSwapchainLength(), pvr::BufferUsageFlags::UniformBuffer,
static_cast<uint32_t>(device->getPhysicalDevice()->getProperties().getLimits().getMinUniformBufferOffsetAlignment()));
buffer = pvr::utils::createBuffer(device, pvrvk::BufferCreateInfo(structuredBufferView.getSize(), pvrvk::BufferUsageFlags::e_UNIFORM_BUFFER_BIT),
pvrvk::MemoryPropertyFlags::e_HOST_VISIBLE_BIT,
pvrvk::MemoryPropertyFlags::e_DEVICE_LOCAL_BIT | pvrvk::MemoryPropertyFlags::e_HOST_VISIBLE_BIT | pvrvk::MemoryPropertyFlags::e_HOST_COHERENT_BIT, vmaAllocator,
pvr::utils::vma::AllocationCreateFlags::e_MAPPED_BIT);
structuredBufferView.pointToMappedMemory(buffer->getDeviceMemory()->getMappedData());
}
/// <summary>Creates the textures used for rendering the statue.</summary>
/// <param name="assetProvider">The pvr::IAssetProvider which will be used for loading resources from memory.</param>
/// <param name="device">The device from which the resources will be allocated.</param>
/// <param name="utilityCommandBuffer">A command buffer to use for queueing up all initialisation commands. This command buffer will be submitted later by the main
/// application.</param>
/// <param name="vmaAllocator">A VMA allocator to use for allocating images and buffers.</param>
void loadTextures(pvr::IAssetProvider& assetProvider, pvrvk::Device device, pvrvk::CommandBuffer& utilityCommandBuffer, pvr::utils::vma::Allocator& vmaAllocator)
{
// Load the Texture PVR file from the disk
pvr::Texture albedoTexture = pvr::textureLoad(*assetProvider.getAssetStream(StatueTexFile + (isASTCSupported ? "_astc.pvr" : ".pvr")), pvr::TextureFileFormat::PVR);
pvr::Texture normalMapTexture = pvr::textureLoad(*assetProvider.getAssetStream(StatueNormalMapTexFile + (isASTCSupported ? "_astc.pvr" : ".pvr")), pvr::TextureFileFormat::PVR);
// Create and Allocate Textures.
albeoImageView = pvr::utils::uploadImageAndView(
device, albedoTexture, true, utilityCommandBuffer, pvrvk::ImageUsageFlags::e_SAMPLED_BIT, pvrvk::ImageLayout::e_SHADER_READ_ONLY_OPTIMAL, vmaAllocator, vmaAllocator);
normalMapImageView = pvr::utils::uploadImageAndView(device, normalMapTexture, true, utilityCommandBuffer, pvrvk::ImageUsageFlags::e_SAMPLED_BIT,
pvrvk::ImageLayout::e_SHADER_READ_ONLY_OPTIMAL, vmaAllocator, vmaAllocator);
}
/// <summary>Creates the descriptor set layouts used for rendering the statue.</summary>
/// <param name="device">The device from which the descriptor set layouts will be allocated.</param>
void createDescriptorSetLayout(pvrvk::Device& device)
{
pvrvk::DescriptorSetLayoutCreateInfo descSetLayout;
descSetLayout.setBinding(0, pvrvk::DescriptorType::e_COMBINED_IMAGE_SAMPLER, 1, pvrvk::ShaderStageFlags::e_FRAGMENT_BIT);
descSetLayout.setBinding(1, pvrvk::DescriptorType::e_COMBINED_IMAGE_SAMPLER, 1, pvrvk::ShaderStageFlags::e_FRAGMENT_BIT);
descSetLayout.setBinding(2, pvrvk::DescriptorType::e_COMBINED_IMAGE_SAMPLER, 1, pvrvk::ShaderStageFlags::e_FRAGMENT_BIT);
descSetLayout.setBinding(3, pvrvk::DescriptorType::e_UNIFORM_BUFFER, 1, pvrvk::ShaderStageFlags::e_VERTEX_BIT);
descriptorSetLayout = device->createDescriptorSetLayout(descSetLayout);
pvrvk::PipelineLayoutCreateInfo pipelineLayoutInfo;
pipelineLayoutInfo.setDescSetLayout(0, descriptorSetLayout);
pvrvk::PushConstantRange pushConstantsRange;
pushConstantsRange.setOffset(0);
pushConstantsRange.setSize(static_cast<uint32_t>(pvr::getSize(pvr::GpuDatatypes::Float)));
pushConstantsRange.setStageFlags(pvrvk::ShaderStageFlags::e_FRAGMENT_BIT);
pipelineLayoutInfo.setPushConstantRange(0, pushConstantsRange);
pipelineLayout = device->createPipelineLayout(pipelineLayoutInfo);
}
/// <summary>Updates the descriptor sets used for rendering the statue.</summary>
/// <param name="device">The device from which the resources will be allocated.</param>
/// <param name="swapchainIndex">The swapchain index of the descriptor set to update.</param>
/// <param name="diffuseIrradianceMap">The diffuse irradiance map used as a replacement to a fixed albedo.</param>
/// <param name="samplerBilinear">A bilinear sampler object.</param>
/// <param name="samplerTrilinear">A trilinear sampler object.</param>
void updateDescriptorSets(pvrvk::Device& device, uint32_t swapchainIndex, pvrvk::ImageView& diffuseIrradianceMap, pvrvk::Sampler& samplerBilinear, pvrvk::Sampler& samplerTrilinear)
{
std::vector<pvrvk::WriteDescriptorSet> writeDescSets;
writeDescSets.push_back(pvrvk::WriteDescriptorSet(pvrvk::DescriptorType::e_COMBINED_IMAGE_SAMPLER, descriptorSets[swapchainIndex], 0)
.setImageInfo(0, pvrvk::DescriptorImageInfo(albeoImageView, samplerBilinear, pvrvk::ImageLayout::e_SHADER_READ_ONLY_OPTIMAL)));
writeDescSets.push_back(pvrvk::WriteDescriptorSet(pvrvk::DescriptorType::e_COMBINED_IMAGE_SAMPLER, descriptorSets[swapchainIndex], 1)
.setImageInfo(0, pvrvk::DescriptorImageInfo(normalMapImageView, samplerTrilinear, pvrvk::ImageLayout::e_SHADER_READ_ONLY_OPTIMAL)));
writeDescSets.push_back(pvrvk::WriteDescriptorSet(pvrvk::DescriptorType::e_COMBINED_IMAGE_SAMPLER, descriptorSets[swapchainIndex], 2)
.setImageInfo(0, pvrvk::DescriptorImageInfo(diffuseIrradianceMap, samplerTrilinear, pvrvk::ImageLayout::e_SHADER_READ_ONLY_OPTIMAL)));
writeDescSets.push_back(
pvrvk::WriteDescriptorSet(pvrvk::DescriptorType::e_UNIFORM_BUFFER, descriptorSets[swapchainIndex], 3)
.setBufferInfo(0, pvrvk::DescriptorBufferInfo(buffer, structuredBufferView.getDynamicSliceOffset(swapchainIndex), structuredBufferView.getDynamicSliceSize())));
device->updateDescriptorSets(writeDescSets.data(), static_cast<uint32_t>(writeDescSets.size()), nullptr, 0);
}
/// <summary>Creates the pipeline.</summary>
/// <param name="assetProvider">The pvr::IAssetProvider which will be used for loading resources from memory.</param>
/// <param name="device">The device to use for allocating the pipelines.</param>
/// <param name="renderpass">The RenderPass to use.</param>
/// <param name="viewportDimensions">The viewport dimensions.</param>
/// <param name="pipelineCache">A pipeline cache object to use when creating pipeline.</param>
void createPipeline(pvr::IAssetProvider& assetProvider, pvrvk::Device& device, const pvrvk::RenderPass& renderpass, const pvrvk::Extent2D& viewportDimensions,
pvrvk::PipelineCache& pipelineCache)
{
pvrvk::GraphicsPipelineCreateInfo pipelineInfo;
pipelineInfo.viewport.setViewportAndScissor(0,
pvrvk::Viewport(0.0f, 0.0f, static_cast<float>(viewportDimensions.getWidth()), static_cast<float>(viewportDimensions.getHeight())),
pvrvk::Rect2D(0, 0, viewportDimensions.getWidth(), viewportDimensions.getHeight()));
pipelineInfo.rasterizer.setCullMode(pvrvk::CullModeFlags::e_BACK_BIT);
// depth stencil state
pipelineInfo.depthStencil.enableDepthWrite(true);
pipelineInfo.depthStencil.enableDepthTest(true);
pipelineInfo.depthStencil.setDepthCompareFunc(pvrvk::CompareOp::e_LESS);
pipelineInfo.depthStencil.enableStencilTest(false);
// blend state
pipelineInfo.colorBlend.setAttachmentState(0, pvrvk::PipelineColorBlendAttachmentState());
pipelineInfo.colorBlend.setAttachmentState(1, pvrvk::PipelineColorBlendAttachmentState());
pipelineInfo.vertexShader.setShader(device->createShaderModule(pvrvk::ShaderModuleCreateInfo(assetProvider.getAssetStream(Files::VertShaderSrcFile)->readToEnd<uint32_t>())));
pipelineInfo.fragmentShader.setShader(device->createShaderModule(pvrvk::ShaderModuleCreateInfo(assetProvider.getAssetStream(Files::FragShaderSrcFile)->readToEnd<uint32_t>())));
const pvr::assets::Mesh& mesh = scene->getMesh(0);
pipelineInfo.inputAssembler.setPrimitiveTopology(pvr::utils::convertToPVRVk(mesh.getPrimitiveType()));
pvr::utils::populateInputAssemblyFromMesh(
mesh, VertexAttribBindings, sizeof(VertexAttribBindings) / sizeof(VertexAttribBindings[0]), pipelineInfo.vertexInput, pipelineInfo.inputAssembler);
pipelineInfo.renderPass = renderpass;
pipelineInfo.pipelineLayout = pipelineLayout;
pipeline = device->createGraphicsPipeline(pipelineInfo, pipelineCache);
}
/// <summary>Draws an assets::Mesh after the model view matrix has been set and the material prepared.</summary>
/// <param name="cmdBuffer">The secondary command buffer to record rendering commands to.</param>
/// <param name="nodeIndex">Node index of the mesh to draw</param>
void drawMesh(pvrvk::SecondaryCommandBuffer& cmdBuffer, int nodeIndex)
{
const uint32_t meshId = scene->getNode(nodeIndex).getObjectId();
const pvr::assets::Mesh& mesh = scene->getMesh(meshId);
// bind the VBO for the mesh
cmdBuffer->bindVertexBuffer(vbos[meshId], 0, 0);
// The geometry can be exported in 4 ways:
// - Indexed Triangle list
// - Non-Indexed Triangle list
// - Indexed Triangle strips
// - Non-Indexed Triangle strips
if (mesh.getNumStrips() == 0)
{
// Indexed Triangle list
if (ibos[meshId])
{
cmdBuffer->bindIndexBuffer(ibos[meshId], 0, pvr::utils::convertToPVRVk(mesh.getFaces().getDataType()));
cmdBuffer->drawIndexed(0, mesh.getNumFaces() * 3, 0, 0, 1);
}
else
{
// Non-Indexed Triangle list
cmdBuffer->draw(0, mesh.getNumFaces() * 3, 0, 1);
}
}
else
{
uint32_t offset = 0;
for (uint32_t i = 0; i < mesh.getNumStrips(); ++i)
{
if (ibos[meshId])
{
// Indexed Triangle strips
cmdBuffer->bindIndexBuffer(ibos[meshId], 0, pvr::utils::convertToPVRVk(mesh.getFaces().getDataType()));
cmdBuffer->drawIndexed(0, mesh.getStripLength(i) + 2, offset * 2, 0, 1);
}
else
{
// Non-Indexed Triangle strips
cmdBuffer->draw(0, mesh.getStripLength(i) + 2, 0, 1);
}
offset += mesh.getStripLength(i) + 2;
}
}
}
/// <summary>Records the secondary command buffers for rendering the statue.</summary>
/// <param name="swapchainIndex">The swapchain index for which the recorded command buffer will be used.</param>
/// <param name="framebuffer">The framebuffer to render into</param>
/// <param name="exposure">The exposure value used to 'expose' the colour prior to post processing</param>
/// <param name="threshold">The threshold value used to determine how much of the colour to retain for the bloom</param>
void recordCommandBuffer(uint32_t swapchainIndex, pvrvk::Framebuffer& framebuffer, float exposure)
{
cmdBuffers[swapchainIndex]->begin(framebuffer, 0, pvrvk::CommandBufferUsageFlags::e_RENDER_PASS_CONTINUE_BIT);
pvr::utils::beginCommandBufferDebugLabel(cmdBuffers[swapchainIndex], pvrvk::DebugUtilsLabel("Statue"));
cmdBuffers[swapchainIndex]->bindPipeline(pipeline);
cmdBuffers[swapchainIndex]->bindDescriptorSet(pvrvk::PipelineBindPoint::e_GRAPHICS, pipelineLayout, 0u, descriptorSets[swapchainIndex]);
cmdBuffers[swapchainIndex]->pushConstants(pipelineLayout, pvrvk::ShaderStageFlags::e_FRAGMENT_BIT, 0, static_cast<uint32_t>(pvr::getSize(pvr::GpuDatatypes::Float)), &exposure);
drawMesh(cmdBuffers[swapchainIndex], 0);
pvr::utils::endCommandBufferDebugLabel(cmdBuffers[swapchainIndex]);
cmdBuffers[swapchainIndex]->end();
}
};
/// <summary>A simple pass used for rendering our skybox.</summary>
struct SkyboxPass
{
pvrvk::GraphicsPipeline pipeline;
pvrvk::PipelineLayout pipelineLayout;
pvrvk::ImageView skyBoxImageView;
pvrvk::DescriptorSetLayout descriptorSetLayout;
std::vector<pvrvk::DescriptorSet> descriptorSets;
std::vector<pvrvk::SecondaryCommandBuffer> cmdBuffers;
uint32_t currentScene;
/// <summary>Initialises the skybox pass.</summary>
/// <param name="assetProvider">The pvr::IAssetProvider which will be used for loading resources from memory.</param>
/// <param name="device">The device from which the resources will be allocated.</param>
/// <param name="swapchain">The swapchain which will determine the number of per swapchain resources to allocate.</param>
/// <param name="commandPool">The command pool from which to allocate command buffers.</param>
/// <param name="descriptorPool">The descriptor pool from which to allocate descriptor sets.</param>
/// <param name="renderpass">The RenderPass to use.</param>
/// <param name="framebuffers">The framebuffers to use.</param>
/// <param name="pipelineCache">A pipeline cache object to use when creating pipelines.</param>
void init(pvr::IAssetProvider& assetProvider, pvrvk::Device& device, pvrvk::Swapchain& swapchain, pvrvk::CommandPool& commandPool, pvrvk::DescriptorPool& descriptorPool,
pvrvk::RenderPass& renderpass, pvrvk::PipelineCache& pipelineCache)
{
this->currentScene = -1;
createDescriptorSetLayout(device);
createPipeline(assetProvider, device, renderpass, swapchain->getDimension(), pipelineCache);
for (uint32_t i = 0; i < swapchain->getSwapchainLength(); ++i) { descriptorSets.push_back(descriptorPool->allocateDescriptorSet(descriptorSetLayout)); }
for (uint32_t i = 0; i < swapchain->getSwapchainLength(); ++i) {cmdBuffers.push_back(commandPool->allocateSecondaryCommandBuffer()); }
}
/// <summary>Creates the texture used for rendering the skybox.</summary>
/// <param name="assetProvider">The pvr::IAssetProvider which will be used for loading resources from memory.</param>
/// <param name="device">The device from which the resources will be allocated.</param>
/// <param name="utilityCommandBuffer">A command buffer to use for queueing up all initialisation commands. This command buffer will be submitted later by the main
/// application.</param>
/// <param name="vmaAllocator">A VMA allocator to use for allocating images and buffers.</param>
/// <param name="currentScene">The current scene to use.</param>
void loadSkyBoxImageView(pvr::IAssetProvider& assetProvider, pvrvk::Device device, pvrvk::CommandBuffer& cmdBuffer, pvr::utils::vma::Allocator& vmaAllocator, uint32_t currentScene_)
{
// Only load the image view if required
if (this->currentScene != currentScene_)
{
skyBoxImageView.reset();
// Load the Texture PVR file from the disk
pvr::Texture skyBoxTexture = pvr::textureLoad(*assetProvider.getAssetStream(SceneTexFileNames[currentScene_].skyboxTexture), pvr::TextureFileFormat::PVR);
// Create and Allocate Textures.
skyBoxImageView = pvr::utils::uploadImageAndView(
device, skyBoxTexture, true, cmdBuffer, pvrvk::ImageUsageFlags::e_SAMPLED_BIT, pvrvk::ImageLayout::e_SHADER_READ_ONLY_OPTIMAL, vmaAllocator, vmaAllocator);
this->currentScene = currentScene_;
}
}
/// <summary>Creates the descriptor set layouts used for rendering the statue.</summary>
/// <param name="device">The device from which the descriptor set layouts will be allocated.</param>
void createDescriptorSetLayout(pvrvk::Device& device)
{
pvrvk::DescriptorSetLayoutCreateInfo descSetLayout;
descSetLayout.setBinding(0, pvrvk::DescriptorType::e_COMBINED_IMAGE_SAMPLER, 1, pvrvk::ShaderStageFlags::e_FRAGMENT_BIT);
descSetLayout.setBinding(1, pvrvk::DescriptorType::e_UNIFORM_BUFFER, 1, pvrvk::ShaderStageFlags::e_VERTEX_BIT);
descriptorSetLayout = device->createDescriptorSetLayout(descSetLayout);
pvrvk::PipelineLayoutCreateInfo pipelineLayoutInfo;
pipelineLayoutInfo.setDescSetLayout(0, descriptorSetLayout);
pvrvk::PushConstantRange pushConstantsRange;
pushConstantsRange.setOffset(0);
pushConstantsRange.setSize(static_cast<uint32_t>(pvr::getSize(pvr::GpuDatatypes::Float)));
pushConstantsRange.setStageFlags(pvrvk::ShaderStageFlags::e_FRAGMENT_BIT);
pipelineLayoutInfo.setPushConstantRange(0, pushConstantsRange);
pipelineLayout = device->createPipelineLayout(pipelineLayoutInfo);
}
/// <summary>Updates the descriptor sets used for rendering the skybox.</summary>
/// <param name="device">The device from which the resources will be allocated.</param>
/// <param name="swapchainIndex">The swapchain index of the descriptor set to update.</param>
/// <param name="samplerTrilinear">A trilinear sampler object.</param>
/// <param name="sceneBuffer">The scene buffer.</param>
/// <param name="sceneBufferView">Buffer view for the scene buffer.</param>
void updateDescriptorSets(
pvrvk::Device& device, uint32_t swapchainIndex, pvrvk::Sampler& samplerTrilinear, pvrvk::Buffer& sceneBuffer, pvr::utils::StructuredBufferView& sceneBufferView)
{
std::vector<pvrvk::WriteDescriptorSet> writeDescSets;
writeDescSets.push_back(pvrvk::WriteDescriptorSet(pvrvk::DescriptorType::e_COMBINED_IMAGE_SAMPLER, descriptorSets[swapchainIndex], 0)
.setImageInfo(0, pvrvk::DescriptorImageInfo(skyBoxImageView, samplerTrilinear, pvrvk::ImageLayout::e_SHADER_READ_ONLY_OPTIMAL)));
writeDescSets.push_back(
pvrvk::WriteDescriptorSet(pvrvk::DescriptorType::e_UNIFORM_BUFFER, descriptorSets[swapchainIndex], 1)
.setBufferInfo(0, pvrvk::DescriptorBufferInfo(sceneBuffer, sceneBufferView.getDynamicSliceOffset(swapchainIndex), sceneBufferView.getDynamicSliceSize())));
device->updateDescriptorSets(writeDescSets.data(), static_cast<uint32_t>(writeDescSets.size()), nullptr, 0);
}
/// <summary>Creates the pipeline.</summary>
/// <param name="assetProvider">The pvr::IAssetProvider which will be used for loading resources from memory.</param>
/// <param name="device">The device to use for allocating the pipelines.</param>
/// <param name="renderpass">The RenderPass to use.</param>
/// <param name="viewportDimensions">The viewport dimensions.</param>
/// <param name="pipelineCache">A pipeline cache object to use when creating pipeline.</param>
void createPipeline(pvr::IAssetProvider& assetProvider, pvrvk::Device& device, const pvrvk::RenderPass& renderpass, const pvrvk::Extent2D& viewportDimensions,
pvrvk::PipelineCache& pipelineCache)
{
pvrvk::GraphicsPipelineCreateInfo pipelineInfo;
pipelineInfo.viewport.setViewportAndScissor(0,
pvrvk::Viewport(0.0f, 0.0f, static_cast<float>(viewportDimensions.getWidth()), static_cast<float>(viewportDimensions.getHeight())),
pvrvk::Rect2D(0, 0, viewportDimensions.getWidth(), viewportDimensions.getHeight()));
pipelineInfo.rasterizer.setCullMode(pvrvk::CullModeFlags::e_BACK_BIT);
pipelineInfo.rasterizer.setFrontFaceWinding(pvrvk::FrontFace::e_COUNTER_CLOCKWISE);
// depth stencil state
pipelineInfo.depthStencil.enableDepthWrite(false);
pipelineInfo.depthStencil.enableDepthTest(true);
pipelineInfo.depthStencil.setDepthCompareFunc(pvrvk::CompareOp::e_LESS_OR_EQUAL);
pipelineInfo.depthStencil.enableStencilTest(false);
// blend state
pipelineInfo.colorBlend.setAttachmentState(0, pvrvk::PipelineColorBlendAttachmentState());
pipelineInfo.colorBlend.setAttachmentState(1, pvrvk::PipelineColorBlendAttachmentState());
pipelineInfo.vertexShader.setShader(
device->createShaderModule(pvrvk::ShaderModuleCreateInfo(assetProvider.getAssetStream(Files::SkyboxVertShaderSrcFile)->readToEnd<uint32_t>())));
pipelineInfo.fragmentShader.setShader(
device->createShaderModule(pvrvk::ShaderModuleCreateInfo(assetProvider.getAssetStream(Files::SkyboxFragShaderSrcFile)->readToEnd<uint32_t>())));
pipelineInfo.vertexInput.clear();
pipelineInfo.inputAssembler.setPrimitiveTopology(pvrvk::PrimitiveTopology::e_TRIANGLE_LIST);
pipelineInfo.renderPass = renderpass;
pipelineInfo.pipelineLayout = pipelineLayout;
pipeline = device->createGraphicsPipeline(pipelineInfo, pipelineCache);
}
/// <summary>Records the secondary command buffers for rendering the skybox.</summary>
/// <param name="swapchainIndex">The swapchain index for which the recorded command buffer will be used.</param>
/// <param name="framebuffer">The framebuffer to render into</param>
/// <param name="exposure">The exposure value used to 'expose' the colour prior to post processing</param>
/// <param name="threshold">The threshold value used to determine how much of the colour to retain for the bloom</param>
void recordCommandBuffer(uint32_t swapchainIndex, pvrvk::Framebuffer& framebuffer, float exposure)
{
cmdBuffers[swapchainIndex]->begin(framebuffer, 0, pvrvk::CommandBufferUsageFlags::e_RENDER_PASS_CONTINUE_BIT);
pvr::utils::beginCommandBufferDebugLabel(cmdBuffers[swapchainIndex], pvrvk::DebugUtilsLabel("Skybox"));
cmdBuffers[swapchainIndex]->bindPipeline(pipeline);
cmdBuffers[swapchainIndex]->bindDescriptorSet(pvrvk::PipelineBindPoint::e_GRAPHICS, pipelineLayout, 0u, descriptorSets[swapchainIndex]);
cmdBuffers[swapchainIndex]->pushConstants(pipelineLayout, pvrvk::ShaderStageFlags::e_FRAGMENT_BIT, 0, static_cast<uint32_t>(pvr::getSize(pvr::GpuDatatypes::Float)), &exposure);
cmdBuffers[swapchainIndex]->draw(0, 6);
pvr::utils::endCommandBufferDebugLabel(cmdBuffers[swapchainIndex]);
cmdBuffers[swapchainIndex]->end();
}
};
/// <summary>A Downsample pass which can be used for downsampling images by 1/4 x 1/4 i.e. 1/16 resolution.</summary>
struct DownSamplePass
{
pvrvk::DescriptorSetLayout descriptorSetLayout;
pvrvk::PipelineLayout pipelineLayout;
std::vector<pvrvk::DescriptorSet> descriptorSets;
std::vector<pvrvk::Framebuffer> framebuffers;
pvrvk::RenderPass renderPass;
std::vector<pvrvk::SecondaryCommandBuffer> cmdBuffers;
pvrvk::GraphicsPipeline pipeline;
glm::vec4 downsampleConfigs[4];
/// <summary>Initialises the Downsample pass.</summary>
/// <param name="assetProvider">The pvr::IAssetProvider which will be used for loading resources from memory.</param>
/// <param name="device">The device from which the resources will be allocated.</param>
/// <param name="swapchain">The swapchain which will determine the number of per swapchain resources to allocate.</param>
/// <param name="commandPool">The command pool from which to allocate command buffers.</param>
/// <param name="descriptorPool">The descriptor pool from which to allocate descriptor sets.</param>
/// <param name="blurFramebufferDimensions">The dimensions to use for the downsample pass. These dimensions should be 1/4 x 1/4 the size of the source image.</param>
/// <param name="inputImageViews">A set of images to downsample.</param>
/// <param name="outputImageViews">A pre-allocated set of images to render downsampled images to.</param>
/// <param name="sampler">A bilinear sampler object.</param>
/// <param name="pipelineCache">A pipeline cache object to use when creating pipelines.</param>
/// <param name="isComputeDownsample">Determines the destination image layout to use as well as the destination PipelineStageFlags.</param>
void init(pvr::IAssetProvider& assetProvider, pvrvk::Device& device, pvrvk::Swapchain& swapchain, pvrvk::CommandPool& commandPool, pvrvk::DescriptorPool& descriptorPool,
const glm::uvec2& blurFramebufferDimensions, std::vector<pvrvk::ImageView>& inputImageViews, std::vector<pvrvk::ImageView>& outputImageViews, pvrvk::Sampler& sampler,
pvrvk::PipelineCache& pipelineCache, bool isComputeDownsample)
{
const glm::vec2 dimensionRatio = glm::vec2(inputImageViews[0]->getImage()->getExtent().getWidth() / outputImageViews[0]->getImage()->getExtent().getWidth(),
inputImageViews[0]->getImage()->getExtent().getHeight() / outputImageViews[0]->getImage()->getExtent().getHeight());
// A set of pre-calculated offsets to use for the downsample
const glm::vec2 offsets[4] = { glm::vec2(-1.0, -1.0), glm::vec2(1.0, -1.0), glm::vec2(-1.0, 1.0), glm::vec2(1.0, 1.0) };
const glm::vec2 step = glm::vec2(1.0f / (blurFramebufferDimensions.x * dimensionRatio.x), 1.0f / (blurFramebufferDimensions.y * dimensionRatio.y));
downsampleConfigs[0] = glm::vec4(step * offsets[0], 0.0f, 0.0f);
downsampleConfigs[1] = glm::vec4(step * offsets[1], 0.0f, 0.0f);
downsampleConfigs[2] = glm::vec4(step * offsets[2], 0.0f, 0.0f);
downsampleConfigs[3] = glm::vec4(step * offsets[3], 0.0f, 0.0f);
createDescriptorSetLayout(device);
createDescriptorSets(device, swapchain, descriptorPool, inputImageViews, sampler);
createFramebuffers(device, swapchain, blurFramebufferDimensions, outputImageViews, isComputeDownsample);
createPipeline(assetProvider, device, blurFramebufferDimensions, pipelineCache);
for (uint32_t i = 0; i < swapchain->getSwapchainLength(); ++i) { cmdBuffers.push_back(commandPool->allocateSecondaryCommandBuffer()); }
}
/// <summary>Creates the descriptor set layout.</summary>
/// <param name="device">The device from which the descriptor set layouts will be allocated.</param>
void createDescriptorSetLayout(pvrvk::Device& device)
{
// create the pre bloom descriptor set layout
pvrvk::DescriptorSetLayoutCreateInfo descSetInfo;
descSetInfo.setBinding(0, pvrvk::DescriptorType::e_COMBINED_IMAGE_SAMPLER, 1u, pvrvk::ShaderStageFlags::e_FRAGMENT_BIT);
descriptorSetLayout = device->createDescriptorSetLayout(descSetInfo);
// create the pipeline layouts
pvrvk::PipelineLayoutCreateInfo pipeLayoutInfo;
pipeLayoutInfo.setDescSetLayout(0, descriptorSetLayout);
uint32_t pushConstantsSize = static_cast<uint32_t>(pvr::getSize(pvr::GpuDatatypes::vec4) * 4);
pvrvk::PushConstantRange pushConstantsRange;
pushConstantsRange.setOffset(0);
pushConstantsRange.setSize(pushConstantsSize);
pushConstantsRange.setStageFlags(pvrvk::ShaderStageFlags::e_VERTEX_BIT);
pipeLayoutInfo.setPushConstantRange(0, pushConstantsRange);
pipelineLayout = device->createPipelineLayout(pipeLayoutInfo);
}
/// <summary>Creates the descriptor sets used for the downsample.</summary>
/// <param name="device">The device from which the resources will be allocated.</param>
/// <param name="swapchain">The swapchain which will determine the number of per swapchain resources to allocate.</param>
/// <param name="descriptorPool">The descriptor pool from which to allocate descriptor sets.</param>
/// <param name="inputImageViews">A set of images to downsample.</param>
/// <param name="sampler">A bilinear sampler object.</param>
void createDescriptorSets(
pvrvk::Device& device, pvrvk::Swapchain& swapchain, pvrvk::DescriptorPool& descriptorPool, std::vector<pvrvk::ImageView>& inputImageViews, pvrvk::Sampler& sampler)
{
std::vector<pvrvk::WriteDescriptorSet> writeDescSets;
for (uint32_t i = 0; i < swapchain->getSwapchainLength(); ++i)
{
descriptorSets.push_back(descriptorPool->allocateDescriptorSet(descriptorSetLayout));
writeDescSets.push_back(pvrvk::WriteDescriptorSet(pvrvk::DescriptorType::e_COMBINED_IMAGE_SAMPLER, descriptorSets[i], 0)
.setImageInfo(0, pvrvk::DescriptorImageInfo(inputImageViews[i], sampler, pvrvk::ImageLayout::e_SHADER_READ_ONLY_OPTIMAL)));
}
device->updateDescriptorSets(writeDescSets.data(), static_cast<uint32_t>(writeDescSets.size()), nullptr, 0);
}
/// <summary>Creates the pipeline.</summary>
/// <param name="assetProvider">The pvr::IAssetProvider which will be used for loading resources from memory.</param>
/// <param name="device">The device to use for allocating the pipelines.</param>
/// <param name="blurFramebufferDimensions">The downsampled framebuffer dimensions.</param>
/// <param name="pipelineCache">A pipeline cache object to use when creating pipeline.</param>
void createPipeline(pvr::IAssetProvider& assetProvider, pvrvk::Device& device, const glm::uvec2& blurFramebufferDimensions, pvrvk::PipelineCache& pipelineCache)
{
pvrvk::GraphicsPipelineCreateInfo pipelineInfo;
pipelineInfo.viewport.setViewportAndScissor(0, pvrvk::Viewport(0.0f, 0.0f, static_cast<float>(blurFramebufferDimensions.x), static_cast<float>(blurFramebufferDimensions.y)),
pvrvk::Rect2D(0, 0, blurFramebufferDimensions.x, blurFramebufferDimensions.y));
pipelineInfo.rasterizer.setCullMode(pvrvk::CullModeFlags::e_FRONT_BIT);
pipelineInfo.rasterizer.setFrontFaceWinding(pvrvk::FrontFace::e_COUNTER_CLOCKWISE);
// disable depth writing and depth testing
pipelineInfo.depthStencil.enableDepthWrite(false);
pipelineInfo.depthStencil.enableDepthTest(false);
// disable stencil testing
pipelineInfo.depthStencil.enableStencilTest(false);
pipelineInfo.colorBlend.setAttachmentState(0, pvrvk::PipelineColorBlendAttachmentState());
// load and create appropriate shaders
pipelineInfo.vertexShader.setShader(
device->createShaderModule(pvrvk::ShaderModuleCreateInfo(assetProvider.getAssetStream(Files::Downsample4x4VertSrcFile)->readToEnd<uint32_t>())));
pipelineInfo.fragmentShader.setShader(
device->createShaderModule(pvrvk::ShaderModuleCreateInfo(assetProvider.getAssetStream(Files::Downsample4x4FragSrcFile)->readToEnd<uint32_t>())));
pipelineInfo.vertexInput.clear();
pipelineInfo.inputAssembler.setPrimitiveTopology(pvrvk::PrimitiveTopology::e_TRIANGLE_STRIP);
pipelineInfo.pipelineLayout = pipelineLayout;
// renderpass/subpass
pipelineInfo.renderPass = renderPass;
pipelineInfo.subpass = 0;
pipeline = device->createGraphicsPipeline(pipelineInfo, pipelineCache);
}
/// <summary>Allocates the framebuffers used for the downsample.</summary>
/// <param name="device">The device from which the framebuffers will be allocated.</param>
/// <param name="swapchain">The swapchain which will determine the number of per swapchain resources to allocate.</param>
/// <param name="blurFramebufferDimensions">The downsampled framebuffer dimensions.</param>
/// <param name="colorImageViews">A pre-allocated set of images to render downsampled images to.</param>
/// <param name="isComputeDownsample">Determines the destination image layout to use as well as the destination PipelineStageFlags.</param>
void createFramebuffers(
pvrvk::Device& device, pvrvk::Swapchain& swapchain, const glm::uvec2& blurFramebufferDimensions, std::vector<pvrvk::ImageView>& colorImageViews, bool isComputeDownsample)
{
pvrvk::RenderPassCreateInfo renderPassInfo;
if (isComputeDownsample)
{
renderPassInfo.setAttachmentDescription(0,
pvrvk::AttachmentDescription::createColorDescription(colorImageViews[0]->getImage()->getFormat(), pvrvk::ImageLayout::e_UNDEFINED, pvrvk::ImageLayout::e_GENERAL,
pvrvk::AttachmentLoadOp::e_DONT_CARE, pvrvk::AttachmentStoreOp::e_STORE, pvrvk::SampleCountFlags::e_1_BIT));
}
else
{
renderPassInfo.setAttachmentDescription(0,
pvrvk::AttachmentDescription::createColorDescription(colorImageViews[0]->getImage()->getFormat(), pvrvk::ImageLayout::e_UNDEFINED,
pvrvk::ImageLayout::e_SHADER_READ_ONLY_OPTIMAL, pvrvk::AttachmentLoadOp::e_DONT_CARE, pvrvk::AttachmentStoreOp::e_STORE, pvrvk::SampleCountFlags::e_1_BIT));
}
pvrvk::SubpassDescription subpass;
subpass.setColorAttachmentReference(0, pvrvk::AttachmentReference(0, pvrvk::ImageLayout::e_COLOR_ATTACHMENT_OPTIMAL));
renderPassInfo.setSubpass(0, subpass);
// Add external subpass dependencies to avoid the implicit subpass dependencies
pvrvk::SubpassDependency externalDependencies[2];
externalDependencies[0] = pvrvk::SubpassDependency(pvrvk::SubpassExternal, 0, pvrvk::PipelineStageFlags::e_COLOR_ATTACHMENT_OUTPUT_BIT,
pvrvk::PipelineStageFlags::e_FRAGMENT_SHADER_BIT, pvrvk::AccessFlags::e_COLOR_ATTACHMENT_WRITE_BIT, pvrvk::AccessFlags::e_SHADER_READ_BIT, pvrvk::DependencyFlags::e_NONE);
if (isComputeDownsample)
{
externalDependencies[1] =
pvrvk::SubpassDependency(0, pvrvk::SubpassExternal, pvrvk::PipelineStageFlags::e_COLOR_ATTACHMENT_OUTPUT_BIT, pvrvk::PipelineStageFlags::e_COMPUTE_SHADER_BIT,
pvrvk::AccessFlags::e_COLOR_ATTACHMENT_WRITE_BIT, pvrvk::AccessFlags::e_SHADER_READ_BIT, pvrvk::DependencyFlags::e_NONE);
}
else
{
externalDependencies[1] =
pvrvk::SubpassDependency(0, pvrvk::SubpassExternal, pvrvk::PipelineStageFlags::e_COLOR_ATTACHMENT_OUTPUT_BIT, pvrvk::PipelineStageFlags::e_FRAGMENT_SHADER_BIT,
pvrvk::AccessFlags::e_COLOR_ATTACHMENT_WRITE_BIT, pvrvk::AccessFlags::e_SHADER_READ_BIT, pvrvk::DependencyFlags::e_NONE);
}
renderPassInfo.addSubpassDependency(externalDependencies[0]);
renderPassInfo.addSubpassDependency(externalDependencies[1]);
renderPass = device->createRenderPass(renderPassInfo);
for (uint32_t i = 0; i < swapchain->getSwapchainLength(); ++i)
{
pvrvk::FramebufferCreateInfo createInfo;
createInfo.setAttachment(0, colorImageViews[i]);
createInfo.setDimensions(blurFramebufferDimensions.x, blurFramebufferDimensions.y);
createInfo.setRenderPass(renderPass);
framebuffers.push_back(device->createFramebuffer(createInfo));
}
}
/// <summary>Records the commands required for the downsample.</summary>
/// <param name="swapchainIndex">The swapchain index for which the recorded command buffer will be used.</param>
void recordCommands(uint32_t swapchainIndex)
{
cmdBuffers[swapchainIndex]->begin(framebuffers[swapchainIndex], 0, pvrvk::CommandBufferUsageFlags::e_RENDER_PASS_CONTINUE_BIT);
pvr::utils::beginCommandBufferDebugLabel(cmdBuffers[swapchainIndex], pvrvk::DebugUtilsLabel("Downsample"));
cmdBuffers[swapchainIndex]->bindPipeline(pipeline);
cmdBuffers[swapchainIndex]->bindDescriptorSet(pvrvk::PipelineBindPoint::e_GRAPHICS, pipelineLayout, 0u, descriptorSets[swapchainIndex]);
cmdBuffers[swapchainIndex]->pushConstants(
pipelineLayout, pvrvk::ShaderStageFlags::e_VERTEX_BIT, 0, static_cast<uint32_t>(pvr::getSize(pvr::GpuDatatypes::vec4) * 4), &downsampleConfigs);
cmdBuffers[swapchainIndex]->draw(0, 3);
pvr::utils::endCommandBufferDebugLabel(cmdBuffers[swapchainIndex]);
cmdBuffers[swapchainIndex]->end();
}
};
// Developed by Masaki Kawase, Bunkasha Games
// Used in DOUBLE-S.T.E.A.L. (aka Wreckless)
// From his GDC2003 Presentation: Frame Buffer Post processing Effects in DOUBLE-S.T.E.A.L (Wreckless)
// Multiple iterations of fixed (per iteration) offset sampling
struct KawaseBlurPass
{
pvrvk::GraphicsPipeline pipeline;
pvrvk::DescriptorSetLayout descriptorSetLayout;
pvrvk::PipelineLayout pipelineLayout;
// 2 Descriptor sets are created. The descriptor sets are ping-ponged between for each Kawase blur iteration:
// iteration 0: (read 0 -> write 1), iteration 1: (read 1 -> write 0), iteration 2: (read 0 -> write 1) etc.
std::vector<pvrvk::DescriptorSet> descriptorSets[2];
// Command buffers are recorded individually for each Kawase blur iteration
std::vector<pvrvk::SecondaryCommandBuffer> cmdBuffers[MaxKawaseIteration];