Repository navigation
Expand file tree
/
Copy pathVulkanApplication.cpp
More file actions
981 lines (847 loc) · 49.1 KB
/
Copy pathVulkanApplication.cpp
File metadata and controls
981 lines (847 loc) · 49.1 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
/**
* Copyright (c) 2025 Mustafa Yemural - www.mustafayemural.com
* Released under the MIT License
* https://opensource.org/licenses/MIT
*/
#include "VulkanApplication.h"
#include <algorithm>
#include <array>
#include "AppCommonConfig.h"
#include "AppConfig.h"
#include "ApplicationData.h"
#include "GltfToSceneObjectConverter.h"
#include "ModelLoader.h"
#include "SceneObjectBuilder.h"
#include "ShaderLoader.h"
#include "TextureLoader.h"
#include "VulkanShaderModule.h"
namespace examples::post_processing_effects::color_processing_tone_mapping::hdr_temperature_adjustment
{
using namespace constants;
using namespace common::asset_manager;
using namespace common::camera;
using namespace common::scene;
using namespace common::utility;
using namespace common::vulkan_wrapper;
using namespace common::vulkan_framework;
using namespace common::window_wrapper;
VulkanApplication::VulkanApplication(ParameterServer&& params)
: ApplicationColorProcessingToneMapping(std::move(params))
{
}
bool VulkanApplication::Init()
{
if (!ApplicationColorProcessingToneMapping::Init()) {
std::cerr << "Application pre-init failed!" << '\n';
return false;
}
try {
InitAssetManager();
CreateInitialResources();
BuildScene();
CreateAndUpdateDescriptorSets();
InitInputSystem();
CreateRenderPass();
CreatePipelines();
CreateFramebuffers();
CreateCommandBuffers();
} catch (const std::exception& e) {
std::cerr << e.what() << '\n';
return false;
}
return true;
}
void VulkanApplication::DrawFrame()
{
inFlightFences_[currentFrameIndex_]->WaitForFence(true, UINT64_MAX);
uint32_t imageIndex = swapChain_->AcquireNextImage(imageAvailableSemaphores_[currentFrameIndex_], nullptr);
if (swapImagesFences_[imageIndex] != nullptr) {
swapImagesFences_[imageIndex]->WaitForFence(true, UINT64_MAX);
}
inFlightFences_[currentFrameIndex_]->ResetFence();
swapImagesFences_[imageIndex] = inFlightFences_[currentFrameIndex_];
UpdateSceneTransforms();
RecordPresentCommandBuffers(imageIndex);
queue_->Submit({cmdBuffersPresent_[imageIndex]}, {imageAvailableSemaphores_[currentFrameIndex_]},
{renderFinishedSemaphores_[imageIndex]}, inFlightFences_[currentFrameIndex_],
{VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT});
queue_->Present({swapChain_}, {imageIndex}, {renderFinishedSemaphores_[imageIndex]});
currentFrameIndex_ = (currentFrameIndex_ + 1) % MAX_FRAMES_IN_FLIGHT;
}
void VulkanApplication::PreUpdate()
{
// Poll events
ApplicationColorProcessingToneMapping::PreUpdate();
// Process continuous inputs
ProcessInput();
}
void VulkanApplication::InitAssetManager()
{
assetManager_ = std::make_unique<AssetManager>();
assetManager_->RegisterLoader<ShaderAsset>(std::make_unique<ShaderLoader>(SHADERS_DIR, SHADER_TYPE));
assetManager_->RegisterLoader<TextureAsset>(std::make_unique<TextureLoader>(ASSETS_DIR));
}
void VulkanApplication::CreateInitialResources() const
{
ResourceDescriptor resourceCreateInfo;
// Fill buffer create infos
resourceCreateInfo.buffers = {{kLightStorageBuffer,
static_cast<std::uint32_t>(sizeof(PointLightGpuData) * pointLights.size()),
VK_BUFFER_USAGE_STORAGE_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT}};
// Fill shader module create infos
const auto geometryVertexShaderAsset = assetManager_->Load<ShaderAsset>(kGeometryVertexShaderFile);
const auto geometryFragmentShaderAsset = assetManager_->Load<ShaderAsset>(kGeometryFragmentShaderFile);
const auto fullscreenVertexShaderAsset = assetManager_->Load<ShaderAsset>(kFullscreenVertexShaderFile);
const auto lightFragmentShaderAsset = assetManager_->Load<ShaderAsset>(kLightFragmentShaderFile);
const auto postProcessingFragmentShaderAsset = assetManager_->Load<ShaderAsset>(kPostProcessingFragmentShaderFile);
resourceCreateInfo.shaders = {
.modules = {{.name = kGeometryVertexShaderKey, .asset = assetManager_->Get(geometryVertexShaderAsset)},
{.name = kGeometryFragmentShaderKey, .asset = assetManager_->Get(geometryFragmentShaderAsset)},
{.name = kFullscreenVertexShaderKey, .asset = assetManager_->Get(fullscreenVertexShaderAsset)},
{.name = kLightFragmentShaderKey, .asset = assetManager_->Get(lightFragmentShaderAsset)},
{.name = kPostProcessingFragmentShaderKey,
.asset = assetManager_->Get(postProcessingFragmentShaderAsset)}}};
resourceCreateInfo.images = {
ImageResourceCreateInfo{
.name = kPositionImage,
.memProperties = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
.format = VK_FORMAT_R16G16B16A16_SFLOAT,
.dimensions = {currentWindowWidth_, currentWindowHeight_, 1},
.usageFlags = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT,
.views = {ImageViewCreateInfo{.viewName = kPositionImageView, .format = VK_FORMAT_R16G16B16A16_SFLOAT}}},
ImageResourceCreateInfo{
.name = kAlbedoImage,
.memProperties = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
.format = VK_FORMAT_R8G8B8A8_UNORM,
.dimensions = {currentWindowWidth_, currentWindowHeight_, 1},
.usageFlags = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT,
.views = {ImageViewCreateInfo{.viewName = kAlbedoImageView, .format = VK_FORMAT_R8G8B8A8_UNORM}}},
ImageResourceCreateInfo{
.name = kNormalImage,
.memProperties = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
.format = VK_FORMAT_R16G16B16A16_SFLOAT,
.dimensions = {currentWindowWidth_, currentWindowHeight_, 1},
.usageFlags = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT,
.views = {ImageViewCreateInfo{.viewName = kNormalImageView, .format = VK_FORMAT_R16G16B16A16_SFLOAT}}},
ImageResourceCreateInfo{.name = kRoughnessMetallicImage,
.memProperties = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
.format = VK_FORMAT_R8G8B8A8_UNORM,
.dimensions = {currentWindowWidth_, currentWindowHeight_, 1},
.usageFlags = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT,
.views = {ImageViewCreateInfo{.viewName = kRoughnessMetallicImageView,
.format = VK_FORMAT_R8G8B8A8_UNORM}}},
ImageResourceCreateInfo{.name = kLightingOutputImage,
.memProperties = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
.format = VK_FORMAT_R16G16B16A16_SFLOAT,
.dimensions = {currentWindowWidth_, currentWindowHeight_, 1},
.usageFlags = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT,
.views = {ImageViewCreateInfo{.viewName = kLightingOutputImageView,
.format = VK_FORMAT_R16G16B16A16_SFLOAT}}},
ImageResourceCreateInfo{
.name = kDepthImage,
.memProperties = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
.format = depthImageFormat_,
.dimensions = {currentWindowWidth_, currentWindowHeight_, 1},
.usageFlags = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT,
.views = {ImageViewCreateInfo{.viewName = kDepthImageView,
.format = depthImageFormat_,
.subresourceRange = {.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1}}}}};
resourceCreateInfo.samplers = {
{.name = kMainSampler, .filtering = {.magFilter = VK_FILTER_LINEAR, .minFilter = VK_FILTER_LINEAR}}};
CreateVulkanResources(resourceCreateInfo);
}
void VulkanApplication::BuildScene()
{
SceneConfig sceneConfig;
sceneConfig.attributeLayout = attributeLayouts;
sceneConfig.enabledMaterialComponents = enabledMaterialComponents;
sceneConfig.primitiveStackCount = 48U;
sceneConfig.primitiveSectorCount = 48U;
sceneConfig.imageTransferCmdPool = cmdPool_;
sceneConfig.imageTransferQueue = queue_;
scene_ = std::make_unique<Scene>(*resources_, sceneConfig);
auto& sceneImageStorage = scene_->GetGpuImageStorage();
// Add camera
const float aspectRatio = static_cast<float>(currentWindowWidth_) / static_cast<float>(currentWindowHeight_);
camera_ = std::make_shared<PerspectiveCamera>(glm::vec3(0.0f, 3.5f, 11.0f), aspectRatio);
// Register textures
for (const auto& [textureName, texturePath, format]: textureAssets) {
const auto asset = assetManager_->Load<TextureAsset>(texturePath);
sceneImageStorage.StoreTexture(textureName, kMainSampler, assetManager_->Get(asset), format);
}
// Create and register scene materials
for (const auto& mat: materials) {
Material material{};
material.albedoColor = mat.albedoColor;
material.albedoMap = mat.albedoTextureName.empty() ? -1 : sceneImageStorage.GetTextureId(mat.albedoTextureName);
material.metallic = mat.metallic;
material.metallicMap =
mat.metallicTextureName.empty() ? -1 : sceneImageStorage.GetTextureId(mat.metallicTextureName);
material.roughness = mat.roughness;
material.roughnessMap =
mat.roughnessTextureName.empty() ? -1 : sceneImageStorage.GetTextureId(mat.roughnessTextureName);
material.uvScale = mat.uvScale;
material.normalMap = mat.normalTextureName.empty() ? -1 : sceneImageStorage.GetTextureId(mat.normalTextureName);
materialRegistry_[mat.materialName] = material;
}
auto rootObjectBuilder = SceneObjectBuilder(*scene_, kRootObject);
// Room parts (floor and walls)
std::uint32_t index = 0;
for (const auto& [meshType, position, eulerAngles, scale, materialName]: roomParts) {
if (!materialRegistry_.contains(materialName)) {
throw std::runtime_error("Material not found: " + materialName);
}
const Material& material = materialRegistry_.at(materialName);
rootObjectBuilder.AddChild(SceneObjectBuilder(*scene_, kRoomObject + std::to_string(index++))
.WithBuiltinMesh(meshType)
.WithMaterial(material)
.WithPosition(position)
.WithEulerAngles(eulerAngles)
.WithScale(scale));
}
// Basic shapes inside the room
index = 0;
for (const auto& [meshType, position, eulerAngles, scale, materialName]: propObjects) {
if (!materialRegistry_.contains(materialName)) {
throw std::runtime_error("Material not found: " + materialName);
}
const Material& material = materialRegistry_.at(materialName);
rootObjectBuilder.AddChild(SceneObjectBuilder(*scene_, kPropObject + std::to_string(index++))
.WithBuiltinMesh(meshType)
.WithMaterial(material)
.WithPosition(position)
.WithEulerAngles(eulerAngles)
.WithScale(scale));
}
const auto& rootObject = rootObjectBuilder.Build();
scene_->AddRootObject(rootObject);
}
void VulkanApplication::CreateAndUpdateDescriptorSets() const
{
// Create descriptor sets
const auto combinedImageSamplerCount = scene_->GetGpuImageStorage().GetTextureCount();
const DescriptorResourceCreateInfo descriptorResourceCreateInfo = {
.maxSets = 3,
.poolSizes = {{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 3},
{VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1},
{VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, combinedImageSamplerCount + 5}},
.layouts =
{
{.name = kMainDescSetLayout,
.bindings = {{0, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_VERTEX_BIT, nullptr},
{1, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_FRAGMENT_BIT, nullptr},
{2, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, combinedImageSamplerCount,
VK_SHADER_STAGE_FRAGMENT_BIT, nullptr}}},
{.name = kLightDescSetLayout,
.bindings =
{{0, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_FRAGMENT_BIT, nullptr},
{1, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_FRAGMENT_BIT, nullptr},
{2, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_FRAGMENT_BIT, nullptr},
{3, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_FRAGMENT_BIT, nullptr},
{4, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_FRAGMENT_BIT, nullptr}}},
{.name = kPostProcessingDescSetLayout,
.bindings = {{0, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_FRAGMENT_BIT,
nullptr}}},
},
.descriptorSets = {{.name = kMainDescSet, .layoutName = kMainDescSetLayout},
{.name = kLightDescSet, .layoutName = kLightDescSetLayout},
{.name = kPostProcessingDescSet, .layoutName = kPostProcessingDescSetLayout}}};
resources_->CreateDescriptorSets(descriptorResourceCreateInfo);
std::vector<VkDescriptorBufferInfo> storageTransformBufferInfos;
storageTransformBufferInfos.emplace_back(scene_->GetTransformStorageBuffer()->GetHandle(), 0, VK_WHOLE_SIZE);
std::vector<VkDescriptorBufferInfo> storageMaterialBufferInfos;
storageMaterialBufferInfos.emplace_back(scene_->GetMaterialStorageBuffer()->GetHandle(), 0, VK_WHOLE_SIZE);
std::vector<VkDescriptorBufferInfo> storageLightBufferInfos;
storageLightBufferInfos.emplace_back(resources_->GetBuffer(kLightStorageBuffer)->GetHandle(), 0, VK_WHOLE_SIZE);
auto descriptorImageInfos = scene_->GetGpuImageStorage().GetDescriptorImageInfos();
std::vector<VkDescriptorImageInfo> positionImageInfos;
positionImageInfos.emplace_back(resources_->GetSampler(kMainSampler)->GetHandle(),
resources_->GetImageView(kPositionImage, kPositionImageView)->GetHandle(),
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
std::vector<VkDescriptorImageInfo> albedoImageInfos;
albedoImageInfos.emplace_back(resources_->GetSampler(kMainSampler)->GetHandle(),
resources_->GetImageView(kAlbedoImage, kAlbedoImageView)->GetHandle(),
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
std::vector<VkDescriptorImageInfo> normalImageInfos;
normalImageInfos.emplace_back(resources_->GetSampler(kMainSampler)->GetHandle(),
resources_->GetImageView(kNormalImage, kNormalImageView)->GetHandle(),
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
std::vector<VkDescriptorImageInfo> roughnessMetallicImageInfos;
roughnessMetallicImageInfos.emplace_back(
resources_->GetSampler(kMainSampler)->GetHandle(),
resources_->GetImageView(kRoughnessMetallicImage, kRoughnessMetallicImageView)->GetHandle(),
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
std::vector<VkDescriptorImageInfo> lightingOutputImageInfos;
lightingOutputImageInfos.emplace_back(
resources_->GetSampler(kMainSampler)->GetHandle(),
resources_->GetImageView(kLightingOutputImage, kLightingOutputImageView)->GetHandle(),
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
BufferWriteRequest transformStorageBufferRequest;
transformStorageBufferRequest.descriptorSetName = kMainDescSet;
transformStorageBufferRequest.bindingIndex = 0;
transformStorageBufferRequest.buffers = storageTransformBufferInfos;
transformStorageBufferRequest.type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
BufferWriteRequest transformMaterialBufferRequest;
transformMaterialBufferRequest.descriptorSetName = kMainDescSet;
transformMaterialBufferRequest.bindingIndex = 1;
transformMaterialBufferRequest.buffers = storageMaterialBufferInfos;
transformMaterialBufferRequest.type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
ImageWriteRequest textureUpdateRequest;
textureUpdateRequest.descriptorSetName = kMainDescSet;
textureUpdateRequest.bindingIndex = 2;
textureUpdateRequest.images = descriptorImageInfos;
textureUpdateRequest.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
ImageWriteRequest positionUpdateRequest;
positionUpdateRequest.descriptorSetName = kLightDescSet;
positionUpdateRequest.bindingIndex = 0;
positionUpdateRequest.images = positionImageInfos;
positionUpdateRequest.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
ImageWriteRequest albedoUpdateRequest;
albedoUpdateRequest.descriptorSetName = kLightDescSet;
albedoUpdateRequest.bindingIndex = 1;
albedoUpdateRequest.images = albedoImageInfos;
albedoUpdateRequest.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
ImageWriteRequest normalUpdateRequest;
normalUpdateRequest.descriptorSetName = kLightDescSet;
normalUpdateRequest.bindingIndex = 2;
normalUpdateRequest.images = normalImageInfos;
normalUpdateRequest.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
ImageWriteRequest roughnessMetallicUpdateRequest;
roughnessMetallicUpdateRequest.descriptorSetName = kLightDescSet;
roughnessMetallicUpdateRequest.bindingIndex = 3;
roughnessMetallicUpdateRequest.images = roughnessMetallicImageInfos;
roughnessMetallicUpdateRequest.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
BufferWriteRequest lightUpdateRequest;
lightUpdateRequest.descriptorSetName = kLightDescSet;
lightUpdateRequest.bindingIndex = 4;
lightUpdateRequest.buffers = storageLightBufferInfos;
lightUpdateRequest.type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
ImageWriteRequest lightingOutputUpdateRequest;
lightingOutputUpdateRequest.descriptorSetName = kPostProcessingDescSet;
lightingOutputUpdateRequest.bindingIndex = 0;
lightingOutputUpdateRequest.images = lightingOutputImageInfos;
lightingOutputUpdateRequest.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
const DescriptorUpdateInfo descriptorSetUpdateInfo = {
.bufferWriteRequests = {transformStorageBufferRequest, transformMaterialBufferRequest, lightUpdateRequest},
.imageWriteRequests = {textureUpdateRequest, positionUpdateRequest, albedoUpdateRequest, normalUpdateRequest,
roughnessMetallicUpdateRequest, lightingOutputUpdateRequest}};
resources_->UpdateDescriptorSet(descriptorSetUpdateInfo);
}
void VulkanApplication::InitInputSystem()
{
lastX_ = static_cast<float>(currentWindowWidth_) / 2.0f;
lastY_ = static_cast<float>(currentWindowHeight_) / 2.0f;
window_->DisableCursor();
window_->OnMouseMove([&](const MouseMoveEvent& event) {
const auto xPos = static_cast<float>(event.x);
const auto yPos = static_cast<float>(event.y);
if (firstMouseTriggered_) {
lastX_ = xPos;
lastY_ = yPos;
firstMouseTriggered_ = false;
}
float xOffset = xPos - lastX_;
float yOffset = lastY_ - yPos;
lastX_ = xPos;
lastY_ = yPos;
const float sensitivity = GetParamFloat(AppSettings::MouseSensitivity) * static_cast<float>(deltaTime_);
xOffset *= sensitivity;
yOffset *= sensitivity;
camera_->Rotate(xOffset, yOffset);
});
window_->OnKey([&](const KeyEvent& event) {
if (event.action != GLFW_PRESS) {
return;
}
constexpr float kExposureStep = 0.5f;
constexpr float kTemperatureStep = 500.0f;
constexpr float kTintStep = 0.1f;
switch (event.key) {
case GLFW_KEY_SPACE:
exposure_ = 1.0f;
temperature_ = 6500.0f;
tint_ = 0.0f;
std::cout << "All values have been reset to default!" << std::endl;
break;
case GLFW_KEY_0:
mode_ = TemperatureMode::OFF;
std::cout << "Current mode: Bypass" << std::endl;
break;
case GLFW_KEY_1:
mode_ = TemperatureMode::WHITE_BALANCE;
std::cout << "Current mode: White Balance" << std::endl;
break;
case GLFW_KEY_2:
mode_ = TemperatureMode::COLOR_TEMPERATURE;
std::cout << "Current mode: Color Temperature" << std::endl;
break;
case GLFW_KEY_Q:
exposure_ = std::min(exposure_ + kExposureStep, 5.0f);
std::cout << "Current exposure: " << exposure_ << std::endl;
break;
case GLFW_KEY_E:
exposure_ = std::max(exposure_ - kExposureStep, -5.0f);
std::cout << "Current exposure: " << exposure_ << std::endl;
break;
case GLFW_KEY_R:
temperature_ = std::min(temperature_ + kTemperatureStep, 12000.0f);
std::cout << "Current temperature: " << temperature_ << std::endl;
break;
case GLFW_KEY_F:
temperature_ = std::max(temperature_ - kTemperatureStep, 2000.0f);
std::cout << "Current temperature: " << temperature_ << std::endl;
break;
case GLFW_KEY_T:
tint_ = std::min(tint_ + kTintStep, 1.0f);
std::cout << "Current tint: " << tint_ << std::endl;
break;
case GLFW_KEY_G:
tint_ = std::max(tint_ - kTintStep, -1.0f);
std::cout << "Current tint: " << tint_ << std::endl;
break;
default:
break;
}
});
}
void VulkanApplication::CreateRenderPass()
{
std::vector geometryColorAttachments{VkAttachmentReference{0, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL},
VkAttachmentReference{1, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL},
VkAttachmentReference{2, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL},
VkAttachmentReference{3, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL}};
VkAttachmentReference depthAttachmentRef{4, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL};
geometryRenderPass_ = device_->CreateRenderPass([&](auto& builder) {
builder.AddAttachment([&](auto& attachmentCreateInfo) {
attachmentCreateInfo.format = VK_FORMAT_R16G16B16A16_SFLOAT;
attachmentCreateInfo.samples = VK_SAMPLE_COUNT_1_BIT;
attachmentCreateInfo.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
attachmentCreateInfo.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
attachmentCreateInfo.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
attachmentCreateInfo.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
attachmentCreateInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
attachmentCreateInfo.finalLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
})
.AddAttachment([](auto& attachmentCreateInfo) {
attachmentCreateInfo.format = VK_FORMAT_R8G8B8A8_UNORM;
attachmentCreateInfo.samples = VK_SAMPLE_COUNT_1_BIT;
attachmentCreateInfo.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
attachmentCreateInfo.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
attachmentCreateInfo.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
attachmentCreateInfo.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
attachmentCreateInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
attachmentCreateInfo.finalLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
})
.AddAttachment([&](auto& attachmentCreateInfo) {
attachmentCreateInfo.format = VK_FORMAT_R16G16B16A16_SFLOAT;
attachmentCreateInfo.samples = VK_SAMPLE_COUNT_1_BIT;
attachmentCreateInfo.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
attachmentCreateInfo.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
attachmentCreateInfo.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
attachmentCreateInfo.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
attachmentCreateInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
attachmentCreateInfo.finalLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
})
.AddAttachment([](auto& attachmentCreateInfo) {
attachmentCreateInfo.format = VK_FORMAT_R8G8B8A8_UNORM;
attachmentCreateInfo.samples = VK_SAMPLE_COUNT_1_BIT;
attachmentCreateInfo.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
attachmentCreateInfo.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
attachmentCreateInfo.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
attachmentCreateInfo.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
attachmentCreateInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
attachmentCreateInfo.finalLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
})
.AddAttachment([&](auto& attachmentCreateInfo) {
attachmentCreateInfo.format = depthImageFormat_;
attachmentCreateInfo.samples = VK_SAMPLE_COUNT_1_BIT;
attachmentCreateInfo.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
attachmentCreateInfo.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
attachmentCreateInfo.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
attachmentCreateInfo.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
attachmentCreateInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
attachmentCreateInfo.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
})
.AddSubpass([&](auto& subpassCreateInfo) {
subpassCreateInfo.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpassCreateInfo.colorAttachmentCount = geometryColorAttachments.size();
subpassCreateInfo.pColorAttachments = geometryColorAttachments.data();
subpassCreateInfo.pDepthStencilAttachment = &depthAttachmentRef;
})
.AddDependency([](auto& dependency) {
dependency.srcSubpass = 0;
dependency.dstSubpass = VK_SUBPASS_EXTERNAL;
dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
dependency.dstStageMask = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
dependency.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
dependency.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
dependency.dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT;
});
});
if (!geometryRenderPass_) {
throw std::runtime_error("Failed to create render pass (for geometry)!");
}
VkAttachmentReference lightingColorAttachment = {0, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL};
lightingRenderPass_ = device_->CreateRenderPass([&](auto& builder) {
builder.AddAttachment([](auto& attachmentCreateInfo) {
attachmentCreateInfo.format = VK_FORMAT_R16G16B16A16_SFLOAT;
attachmentCreateInfo.samples = VK_SAMPLE_COUNT_1_BIT;
attachmentCreateInfo.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
attachmentCreateInfo.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
attachmentCreateInfo.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
attachmentCreateInfo.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
attachmentCreateInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
attachmentCreateInfo.finalLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
})
.AddSubpass([&](auto& subpassCreateInfo) {
subpassCreateInfo.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpassCreateInfo.colorAttachmentCount = 1;
subpassCreateInfo.pColorAttachments = &lightingColorAttachment;
});
});
if (!lightingRenderPass_) {
throw std::runtime_error("Failed to create render pass (for lighting)!");
}
VkAttachmentReference presentColorAttachment = {0, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL};
postProcessingRenderPass_ = device_->CreateRenderPass([&](auto& builder) {
builder.AddAttachment([](auto& attachmentCreateInfo) {
attachmentCreateInfo.format = VK_FORMAT_B8G8R8A8_SRGB;
attachmentCreateInfo.samples = VK_SAMPLE_COUNT_1_BIT;
attachmentCreateInfo.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
attachmentCreateInfo.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
attachmentCreateInfo.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
attachmentCreateInfo.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
attachmentCreateInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
attachmentCreateInfo.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
})
.AddSubpass([&](auto& subpassCreateInfo) {
subpassCreateInfo.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpassCreateInfo.colorAttachmentCount = 1;
subpassCreateInfo.pColorAttachments = &presentColorAttachment;
});
});
if (!postProcessingRenderPass_) {
throw std::runtime_error("Failed to create render pass (for post-processing)!");
}
}
void VulkanApplication::CreatePipelines()
{
VkPushConstantRange meshPushConstant;
meshPushConstant.offset = 0;
meshPushConstant.size = sizeof(MeshPushConstants);
meshPushConstant.stageFlags = VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT;
geometryPipelineLayout_ =
device_->CreatePipelineLayout({resources_->GetDescriptorLayout(kMainDescSetLayout)}, {meshPushConstant});
if (!geometryPipelineLayout_) {
throw std::runtime_error("Failed to create pipeline layout!");
}
VkViewport viewport{0, 0, static_cast<float>(currentWindowWidth_), static_cast<float>(currentWindowHeight_),
0.0f, 1.0f};
VkRect2D scissor{0, 0, currentWindowWidth_, currentWindowHeight_};
VkPipelineColorBlendAttachmentState colorBlendAttachment{};
colorBlendAttachment.blendEnable = VK_FALSE;
colorBlendAttachment.colorWriteMask =
VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
std::vector blendAttachments(4, colorBlendAttachment);
const auto bindings = scene_->GetBindingDescriptions();
const auto attributes = scene_->GetAttributeDescriptions();
geometryPassPipeline_ =
device_->CreateGraphicsPipeline(geometryPipelineLayout_, geometryRenderPass_, [&](auto& builder) {
builder.AddShaderStage([&](auto& shaderStageCreateInfo) {
shaderStageCreateInfo.stage = VK_SHADER_STAGE_VERTEX_BIT;
shaderStageCreateInfo.module = resources_->GetShaderModule(kGeometryVertexShaderKey)->GetHandle();
});
builder.AddShaderStage([&](auto& shaderStageCreateInfo) {
shaderStageCreateInfo.stage = VK_SHADER_STAGE_FRAGMENT_BIT;
shaderStageCreateInfo.module = resources_->GetShaderModule(kGeometryFragmentShaderKey)->GetHandle();
});
builder.SetVertexInputState([&](auto& vertexInputStateCreateInfo) {
vertexInputStateCreateInfo.vertexBindingDescriptionCount = bindings.size();
vertexInputStateCreateInfo.pVertexBindingDescriptions = bindings.data();
vertexInputStateCreateInfo.vertexAttributeDescriptionCount = attributes.size();
vertexInputStateCreateInfo.pVertexAttributeDescriptions = attributes.data();
});
builder.SetViewportState([&](auto& viewportStateCreateInfo) {
viewportStateCreateInfo.viewportCount = 1;
viewportStateCreateInfo.pViewports = &viewport;
viewportStateCreateInfo.scissorCount = 1;
viewportStateCreateInfo.pScissors = &scissor;
});
builder.SetColorBlendState([&](auto& blendStateCreateInfo) {
blendStateCreateInfo.attachmentCount = blendAttachments.size();
blendStateCreateInfo.pAttachments = blendAttachments.data();
});
builder.SetDepthStencilState([&](auto& depthStencilStateCreateInfo) {
depthStencilStateCreateInfo.depthTestEnable = VK_TRUE;
depthStencilStateCreateInfo.depthWriteEnable = VK_TRUE;
depthStencilStateCreateInfo.depthCompareOp = VK_COMPARE_OP_LESS;
});
});
if (!geometryPassPipeline_) {
throw std::runtime_error("Failed to create graphics pipeline (for geometry)!");
}
VkPushConstantRange lightingPushConstant;
lightingPushConstant.offset = 0;
lightingPushConstant.size = sizeof(LightingPushConstants);
lightingPushConstant.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
lightPipelineLayout_ = device_->CreatePipelineLayout({resources_->GetDescriptorLayout(kLightDescSetLayout)},
{lightingPushConstant});
if (!lightPipelineLayout_) {
throw std::runtime_error("Failed to create pipeline layout!");
}
lightPassPipeline_ = device_->CreateGraphicsPipeline(lightPipelineLayout_, lightingRenderPass_, [&](auto& builder) {
builder.AddShaderStage([&](auto& shaderStageCreateInfo) {
shaderStageCreateInfo.stage = VK_SHADER_STAGE_VERTEX_BIT;
shaderStageCreateInfo.module = resources_->GetShaderModule(kFullscreenVertexShaderKey)->GetHandle();
});
builder.AddShaderStage([&](auto& shaderStageCreateInfo) {
shaderStageCreateInfo.stage = VK_SHADER_STAGE_FRAGMENT_BIT;
shaderStageCreateInfo.module = resources_->GetShaderModule(kLightFragmentShaderKey)->GetHandle();
});
builder.SetVertexInputState([&](auto& vertexInputStateCreateInfo) {
vertexInputStateCreateInfo.vertexBindingDescriptionCount = 0;
vertexInputStateCreateInfo.vertexAttributeDescriptionCount = 0;
});
builder.SetViewportState([&](auto& viewportStateCreateInfo) {
viewportStateCreateInfo.viewportCount = 1;
viewportStateCreateInfo.pViewports = &viewport;
viewportStateCreateInfo.scissorCount = 1;
viewportStateCreateInfo.pScissors = &scissor;
});
builder.SetColorBlendState([&](auto& blendStateCreateInfo) {
blendStateCreateInfo.attachmentCount = 1;
blendStateCreateInfo.pAttachments = blendAttachments.data();
});
builder.SetDepthStencilState([&](auto& depthStencilStateCreateInfo) {
depthStencilStateCreateInfo.depthTestEnable = VK_FALSE;
depthStencilStateCreateInfo.depthWriteEnable = VK_FALSE;
});
});
if (!lightPassPipeline_) {
throw std::runtime_error("Failed to create graphics pipeline (for light)!");
}
VkPushConstantRange temperaturePushConstant;
temperaturePushConstant.offset = 0;
temperaturePushConstant.size = sizeof(TemperaturePushConstants);
temperaturePushConstant.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
postProcessingPipelineLayout_ = device_->CreatePipelineLayout(
{resources_->GetDescriptorLayout(kPostProcessingDescSetLayout)}, {temperaturePushConstant});
if (!postProcessingPipelineLayout_) {
throw std::runtime_error("Failed to create pipeline layout!");
}
postProcessingPassPipeline_ = device_->CreateGraphicsPipeline(
postProcessingPipelineLayout_, postProcessingRenderPass_, [&](auto& builder) {
builder.AddShaderStage([&](auto& shaderStageCreateInfo) {
shaderStageCreateInfo.stage = VK_SHADER_STAGE_VERTEX_BIT;
shaderStageCreateInfo.module = resources_->GetShaderModule(kFullscreenVertexShaderKey)->GetHandle();
});
builder.AddShaderStage([&](auto& shaderStageCreateInfo) {
shaderStageCreateInfo.stage = VK_SHADER_STAGE_FRAGMENT_BIT;
shaderStageCreateInfo.module =
resources_->GetShaderModule(kPostProcessingFragmentShaderKey)->GetHandle();
});
builder.SetVertexInputState([&](auto& vertexInputStateCreateInfo) {
vertexInputStateCreateInfo.vertexBindingDescriptionCount = 0;
vertexInputStateCreateInfo.vertexAttributeDescriptionCount = 0;
});
builder.SetViewportState([&](auto& viewportStateCreateInfo) {
viewportStateCreateInfo.viewportCount = 1;
viewportStateCreateInfo.pViewports = &viewport;
viewportStateCreateInfo.scissorCount = 1;
viewportStateCreateInfo.pScissors = &scissor;
});
builder.SetColorBlendState([&](auto& blendStateCreateInfo) {
blendStateCreateInfo.attachmentCount = 1;
blendStateCreateInfo.pAttachments = blendAttachments.data();
});
builder.SetDepthStencilState([&](auto& depthStencilStateCreateInfo) {
depthStencilStateCreateInfo.depthTestEnable = VK_FALSE;
depthStencilStateCreateInfo.depthWriteEnable = VK_FALSE;
});
});
if (!postProcessingPassPipeline_) {
throw std::runtime_error("Failed to create graphics pipeline (for post-processing)!");
}
}
void VulkanApplication::CreateFramebuffers()
{
// Geometry framebuffer
const auto& positionImageView = resources_->GetImageView(kPositionImage, kPositionImageView);
const auto& albedoImageView = resources_->GetImageView(kAlbedoImage, kAlbedoImageView);
const auto& normalImageView = resources_->GetImageView(kNormalImage, kNormalImageView);
const auto& roughnessMetallicImageView =
resources_->GetImageView(kRoughnessMetallicImage, kRoughnessMetallicImageView);
const auto& depthImageView = resources_->GetImageView(kDepthImage, kDepthImageView);
geometryFramebuffer_ = device_->CreateFramebuffer(
geometryRenderPass_,
{positionImageView, albedoImageView, normalImageView, roughnessMetallicImageView, depthImageView},
[&](auto& builder) { builder.SetDimensions(currentWindowWidth_, currentWindowHeight_); });
if (!geometryFramebuffer_) {
throw std::runtime_error("Failed to create framebuffer (for geometry)!");
}
// Lighting framebuffer
const auto& lightingOutputImageView = resources_->GetImageView(kLightingOutputImage, kLightingOutputImageView);
lightingFramebuffer_ =
device_->CreateFramebuffer(lightingRenderPass_, {lightingOutputImageView}, [&](auto& builder) {
builder.SetDimensions(currentWindowWidth_, currentWindowHeight_);
});
if (!lightingFramebuffer_) {
throw std::runtime_error("Failed to create framebuffer (for lighting)!");
}
// Present framebuffers (post-processing)
for (const auto& swapImage: swapChainImageViews_) {
auto framebuffer = device_->CreateFramebuffer(postProcessingRenderPass_, {swapImage}, [&](auto& builder) {
builder.SetDimensions(currentWindowWidth_, currentWindowHeight_);
});
if (!framebuffer) {
throw std::runtime_error("Failed to create framebuffer (for present)!");
}
presentFramebuffers_.push_back(framebuffer);
}
}
void VulkanApplication::CreateCommandBuffers()
{
cmdBuffersPresent_ = cmdPool_->CreateCommandBuffers(presentFramebuffers_.size(), VK_COMMAND_BUFFER_LEVEL_PRIMARY);
if (cmdBuffersPresent_.empty()) {
throw std::runtime_error("Failed to create command buffers!");
}
}
void VulkanApplication::RecordPresentCommandBuffers(const std::uint32_t currentImageIndex)
{
std::array<VkClearValue, 5> geometryPassClearValues{};
geometryPassClearValues[0].color = {{0.0f, 0.0f, 0.0f, 0.0f}}; // Position
geometryPassClearValues[1].color = params_.Get<VkClearColorValue>(AppSettings::ClearColor); // Albedo
geometryPassClearValues[2].color = {{0.0f, 0.0f, 0.0f, 0.0f}}; // Normal
geometryPassClearValues[3].color = {{0.0f, 0.0f, 0.0f, 0.0f}}; // Roughness/Metallic
geometryPassClearValues[4].depthStencil = {1.0f, 0}; // Depth
std::array<VkClearValue, 1> lightPassClearValues{};
lightPassClearValues[0].color = {{0.0f, 0.0f, 0.0f, 1.0f}}; // Not important
std::array<VkClearValue, 1> postProcessingPassClearValues{};
postProcessingPassClearValues[0].color = {{0.0f, 0.0f, 0.0f, 1.0f}}; // Not important
const auto& currentCmdBuffer = cmdBuffersPresent_[currentImageIndex];
if (!currentCmdBuffer->BeginCommandBuffer(nullptr)) {
throw std::runtime_error("Failed to begin recording command buffer!");
}
// Geometry Pass
{
currentCmdBuffer->BeginRenderPass(
[&](auto& beginInfo) {
beginInfo.renderPass = geometryRenderPass_->GetHandle();
beginInfo.framebuffer = geometryFramebuffer_->GetHandle();
beginInfo.renderArea.offset = {0, 0};
beginInfo.renderArea.extent = VkExtent2D(currentWindowWidth_, currentWindowHeight_);
beginInfo.clearValueCount = geometryPassClearValues.size();
beginInfo.pClearValues = geometryPassClearValues.data();
},
VK_SUBPASS_CONTENTS_INLINE);
const std::vector cubeDescSets{resources_->GetDescriptorSet(kMainDescSet)};
currentCmdBuffer->BindDescriptorSets(VK_PIPELINE_BIND_POINT_GRAPHICS, geometryPipelineLayout_, 0, cubeDescSets);
const std::vector vertexBuffers(scene_->GetAttributeCount(), scene_->GetGeometryBuffer());
// Draw scene objects
currentCmdBuffer->BindPipeline(geometryPassPipeline_, VK_PIPELINE_BIND_POINT_GRAPHICS);
scene_->Traverse([&](const SceneObject& sceneObject) {
if (sceneObject.HasRenderable()) {
const auto [vertexOffsets, indexOffset, indexCount] = sceneObject.GetMeshGpu().value();
currentCmdBuffer->BindVertexBuffers(vertexBuffers, 0, vertexBuffers.size(), vertexOffsets);
currentCmdBuffer->BindIndexBuffer(scene_->GetGeometryBuffer(), indexOffset);
MeshPushConstants meshPushConstants{};
meshPushConstants.objectId = sceneObject.GetObjectId();
meshPushConstants.view = camera_->GetViewMatrix();
meshPushConstants.projection = camera_->GetProjectionMatrix();
currentCmdBuffer->PushConstants(geometryPipelineLayout_,
VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0,
sizeof(meshPushConstants), &meshPushConstants);
currentCmdBuffer->DrawIndexed(indexCount, 1, 0, 0, 0);
}
});
currentCmdBuffer->EndRenderPass();
}
// Light Pass
{
currentCmdBuffer->BeginRenderPass(
[&](auto& beginInfo) {
beginInfo.renderPass = lightingRenderPass_->GetHandle();
beginInfo.framebuffer = lightingFramebuffer_->GetHandle();
beginInfo.renderArea.offset = {0, 0};
beginInfo.renderArea.extent = VkExtent2D(currentWindowWidth_, currentWindowHeight_);
beginInfo.clearValueCount = lightPassClearValues.size();
beginInfo.pClearValues = lightPassClearValues.data();
},
VK_SUBPASS_CONTENTS_INLINE);
const std::vector lightDescSets{resources_->GetDescriptorSet(kLightDescSet)};
currentCmdBuffer->BindDescriptorSets(VK_PIPELINE_BIND_POINT_GRAPHICS, lightPipelineLayout_, 0, lightDescSets);
currentCmdBuffer->BindPipeline(lightPassPipeline_, VK_PIPELINE_BIND_POINT_GRAPHICS);
LightingPushConstants lightingPushConstants{};
lightingPushConstants.lightCount = static_cast<std::uint32_t>(pointLights.size());
currentCmdBuffer->PushConstants(lightPipelineLayout_, VK_SHADER_STAGE_FRAGMENT_BIT, 0,
sizeof(lightingPushConstants), &lightingPushConstants);
// Draw fullscreen quad
currentCmdBuffer->Draw(6, 1, 0, 0);
currentCmdBuffer->EndRenderPass();
}
// Post-Processing Pass
{
currentCmdBuffer->BeginRenderPass(
[&](auto& beginInfo) {
beginInfo.renderPass = postProcessingRenderPass_->GetHandle();
beginInfo.framebuffer = presentFramebuffers_[currentImageIndex]->GetHandle();
beginInfo.renderArea.offset = {0, 0};
beginInfo.renderArea.extent = VkExtent2D(currentWindowWidth_, currentWindowHeight_);
beginInfo.clearValueCount = postProcessingPassClearValues.size();
beginInfo.pClearValues = postProcessingPassClearValues.data();
},
VK_SUBPASS_CONTENTS_INLINE);
const std::vector postProcessingDescSets{resources_->GetDescriptorSet(kPostProcessingDescSet)};
currentCmdBuffer->BindDescriptorSets(VK_PIPELINE_BIND_POINT_GRAPHICS, postProcessingPipelineLayout_, 0,
postProcessingDescSets);
currentCmdBuffer->BindPipeline(postProcessingPassPipeline_, VK_PIPELINE_BIND_POINT_GRAPHICS);
TemperaturePushConstants temperaturePushConstants{};
temperaturePushConstants.exposure = exposure_;
temperaturePushConstants.temperature = temperature_;
temperaturePushConstants.tint = tint_;
temperaturePushConstants.mode = static_cast<std::uint32_t>(mode_);
currentCmdBuffer->PushConstants(postProcessingPipelineLayout_, VK_SHADER_STAGE_FRAGMENT_BIT, 0,
sizeof(temperaturePushConstants), &temperaturePushConstants);
// Draw fullscreen quad
currentCmdBuffer->Draw(6, 1, 0, 0);
currentCmdBuffer->EndRenderPass();
}
if (!currentCmdBuffer->EndCommandBuffer()) {
throw std::runtime_error("Failed to end recording command buffer!");
}
}
void VulkanApplication::UpdateSceneTransforms() const
{
// Covert point light position from world-space to view-space
std::vector<PointLightGpuData> pointLightInfos;
for (const auto& pointLight: pointLights) {
PointLightGpuData pointLightData{};
pointLightData.lightPosition = camera_->GetViewMatrix() * pointLight.lightPosition;
pointLightData.lightColorIntensity = pointLight.lightColorIntensity;
pointLightInfos.push_back(pointLightData);
}
resources_->SetBuffer(kLightStorageBuffer, pointLightInfos.data(),
pointLightInfos.size() * sizeof(PointLightGpuData));
}
void VulkanApplication::ProcessInput() const
{
const float cameraSpeed = GetParamFloat(AppSettings::CameraSpeed) * static_cast<float>(deltaTime_);
if (window_->IsKeyPressed(GLFW_KEY_W)) {
camera_->Move(camera_->GetFrontVector() * cameraSpeed);
}
if (window_->IsKeyPressed(GLFW_KEY_S)) {
camera_->Move(-camera_->GetFrontVector() * cameraSpeed);
}
if (window_->IsKeyPressed(GLFW_KEY_A)) {
camera_->Move(-camera_->GetRightVector() * cameraSpeed);
}
if (window_->IsKeyPressed(GLFW_KEY_D)) {
camera_->Move(camera_->GetRightVector() * cameraSpeed);
}
}
} // namespace examples::post_processing_effects::color_processing_tone_mapping::hdr_temperature_adjustment