-
Notifications
You must be signed in to change notification settings - Fork 115
Expand file tree
/
Copy pathvulkan.cpp
More file actions
2032 lines (1724 loc) · 82.8 KB
/
Copy pathvulkan.cpp
File metadata and controls
2032 lines (1724 loc) · 82.8 KB
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
/*
* Physically Based Rendering
* Copyright (c) 2017-2018 Michał Siejak
*
* Vulkan 1.0 renderer.
*/
#if defined(ENABLE_VULKAN)
#include <stdexcept>
#include <algorithm>
#include <array>
#include <vector>
#include <map>
#define GLM_FORCE_DEPTH_ZERO_TO_ONE
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/euler_angles.hpp>
#include "vulkan.hpp"
#include "common/mesh.hpp"
#include "common/image.hpp"
#include "common/utils.hpp"
#include <GLFW/glfw3.h>
#define VKSUCCESS(x) ((x) == VK_SUCCESS)
#define VKFAILED(x) ((x) != VK_SUCCESS)
namespace Vulkan {
struct TransformUniforms
{
glm::mat4 viewProjectionMatrix;
glm::mat4 skyProjectionMatrix;
glm::mat4 sceneRotationMatrix;
};
struct ShadingUniforms
{
struct {
glm::vec4 direction;
glm::vec4 radiance;
} lights[SceneSettings::NumLights];
glm::vec4 eyePosition;
};
struct SpecularFilterPushConstants
{
uint32_t level;
float roughness;
};
GLFWwindow* Renderer::initialize(int width, int height, int maxSamples)
{
if(VKFAILED(volkInitialize())) {
throw std::runtime_error("Vulkan loader has not been found");
}
// Create instance
{
std::vector<const char*> instanceLayers;
std::vector<const char*> instanceExtensions;
uint32_t glfwNumRequiredExtensions;
const char** glfwRequiredExtensions = glfwGetRequiredInstanceExtensions(&glfwNumRequiredExtensions);
if(glfwNumRequiredExtensions > 0) {
instanceExtensions = std::vector<const char*>{glfwRequiredExtensions, glfwRequiredExtensions + glfwNumRequiredExtensions};
}
#if _DEBUG
instanceLayers.push_back("VK_LAYER_LUNARG_standard_validation");
instanceExtensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
#endif
VkApplicationInfo appInfo = { VK_STRUCTURE_TYPE_APPLICATION_INFO };
appInfo.apiVersion = VK_MAKE_VERSION(1, 0, 0);
VkInstanceCreateInfo instanceCreateInfo = { VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO };
instanceCreateInfo.pApplicationInfo = &appInfo;
if(!instanceLayers.empty()) {
instanceCreateInfo.enabledLayerCount = (uint32_t)instanceLayers.size();
instanceCreateInfo.ppEnabledLayerNames = &instanceLayers[0];
}
if(!instanceExtensions.empty()) {
instanceCreateInfo.enabledExtensionCount = (uint32_t)instanceExtensions.size();
instanceCreateInfo.ppEnabledExtensionNames = &instanceExtensions[0];
}
if(VKFAILED(vkCreateInstance(&instanceCreateInfo, nullptr, &m_instance))) {
throw std::runtime_error("Failed to create Vulkan instance");
}
volkLoadInstance(m_instance);
}
#if _DEBUG
// Initialize debug callback
{
VkDebugReportCallbackCreateInfoEXT createInfo = { VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT };
createInfo.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT | VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT;
createInfo.pfnCallback = Renderer::logMessage;
if(VKFAILED(vkCreateDebugReportCallbackEXT(m_instance, &createInfo, nullptr, &m_logCallback))) {
throw std::runtime_error("Failed to install debug report callback");
}
}
#endif
// Create window & WSI surface
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
GLFWwindow* window = glfwCreateWindow(width, height, "Physically Based Rendering (Vulkan)", nullptr, nullptr);
if(!window) {
throw std::runtime_error("Failed to create window");
}
if(VKFAILED(glfwCreateWindowSurface(m_instance, window, nullptr, &m_surface))) {
throw std::runtime_error("Failed to create window surface");
}
// Find suitable physical device
const std::vector<const char*> requiredDeviceExtensions = {
"VK_KHR_swapchain"
};
VkPhysicalDeviceFeatures requiredDeviceFeatures = {};
requiredDeviceFeatures.shaderStorageImageExtendedFormats = VK_TRUE;
requiredDeviceFeatures.samplerAnisotropy = VK_TRUE;
m_phyDevice = choosePhyDevice(m_surface, requiredDeviceFeatures, requiredDeviceExtensions);
queryPhyDeviceSurfaceCapabilities(m_phyDevice, m_surface);
// Create logical device
{
float queuePriority = 1.0f;
VkDeviceQueueCreateInfo queueCreateInfo = { VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO };
queueCreateInfo.queueFamilyIndex = m_phyDevice.queueFamilyIndex;
queueCreateInfo.queueCount = 1;
queueCreateInfo.pQueuePriorities = &queuePriority;
VkDeviceCreateInfo createInfo = { VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO };
createInfo.queueCreateInfoCount = 1;
createInfo.pQueueCreateInfos = &queueCreateInfo;
createInfo.pEnabledFeatures = &requiredDeviceFeatures;
createInfo.enabledExtensionCount = (uint32_t)requiredDeviceExtensions.size();
createInfo.ppEnabledExtensionNames = &requiredDeviceExtensions[0];
if(VKFAILED(vkCreateDevice(m_phyDevice.handle, &createInfo, nullptr, &m_device))) {
throw std::runtime_error("Failed to create Vulkan logical device");
}
volkLoadDevice(m_device);
vkGetDeviceQueue(m_device, m_phyDevice.queueFamilyIndex, 0, &m_queue);
}
// Create swap chain
{
uint32_t selectedMinImageCount = 2;
selectedMinImageCount = glm::clamp(selectedMinImageCount, m_phyDevice.surfaceCaps.minImageCount, m_phyDevice.surfaceCaps.maxImageCount);
VkPresentModeKHR selectedPresentMode = VK_PRESENT_MODE_FIFO_KHR;
if(std::find(m_phyDevice.presentModes.begin(), m_phyDevice.presentModes.end(), selectedPresentMode) == m_phyDevice.presentModes.end()) {
selectedPresentMode = m_phyDevice.presentModes[0];
}
VkSwapchainCreateInfoKHR createInfo = { VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR };
createInfo.surface = m_surface;
createInfo.minImageCount = selectedMinImageCount;
createInfo.imageFormat = VK_FORMAT_B8G8R8A8_UNORM;
createInfo.imageColorSpace = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR;
createInfo.imageExtent = m_phyDevice.surfaceCaps.currentExtent;
createInfo.imageArrayLayers = 1;
createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
createInfo.preTransform = m_phyDevice.surfaceCaps.currentTransform;
createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
createInfo.presentMode = selectedPresentMode;
createInfo.clipped = VK_TRUE;
createInfo.oldSwapchain = VK_NULL_HANDLE;
if(VKFAILED(vkCreateSwapchainKHR(m_device, &createInfo, nullptr, &m_swapchain))) {
throw std::runtime_error("Failed to create swap chain");
}
if(VKSUCCESS(vkGetSwapchainImagesKHR(m_device, m_swapchain, &m_numFrames, nullptr)) && m_numFrames > 0) {
m_swapchainImages.resize(m_numFrames);
if(VKFAILED(vkGetSwapchainImagesKHR(m_device, m_swapchain, &m_numFrames, &m_swapchainImages[0]))) {
m_numFrames = 0;
}
}
if(m_numFrames == 0) {
throw std::runtime_error("Failed to retrieve swapchain image handles");
}
}
// Create swapchain image views
m_swapchainViews.resize(m_numFrames);
for(uint32_t i=0; i<m_numFrames; ++i) {
VkImageViewCreateInfo viewCreateInfo = { VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO };
viewCreateInfo.image = m_swapchainImages[i];
viewCreateInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
viewCreateInfo.format = VK_FORMAT_B8G8R8A8_UNORM;
viewCreateInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
viewCreateInfo.subresourceRange.levelCount = 1;
viewCreateInfo.subresourceRange.layerCount = 1;
if(VKFAILED(vkCreateImageView(m_device, &viewCreateInfo, nullptr, &m_swapchainViews[i]))) {
throw std::runtime_error("Failed to create swapchain image view");
}
}
// Create render targets
{
const VkFormat colorFormat = VK_FORMAT_R16G16B16A16_SFLOAT;
const VkFormat depthFormat = VK_FORMAT_D32_SFLOAT;
const uint32_t maxColorSamples = queryRenderTargetFormatMaxSamples(colorFormat, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT);
const uint32_t maxDepthSamples = queryRenderTargetFormatMaxSamples(depthFormat, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT);
m_renderSamples = std::min({uint32_t(maxSamples), maxColorSamples, maxDepthSamples});
assert(m_renderSamples >= 1);
m_renderTargets.resize(m_numFrames);
m_resolveRenderTargets.resize(m_numFrames);
for(uint32_t i=0; i<m_numFrames; ++i) {
m_renderTargets[i] = createRenderTarget(width, height, m_renderSamples, colorFormat, depthFormat);
if(m_renderSamples > 1) {
m_resolveRenderTargets[i] = createRenderTarget(width, height, 1, colorFormat, VK_FORMAT_UNDEFINED);
}
}
}
// Create command pool & allocate command buffers
m_commandBuffers.resize(m_numFrames);
{
VkCommandPoolCreateInfo createInfo = { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO };
createInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
createInfo.queueFamilyIndex = m_phyDevice.queueFamilyIndex;
if(VKFAILED(vkCreateCommandPool(m_device, &createInfo, nullptr, &m_commandPool))) {
throw std::runtime_error("Failed to create command pool");
}
VkCommandBufferAllocateInfo allocateInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO };
allocateInfo.commandPool = m_commandPool;
allocateInfo.commandBufferCount = m_numFrames;
allocateInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
if(VKFAILED(vkAllocateCommandBuffers(m_device, &allocateInfo, &m_commandBuffers[0]))) {
throw std::runtime_error("Failed to allocate command buffer");
}
}
// Create fences
m_submitFences.resize(m_numFrames);
{
VkFenceCreateInfo createInfo = { VK_STRUCTURE_TYPE_FENCE_CREATE_INFO };
if(VKFAILED(vkCreateFence(m_device, &createInfo, nullptr, &m_presentationFence))) {
throw std::runtime_error("Failed to create presentation fence");
}
for(auto& fence : m_submitFences) {
if(VKFAILED(vkCreateFence(m_device, &createInfo, nullptr, &fence))) {
throw std::runtime_error("Failed to create queue submission fence");
}
}
}
// Acquire initial swapchain image
{
if(VKFAILED(vkAcquireNextImageKHR(m_device, m_swapchain, UINT64_MAX, VK_NULL_HANDLE, m_presentationFence, &m_frameIndex))) {
throw std::runtime_error("Failed to acquire initial swapchain image for rendering");
}
vkWaitForFences(m_device, 1, &m_presentationFence, VK_TRUE, UINT64_MAX);
vkResetFences(m_device, 1, &m_presentationFence);
}
// Create descriptor pool
{
const std::array<VkDescriptorPoolSize, 3> poolSizes = {{
{ VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 16 },
{ VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 16 },
{ VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, 16 },
}};
VkDescriptorPoolCreateInfo createInfo = { VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO };
createInfo.maxSets = 16;
createInfo.poolSizeCount = (uint32_t)poolSizes.size();
createInfo.pPoolSizes = poolSizes.data();
if(VKFAILED(vkCreateDescriptorPool(m_device, &createInfo, nullptr, &m_descriptorPool))) {
throw std::runtime_error("Failed to create descriptor pool");
}
}
m_frameRect = { 0, 0, (uint32_t)width, (uint32_t)height };
m_frameCount = 0;
std::printf("Vulkan 1.0 Renderer [%s]\n", m_phyDevice.properties.deviceName);
return window;
}
void Renderer::shutdown()
{
vkDeviceWaitIdle(m_device);
destroyTexture(m_envTexture);
destroyTexture(m_irmapTexture);
destroyTexture(m_spBRDF_LUT);
destroyMeshBuffer(m_skybox);
destroyMeshBuffer(m_pbrModel);
destroyTexture(m_albedoTexture);
destroyTexture(m_normalTexture);
destroyTexture(m_metalnessTexture);
destroyTexture(m_roughnessTexture);
destroyUniformBuffer(m_uniformBuffer);
vkDestroySampler(m_device, m_defaultSampler, nullptr);
vkDestroySampler(m_device, m_spBRDFSampler, nullptr);
vkDestroyPipelineLayout(m_device, m_pbrPipelineLayout, nullptr);
vkDestroyPipeline(m_device, m_pbrPipeline, nullptr);
vkDestroyPipelineLayout(m_device, m_skyboxPipelineLayout, nullptr);
vkDestroyPipeline(m_device, m_skyboxPipeline, nullptr);
vkDestroyPipelineLayout(m_device, m_tonemapPipelineLayout, nullptr);
vkDestroyPipeline(m_device, m_tonemapPipeline, nullptr);
vkDestroyRenderPass(m_device, m_renderPass, nullptr);
for(uint32_t i=0; i<m_numFrames; ++i) {
destroyRenderTarget(m_renderTargets[i]);
if(m_renderSamples > 1) {
destroyRenderTarget(m_resolveRenderTargets[i]);
}
vkDestroyFramebuffer(m_device, m_framebuffers[i], nullptr);
vkDestroyImageView(m_device, m_swapchainViews[i], nullptr);
vkDestroyFence(m_device, m_submitFences[i], nullptr);
}
vkDestroyDescriptorPool(m_device, m_descriptorPool, nullptr);
vkDestroyCommandPool(m_device, m_commandPool, nullptr);
vkDestroyFence(m_device, m_presentationFence, nullptr);
vkDestroySwapchainKHR(m_device, m_swapchain, nullptr);
vkDestroySurfaceKHR(m_instance, m_surface, nullptr);
vkDestroyDevice(m_device, nullptr);
#if _DEBUG
vkDestroyDebugReportCallbackEXT(m_instance, m_logCallback, nullptr);
#endif
vkDestroyInstance(m_instance, nullptr);
}
void Renderer::setup()
{
// Parameters
static constexpr uint32_t kEnvMapSize = 1024;
static constexpr uint32_t kIrradianceMapSize = 32;
static constexpr uint32_t kBRDF_LUT_Size = 256;
static constexpr uint32_t kEnvMapLevels = Utility::numMipmapLevels(kEnvMapSize, kEnvMapSize);
static constexpr VkDeviceSize kUniformBufferSize = 64 * 1024;
// Common descriptor set layouts
struct {
VkDescriptorSetLayout uniforms;
VkDescriptorSetLayout pbr;
VkDescriptorSetLayout skybox;
VkDescriptorSetLayout tonemap;
VkDescriptorSetLayout compute;
} setLayout;
// Friendly binding names for per-frame uniform blocks
enum UniformsDescriptorSetBindingNames : uint32_t {
Binding_TransformUniforms = 0,
Binding_ShadingUniforms = 1,
};
// Friendly binding names for compute pipeline descriptor set
enum ComputeDescriptorSetBindingNames : uint32_t {
Binding_InputTexture = 0,
Binding_OutputTexture = 1,
Binding_OutputMipTail = 2,
};
// Create host-mapped uniform buffer for sub-allocation of uniform block ranges.
m_uniformBuffer = createUniformBuffer(kUniformBufferSize);
// Create samplers.
VkSampler computeSampler;
{
VkSamplerCreateInfo createInfo = { VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO };
// Linear, non-anisotropic sampler, wrap address mode (post processing compute shaders)
createInfo.minFilter = VK_FILTER_LINEAR;
createInfo.magFilter = VK_FILTER_LINEAR;
createInfo.borderColor = VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK;
if(VKFAILED(vkCreateSampler(m_device, &createInfo, nullptr, &computeSampler))) {
throw std::runtime_error("Failed to create pre-processing sampler");
}
// Linear, anisotropic sampler, wrap address mode (rendering)
createInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
createInfo.anisotropyEnable = VK_TRUE;
createInfo.maxAnisotropy = m_phyDevice.properties.limits.maxSamplerAnisotropy;
createInfo.minLod = 0.0f;
createInfo.maxLod = FLT_MAX;
if(VKFAILED(vkCreateSampler(m_device, &createInfo, nullptr, &m_defaultSampler))) {
throw std::runtime_error("Failed to create default anisotropic sampler");
}
// Linear, non-anisotropic sampler, clamp address mode (sampling BRDF LUT)
createInfo.anisotropyEnable = VK_FALSE;
createInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
createInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
if(VKFAILED(vkCreateSampler(m_device, &createInfo, nullptr, &m_spBRDFSampler))) {
throw std::runtime_error("Failed to create BRDF LUT sampler");
}
}
// Create temporary descriptor pool for pre-processing compute shaders.
VkDescriptorPool computeDescriptorPool;
{
const std::array<VkDescriptorPoolSize, 2> poolSizes = {{
{ VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1 },
{ VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, kEnvMapLevels },
}};
VkDescriptorPoolCreateInfo createInfo = { VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO };
createInfo.maxSets = 2;
createInfo.poolSizeCount = (uint32_t)poolSizes.size();
createInfo.pPoolSizes = poolSizes.data();
if(VKFAILED(vkCreateDescriptorPool(m_device, &createInfo, nullptr, &computeDescriptorPool))) {
throw std::runtime_error("Failed to create setup descriptor pool");
}
}
// Create common descriptor set & pipeline layout for pre-processing compute shaders.
VkPipelineLayout computePipelineLayout;
VkDescriptorSet computeDescriptorSet;
{
const std::vector<VkDescriptorSetLayoutBinding> descriptorSetLayoutBindings = {
{ Binding_InputTexture, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_COMPUTE_BIT, &computeSampler },
{ Binding_OutputTexture, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, VK_SHADER_STAGE_COMPUTE_BIT, nullptr },
{ Binding_OutputMipTail, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, kEnvMapLevels-1, VK_SHADER_STAGE_COMPUTE_BIT, nullptr },
};
setLayout.compute = createDescriptorSetLayout(&descriptorSetLayoutBindings);
computeDescriptorSet = allocateDescriptorSet(computeDescriptorPool, setLayout.compute);
const std::vector<VkDescriptorSetLayout> pipelineSetLayouts = {
setLayout.compute,
};
const std::vector<VkPushConstantRange> pipelinePushConstantRanges = {
{ VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(SpecularFilterPushConstants) },
};
computePipelineLayout = createPipelineLayout(&pipelineSetLayouts, &pipelinePushConstantRanges);
}
// Create descriptor set layout for per-frame shader uniforms
{
const std::vector<VkDescriptorSetLayoutBinding> descriptorSetLayoutBindings = {
{ Binding_TransformUniforms, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, VK_SHADER_STAGE_VERTEX_BIT, nullptr },
{ Binding_ShadingUniforms, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, VK_SHADER_STAGE_FRAGMENT_BIT, nullptr },
};
setLayout.uniforms = createDescriptorSetLayout(&descriptorSetLayoutBindings);
}
// Allocate & update per-frame uniform buffer descriptor sets
{
m_uniformsDescriptorSets.resize(m_numFrames);
for(uint32_t i=0; i<m_numFrames; ++i) {
m_uniformsDescriptorSets[i] = allocateDescriptorSet(m_descriptorPool, setLayout.uniforms);
// Sub-allocate storage for uniform blocks
m_transformUniforms.push_back(allocFromUniformBuffer<TransformUniforms>(m_uniformBuffer));
updateDescriptorSet(m_uniformsDescriptorSets[i], Binding_TransformUniforms, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, { m_transformUniforms[i].descriptorInfo });
m_shadingUniforms.push_back(allocFromUniformBuffer<ShadingUniforms>(m_uniformBuffer));
updateDescriptorSet(m_uniformsDescriptorSets[i], Binding_ShadingUniforms, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, { m_shadingUniforms[i].descriptorInfo });
}
}
// Create render pass
{
enum AttachmentName : uint32_t {
MainColorAttachment = 0,
MainDepthStencilAttachment,
SwapchainColorAttachment,
ResolveColorAttachment,
};
std::vector<VkAttachmentDescription> attachments = {
// Main color attachment (0)
{
0,
m_renderTargets[0].colorFormat,
static_cast<VkSampleCountFlagBits>(m_renderSamples),
VK_ATTACHMENT_LOAD_OP_DONT_CARE,
VK_ATTACHMENT_STORE_OP_DONT_CARE,
VK_ATTACHMENT_LOAD_OP_DONT_CARE,
VK_ATTACHMENT_STORE_OP_DONT_CARE,
VK_IMAGE_LAYOUT_UNDEFINED,
VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
},
// Main depth-stencil attachment (1)
{
0,
m_renderTargets[0].depthFormat,
static_cast<VkSampleCountFlagBits>(m_renderSamples),
VK_ATTACHMENT_LOAD_OP_CLEAR,
VK_ATTACHMENT_STORE_OP_DONT_CARE,
VK_ATTACHMENT_LOAD_OP_DONT_CARE,
VK_ATTACHMENT_STORE_OP_DONT_CARE,
VK_IMAGE_LAYOUT_UNDEFINED,
VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
},
// Swapchain color attachment (2)
{
0,
VK_FORMAT_B8G8R8A8_UNORM,
VK_SAMPLE_COUNT_1_BIT,
VK_ATTACHMENT_LOAD_OP_DONT_CARE,
VK_ATTACHMENT_STORE_OP_STORE,
VK_ATTACHMENT_LOAD_OP_DONT_CARE,
VK_ATTACHMENT_STORE_OP_DONT_CARE,
VK_IMAGE_LAYOUT_UNDEFINED,
VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
},
};
if(m_renderSamples > 1) {
// Resolve color attachment (3)
const VkAttachmentDescription resolveAttachment =
{
0,
m_resolveRenderTargets[0].colorFormat,
VK_SAMPLE_COUNT_1_BIT,
VK_ATTACHMENT_LOAD_OP_DONT_CARE,
VK_ATTACHMENT_STORE_OP_DONT_CARE,
VK_ATTACHMENT_LOAD_OP_DONT_CARE,
VK_ATTACHMENT_STORE_OP_DONT_CARE,
VK_IMAGE_LAYOUT_UNDEFINED,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
};
attachments.push_back(resolveAttachment);
};
// Main subpass
const std::array<VkAttachmentReference, 1> mainPassColorRefs = {
{ MainColorAttachment, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL },
};
const std::array<VkAttachmentReference, 1> mainPassResolveRefs = {
{ ResolveColorAttachment, VK_IMAGE_LAYOUT_GENERAL },
};
const VkAttachmentReference mainPassDepthStencilRef = {
MainDepthStencilAttachment, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL
};
VkSubpassDescription mainPass = {};
mainPass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
mainPass.colorAttachmentCount = (uint32_t)mainPassColorRefs.size();
mainPass.pColorAttachments = mainPassColorRefs.data();
mainPass.pDepthStencilAttachment = &mainPassDepthStencilRef;
if(m_renderSamples > 1) {
mainPass.pResolveAttachments = mainPassResolveRefs.data();
}
// Tonemapping subpass
const std::array<VkAttachmentReference, 1> tonemapPassInputRefs = {
{ MainColorAttachment, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL },
};
const std::array<VkAttachmentReference, 1> tonemapPassMultisampleInputRefs = {
{ ResolveColorAttachment, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL },
};
const std::array<VkAttachmentReference, 1> tonemapPassColorRefs = {
{ SwapchainColorAttachment, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL },
};
VkSubpassDescription tonemapPass = {};
tonemapPass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
tonemapPass.colorAttachmentCount = (uint32_t)tonemapPassColorRefs.size();
tonemapPass.pColorAttachments = tonemapPassColorRefs.data();
if(m_renderSamples > 1) {
tonemapPass.inputAttachmentCount = (uint32_t)tonemapPassMultisampleInputRefs.size();
tonemapPass.pInputAttachments = tonemapPassMultisampleInputRefs.data();
}
else {
tonemapPass.inputAttachmentCount = (uint32_t)tonemapPassInputRefs.size();
tonemapPass.pInputAttachments = tonemapPassInputRefs.data();
}
const std::array<VkSubpassDescription, 2> subpasses = {
mainPass,
tonemapPass,
};
// Main->Tonemapping dependency
const VkSubpassDependency mainToTonemapDependency = {
0,
1,
VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
VK_ACCESS_SHADER_READ_BIT,
VK_DEPENDENCY_BY_REGION_BIT,
};
VkRenderPassCreateInfo createInfo = { VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO };
createInfo.attachmentCount = (uint32_t)attachments.size();
createInfo.pAttachments = attachments.data();
createInfo.subpassCount = (uint32_t)subpasses.size();
createInfo.pSubpasses = subpasses.data();
createInfo.dependencyCount = 1;
createInfo.pDependencies = &mainToTonemapDependency;
if(VKFAILED(vkCreateRenderPass(m_device, &createInfo, nullptr, &m_renderPass))) {
throw std::runtime_error("Failed to create render pass");
}
}
// Create framebuffers
{
m_framebuffers.resize(m_numFrames);
for(uint32_t i=0; i<m_framebuffers.size(); ++i) {
std::vector<VkImageView> attachments = {
m_renderTargets[i].colorView,
m_renderTargets[i].depthView,
m_swapchainViews[i],
};
if(m_renderSamples > 1) {
attachments.push_back(m_resolveRenderTargets[i].colorView);
}
VkFramebufferCreateInfo createInfo = { VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO };
createInfo.renderPass = m_renderPass;
createInfo.attachmentCount = (uint32_t)attachments.size();
createInfo.pAttachments = attachments.data();
createInfo.width = m_frameRect.extent.width;
createInfo.height = m_frameRect.extent.height;
createInfo.layers = 1;
if(VKFAILED(vkCreateFramebuffer(m_device, &createInfo, nullptr, &m_framebuffers[i]))) {
throw std::runtime_error("Failed to create framebuffer");
}
}
}
// Allocate common textures for later processing.
{
// Environment map (with pre-filtered mip chain)
m_envTexture = createTexture(kEnvMapSize, kEnvMapSize, 6, VK_FORMAT_R16G16B16A16_SFLOAT, 0, VK_IMAGE_USAGE_STORAGE_BIT);
// Irradiance map
m_irmapTexture = createTexture(kIrradianceMapSize, kIrradianceMapSize, 6, VK_FORMAT_R16G16B16A16_SFLOAT, 1, VK_IMAGE_USAGE_STORAGE_BIT);
// 2D LUT for split-sum approximation
m_spBRDF_LUT = createTexture(kBRDF_LUT_Size, kBRDF_LUT_Size, 1, VK_FORMAT_R16G16_SFLOAT, 1, VK_IMAGE_USAGE_STORAGE_BIT);
}
// Create graphics pipeline & descriptor set layout for tone mapping
{
const std::vector<VkDescriptorSetLayoutBinding> descriptorSetLayoutBindings = {
{ 0, VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, 1, VK_SHADER_STAGE_FRAGMENT_BIT, nullptr },
};
setLayout.tonemap = createDescriptorSetLayout(&descriptorSetLayoutBindings);
const std::vector<VkDescriptorSetLayout> pipelineDescriptorSetLayouts = {
setLayout.tonemap,
};
m_tonemapPipelineLayout = createPipelineLayout(&pipelineDescriptorSetLayouts);
m_tonemapPipeline = createGraphicsPipeline(
1,
"shaders/spirv/tonemap_vs.spv",
"shaders/spirv/tonemap_fs.spv",
m_tonemapPipelineLayout);
}
// Allocate & update descriptor sets for tone mapping input (per-frame)
{
m_tonemapDescriptorSets.resize(m_numFrames);
for(uint32_t i=0; i<m_numFrames; ++i) {
const VkDescriptorImageInfo imageInfo = {
VK_NULL_HANDLE,
(m_renderSamples > 1) ? m_resolveRenderTargets[i].colorView : m_renderTargets[i].colorView,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
};
m_tonemapDescriptorSets[i] = allocateDescriptorSet(m_descriptorPool, setLayout.tonemap);
updateDescriptorSet(m_tonemapDescriptorSets[i], 0, VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, { imageInfo });
}
}
// Load PBR model assets.
m_pbrModel = createMeshBuffer(Mesh::fromFile("meshes/cerberus.fbx"));
m_albedoTexture = createTexture(Image::fromFile("textures/cerberus_A.png"), VK_FORMAT_R8G8B8A8_SRGB);
m_normalTexture = createTexture(Image::fromFile("textures/cerberus_N.png"), VK_FORMAT_R8G8B8A8_UNORM);
m_metalnessTexture = createTexture(Image::fromFile("textures/cerberus_M.png", 1), VK_FORMAT_R8_UNORM);
m_roughnessTexture = createTexture(Image::fromFile("textures/cerberus_R.png", 1), VK_FORMAT_R8_UNORM);
// Create graphics pipeline & descriptor set layout for rendering PBR model
{
const std::vector<VkVertexInputBindingDescription> vertexInputBindings = {
{ 0, sizeof(Mesh::Vertex), VK_VERTEX_INPUT_RATE_VERTEX },
};
const std::vector<VkVertexInputAttributeDescription> vertexAttributes = {
{ 0, 0, VK_FORMAT_R32G32B32_SFLOAT, 0 }, // Position
{ 1, 0, VK_FORMAT_R32G32B32_SFLOAT, 12 }, // Normal
{ 2, 0, VK_FORMAT_R32G32B32_SFLOAT, 24 }, // Tangent
{ 3, 0, VK_FORMAT_R32G32B32_SFLOAT, 36 }, // Bitangent
{ 4, 0, VK_FORMAT_R32G32_SFLOAT, 48 }, // Texcoord
};
const std::vector<VkDescriptorSetLayoutBinding> descriptorSetLayoutBindings = {
{ 0, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_FRAGMENT_BIT, &m_defaultSampler }, // Albedo texture
{ 1, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_FRAGMENT_BIT, &m_defaultSampler }, // Normal texture
{ 2, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_FRAGMENT_BIT, &m_defaultSampler }, // Metalness texture
{ 3, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_FRAGMENT_BIT, &m_defaultSampler }, // Roughness texture
{ 4, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_FRAGMENT_BIT, &m_defaultSampler }, // Specular env map texture
{ 5, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_FRAGMENT_BIT, &m_defaultSampler }, // Irradiance map texture
{ 6, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_FRAGMENT_BIT, &m_spBRDFSampler }, // Specular BRDF LUT
};
setLayout.pbr = createDescriptorSetLayout(&descriptorSetLayoutBindings);
const std::vector<VkDescriptorSetLayout> pipelineDescriptorSetLayouts = {
setLayout.uniforms,
setLayout.pbr,
};
m_pbrPipelineLayout = createPipelineLayout(&pipelineDescriptorSetLayouts);
VkPipelineMultisampleStateCreateInfo multisampleState = { VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO };
multisampleState.rasterizationSamples = static_cast<VkSampleCountFlagBits>(m_renderTargets[0].samples);
VkPipelineDepthStencilStateCreateInfo depthStencilState = { VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO };
depthStencilState.depthTestEnable = VK_TRUE;
depthStencilState.depthWriteEnable = VK_TRUE;
depthStencilState.depthCompareOp = VK_COMPARE_OP_LESS_OR_EQUAL;
m_pbrPipeline = createGraphicsPipeline(
0,
"shaders/spirv/pbr_vs.spv",
"shaders/spirv/pbr_fs.spv",
m_pbrPipelineLayout,
&vertexInputBindings,
&vertexAttributes,
&multisampleState,
&depthStencilState);
}
// Allocate & update descriptor set for PBR model
{
const std::vector<VkDescriptorImageInfo> textures = {
{ VK_NULL_HANDLE, m_albedoTexture.view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL },
{ VK_NULL_HANDLE, m_normalTexture.view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL },
{ VK_NULL_HANDLE, m_metalnessTexture.view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL },
{ VK_NULL_HANDLE, m_roughnessTexture.view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL },
{ VK_NULL_HANDLE, m_envTexture.view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL },
{ VK_NULL_HANDLE, m_irmapTexture.view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL },
{ VK_NULL_HANDLE, m_spBRDF_LUT.view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL },
};
m_pbrDescriptorSet = allocateDescriptorSet(m_descriptorPool, setLayout.pbr);
updateDescriptorSet(m_pbrDescriptorSet, 0, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, textures);
}
// Load skybox assets.
m_skybox = createMeshBuffer(Mesh::fromFile("meshes/skybox.obj"));
// Create graphics pipeline & descriptor set layout for skybox
{
const std::vector<VkVertexInputBindingDescription> vertexInputBindings = {
{ 0, sizeof(Mesh::Vertex), VK_VERTEX_INPUT_RATE_VERTEX },
};
const std::vector<VkVertexInputAttributeDescription> vertexAttributes = {
{ 0, 0, VK_FORMAT_R32G32B32_SFLOAT, 0}, // Position
};
const std::vector<VkDescriptorSetLayoutBinding> descriptorSetLayoutBindings = {
{ 0, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_FRAGMENT_BIT, &m_defaultSampler }, // Environment texture
};
setLayout.skybox = createDescriptorSetLayout(&descriptorSetLayoutBindings);
const std::vector<VkDescriptorSetLayout> pipelineDescriptorSetLayouts = {
setLayout.uniforms,
setLayout.skybox,
};
m_skyboxPipelineLayout = createPipelineLayout(&pipelineDescriptorSetLayouts);
VkPipelineMultisampleStateCreateInfo multisampleState = { VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO };
multisampleState.rasterizationSamples = static_cast<VkSampleCountFlagBits>(m_renderTargets[0].samples);
VkPipelineDepthStencilStateCreateInfo depthStencilState = { VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO };
depthStencilState.depthTestEnable = VK_FALSE;
m_skyboxPipeline = createGraphicsPipeline(0,
"shaders/spirv/skybox_vs.spv",
"shaders/spirv/skybox_fs.spv",
m_skyboxPipelineLayout,
&vertexInputBindings,
&vertexAttributes,
&multisampleState,
&depthStencilState);
}
// Allocate & update descriptor set for skybox.
{
const VkDescriptorImageInfo skyboxTexture = { VK_NULL_HANDLE, m_envTexture.view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL };
m_skyboxDescriptorSet = allocateDescriptorSet(m_descriptorPool, setLayout.skybox);
updateDescriptorSet(m_skyboxDescriptorSet, 0, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, { skyboxTexture });
}
// Load & pre-process environment map.
{
Texture envTextureUnfiltered = createTexture(kEnvMapSize, kEnvMapSize, 6, VK_FORMAT_R16G16B16A16_SFLOAT, 0, VK_IMAGE_USAGE_STORAGE_BIT);
// Load & convert equirectangular envuronment map to cubemap texture
{
VkPipeline pipeline = createComputePipeline("shaders/spirv/equirect2cube_cs.spv", computePipelineLayout);
Texture envTextureEquirect = createTexture(Image::fromFile("environment.hdr"), VK_FORMAT_R32G32B32A32_SFLOAT, 1);
const VkDescriptorImageInfo inputTexture = { VK_NULL_HANDLE, envTextureEquirect.view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL };
const VkDescriptorImageInfo outputTexture = { VK_NULL_HANDLE, envTextureUnfiltered.view, VK_IMAGE_LAYOUT_GENERAL };
updateDescriptorSet(computeDescriptorSet, Binding_InputTexture, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, { inputTexture });
updateDescriptorSet(computeDescriptorSet, Binding_OutputTexture, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, { outputTexture });
VkCommandBuffer commandBuffer = beginImmediateCommandBuffer();
{
const auto preDispatchBarrier = ImageMemoryBarrier(envTextureUnfiltered, 0, VK_ACCESS_SHADER_WRITE_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL).mipLevels(0, 1);
pipelineBarrier(commandBuffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, { preDispatchBarrier });
vkCmdBindPipeline(commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline);
vkCmdBindDescriptorSets(commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, computePipelineLayout, 0, 1, &computeDescriptorSet, 0, nullptr);
vkCmdDispatch(commandBuffer, kEnvMapSize/32, kEnvMapSize/32, 6);
const auto postDispatchBarrier = ImageMemoryBarrier(envTextureUnfiltered, VK_ACCESS_SHADER_WRITE_BIT, 0, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL).mipLevels(0, 1);
pipelineBarrier(commandBuffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, { postDispatchBarrier });
}
executeImmediateCommandBuffer(commandBuffer);
vkDestroyPipeline(m_device, pipeline, nullptr);
destroyTexture(envTextureEquirect);
generateMipmaps(envTextureUnfiltered);
}
// Compute pre-filtered specular environment map.
{
const uint32_t numMipTailLevels = kEnvMapLevels - 1;
VkPipeline pipeline;
{
const VkSpecializationMapEntry specializationMap = { 0, 0, sizeof(uint32_t) };
const uint32_t specializationData[] = { numMipTailLevels };
const VkSpecializationInfo specializationInfo = { 1, &specializationMap, sizeof(specializationData), specializationData };
pipeline = createComputePipeline("shaders/spirv/spmap_cs.spv", computePipelineLayout, &specializationInfo);
}
VkCommandBuffer commandBuffer = beginImmediateCommandBuffer();
// Copy base mipmap level into destination environment map.
{
const std::vector<ImageMemoryBarrier> preCopyBarriers = {
ImageMemoryBarrier(envTextureUnfiltered, 0, VK_ACCESS_TRANSFER_READ_BIT, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL).mipLevels(0, 1),
ImageMemoryBarrier(m_envTexture, 0, VK_ACCESS_TRANSFER_WRITE_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL),
};
const std::vector<ImageMemoryBarrier> postCopyBarriers = {
ImageMemoryBarrier(envTextureUnfiltered, VK_ACCESS_TRANSFER_READ_BIT, VK_ACCESS_SHADER_READ_BIT, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL).mipLevels(0, 1),
ImageMemoryBarrier(m_envTexture, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_SHADER_WRITE_BIT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL),
};
pipelineBarrier(commandBuffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, preCopyBarriers);
VkImageCopy copyRegion = {};
copyRegion.extent = { m_envTexture.width, m_envTexture.height, 1 };
copyRegion.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
copyRegion.srcSubresource.layerCount = m_envTexture.layers;
copyRegion.dstSubresource = copyRegion.srcSubresource;
vkCmdCopyImage(commandBuffer,
envTextureUnfiltered.image.resource, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
m_envTexture.image.resource, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1, ©Region);
pipelineBarrier(commandBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, postCopyBarriers);
}
// Pre-filter rest of the mip-chain.
std::vector<VkImageView> envTextureMipTailViews;
{
std::vector<VkDescriptorImageInfo> envTextureMipTailDescriptors;
const VkDescriptorImageInfo inputTexture = { VK_NULL_HANDLE, envTextureUnfiltered.view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL };
updateDescriptorSet(computeDescriptorSet, Binding_InputTexture, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, { inputTexture });
for(uint32_t level=1; level<kEnvMapLevels; ++level) {
envTextureMipTailViews.push_back(createTextureView(m_envTexture, VK_FORMAT_R16G16B16A16_SFLOAT, VK_IMAGE_ASPECT_COLOR_BIT, level, 1));
envTextureMipTailDescriptors.push_back(VkDescriptorImageInfo{ VK_NULL_HANDLE, envTextureMipTailViews[level-1], VK_IMAGE_LAYOUT_GENERAL });
}
updateDescriptorSet(computeDescriptorSet, Binding_OutputMipTail, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, envTextureMipTailDescriptors);
vkCmdBindPipeline(commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline);
vkCmdBindDescriptorSets(commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, computePipelineLayout, 0, 1, &computeDescriptorSet, 0, nullptr);
const float deltaRoughness = 1.0f / std::max(float(numMipTailLevels), 1.0f);
for(uint32_t level=1, size=kEnvMapSize/2; level<kEnvMapLevels; ++level, size/=2) {
const uint32_t numGroups = std::max<uint32_t>(1, size/32);
const SpecularFilterPushConstants pushConstants = { level-1, level * deltaRoughness };
vkCmdPushConstants(commandBuffer, computePipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(SpecularFilterPushConstants), &pushConstants);
vkCmdDispatch(commandBuffer, numGroups, numGroups, 6);
}
const auto barrier = ImageMemoryBarrier(m_envTexture, VK_ACCESS_SHADER_WRITE_BIT, 0, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
pipelineBarrier(commandBuffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, { barrier });
}
executeImmediateCommandBuffer(commandBuffer);
for(VkImageView mipTailView : envTextureMipTailViews) {
vkDestroyImageView(m_device, mipTailView, nullptr);
}
vkDestroyPipeline(m_device, pipeline, nullptr);
destroyTexture(envTextureUnfiltered);
}
// Compute diffuse irradiance cubemap
{
VkPipeline pipeline = createComputePipeline("shaders/spirv/irmap_cs.spv", computePipelineLayout);
const VkDescriptorImageInfo inputTexture = { VK_NULL_HANDLE, m_envTexture.view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL };
const VkDescriptorImageInfo outputTexture = { VK_NULL_HANDLE, m_irmapTexture.view, VK_IMAGE_LAYOUT_GENERAL };
updateDescriptorSet(computeDescriptorSet, Binding_InputTexture, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, { inputTexture });
updateDescriptorSet(computeDescriptorSet, Binding_OutputTexture, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, { outputTexture });
VkCommandBuffer commandBuffer = beginImmediateCommandBuffer();
{
const auto preDispatchBarrier = ImageMemoryBarrier(m_irmapTexture, 0, VK_ACCESS_SHADER_WRITE_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL);
pipelineBarrier(commandBuffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, { preDispatchBarrier });
vkCmdBindPipeline(commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline);
vkCmdBindDescriptorSets(commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, computePipelineLayout, 0, 1, &computeDescriptorSet, 0, nullptr);
vkCmdDispatch(commandBuffer, kIrradianceMapSize/32, kIrradianceMapSize/32, 6);
const auto postDispatchBarrier = ImageMemoryBarrier(m_irmapTexture, VK_ACCESS_SHADER_WRITE_BIT, 0, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
pipelineBarrier(commandBuffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, { postDispatchBarrier });
}
executeImmediateCommandBuffer(commandBuffer);
vkDestroyPipeline(m_device, pipeline, nullptr);
}
// Compute Cook-Torrance BRDF 2D LUT for split-sum approximation.
{
VkPipeline pipeline = createComputePipeline("shaders/spirv/spbrdf_cs.spv", computePipelineLayout);
const VkDescriptorImageInfo outputTexture = { VK_NULL_HANDLE, m_spBRDF_LUT.view, VK_IMAGE_LAYOUT_GENERAL };
updateDescriptorSet(computeDescriptorSet, Binding_OutputTexture, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, { outputTexture });
VkCommandBuffer commandBuffer = beginImmediateCommandBuffer();
{
const auto preDispatchBarrier = ImageMemoryBarrier(m_spBRDF_LUT, 0, VK_ACCESS_SHADER_WRITE_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL);
pipelineBarrier(commandBuffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, { preDispatchBarrier });
vkCmdBindPipeline(commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline);
vkCmdBindDescriptorSets(commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, computePipelineLayout, 0, 1, &computeDescriptorSet, 0, nullptr);
vkCmdDispatch(commandBuffer, kBRDF_LUT_Size/32, kBRDF_LUT_Size/32, 6);
const auto postDispatchBarrier = ImageMemoryBarrier(m_spBRDF_LUT, VK_ACCESS_SHADER_WRITE_BIT, 0, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
pipelineBarrier(commandBuffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, { postDispatchBarrier });
}
executeImmediateCommandBuffer(commandBuffer);
vkDestroyPipeline(m_device, pipeline, nullptr);
}
}
// Clean up
vkDestroyDescriptorSetLayout(m_device, setLayout.uniforms, nullptr);
vkDestroyDescriptorSetLayout(m_device, setLayout.pbr, nullptr);
vkDestroyDescriptorSetLayout(m_device, setLayout.skybox, nullptr);
vkDestroyDescriptorSetLayout(m_device, setLayout.tonemap, nullptr);
vkDestroyDescriptorSetLayout(m_device, setLayout.compute, nullptr);
vkDestroySampler(m_device, computeSampler, nullptr);
vkDestroyPipelineLayout(m_device, computePipelineLayout, nullptr);
vkDestroyDescriptorPool(m_device, computeDescriptorPool, nullptr);
}
void Renderer::render(GLFWwindow* window, const ViewSettings& view, const SceneSettings& scene)
{
const VkDeviceSize zeroOffset = 0;
glm::mat4 projectionMatrix = glm::perspectiveFov(view.fov, float(m_frameRect.extent.width), float(m_frameRect.extent.height), 1.0f, 1000.0f);
projectionMatrix[1][1] *= -1.0f; // Vulkan uses right handed NDC with Y axis pointing down, compensate for that.
const glm::mat4 viewRotationMatrix = glm::eulerAngleXY(glm::radians(view.pitch), glm::radians(view.yaw));
const glm::mat4 sceneRotationMatrix = glm::eulerAngleXY(glm::radians(scene.pitch), glm::radians(scene.yaw));
const glm::mat4 viewMatrix = glm::translate(glm::mat4{ 1.0f }, { 0.0f, 0.0f, -view.distance }) * viewRotationMatrix;
const glm::vec3 eyePosition = glm::inverse(viewMatrix)[3];
VkCommandBuffer commandBuffer = m_commandBuffers[m_frameIndex];
VkImage swapchainImage = m_swapchainImages[m_frameIndex];
VkFramebuffer framebuffer = m_framebuffers[m_frameIndex];
VkDescriptorSet uniformsDescriptorSet = m_uniformsDescriptorSets[m_frameIndex];
VkDescriptorSet tonemapDescriptorSet = m_tonemapDescriptorSets[m_frameIndex];
// Update transform uniforms
{
TransformUniforms* const transformUniforms = m_transformUniforms[m_frameIndex].as<TransformUniforms>();
transformUniforms->viewProjectionMatrix = projectionMatrix * viewMatrix;