-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEngine.cpp
1136 lines (856 loc) · 39.2 KB
/
Engine.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
#include "Engine.h"
#include <SDL.h>
#include <SDL_vulkan.h>
#include "Initializers.h"
#include "VkBootstrap.h"
#include <iostream>
#include <fstream>
#define VMA_IMPLEMENTATION
#include "vk_mem_alloc.h"
constexpr bool bUseValidationLayers = true;
//we want to immediately abort when there is an error. In normal engines this would give an error message to the user, or perform a dump of state.
using namespace std;
#define VK_CHECK(x) \
do \
{ \
VkResult err = x; \
if (err) \
{ \
std::cout <<"Detected Vulkan error: " << err << std::endl; \
abort(); \
} \
} while (0)
void VulkanEngine::init()
{
// We initialize SDL and create a window with it.
SDL_Init(SDL_INIT_VIDEO);
SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_VULKAN);
_window = SDL_CreateWindow(
"Vulkan Engine",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
_windowExtent.width,
_windowExtent.height,
window_flags
);
init_vulkan();
init_swapchain();
init_default_renderpass();
init_framebuffers();
init_commands();
init_sync_structures();
load_octrees();
init_descriptors();
init_pipelines();
load_meshes();
init_scene();
//everything went fine
_isInitialized = true;
}
void VulkanEngine::cleanup()
{
if (_isInitialized) {
//make sure the gpu has stopped doing its things
vkDeviceWaitIdle(_device);
_mainDeletionQueue.flush();
vkDestroySurfaceKHR(_instance, _surface, nullptr);
vkDestroyDevice(_device, nullptr);
vkb::destroy_debug_utils_messenger(_instance, _debug_messenger);
vkDestroyInstance(_instance, nullptr);
SDL_DestroyWindow(_window);
}
}
void VulkanEngine::draw()
{
//wait until the gpu has finished rendering the last frame. Timeout of 1 second
VK_CHECK(vkWaitForFences(_device, 1, &get_current_frame()._renderFence, true, 1000000000));
VK_CHECK(vkResetFences(_device, 1, &get_current_frame()._renderFence));
//now that we are sure that the commands finished executing, we can safely reset the command buffer to begin recording again.
VK_CHECK(vkResetCommandBuffer(get_current_frame()._mainCommandBuffer, 0));
//request image from the swapchain
uint32_t swapchainImageIndex;
VK_CHECK(vkAcquireNextImageKHR(_device, _swapchain, 1000000000, get_current_frame()._presentSemaphore, nullptr, &swapchainImageIndex));
//naming it cmd for shorter writing
VkCommandBuffer cmd = get_current_frame()._mainCommandBuffer;
//begin the command buffer recording. We will use this command buffer exactly once, so we want to let vulkan know that
VkCommandBufferBeginInfo cmdBeginInfo = vkinit::command_buffer_begin_info(VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT);
VK_CHECK(vkBeginCommandBuffer(cmd, &cmdBeginInfo));
VkClearValue clearValue;
clearValue.color = { { 0.0f, 0.0f, 0.0f, 1.0f } };
//clear depth at 1
VkClearValue depthClear;
depthClear.depthStencil.depth = 1.f;
//start the main renderpass.
//We will use the clear color from above, and the framebuffer of the index the swapchain gave us
VkRenderPassBeginInfo rpInfo = vkinit::renderpass_begin_info(_renderPass, _windowExtent, _framebuffers[swapchainImageIndex]);
//connect clear values
rpInfo.clearValueCount = 2;
VkClearValue clearValues[] = { clearValue, depthClear };
rpInfo.pClearValues = &clearValues[0];
vkCmdBeginRenderPass(cmd, &rpInfo, VK_SUBPASS_CONTENTS_INLINE);
draw_objects(cmd, _renderables.data(), _renderables.size());
//finalize the render pass
vkCmdEndRenderPass(cmd);
//finalize the command buffer (we can no longer add commands, but it can now be executed)
VK_CHECK(vkEndCommandBuffer(cmd));
//prepare the submission to the queue.
//we want to wait on the _presentSemaphore, as that semaphore is signaled when the swapchain is ready
//we will signal the _renderSemaphore, to signal that rendering has finished
VkSubmitInfo submit = vkinit::submit_info(&cmd);
VkPipelineStageFlags waitStage = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
submit.pWaitDstStageMask = &waitStage;
submit.waitSemaphoreCount = 1;
submit.pWaitSemaphores = &get_current_frame()._presentSemaphore;
submit.signalSemaphoreCount = 1;
submit.pSignalSemaphores = &get_current_frame()._renderSemaphore;
//submit command buffer to the queue and execute it.
// _renderFence will now block until the graphic commands finish execution
VK_CHECK(vkQueueSubmit(_graphicsQueue, 1, &submit, get_current_frame()._renderFence));
//prepare present
// this will put the image we just rendered to into the visible window.
// we want to wait on the _renderSemaphore for that,
// as its necessary that drawing commands have finished before the image is displayed to the user
VkPresentInfoKHR presentInfo = vkinit::present_info();
presentInfo.pSwapchains = &_swapchain;
presentInfo.swapchainCount = 1;
presentInfo.pWaitSemaphores = &get_current_frame()._renderSemaphore;
presentInfo.waitSemaphoreCount = 1;
presentInfo.pImageIndices = &swapchainImageIndex;
VK_CHECK(vkQueuePresentKHR(_graphicsQueue, &presentInfo));
//increase the number of frames drawn
_frameNumber++;
}
void VulkanEngine::run()
{
SDL_Event e;
bool bQuit = false;
//main loop
while (!bQuit)
{
//Handle events on queue
while (SDL_PollEvent(&e) != 0)
{
//close the window when user alt-f4s or clicks the X button
if (e.type == SDL_QUIT)
{
bQuit = true;
}
else if (e.type == SDL_KEYDOWN)
{
if (e.key.keysym.sym == SDLK_SPACE)
{
_selectedShader += 1;
if (_selectedShader > 1)
{
_selectedShader = 0;
}
}
}
}
draw();
}
}
FrameData& VulkanEngine::get_current_frame()
{
return _frames[_frameNumber % FRAME_OVERLAP];
}
FrameData& VulkanEngine::get_last_frame()
{
return _frames[(_frameNumber -1) % 2];
}
void VulkanEngine::init_vulkan()
{
vkb::InstanceBuilder builder;
//make the vulkan instance, with basic debug features
auto inst_ret = builder.set_app_name("Example Vulkan Application")
.request_validation_layers(bUseValidationLayers)
.use_default_debug_messenger()
.require_api_version(1, 2, 0)
.build();
vkb::Instance vkb_inst = inst_ret.value();
//grab the instance
_instance = vkb_inst.instance;
_debug_messenger = vkb_inst.debug_messenger;
SDL_Vulkan_CreateSurface(_window, _instance, &_surface);
//use vkbootstrap to select a gpu.
//We want a gpu that can write to the SDL surface and supports vulkan 1.2
VkPhysicalDeviceVulkan11Features features = {};
features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
features.shaderDrawParameters = true;
vkb::PhysicalDeviceSelector selector{ vkb_inst };
vkb::PhysicalDevice physicalDevice = selector
.set_minimum_version(1, 2)
.set_surface(_surface)
.select()
.value();
//create the final vulkan device
vkb::DeviceBuilder deviceBuilder{ physicalDevice };
vkb::Device vkbDevice = deviceBuilder.add_pNext(&features).build().value();
// Get the VkDevice handle used in the rest of a vulkan application
_device = vkbDevice.device;
_chosenGPU = physicalDevice.physical_device;
// use vkbootstrap to get a Graphics queue
_graphicsQueue = vkbDevice.get_queue(vkb::QueueType::graphics).value();
_graphicsQueueFamily = vkbDevice.get_queue_index(vkb::QueueType::graphics).value();
//initialize the memory allocator
VmaAllocatorCreateInfo allocatorInfo = {};
allocatorInfo.physicalDevice = _chosenGPU;
allocatorInfo.device = _device;
allocatorInfo.instance = _instance;
vmaCreateAllocator(&allocatorInfo, &_allocator);
_mainDeletionQueue.push_function([&]() {
vmaDestroyAllocator(_allocator);
});
vkGetPhysicalDeviceProperties(_chosenGPU, &_gpuProperties);
std::cout << "The gpu has a minimum buffer alignment of " << _gpuProperties.limits.minUniformBufferOffsetAlignment << std::endl;
}
void VulkanEngine::init_swapchain()
{
vkb::SwapchainBuilder swapchainBuilder{_chosenGPU,_device,_surface };
vkb::Swapchain vkbSwapchain = swapchainBuilder
.use_default_format_selection()
//use vsync present mode
.set_desired_present_mode(VK_PRESENT_MODE_FIFO_KHR)
.set_desired_extent(_windowExtent.width, _windowExtent.height)
.build()
.value();
//store swapchain and its related images
_swapchain = vkbSwapchain.swapchain;
_swapchainImages = vkbSwapchain.get_images().value();
_swapchainImageViews = vkbSwapchain.get_image_views().value();
_swachainImageFormat = vkbSwapchain.image_format;
_mainDeletionQueue.push_function([=]() {
vkDestroySwapchainKHR(_device, _swapchain, nullptr);
});
//depth image size will match the window
VkExtent3D depthImageExtent = {
_windowExtent.width,
_windowExtent.height,
1
};
//hardcoding the depth format to 32 bit float
_depthFormat = VK_FORMAT_D32_SFLOAT;
//the depth image will be a image with the format we selected and Depth Attachment usage flag
VkImageCreateInfo dimg_info = vkinit::image_create_info(_depthFormat, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, depthImageExtent);
//for the depth image, we want to allocate it from gpu local memory
VmaAllocationCreateInfo dimg_allocinfo = {};
dimg_allocinfo.usage = VMA_MEMORY_USAGE_GPU_ONLY;
dimg_allocinfo.requiredFlags = VkMemoryPropertyFlags(VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
//allocate and create the image
vmaCreateImage(_allocator, &dimg_info, &dimg_allocinfo, &_depthImage._image, &_depthImage._allocation, nullptr);
//build a image-view for the depth image to use for rendering
VkImageViewCreateInfo dview_info = vkinit::imageview_create_info(_depthFormat, _depthImage._image, VK_IMAGE_ASPECT_DEPTH_BIT);;
VK_CHECK(vkCreateImageView(_device, &dview_info, nullptr, &_depthImageView));
//add to deletion queues
_mainDeletionQueue.push_function([=]() {
vkDestroyImageView(_device, _depthImageView, nullptr);
vmaDestroyImage(_allocator, _depthImage._image, _depthImage._allocation);
});
}
void VulkanEngine::init_default_renderpass()
{
//we define an attachment description for our main color image
//the attachment is loaded as "clear" when renderpass start
//the attachment is stored when renderpass ends
//the attachment layout starts as "undefined", and transitions to "Present" so its possible to display it
//we dont care about stencil, and dont use multisampling
VkAttachmentDescription color_attachment = {};
color_attachment.format = _swachainImageFormat;
color_attachment.samples = VK_SAMPLE_COUNT_1_BIT;
color_attachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
color_attachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
color_attachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
color_attachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
color_attachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
color_attachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
VkAttachmentReference color_attachment_ref = {};
color_attachment_ref.attachment = 0;
color_attachment_ref.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
VkAttachmentDescription depth_attachment = {};
// Depth attachment
depth_attachment.flags = 0;
depth_attachment.format = _depthFormat;
depth_attachment.samples = VK_SAMPLE_COUNT_1_BIT;
depth_attachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
depth_attachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
depth_attachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
depth_attachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
depth_attachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
depth_attachment.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
VkAttachmentReference depth_attachment_ref = {};
depth_attachment_ref.attachment = 1;
depth_attachment_ref.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
//we are going to create 1 subpass, which is the minimum you can do
VkSubpassDescription subpass = {};
subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpass.colorAttachmentCount = 1;
subpass.pColorAttachments = &color_attachment_ref;
//hook the depth attachment into the subpass
subpass.pDepthStencilAttachment = &depth_attachment_ref;
//1 dependency, which is from "outside" into the subpass. And we can read or write color
VkSubpassDependency dependency = {};
dependency.srcSubpass = VK_SUBPASS_EXTERNAL;
dependency.dstSubpass = 0;
dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
dependency.srcAccessMask = 0;
dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
//dependency from outside to the subpass, making this subpass dependent on the previous renderpasses
VkSubpassDependency depth_dependency = {};
depth_dependency.srcSubpass = VK_SUBPASS_EXTERNAL;
depth_dependency.dstSubpass = 0;
depth_dependency.srcStageMask = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
depth_dependency.srcAccessMask = 0;
depth_dependency.dstStageMask = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
depth_dependency.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
//array of 2 dependencies, one for color, two for depth
VkSubpassDependency dependencies[2] = { dependency, depth_dependency };
//array of 2 attachments, one for the color, and other for depth
VkAttachmentDescription attachments[2] = { color_attachment,depth_attachment };
VkRenderPassCreateInfo render_pass_info = {};
render_pass_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
//2 attachments from attachment array
render_pass_info.attachmentCount = 2;
render_pass_info.pAttachments = &attachments[0];
render_pass_info.subpassCount = 1;
render_pass_info.pSubpasses = &subpass;
//2 dependencies from dependency array
render_pass_info.dependencyCount = 2;
render_pass_info.pDependencies = &dependencies[0];
VK_CHECK(vkCreateRenderPass(_device, &render_pass_info, nullptr, &_renderPass));
_mainDeletionQueue.push_function([=]() {
vkDestroyRenderPass(_device, _renderPass, nullptr);
});
}
void VulkanEngine::init_framebuffers()
{
//create the framebuffers for the swapchain images. This will connect the render-pass to the images for rendering
VkFramebufferCreateInfo fb_info = vkinit::framebuffer_create_info(_renderPass, _windowExtent);
const uint32_t swapchain_imagecount = _swapchainImages.size();
_framebuffers = std::vector<VkFramebuffer>(swapchain_imagecount);
for (int i = 0; i < swapchain_imagecount; i++) {
VkImageView attachments[2];
attachments[0] = _swapchainImageViews[i];
attachments[1] = _depthImageView;
fb_info.pAttachments = attachments;
fb_info.attachmentCount = 2;
VK_CHECK(vkCreateFramebuffer(_device, &fb_info, nullptr, &_framebuffers[i]));
_mainDeletionQueue.push_function([=]() {
vkDestroyFramebuffer(_device, _framebuffers[i], nullptr);
vkDestroyImageView(_device, _swapchainImageViews[i], nullptr);
});
}
}
void VulkanEngine::init_commands()
{
//create a command pool for commands submitted to the graphics queue.
//we also want the pool to allow for resetting of individual command buffers
VkCommandPoolCreateInfo commandPoolInfo = vkinit::command_pool_create_info(_graphicsQueueFamily, VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT);
for (int i = 0; i < FRAME_OVERLAP; i++) {
VK_CHECK(vkCreateCommandPool(_device, &commandPoolInfo, nullptr, &_frames[i]._commandPool));
//allocate the default command buffer that we will use for rendering
VkCommandBufferAllocateInfo cmdAllocInfo = vkinit::command_buffer_allocate_info(_frames[i]._commandPool, 1);
VK_CHECK(vkAllocateCommandBuffers(_device, &cmdAllocInfo, &_frames[i]._mainCommandBuffer));
_mainDeletionQueue.push_function([=]() {
vkDestroyCommandPool(_device, _frames[i]._commandPool, nullptr);
});
}
}
void VulkanEngine::init_sync_structures()
{
//create syncronization structures
//one fence to control when the gpu has finished rendering the frame,
//and 2 semaphores to syncronize rendering with swapchain
//we want the fence to start signalled so we can wait on it on the first frame
VkFenceCreateInfo fenceCreateInfo = vkinit::fence_create_info(VK_FENCE_CREATE_SIGNALED_BIT);
VkSemaphoreCreateInfo semaphoreCreateInfo = vkinit::semaphore_create_info();
for (int i = 0; i < FRAME_OVERLAP; i++) {
VK_CHECK(vkCreateFence(_device, &fenceCreateInfo, nullptr, &_frames[i]._renderFence));
//enqueue the destruction of the fence
_mainDeletionQueue.push_function([=]() {
vkDestroyFence(_device, _frames[i]._renderFence, nullptr);
});
VK_CHECK(vkCreateSemaphore(_device, &semaphoreCreateInfo, nullptr, &_frames[i]._presentSemaphore));
VK_CHECK(vkCreateSemaphore(_device, &semaphoreCreateInfo, nullptr, &_frames[i]._renderSemaphore));
//enqueue the destruction of semaphores
_mainDeletionQueue.push_function([=]() {
vkDestroySemaphore(_device, _frames[i]._presentSemaphore, nullptr);
vkDestroySemaphore(_device, _frames[i]._renderSemaphore, nullptr);
});
}
}
void VulkanEngine::init_pipelines()
{
VkShaderModule colorMeshShader;
if (!load_shader_module("./shaders/octree.frag.spv", &colorMeshShader))
{
std::cout << "Error when building the colored mesh shader" << std::endl;
}
VkShaderModule meshVertShader;
if (!load_shader_module("./shaders/octree.vert.spv", &meshVertShader))
{
std::cout << "Error when building the mesh vertex shader module" << std::endl;
}
//build the stage-create-info for both vertex and fragment stages. This lets the pipeline know the shader modules per stage
PipelineBuilder pipelineBuilder;
pipelineBuilder._shaderStages.push_back(
vkinit::pipeline_shader_stage_create_info(VK_SHADER_STAGE_VERTEX_BIT, meshVertShader));
pipelineBuilder._shaderStages.push_back(
vkinit::pipeline_shader_stage_create_info(VK_SHADER_STAGE_FRAGMENT_BIT, colorMeshShader));
//we start from just the default empty pipeline layout info
VkPipelineLayoutCreateInfo mesh_pipeline_layout_info = vkinit::pipeline_layout_create_info();
//setup push constants
VkPushConstantRange push_constant;
//offset 0
push_constant.offset = 0;
//size of a MeshPushConstant struct
push_constant.size = sizeof(MeshPushConstants);
//for the vertex shader
push_constant.stageFlags = VK_SHADER_STAGE_VERTEX_BIT;
mesh_pipeline_layout_info.pPushConstantRanges = &push_constant;
mesh_pipeline_layout_info.pushConstantRangeCount = 1;
VkDescriptorSetLayout setLayouts[] = { _globalSetLayout, _octreeSetLayout };
mesh_pipeline_layout_info.setLayoutCount = 2;
mesh_pipeline_layout_info.pSetLayouts = setLayouts;
VkPipelineLayout meshPipLayout;
VK_CHECK(vkCreatePipelineLayout(_device, &mesh_pipeline_layout_info, nullptr, &meshPipLayout));
//hook the push constants layout
pipelineBuilder._pipelineLayout = meshPipLayout;
//vertex input controls how to read vertices from vertex buffers. We arent using it yet
pipelineBuilder._vertexInputInfo = vkinit::vertex_input_state_create_info();
//input assembly is the configuration for drawing triangle lists, strips, or individual points.
//we are just going to draw triangle list
pipelineBuilder._inputAssembly = vkinit::input_assembly_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST);
//build viewport and scissor from the swapchain extents
pipelineBuilder._viewport.x = 0.0f;
pipelineBuilder._viewport.y = 0.0f;
pipelineBuilder._viewport.width = (float)_windowExtent.width;
pipelineBuilder._viewport.height = (float)_windowExtent.height;
pipelineBuilder._viewport.minDepth = 0.0f;
pipelineBuilder._viewport.maxDepth = 1.0f;
pipelineBuilder._scissor.offset = { 0, 0 };
pipelineBuilder._scissor.extent = _windowExtent;
//configure the rasterizer to draw filled triangles
pipelineBuilder._rasterizer = vkinit::rasterization_state_create_info(VK_POLYGON_MODE_FILL);
//we dont use multisampling, so just run the default one
pipelineBuilder._multisampling = vkinit::multisampling_state_create_info();
//a single blend attachment with no blending and writing to RGBA
pipelineBuilder._colorBlendAttachment = vkinit::color_blend_attachment_state();
//default depthtesting
pipelineBuilder._depthStencil = vkinit::depth_stencil_create_info(true, true, VK_COMPARE_OP_LESS_OR_EQUAL);
//build the mesh pipeline
VertexInputDescription vertexDescription = Vertex::get_vertex_description();
//connect the pipeline builder vertex input info to the one we get from Vertex
pipelineBuilder._vertexInputInfo.pVertexAttributeDescriptions = vertexDescription.attributes.data();
pipelineBuilder._vertexInputInfo.vertexAttributeDescriptionCount = vertexDescription.attributes.size();
pipelineBuilder._vertexInputInfo.pVertexBindingDescriptions = vertexDescription.bindings.data();
pipelineBuilder._vertexInputInfo.vertexBindingDescriptionCount = vertexDescription.bindings.size();
//build the mesh triangle pipeline
VkPipeline meshPipeline = pipelineBuilder.build_pipeline(_device, _renderPass);
create_material(meshPipeline, meshPipLayout, "defaultmesh");
vkDestroyShaderModule(_device, meshVertShader, nullptr);
vkDestroyShaderModule(_device, colorMeshShader, nullptr);
_mainDeletionQueue.push_function([=]() {
vkDestroyPipeline(_device, meshPipeline, nullptr);
vkDestroyPipelineLayout(_device, meshPipLayout, nullptr);
});
}
bool VulkanEngine::load_shader_module(const char* filePath, VkShaderModule* outShaderModule)
{
//open the file. With cursor at the end
std::ifstream file(filePath, std::ios::ate | std::ios::binary);
if (!file.is_open()) {
return false;
}
//find what the size of the file is by looking up the location of the cursor
//because the cursor is at the end, it gives the size directly in bytes
size_t fileSize = (size_t)file.tellg();
//spirv expects the buffer to be on uint32, so make sure to reserve a int vector big enough for the entire file
std::vector<uint32_t> buffer(fileSize / sizeof(uint32_t));
//put file cursor at beggining
file.seekg(0);
//load the entire file into the buffer
file.read((char*)buffer.data(), fileSize);
//now that the file is loaded into the buffer, we can close it
file.close();
//create a new shader module, using the buffer we loaded
VkShaderModuleCreateInfo createInfo = {};
createInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
createInfo.pNext = nullptr;
//codeSize has to be in bytes, so multply the ints in the buffer by size of int to know the real size of the buffer
createInfo.codeSize = buffer.size() * sizeof(uint32_t);
createInfo.pCode = buffer.data();
//check that the creation goes well.
VkShaderModule shaderModule;
if (vkCreateShaderModule(_device, &createInfo, nullptr, &shaderModule) != VK_SUCCESS) {
return false;
}
*outShaderModule = shaderModule;
return true;
}
VkPipeline PipelineBuilder::build_pipeline(VkDevice device, VkRenderPass pass)
{
//make viewport state from our stored viewport and scissor.
//at the moment we wont support multiple viewports or scissors
VkPipelineViewportStateCreateInfo viewportState = {};
viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
viewportState.pNext = nullptr;
viewportState.viewportCount = 1;
viewportState.pViewports = &_viewport;
viewportState.scissorCount = 1;
viewportState.pScissors = &_scissor;
//setup dummy color blending. We arent using transparent objects yet
//the blending is just "no blend", but we do write to the color attachment
VkPipelineColorBlendStateCreateInfo colorBlending = {};
colorBlending.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
colorBlending.pNext = nullptr;
colorBlending.logicOpEnable = VK_FALSE;
colorBlending.logicOp = VK_LOGIC_OP_COPY;
colorBlending.attachmentCount = 1;
colorBlending.pAttachments = &_colorBlendAttachment;
//build the actual pipeline
//we now use all of the info structs we have been writing into into this one to create the pipeline
VkGraphicsPipelineCreateInfo pipelineInfo = {};
pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
pipelineInfo.pNext = nullptr;
pipelineInfo.stageCount = _shaderStages.size();
pipelineInfo.pStages = _shaderStages.data();
pipelineInfo.pVertexInputState = &_vertexInputInfo;
pipelineInfo.pInputAssemblyState = &_inputAssembly;
pipelineInfo.pViewportState = &viewportState;
pipelineInfo.pRasterizationState = &_rasterizer;
pipelineInfo.pMultisampleState = &_multisampling;
pipelineInfo.pColorBlendState = &colorBlending;
pipelineInfo.pDepthStencilState = &_depthStencil;
pipelineInfo.layout = _pipelineLayout;
pipelineInfo.renderPass = pass;
pipelineInfo.subpass = 0;
pipelineInfo.basePipelineHandle = VK_NULL_HANDLE;
//its easy to error out on create graphics pipeline, so we handle it a bit better than the common VK_CHECK case
VkPipeline newPipeline;
if (vkCreateGraphicsPipelines(
device, VK_NULL_HANDLE, 1, &pipelineInfo, nullptr, &newPipeline) != VK_SUCCESS) {
std::cout << "failed to create pipline\n";
return VK_NULL_HANDLE; // failed to create graphics pipeline
}
else
{
return newPipeline;
}
}
void VulkanEngine::load_meshes()
{
Mesh rectMesh{};
rectMesh._vertices.resize(4);
rectMesh._indices.resize(6);
rectMesh._vertices[0].position = { -1.f, -1.f, 0.0f };
rectMesh._vertices[1].position = { 1.f, -1.f, 0.0f };
rectMesh._vertices[2].position = { 1.f, 1.f, 0.0f };
rectMesh._vertices[3].position = { -1.f, 1.f, 0.0f };
//vertex colors, all green
rectMesh._vertices[0].color = { 1.f, 1.f, 1.f };
rectMesh._vertices[1].color = { 1.f, 1.f, 1.f };
rectMesh._vertices[2].color = { 1.f, 1.f, 1.f };
rectMesh._vertices[3].color = { 1.f, 1.f, 1.f };
//we dont care about the vertex normals
rectMesh._indices = { 0, 1, 2, 2, 3, 0 };
upload_mesh(rectMesh);
_meshes["rectangle"] = rectMesh;
}
void VulkanEngine::load_octrees()
{
Octree armadilloOctree;
armadilloOctree.load_from_npy("C:/MyWork/sparse-voxel-octree-renderer/assets/armadillo2.npz");
upload_octree(armadilloOctree);
_octrees["armadillo"] = armadilloOctree;
unsigned int* arr = armadilloOctree.pyramid.data();
for (int i = 0; i < armadilloOctree.pyramid.size(); i++)
{
std::cout << arr[i] << " ";
}
}
void VulkanEngine::upload_mesh(Mesh& mesh)
{
//allocate vertex buffer
VkBufferCreateInfo bufferInfo = {};
bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
bufferInfo.pNext = nullptr;
//this is the total size, in bytes, of the buffer we are allocating
bufferInfo.size = mesh._vertices.size() * sizeof(Vertex);
//this buffer is going to be used as a Vertex Buffer
bufferInfo.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT;
//let the VMA library know that this data should be writeable by CPU, but also readable by GPU
VmaAllocationCreateInfo vmaallocInfo = {};
vmaallocInfo.usage = VMA_MEMORY_USAGE_CPU_TO_GPU;
//allocate the buffer
VK_CHECK(vmaCreateBuffer(_allocator, &bufferInfo, &vmaallocInfo,
&mesh._vertexBuffer._buffer,
&mesh._vertexBuffer._allocation,
nullptr));
// Index Buffer
bufferInfo.size = mesh._indices.size() * sizeof(uint32_t);
bufferInfo.usage = VK_BUFFER_USAGE_INDEX_BUFFER_BIT;
VK_CHECK(vmaCreateBuffer(_allocator, &bufferInfo, &vmaallocInfo,
&mesh._indexBuffer._buffer,
&mesh._indexBuffer._allocation,
nullptr));
//add the destruction of triangle mesh buffer to the deletion queue
_mainDeletionQueue.push_function([=]() {
vmaDestroyBuffer(_allocator, mesh._vertexBuffer._buffer, mesh._vertexBuffer._allocation);
vmaDestroyBuffer(_allocator, mesh._indexBuffer._buffer, mesh._indexBuffer._allocation);
});
//copy vertex and index data
void* data;
vmaMapMemory(_allocator, mesh._vertexBuffer._allocation, &data);
memcpy(data, mesh._vertices.data(), mesh._vertices.size() * sizeof(Vertex));
vmaUnmapMemory(_allocator, mesh._vertexBuffer._allocation);
vmaMapMemory(_allocator, mesh._indexBuffer._allocation, &data);
memcpy(data, mesh._indices.data(), mesh._indices.size() * sizeof(uint32_t));
vmaUnmapMemory(_allocator, mesh._indexBuffer._allocation);
}
void VulkanEngine::upload_octree(Octree& octree)
{
// Not implemented.
}
Material* VulkanEngine::create_material(VkPipeline pipeline, VkPipelineLayout layout, const std::string& name)
{
Material mat;
mat.pipeline = pipeline;
mat.pipelineLayout = layout;
_materials[name] = mat;
return &_materials[name];
}
Material* VulkanEngine::get_material(const std::string& name)
{
//search for the object, and return nullpointer if not found
auto it = _materials.find(name);
if (it == _materials.end()) {
return nullptr;
}
else {
return &(*it).second;
}
}
Mesh* VulkanEngine::get_mesh(const std::string& name)
{
auto it = _meshes.find(name);
if (it == _meshes.end()) {
return nullptr;
}
else {
return &(*it).second;
}
}
Octree* VulkanEngine::get_octree(const std::string& name)\
{
auto it = _octrees.find(name);
if (it == _octrees.end())
return nullptr;
else
return &(*it).second;
}
static bool test = true;
void VulkanEngine::draw_objects(VkCommandBuffer cmd,RenderObject* first, int count)
{
//make a model view matrix for rendering the object
//camera view
glm::vec3 camPos = { 0.f, 0.f, 0.f };
glm::mat4 view = glm::translate(glm::mat4(1.f), camPos);
//camera projection
glm::mat4 projection = glm::perspective(glm::radians(70.f), 900.f / 900.f, 0.f, 1.f);
projection[1][1] *= -1;
GPUCameraData camData;
camData.proj = projection;
camData.view = view;
camData.viewproj = projection * view;
void* data;
vmaMapMemory(_allocator, get_current_frame().cameraBuffer._allocation, &data);
memcpy(data, &camData, sizeof(GPUCameraData));
vmaUnmapMemory(_allocator, get_current_frame().cameraBuffer._allocation);
float framed = (_frameNumber / 120.f);
_sceneParameters.ambientColor = { sin(framed),0,cos(framed),1 };
char* sceneData;
vmaMapMemory(_allocator, _sceneParameterBuffer._allocation , (void**)&sceneData);
int frameIndex = _frameNumber % FRAME_OVERLAP;
sceneData += pad_uniform_buffer_size(sizeof(GPUSceneData)) * frameIndex;
memcpy(sceneData, &_sceneParameters, sizeof(GPUSceneData));
vmaUnmapMemory(_allocator, _sceneParameterBuffer._allocation);
void* pointsData;
vmaMapMemory(_allocator, get_current_frame().pointsBuffer._allocation, &pointsData);
void* pyramidData;
vmaMapMemory(_allocator, get_current_frame().pyramidBuffer._allocation, &pyramidData);
unsigned int* pointsSSBO = (unsigned int*)pointsData;
memcpy(pointsData, _octrees["armadillo"].points.data(), _octrees["armadillo"].points.size() * sizeof(unsigned int));
unsigned int* pyramidSSBO = (unsigned int*)pyramidData;
memcpy(pyramidData, _octrees["armadillo"].pyramid.data(), _octrees["armadillo"].pyramid.size() * sizeof(unsigned int));
vmaUnmapMemory(_allocator, get_current_frame().pointsBuffer._allocation);
vmaUnmapMemory(_allocator, get_current_frame().pyramidBuffer._allocation);
Mesh* lastMesh = nullptr;
Material* lastMaterial = nullptr;
for (int i = 0; i < count; i++)
{
RenderObject& object = first[i];
//only bind the pipeline if it doesnt match with the already bound one
if (object.material != lastMaterial) {
vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, object.material->pipeline);
lastMaterial = object.material;
uint32_t uniform_offset = pad_uniform_buffer_size(sizeof(GPUSceneData)) * frameIndex;
vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, object.material->pipelineLayout, 0, 1, &get_current_frame().globalDescriptor, 1, &uniform_offset);
//octree data descriptor
vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, object.material->pipelineLayout, 1, 1, &get_current_frame().octreeDescriptor, 0, nullptr);
}
glm::mat4 model = object.transformMatrix;
//final render matrix, that we are calculating on the cpu
glm::mat4 mesh_matrix = model;
MeshPushConstants constants;
constants.render_matrix = mesh_matrix;
//upload the mesh to the gpu via pushconstants
vkCmdPushConstants(cmd, object.material->pipelineLayout, VK_SHADER_STAGE_VERTEX_BIT, 0, sizeof(MeshPushConstants), &constants);
//only bind the mesh if its a different one from last bind
if (object.mesh != lastMesh) {
//bind the mesh vertex buffer with offset 0
VkDeviceSize offset = 0;
vkCmdBindVertexBuffers(cmd, 0, 1, &object.mesh->_vertexBuffer._buffer, &offset);
vkCmdBindIndexBuffer(cmd, object.mesh->_indexBuffer._buffer, 0, VK_INDEX_TYPE_UINT32);
lastMesh = object.mesh;
}
//we can now draw
vkCmdDrawIndexed(cmd, object.mesh->_indices.size(), 1, 0, 0, 0);
}
}
void VulkanEngine::init_scene()
{
// Need to push quad for octree shader rendering.
RenderObject rect;
rect.mesh = get_mesh("rectangle");
rect.material = get_material("defaultmesh");
rect.transformMatrix = glm::mat4{ 1.0f };
_renderables.push_back(rect);
RenderObjectOctree octreeModel;
octreeModel.octree = get_octree("armadillo");
octreeModel.material = get_material("defaultmesh");
octreeModel.transformMatrix = glm::mat4{ 1.0f };
_renderableOctrees.push_back(octreeModel);
}
AllocatedBuffer VulkanEngine::create_buffer(size_t allocSize, VkBufferUsageFlags usage, VmaMemoryUsage memoryUsage)
{
//allocate vertex buffer
VkBufferCreateInfo bufferInfo = {};
bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
bufferInfo.pNext = nullptr;
bufferInfo.size = allocSize;
bufferInfo.usage = usage;
//let the VMA library know that this data should be writeable by CPU, but also readable by GPU
VmaAllocationCreateInfo vmaallocInfo = {};
vmaallocInfo.usage = memoryUsage;
AllocatedBuffer newBuffer;
//allocate the buffer
VK_CHECK(vmaCreateBuffer(_allocator, &bufferInfo, &vmaallocInfo,
&newBuffer._buffer,
&newBuffer._allocation,
nullptr));
return newBuffer;
}
size_t VulkanEngine::pad_uniform_buffer_size(size_t originalSize)
{
// Calculate required alignment based on minimum device offset alignment