This repository has been archived by the owner on Feb 24, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.cpp
1444 lines (1197 loc) · 58.9 KB
/
main.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
//
// This file is part of the "ogl_to_vlk" project
// See "LICENSE" for license information.
//
#if defined(__APPLE__)
#define VK_USE_PLATFORM_MACOS_MVK 1
#include <QuartzCore/CAMetalLayer.h>
#elif defined(_WIN64)
#define VK_USE_PLATFORM_WIN32_KHR 1
#endif
#include <iostream>
#include <vector>
#include <array>
#include <vulkan/vulkan.h>
#include <platform/Window.h>
#include <sc/Spirv_compiler.h>
using namespace std;
using namespace Platform;
using namespace Sc;
//----------------------------------------------------------------------------------------------------------------------
constexpr auto image_available_index {0};
constexpr auto rendering_done_index {1};
//----------------------------------------------------------------------------------------------------------------------
// 위치와 색상 정보를 가진 버텍스 정보를 정의합니다.
struct Vertex {
float x, y, z; // 위치 정보
float r, g, b; // 색상 정보
};
//----------------------------------------------------------------------------------------------------------------------
class Chapter10 {
public:
Chapter10(Window* window) :
window_ {window},
instance_ {VK_NULL_HANDLE},
physical_device_ {VK_NULL_HANDLE},
physical_device_memory_properties_ {},
queue_family_index_ {UINT32_MAX},
device_ {VK_NULL_HANDLE},
queue_ {VK_NULL_HANDLE},
command_pool_ {VK_NULL_HANDLE},
command_buffer_ {VK_NULL_HANDLE},
fence_ {VK_NULL_HANDLE},
semaphores_ {},
vertex_buffer_ {VK_NULL_HANDLE},
surface_ {VK_NULL_HANDLE},
swapchain_ {VK_NULL_HANDLE},
swapchain_image_extent_ {0, 0},
render_pass_ {VK_NULL_HANDLE},
framebuffers_{},
shader_modules_{},
pipeline_layout_ {VK_NULL_HANDLE},
pipeline_ {VK_NULL_HANDLE}
{
init_signals_();
init_instance_();
find_best_physical_device_();
init_physical_device_memory_properties_();
find_queue_family_index_();
init_device_();
init_queue_();
init_command_pool_();
init_command_buffer_();
init_semaphores_();
init_fence_();
init_vertex_resources_();
}
~Chapter10()
{
fini_vertex_resources_();
fini_fence_();
fini_semaphores_();
fini_command_pool_();
fini_device_();
fini_instance_();
}
private:
void init_signals_()
{
window_->startup_signal.connect(this, &Chapter10::on_startup);
window_->shutdown_signal.connect(this, &Chapter10::on_shutdown);
window_->render_signal.connect(this, &Chapter10::on_render);
}
void init_instance_()
{
// 벌칸 프로그램을 작성하는데 있어서 반드시 필요한 레이어입니다.
// 하지만 CPU를 굉장히 많이 사용하기 때문에 개발중에만 사용해야 합니다.
vector<const char*> layer_names {
"VK_LAYER_KHRONOS_validation"
};
// 사용하려는 인스턴스 익스텐션의 이름을 정의합니다.
// 사용하려는 익스텐션들이 시스템에서 지원되는지 먼저 확인해야합니다.
// 예제의 간소화를 위해서 사용하려는 익스텐션들을 확인 없이 사용합니다.
vector<const char*> extension_names {
"VK_KHR_surface",
#if defined(_WIN64)
"VK_KHR_win32_surface"
#else
"VK_MVK_macos_surface"
#endif
};
// 생성하려는 인스턴스를 정의합니다.
VkInstanceCreateInfo create_info {};
create_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
create_info.enabledLayerCount = layer_names.size();
create_info.ppEnabledLayerNames = &layer_names[0];
create_info.enabledExtensionCount = extension_names.size();
create_info.ppEnabledExtensionNames = &extension_names[0];
// 인스턴스를 생성합니다.
auto result = vkCreateInstance(&create_info, nullptr, &instance_);
switch (result) {
case VK_ERROR_OUT_OF_HOST_MEMORY:
cout << "VK_ERROR_OUT_OF_HOST_MEMORY" << endl;
break;
case VK_ERROR_OUT_OF_DEVICE_MEMORY:
cout << "VK_ERROR_OUT_OF_DEVICE_MEMORY" << endl;
break;
case VK_ERROR_INITIALIZATION_FAILED:
cout << "VK_ERROR_INITIALIZATION_FAILED" << endl;
break;
case VK_ERROR_LAYER_NOT_PRESENT:
cout << "VK_ERROR_LAYER_NOT_PRESENT" << endl;
break;
case VK_ERROR_INCOMPATIBLE_DRIVER:
cout << "VK_ERROR_INCOMPATIBLE_DRIVER" << endl;
break;
default:
break;
}
assert(result == VK_SUCCESS);
}
void find_best_physical_device_()
{
// 사용가능한 물리 디바이스의 수를 얻기 위한 변수를 선언합니다.
uint32_t count {0};
// 사용가능한 물리 디바이스의 수를 얻어옵니다.
vkEnumeratePhysicalDevices(instance_, &count, nullptr);
// 사용가능한 물리 디바이스들의 정보를 얻기 위한 변수를 선언합니다.
vector<VkPhysicalDevice> physical_devices;
// 사용가능한 물리 디바이스들의 정보를 얻기 위한 메모리를 할당합니다.
physical_devices.resize(count);
// 사용가능한 물리 디바이스들의 핸들을 얻어옵니다.
vkEnumeratePhysicalDevices(instance_, &count, &physical_devices[0]);
// 어플리케이션에선 사용가능한 물리 디바이스들 중에서 어플리케이션에
// 적합한 물리 디바이스를 찾아야 합니다.
// 예제의 간소화를 위해서 첫 번째 물리 디바이스를 사용합니다.
physical_device_ = physical_devices[0];
}
void init_physical_device_memory_properties_()
{
// 물리 디바이스 메모리 성질을 얻어옵니다.
vkGetPhysicalDeviceMemoryProperties(physical_device_, &physical_device_memory_properties_);
}
void find_queue_family_index_()
{
// 사용가능한 큐 패밀리의 수를 얻기 위한 변수를 선언합니다.
uint32_t count {0};
// 사용가능한 큐 패밀리의 수를 얻어옵니다.
vkGetPhysicalDeviceQueueFamilyProperties(physical_device_, &count, 0);
// 사용가능한 큐 패밀리의 정보를 얻기 위한 변수를 선언합니다.
vector<VkQueueFamilyProperties> properties;
// 사용가능한 큐 패밀리의 정보를 얻기 위한 메모리를 할당합니다.
properties.resize(count);
// 사용가능한 큐 패밀리의 정보를 얻어옵니다.
vkGetPhysicalDeviceQueueFamilyProperties(physical_device_, &count, &properties[0]);
for (auto i = 0; i != properties.size(); ++i) {
// 큐 패밀리에서 사용가능한 큐가 있는지 확인합니다.
if (properties[i].queueCount < 1)
continue;
// 큐 패밀리가 그래픽스 기능을 제공하는지 확인합니다.
if (VK_QUEUE_GRAPHICS_BIT & properties[i].queueFlags) {
queue_family_index_ = i;
break;
}
// 컴퓨트, 복사에 특화된 큐 패밀리가 존재할 수 있습니다.
// 목적에 맞는 큐 패밀리를 사용하시면 어플리케이션을 더 효율적으로 동작시킬 수 있습니다.
// 예제의 간소화를 위해서 그래픽스를 지원하는 한개의 큐 패밀리만 사용합니다.
}
assert(queue_family_index_ != UINT32_MAX);
}
void init_device_()
{
// 큐의 우선순위를 지정합니다.
// 여러개의 큐를 사용할 경우 다르게 우선순위를 지정할 수 있습니다.
constexpr auto priority = 1.0f;
// 생성하려는 큐를 정의합니다.
VkDeviceQueueCreateInfo queue_create_info {};
queue_create_info.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
queue_create_info.queueFamilyIndex = queue_family_index_;
queue_create_info.queueCount = 1;
queue_create_info.pQueuePriorities = &priority;
// 사용하려는 디바이스 익스텐션의 이름을 정의합니다.
// 사용하려는 익스텐션들이 시스템에서 지원되는지 먼저 확인해야합니다.
// 예제의 간소화를 위해서 사용하려는 익스텐션들을 확인 없이 사용합니다.
vector<const char*> extension_names {
"VK_KHR_swapchain",
};
// 생성하려는 디바이스를 정의합니다.
VkDeviceCreateInfo create_info {};
create_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
create_info.queueCreateInfoCount = 1;
create_info.pQueueCreateInfos = &queue_create_info;
create_info.enabledExtensionCount = extension_names.size();
create_info.ppEnabledExtensionNames = &extension_names[0];
// 디바이스를 생성합니다.
auto result = vkCreateDevice(physical_device_, &create_info, nullptr, &device_);
switch (result) {
case VK_ERROR_OUT_OF_HOST_MEMORY:
cout << "VK_ERROR_OUT_OF_HOST_MEMORY" << endl;
break;
case VK_ERROR_OUT_OF_DEVICE_MEMORY:
cout << "VK_ERROR_OUT_OF_DEVICE_MEMORY" << endl;
break;
case VK_ERROR_INITIALIZATION_FAILED:
cout << "VK_ERROR_INITIALIZATION_FAILED" << endl;
break;
case VK_ERROR_EXTENSION_NOT_PRESENT:
cout << "VK_ERROR_EXTENSION_NOT_PRESENT" << endl;
break;
case VK_ERROR_FEATURE_NOT_PRESENT:
cout << "VK_ERROR_FEATURE_NOT_PRESENT" << endl;
break;
case VK_ERROR_TOO_MANY_OBJECTS:
cout << "VK_ERROR_TOO_MANY_OBJECTS" << endl;
break;
case VK_ERROR_DEVICE_LOST:
cout << "VK_ERROR_DEVICE_LOST" << endl;
break;
default:
break;
}
assert(result == VK_SUCCESS);
}
void init_queue_()
{
// 디바이스로 부터 생성된 큐의 핸들을 얻어옵니다.
vkGetDeviceQueue(device_, queue_family_index_, 0, &queue_);
}
void init_command_pool_()
{
// 생성하려는 커맨드 풀을 정의합니다.
VkCommandPoolCreateInfo create_info {};
create_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
create_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
create_info.queueFamilyIndex = queue_family_index_;
// 커맨드 풀을 생성합니다.
auto result = vkCreateCommandPool(device_, &create_info, nullptr, &command_pool_);
switch (result) {
case VK_ERROR_OUT_OF_HOST_MEMORY:
cout << "VK_ERROR_OUT_OF_HOST_MEMORY" << endl;
break;
case VK_ERROR_OUT_OF_DEVICE_MEMORY:
cout << "VK_ERROR_OUT_OF_DEVICE_MEMORY" << endl;
break;
default:
break;
}
assert(result == VK_SUCCESS);
}
void init_command_buffer_()
{
// 생성할 커맨드 버퍼를 정의합니다.
VkCommandBufferAllocateInfo allocate_info {};
allocate_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
allocate_info.commandPool = command_pool_;
allocate_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
allocate_info.commandBufferCount = 1;
// 커맨드 버퍼를 생성합니다.
auto result = vkAllocateCommandBuffers(device_, &allocate_info, &command_buffer_);
switch (result) {
case VK_ERROR_OUT_OF_HOST_MEMORY:
cout << "VK_ERROR_OUT_OF_HOST_MEMORY" << endl;
break;
case VK_ERROR_OUT_OF_DEVICE_MEMORY:
cout << "VK_ERROR_OUT_OF_DEVICE_MEMORY" << endl;
break;
default:
break;
}
assert(result == VK_SUCCESS);
}
void init_semaphores_()
{
// 세마포어는 큐와 큐의 동기화를 위해 사용됩니다.
// 생성하려는 세마포어를 정의합니다.
VkSemaphoreCreateInfo create_info {};
create_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
// 두 개의 세마포어를 생성합니다.
// - 첫 번째 세마포어는 스왑체인 이미지가 준비된 후에 제출한 커맨드 버퍼가 처리되기 위해 사용됩니다.
// - 두 번째 세마포어는 제출한 커맨드 버퍼가 처리된 후에 화면에 출력을 하기 위해 사용됩니다.
for (auto& semaphore : semaphores_) {
auto result = vkCreateSemaphore(device_, &create_info, nullptr, &semaphore);
switch (result) {
case VK_ERROR_OUT_OF_HOST_MEMORY:
cout << "VK_ERROR_OUT_OF_HOST_MEMORY" << endl;
break;
case VK_ERROR_OUT_OF_DEVICE_MEMORY:
cout << "VK_ERROR_OUT_OF_DEVICE_MEMORY" << endl;
break;
default:
break;
}
assert(result == VK_SUCCESS);
}
}
void init_fence_()
{
// 펜스는 호스트와 디바이스의 동기화를 위해 사용됩니다.
// 생성하려는 펜스를 정의합니다.
VkFenceCreateInfo create_info {};
create_info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
// 커맨드 버퍼가 모두 처리됬는지를 알기 위해 사용된 펜스는 처음에 시그널 상태면 어플리케이션의 로직이 단순해집니다.
create_info.flags = VK_FENCE_CREATE_SIGNALED_BIT;
// 펜스를 생성합니다.
auto result = vkCreateFence(device_, &create_info, nullptr, &fence_);
switch (result) {
case VK_ERROR_OUT_OF_HOST_MEMORY:
cout << "VK_ERROR_OUT_OF_HOST_MEMORY" << endl;
break;
case VK_ERROR_OUT_OF_DEVICE_MEMORY:
cout << "VK_ERROR_OUT_OF_DEVICE_MEMORY" << endl;
break;
default:
break;
}
assert(result == VK_SUCCESS);
}
uint32_t find_memory_type_index(const VkMemoryRequirements& requirements, VkMemoryPropertyFlags properties)
{
// 메모리 요구사항과 필요한 메모리 성질을 모두 만족하는 메모리 타입 인덱스를 찾습니다.
for (auto i = 0; i != physical_device_memory_properties_.memoryTypeCount; ++i) {
// 메모리가 i번째 메모리 타입에 할당 가능한지 검사합니다.
if (!(requirements.memoryTypeBits & (1 << i)))
continue;
// 개발자가 요구한 메모리 성질을 만족하는지 검사합니다.
if ((physical_device_memory_properties_.memoryTypes[i].propertyFlags & properties) != properties)
continue;
return i;
}
assert(false);
return UINT32_MAX;
}
void init_vertex_resources_()
{
// 삼각형을 그리기 위해 필요한 버텍스 정보를 정의합니다.
vector<Vertex> vertices = {
/* 위치 */ /* 색상 */
{ 0.0, -0.5, 0.0, 1.0, 0.0, 0.0},
{ 0.5, 0.5, 0.0, 0.0, 1.0, 0.0},
{-0.5, 0.5, 0.0, 0.0, 0.0, 1.0}
};
// 생성하려는 버텍스 버퍼를 정의합니다.
VkBufferCreateInfo create_info {};
create_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
create_info.size = sizeof(Vertex) * vertices.size();
// 버퍼의 사용처를 VERTEX_BUFFER_BIT을 설정하지 않으면 버텍스 버퍼로 사용할 수 없습니다.
create_info.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT;
// 버퍼를 생성합니다.
auto result = vkCreateBuffer(device_, &create_info, nullptr, &vertex_buffer_);
switch (result) {
case VK_ERROR_OUT_OF_HOST_MEMORY:
cout << "VK_ERROR_OUT_OF_HOST_MEMORY" << endl;
break;
case VK_ERROR_OUT_OF_DEVICE_MEMORY:
cout << "VK_ERROR_OUT_OF_DEVICE_MEMORY" << endl;
break;
default:
break;
}
assert(result == VK_SUCCESS);
// 메모리 요구사항을 얻어올 변수를 선언합니다.
VkMemoryRequirements requirements;
// 버퍼를 위해 필요한 메모리 요구사항을 얻어옵니다.
vkGetBufferMemoryRequirements(device_, vertex_buffer_, &requirements);
// 할당하려는 메모리를 정의합니다.
VkMemoryAllocateInfo alloc_info {};
alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
alloc_info.allocationSize = requirements.size;
// CPU에서 접근 가능하고 CPU와 GPU의 메모리 동기화가 보장되는 메모리 타입을 선택합니다.
alloc_info.memoryTypeIndex = find_memory_type_index(requirements, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
// 메모리를 할당합니다.
result = vkAllocateMemory(device_, &alloc_info, nullptr, &vertex_device_memory_);
switch (result) {
case VK_ERROR_OUT_OF_HOST_MEMORY:
cout << "VK_ERROR_OUT_OF_HOST_MEMORY" << endl;
break;
case VK_ERROR_OUT_OF_DEVICE_MEMORY:
cout << "VK_ERROR_OUT_OF_DEVICE_MEMORY" << endl;
break;
case VK_ERROR_TOO_MANY_OBJECTS:
cout << "VK_ERROR_TOO_MANY_OBJECTS" << endl;
break;
default:
break;
}
assert(result == VK_SUCCESS);
// 버퍼와 메모리를 바인드합니다.
result = vkBindBufferMemory(device_, vertex_buffer_, vertex_device_memory_, 0);
switch (result) {
case VK_ERROR_OUT_OF_HOST_MEMORY:
cout << "VK_ERROR_OUT_OF_HOST_MEMORY" << endl;
break;
case VK_ERROR_OUT_OF_DEVICE_MEMORY:
cout << "VK_ERROR_OUT_OF_DEVICE_MEMORY" << endl;
break;
default:
break;
}
assert(result == VK_SUCCESS);
// CPU에서 메모리에 접근하기 위한 버추얼 어드레스를 가져옵니다.
void* contents;
result = vkMapMemory(device_, vertex_device_memory_, 0, sizeof(Vertex) * vertices.size(), 0, &contents);
switch (result) {
case VK_ERROR_OUT_OF_HOST_MEMORY:
cout << "VK_ERROR_OUT_OF_HOST_MEMORY" << endl;
break;
case VK_ERROR_OUT_OF_DEVICE_MEMORY:
cout << "VK_ERROR_OUT_OF_DEVICE_MEMORY" << endl;
break;
case VK_ERROR_MEMORY_MAP_FAILED:
cout << "VK_ERROR_MEMORY_MAP_FAILED" << endl;
break;
default:
break;
}
assert(result == VK_SUCCESS);
// 버텍스 정보를 메모리에 복사합니다.
memcpy(contents, &vertices[0], sizeof(Vertex) * vertices.size());
// CPU에서 메모리의 접근을 끝마칩니다.
vkUnmapMemory(device_, vertex_device_memory_);
// CPU에서 메모리를 자주 접근하는 경우에 언맵을 하지 않고
// 맵을 통해 얻어온 버츄얼 어드레스를 계속 사용해도 됩니다.
}
void init_surface_()
{
// 서피스는 윈도우 시스템마다 생성하는 API가 다릅니다.
// 하지만 서피스를 생성하기 위해서 필요한 정보와 근본적인 방법은 같다는 것을 알아차릴 수 있습니다.
#if defined(__APPLE__)
auto ns_window = (__bridge NSWindow*)window_->window();
auto content_view = [ns_window contentView];
// 애플 운영 체제에서 벌칸은 메탈을 기반으로 동작합니다. 즉 벌칸 API를 메탈로 구현한 것입니다.
// 그러므로 애플 운영 체제에서 벌칸을 사용하기 위해선 CAMetalLayer에 대한 설정이 필요합니다.
[content_view setLayer:[CAMetalLayer layer]];
// 생성하려는 서피스를 정의합니다.
VkMacOSSurfaceCreateInfoMVK create_info {};
create_info.sType = VK_STRUCTURE_TYPE_MACOS_SURFACE_CREATE_INFO_MVK;
create_info.pView = (__bridge void*)content_view;
// 서피스를 생성합니다.
auto result = vkCreateMacOSSurfaceMVK(instance_, &create_info, nullptr, &surface_);
#elif defined(_WIN64)
// 생성하려는 서피스를 정의합니다.
VkWin32SurfaceCreateInfoKHR create_info {};
create_info.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR;
create_info.hinstance = GetModuleHandle(NULL);
create_info.hwnd = static_cast<HWND>(window_->window());
// 서피스를 생성합니다.
auto result = vkCreateWin32SurfaceKHR(instance_, &create_info, nullptr, &surface_);
#endif
switch (result) {
case VK_ERROR_OUT_OF_HOST_MEMORY:
cout << "VK_ERROR_OUT_OF_HOST_MEMORY" << endl;
break;
case VK_ERROR_OUT_OF_DEVICE_MEMORY:
cout << "VK_ERROR_OUT_OF_DEVICE_MEMORY" << endl;
break;
case VK_ERROR_NATIVE_WINDOW_IN_USE_KHR:
cout << "VK_ERROR_NATIVE_WINDOW_IN_USE_KHR" << endl;
break;
default:
break;
}
assert(result == VK_SUCCESS);
// 서피스의 지원 여부를 얻어올 변수를 선언합니다.
VkBool32 supported;
// 물리 디바이스의 큐 패밀리가 서피스를 지원하는지 확인합니다.
vkGetPhysicalDeviceSurfaceSupportKHR(physical_device_, queue_family_index_, surface_, &supported);
assert(supported == VK_TRUE);
}
auto default_surface_format_()
{
// 사용 가능한 서피스 포맷의 수를 얻기 위한 변수를 선언합니다.
uint32_t count;
// 사용 가능한 서피스 포맷의 수를 얻어옵니다.
vkGetPhysicalDeviceSurfaceFormatsKHR(physical_device_, surface_, &count, nullptr);
// 사용가능한 서피스 포맷들을 얻기 위한 변수를 선언합니다.
vector<VkSurfaceFormatKHR> formats;
// 사용가능한 서피스 포맷들을 얻기 위한 메모리를 할당합니다.
formats.resize(count);
// 사용가능한 서피스 포맷들을 얻어옵니다.
vkGetPhysicalDeviceSurfaceFormatsKHR(physical_device_, surface_, &count, &formats[0]);
// 어플리케이션은 여러 조건을 고려해서 최적의 서피스 포맷을 선택해야합니다.
// 예제의 간소화를 위해서 첫 번째 서피스 포맷을 사용합니다.
return formats[0];
}
void init_swapchain_()
{
auto surface_format = default_surface_format_();
// 서피스의 능력을 얻기 위한 변수를 선언합니다.
VkSurfaceCapabilitiesKHR surface_capabilities;
// 서피스의 능력을 얻어옵니다.
vkGetPhysicalDeviceSurfaceCapabilitiesKHR(physical_device_, surface_, &surface_capabilities);
// 사용할 수 있는 컴포짓 알파 모드를 검색한다.
VkCompositeAlphaFlagBitsKHR composite_alpha {static_cast<VkCompositeAlphaFlagBitsKHR>(0)};
// 사용 가능한 컴포지트 알파 모드를 검색합니다.
for (auto i = 0; i != 32; ++i) {
VkCompositeAlphaFlagBitsKHR flag = static_cast<VkCompositeAlphaFlagBitsKHR>(0x1 << i);
// 예제의 간소화를 위해 사용가능한 첫 번째 컴포지트 알파 모드를 사용합니다.
if (surface_capabilities.supportedUsageFlags & flag) {
composite_alpha = flag;
break;
}
}
// 스왑체인 이미지의 크기를 저장합니다.
swapchain_image_extent_ = surface_capabilities.currentExtent;
// 생성하려는 스왑체인을 정의합니다.
// 예제의 간소화를 위해 FIFO 프레젠트 모드를 사용합니다.
VkSwapchainCreateInfoKHR create_info {};
create_info.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
create_info.surface = surface_;
create_info.minImageCount = 2; // 더블 버퍼링을 사용합니다.
create_info.imageFormat = surface_format.format;
create_info.imageColorSpace = surface_format.colorSpace;
create_info.imageExtent = surface_capabilities.currentExtent;
create_info.imageArrayLayers = 1; // VR과 같은 특수한 경우를 제외하곤 항상 1입니다.
create_info.imageUsage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
create_info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
create_info.preTransform = surface_capabilities.currentTransform;
create_info.compositeAlpha = composite_alpha;
create_info.presentMode = VK_PRESENT_MODE_FIFO_KHR;
// 스왑체인을 생성합니다.
auto result = vkCreateSwapchainKHR(device_, &create_info, nullptr, &swapchain_);
switch (result) {
case VK_ERROR_OUT_OF_HOST_MEMORY:
cout << "VK_ERROR_OUT_OF_HOST_MEMORY" << endl;
break;
case VK_ERROR_OUT_OF_DEVICE_MEMORY:
cout << "VK_ERROR_OUT_OF_DEVICE_MEMORY" << endl;
break;
case VK_ERROR_DEVICE_LOST:
cout << "VK_ERROR_DEVICE_LOST" << endl;
break;
case VK_ERROR_SURFACE_LOST_KHR:
cout << "VK_ERROR_SURFACE_LOST_KHR" << endl;
break;
case VK_ERROR_NATIVE_WINDOW_IN_USE_KHR:
cout << "VK_ERROR_NATIVE_WINDOW_IN_USE_KHR" << endl;
break;
case VK_ERROR_INITIALIZATION_FAILED:
cout << "VK_ERROR_INITIALIZATION_FAILED" << endl;
break;
default:
break;
}
assert(result == VK_SUCCESS);
}
void init_swapchain_images_()
{
// 사용 가능한 스왑체인 이미지의 개수를 얻기 위한 변수를 선언합니다.
uint32_t count;
// 사용 가능한 스왑체인 이미지의 개수를 얻어옵니다.
vkGetSwapchainImagesKHR(device_, swapchain_, &count, nullptr);
// 사용 가능한 스왑체인 이미지를 얻기 위한 메모리를 할당합니다.
swapchain_images_.resize(count);
// 사용 가능한 스왑체인 이미지를 얻어옵니다.
vkGetSwapchainImagesKHR(device_, swapchain_, &count, &swapchain_images_[0]);
// 스왑체인 생성시 정의한 이미지의 개수는 최소 이미지의 개수이기 때문에
// 실제로 더 많은 이미지가 생성될 수 있습니다.
// 커맨드를 기록하기 위해 커맨드 버퍼의 사용목적을 정의한다.
VkCommandBufferBeginInfo begin_info {};
begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
begin_info.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
// 커맨드 버퍼에 커맨드 기록을 시작한다.
vkBeginCommandBuffer(command_buffer_, &begin_info);
// 스왑체인 이미지의 레이아웃을 PRESENT_SRC로 변경하는 배리어를 정의한다.
// PRESENT_SRC로 변경하는 이유는 렌더링을 위한 커맨드를 단순화하기 위해서이다.
vector<VkImageMemoryBarrier> barriers;
for (auto& image : swapchain_images_) {
VkImageMemoryBarrier barrier {};
barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
barrier.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
barrier.srcQueueFamilyIndex = queue_family_index_;
barrier.dstQueueFamilyIndex = queue_family_index_;
barrier.image = image;
barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
barrier.subresourceRange.levelCount = 1;
barrier.subresourceRange.layerCount = 1;
barriers.push_back(barrier);
}
// 정의된 배리어를 실행하는 커맨드를 커맨드 버퍼에 기록한다.
vkCmdPipelineBarrier(command_buffer_,
VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
0,
0, nullptr,
0, nullptr,
barriers.size(), &barriers[0]);
// 커맨드 버퍼에 커맨드 기록을 끝마친다.
vkEndCommandBuffer(command_buffer_);
// 어떤 기록된 커맨드를 큐에 제출할지 정의한다.
VkSubmitInfo submit_info {};
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info.commandBufferCount = 1;
submit_info.pCommandBuffers = &command_buffer_;
// 기록된 커맨드를 큐에 제출한다.
vkQueueSubmit(queue_, 1, &submit_info, VK_NULL_HANDLE);
// 커맨드 버퍼들이 모두 처리될 때까지 기다린다.
vkDeviceWaitIdle(device_);
}
void init_swapchain_image_views_()
{
// 그래픽스 파이프라인에서 이미지를 접근하기 위해선 이미지 뷰가 필요합니다.
auto surface_format = default_surface_format_();
// 생성하려는 이미지 뷰를 정의합니다.
VkImageViewCreateInfo create_info {};
create_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
create_info.viewType = VK_IMAGE_VIEW_TYPE_2D;
create_info.format = surface_format.format;
create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
create_info.subresourceRange.levelCount = 1;
create_info.subresourceRange.layerCount = 1;
// 이미지 뷰를 위한 메모리를 할당합니다.
swapchain_image_views_.resize(swapchain_images_.size());
for (auto i = 0; i != swapchain_images_.size(); ++i) {
// 이미지 뷰를 생성할 이미지를 정의합니다.
create_info.image = swapchain_images_[i];
// 이미지 뷰를 생성합니다.
auto result = vkCreateImageView(device_, &create_info, nullptr, &swapchain_image_views_[i]);
switch (result) {
case VK_ERROR_OUT_OF_HOST_MEMORY:
cout << "VK_ERROR_OUT_OF_HOST_MEMORY" << endl;
break;
case VK_ERROR_OUT_OF_DEVICE_MEMORY:
cout << "VK_ERROR_OUT_OF_DEVICE_MEMORY" << endl;
break;
default:
break;
}
assert(result == VK_SUCCESS);
}
}
void init_render_pass_()
{
auto surface_format = default_surface_format_();
// 렌더패스의 어태치먼트를 정의합니다.
VkAttachmentDescription attachment_desc {};
attachment_desc.format = surface_format.format;
attachment_desc.samples = VK_SAMPLE_COUNT_1_BIT;
attachment_desc.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
attachment_desc.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
attachment_desc.initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
attachment_desc.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
// 서브패스에서 렌더패스의 어떤 어태치먼트를 참조할지 정의합니다.
VkAttachmentReference color_attachment_ref {};
color_attachment_ref.attachment = 0;
color_attachment_ref.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
// 렌더패스의 서브패스를 정의합니다.
VkSubpassDescription subpass_desc {};
subpass_desc.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpass_desc.colorAttachmentCount = 1;
subpass_desc.pColorAttachments = &color_attachment_ref;
// 렌더패스를 정의합니다.
VkRenderPassCreateInfo create_info {};
create_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
create_info.attachmentCount = 1;
create_info.pAttachments = &attachment_desc;
create_info.subpassCount = 1;
create_info.pSubpasses = &subpass_desc;
// 렌더패스를 생성합니다.
auto result = vkCreateRenderPass(device_, &create_info, nullptr, &render_pass_);
switch (result) {
case VK_ERROR_OUT_OF_HOST_MEMORY:
cout << "VK_ERROR_OUT_OF_HOST_MEMORY" << endl;
break;
case VK_ERROR_OUT_OF_DEVICE_MEMORY:
cout << "VK_ERROR_OUT_OF_DEVICE_MEMORY" << endl;
break;
default:
break;
}
assert(result == VK_SUCCESS);
}
void init_framebuffers_()
{
// 생성하려는 프레임버퍼를 정의합니다.
VkFramebufferCreateInfo create_info {};
create_info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
create_info.renderPass = render_pass_;
create_info.attachmentCount = 1;
create_info.width = swapchain_image_extent_.width;
create_info.height = swapchain_image_extent_.height;
create_info.layers = 1;
// 프레임버퍼를 위한 메모리를 할당합니다.
framebuffers_.resize(swapchain_image_views_.size());
for (auto i = 0; i != swapchain_image_views_.size(); ++i) {
create_info.pAttachments = &swapchain_image_views_[i];
// 프레임버퍼를 생성합니다.
auto result = vkCreateFramebuffer(device_, &create_info, nullptr, &framebuffers_[i]);
switch (result) {
case VK_ERROR_OUT_OF_HOST_MEMORY:
cout << "VK_ERROR_OUT_OF_HOST_MEMORY" << endl;
break;
case VK_ERROR_OUT_OF_DEVICE_MEMORY:
cout << "VK_ERROR_OUT_OF_DEVICE_MEMORY" << endl;
break;
default:
break;
}
assert(result == VK_SUCCESS);
}
}
void init_shader_modules_()
{
{
const string vksl = {
// 더이상 셰이더 안에서 정의되어있던 버텍스 정보를 사용하지 않고 버텍스 버퍼로부터 데이터를 읽어온다.
"precision mediump float; \n"
" \n"
"layout(location = 0) in vec3 i_pos; \n"
"layout(location = 1) in vec3 i_col; \n"
" \n"
"layout(location = 0) out vec3 o_col; \n"
" \n"
"void main() { \n"
" \n"
" gl_Position = vec4(i_pos, 1.0); \n"
" o_col = i_col; \n"
"} \n"
};
// 런타임 컴파일러를 사용해서 VKSL을 SPIRV로 컴파일합니다.
auto spirv = Spirv_compiler().compile(Shader_type::vertex, vksl);
// 생성하려는 셰이더 모듈을 정의합니다.
VkShaderModuleCreateInfo create_info {};
create_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
create_info.codeSize = spirv.size() * sizeof(uint32_t);
create_info.pCode = &spirv[0];
// 셰이더 모듈을 생성합니다.
auto result = vkCreateShaderModule(device_, &create_info, nullptr, &shader_modules_[0]);
switch (result) {
case VK_ERROR_OUT_OF_HOST_MEMORY:
cout << "VK_ERROR_OUT_OF_HOST_MEMORY" << endl;
break;
case VK_ERROR_OUT_OF_DEVICE_MEMORY:
cout << "VK_ERROR_OUT_OF_DEVICE_MEMORY" << endl;
break;
default:
break;
}
assert(result == VK_SUCCESS);
}
{
const string vksl = {
"precision mediump float; \n"
" \n"
"layout(location = 0) in vec3 i_col; \n"
" \n"
"layout(location = 0) out vec4 fragment_color0; \n"
" \n"
"void main() { \n"
" fragment_color0 = vec4(i_col, 1.0); \n"
"} \n"
};
// 런타임 컴파일러를 사용해서 VKSL을 SPIRV로 컴파일합니다.
auto spirv = Spirv_compiler().compile(Shader_type::fragment, vksl);
// 생성하려는 셰이더 모듈을 정의합니다.
VkShaderModuleCreateInfo create_info {};
create_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
create_info.codeSize = spirv.size() * sizeof(uint32_t);
create_info.pCode = &spirv[0];
// 셰이더 모듈을 생성합니다.
auto result = vkCreateShaderModule(device_, &create_info, nullptr, &shader_modules_[1]);
switch (result) {
case VK_ERROR_OUT_OF_HOST_MEMORY:
cout << "VK_ERROR_OUT_OF_HOST_MEMORY" << endl;
break;
case VK_ERROR_OUT_OF_DEVICE_MEMORY:
cout << "VK_ERROR_OUT_OF_DEVICE_MEMORY" << endl;
break;
default:
break;
}
assert(result == VK_SUCCESS);
}
}
void init_pipeline_layout_()
{
// 생성하려는 파이프라인 레이아웃을 정의합니다.
VkPipelineLayoutCreateInfo create_info {};
create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
// 파이프라인 레이아웃을 생성합니다.
auto result = vkCreatePipelineLayout(device_, &create_info, nullptr, &pipeline_layout_);
switch (result) {
case VK_ERROR_OUT_OF_HOST_MEMORY:
cout << "VK_ERROR_OUT_OF_HOST_MEMORY" << endl;
break;
case VK_ERROR_OUT_OF_DEVICE_MEMORY:
cout << "VK_ERROR_OUT_OF_DEVICE_MEMORY" << endl;
break;
default:
break;
}
assert(result == VK_SUCCESS);
}
void init_pipeline_()
{
// 파이프라인 셰이더 스테이지들을 정의합니다.
array<VkPipelineShaderStageCreateInfo, 2> stages;
{
// 생성하려는 파이프라인 버텍스 셰이더 스테이지를 정의합니다.
VkPipelineShaderStageCreateInfo stage {};
stage.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
stage.stage = VK_SHADER_STAGE_VERTEX_BIT;
stage.module = shader_modules_[0];
stage.pName = "main";
stages[0] = stage;
}
{
// 생성하려는 파이프라인 프래그먼트 셰이더 스테이지를 정의합니다.
VkPipelineShaderStageCreateInfo stage {};
stage.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
stage.stage = VK_SHADER_STAGE_FRAGMENT_BIT;
stage.module = shader_modules_[1];
stage.pName = "main";
stages[1] = stage;
}
// 버텍스 인풋 바인딩을 정의합니다.
VkVertexInputBindingDescription vertex_input_binding {};
vertex_input_binding.binding = 0;
vertex_input_binding.stride = sizeof(Vertex);
vertex_input_binding.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
vector<VkVertexInputAttributeDescription> vertex_input_attributes;
{
// 위치에 대한 버텍스 인풋 애트리뷰트를 정의합니다.
VkVertexInputAttributeDescription vertex_input_attribute {};
vertex_input_attribute.location = 0; // 셰이더에서 정의한 로케이션
vertex_input_attribute.binding = 0; // 버텍스 버퍼의 바인딩 인덱스
vertex_input_attribute.format = VK_FORMAT_R32G32B32_SFLOAT;
vertex_input_attribute.offset = offsetof(Vertex, x);
vertex_input_attributes.push_back(vertex_input_attribute);