-
Notifications
You must be signed in to change notification settings - Fork 172
/
Copy pathVulkanMain.cpp
1326 lines (1183 loc) · 47.8 KB
/
VulkanMain.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
// Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <android/log.h>
#include <cassert>
#include <vector>
#include "vulkan_wrapper.h"
#define STB_IMAGE_IMPLEMENTATION
#define STBI_ONLY_PNG
#include <stb/stb_image.h>
#include "CreateShaderModule.h"
#include "VulkanMain.hpp"
// Android log function wrappers
static const char* kTAG = "Vulkan-Tutorial06";
#define LOGI(...) \
((void)__android_log_print(ANDROID_LOG_INFO, kTAG, __VA_ARGS__))
#define LOGW(...) \
((void)__android_log_print(ANDROID_LOG_WARN, kTAG, __VA_ARGS__))
#define LOGE(...) \
((void)__android_log_print(ANDROID_LOG_ERROR, kTAG, __VA_ARGS__))
// Vulkan call wrapper
#define CALL_VK(func) \
if (VK_SUCCESS != (func)) { \
__android_log_print(ANDROID_LOG_ERROR, "Tutorial ", \
"Vulkan error. File[%s], line[%d]", __FILE__, \
__LINE__); \
assert(false); \
}
// A macro to check value is VK_SUCCESS
// Used also for non-vulkan functions but return VK_SUCCESS
#define VK_CHECK(x) CALL_VK(x)
// Global Variables ...
struct VulkanDeviceInfo {
bool initialized_;
VkInstance instance_;
VkPhysicalDevice gpuDevice_;
VkPhysicalDeviceMemoryProperties gpuMemoryProperties_;
VkDevice device_;
uint32_t queueFamilyIndex_;
VkSurfaceKHR surface_;
VkQueue queue_;
};
VulkanDeviceInfo device;
struct VulkanSwapchainInfo {
VkSwapchainKHR swapchain_;
uint32_t swapchainLength_;
VkExtent2D displaySize_;
VkFormat displayFormat_;
// array of frame buffers and views
VkFramebuffer* framebuffers_;
VkImage* displayImages_;
VkImageView* displayViews_;
};
VulkanSwapchainInfo swapchain;
typedef struct texture_object {
VkSampler sampler;
VkImage image;
VkImageLayout imageLayout;
VkDeviceMemory mem;
VkImageView view;
int32_t tex_width;
int32_t tex_height;
} texture_object;
static const VkFormat kTexFmt = VK_FORMAT_R8G8B8A8_UNORM;
#define TUTORIAL_TEXTURE_COUNT 1
const char* texFiles[TUTORIAL_TEXTURE_COUNT] = {
"sample_tex.png",
};
struct texture_object textures[TUTORIAL_TEXTURE_COUNT];
struct VulkanBufferInfo {
VkBuffer vertexBuf_;
};
VulkanBufferInfo buffers;
struct VulkanGfxPipelineInfo {
VkDescriptorSetLayout dscLayout_;
VkDescriptorPool descPool_;
VkDescriptorSet descSet_;
VkPipelineLayout layout_;
VkPipelineCache cache_;
VkPipeline pipeline_;
};
VulkanGfxPipelineInfo gfxPipeline;
struct VulkanRenderInfo {
VkRenderPass renderPass_;
VkCommandPool cmdPool_;
VkCommandBuffer* cmdBuffer_;
uint32_t cmdBufferLen_;
VkSemaphore semaphore_;
VkFence fence_;
};
VulkanRenderInfo render;
// Android Native App pointer...
android_app* androidAppCtx = nullptr;
void setImageLayout(VkCommandBuffer cmdBuffer, VkImage image,
VkImageLayout oldImageLayout, VkImageLayout newImageLayout,
VkPipelineStageFlags srcStages,
VkPipelineStageFlags destStages);
// Create vulkan device
void CreateVulkanDevice(ANativeWindow* platformWindow,
VkApplicationInfo* appInfo) {
std::vector<const char*> instance_extensions;
std::vector<const char*> device_extensions;
instance_extensions.push_back("VK_KHR_surface");
instance_extensions.push_back("VK_KHR_android_surface");
device_extensions.push_back("VK_KHR_swapchain");
// **********************************************************
// Create the Vulkan instance
VkInstanceCreateInfo instanceCreateInfo{
.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
.pNext = nullptr,
.pApplicationInfo = appInfo,
.enabledLayerCount = 0,
.ppEnabledLayerNames = nullptr,
.enabledExtensionCount =
static_cast<uint32_t>(instance_extensions.size()),
.ppEnabledExtensionNames = instance_extensions.data(),
};
CALL_VK(vkCreateInstance(&instanceCreateInfo, nullptr, &device.instance_));
VkAndroidSurfaceCreateInfoKHR createInfo{
.sType = VK_STRUCTURE_TYPE_ANDROID_SURFACE_CREATE_INFO_KHR,
.pNext = nullptr,
.flags = 0,
.window = platformWindow};
CALL_VK(vkCreateAndroidSurfaceKHR(device.instance_, &createInfo, nullptr,
&device.surface_));
// Find one GPU to use:
// On Android, every GPU device is equal -- supporting
// graphics/compute/present
// for this sample, we use the very first GPU device found on the system
uint32_t gpuCount = 0;
CALL_VK(vkEnumeratePhysicalDevices(device.instance_, &gpuCount, nullptr));
VkPhysicalDevice tmpGpus[gpuCount];
CALL_VK(vkEnumeratePhysicalDevices(device.instance_, &gpuCount, tmpGpus));
device.gpuDevice_ = tmpGpus[0]; // Pick up the first GPU Device
vkGetPhysicalDeviceMemoryProperties(device.gpuDevice_,
&device.gpuMemoryProperties_);
// Find a GFX queue family
uint32_t queueFamilyCount;
vkGetPhysicalDeviceQueueFamilyProperties(device.gpuDevice_, &queueFamilyCount,
nullptr);
assert(queueFamilyCount);
std::vector<VkQueueFamilyProperties> queueFamilyProperties(queueFamilyCount);
vkGetPhysicalDeviceQueueFamilyProperties(device.gpuDevice_, &queueFamilyCount,
queueFamilyProperties.data());
uint32_t queueFamilyIndex;
for (queueFamilyIndex = 0; queueFamilyIndex < queueFamilyCount;
queueFamilyIndex++) {
if (queueFamilyProperties[queueFamilyIndex].queueFlags &
VK_QUEUE_GRAPHICS_BIT) {
break;
}
}
assert(queueFamilyIndex < queueFamilyCount);
device.queueFamilyIndex_ = queueFamilyIndex;
// Create a logical device (vulkan device)
float priorities[] = {
1.0f,
};
VkDeviceQueueCreateInfo queueCreateInfo{
.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO,
.pNext = nullptr,
.flags = 0,
.queueFamilyIndex = device.queueFamilyIndex_,
.queueCount = 1,
.pQueuePriorities = priorities,
};
VkDeviceCreateInfo deviceCreateInfo{
.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO,
.pNext = nullptr,
.queueCreateInfoCount = 1,
.pQueueCreateInfos = &queueCreateInfo,
.enabledLayerCount = 0,
.ppEnabledLayerNames = nullptr,
.enabledExtensionCount = static_cast<uint32_t>(device_extensions.size()),
.ppEnabledExtensionNames = device_extensions.data(),
.pEnabledFeatures = nullptr,
};
CALL_VK(vkCreateDevice(device.gpuDevice_, &deviceCreateInfo, nullptr,
&device.device_));
vkGetDeviceQueue(device.device_, 0, 0, &device.queue_);
}
void CreateSwapChain(void) {
LOGI("->createSwapChain");
memset(&swapchain, 0, sizeof(swapchain));
// **********************************************************
// Get the surface capabilities because:
// - It contains the minimal and max length of the chain, we will need it
// - It's necessary to query the supported surface format (R8G8B8A8 for
// instance ...)
VkSurfaceCapabilitiesKHR surfaceCapabilities;
vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device.gpuDevice_, device.surface_,
&surfaceCapabilities);
// Query the list of supported surface format and choose one we like
uint32_t formatCount = 0;
vkGetPhysicalDeviceSurfaceFormatsKHR(device.gpuDevice_, device.surface_,
&formatCount, nullptr);
VkSurfaceFormatKHR* formats = new VkSurfaceFormatKHR[formatCount];
vkGetPhysicalDeviceSurfaceFormatsKHR(device.gpuDevice_, device.surface_,
&formatCount, formats);
LOGI("Got %d formats", formatCount);
uint32_t chosenFormat;
for (chosenFormat = 0; chosenFormat < formatCount; chosenFormat++) {
if (formats[chosenFormat].format == VK_FORMAT_R8G8B8A8_UNORM) break;
}
assert(chosenFormat < formatCount);
swapchain.displaySize_ = surfaceCapabilities.currentExtent;
swapchain.displayFormat_ = formats[chosenFormat].format;
// **********************************************************
// Create a swap chain (here we choose the minimum available number of surface
// in the chain)
VkSwapchainCreateInfoKHR swapchainCreateInfo{
.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR,
.pNext = nullptr,
.surface = device.surface_,
.minImageCount = surfaceCapabilities.minImageCount,
.imageFormat = formats[chosenFormat].format,
.imageColorSpace = formats[chosenFormat].colorSpace,
.imageExtent = surfaceCapabilities.currentExtent,
.imageArrayLayers = 1,
.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT,
.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE,
.queueFamilyIndexCount = 1,
.pQueueFamilyIndices = &device.queueFamilyIndex_,
.preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR,
.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR,
.presentMode = VK_PRESENT_MODE_FIFO_KHR,
.clipped = VK_FALSE,
.oldSwapchain = VK_NULL_HANDLE,
};
CALL_VK(vkCreateSwapchainKHR(device.device_, &swapchainCreateInfo, nullptr,
&swapchain.swapchain_));
// Get the length of the created swap chain
CALL_VK(vkGetSwapchainImagesKHR(device.device_, swapchain.swapchain_,
&swapchain.swapchainLength_, nullptr));
delete[] formats;
LOGI("<-createSwapChain");
}
void DeleteSwapChain(void) {
for (int i = 0; i < swapchain.swapchainLength_; i++) {
vkDestroyFramebuffer(device.device_, swapchain.framebuffers_[i], nullptr);
vkDestroyImageView(device.device_, swapchain.displayViews_[i], nullptr);
}
delete[] swapchain.framebuffers_;
delete[] swapchain.displayViews_;
delete[] swapchain.displayImages_;
vkDestroySwapchainKHR(device.device_, swapchain.swapchain_, nullptr);
}
void CreateFrameBuffers(VkRenderPass& renderPass,
VkImageView depthView = VK_NULL_HANDLE) {
// query display attachment to swapchain
uint32_t SwapchainImagesCount = 0;
CALL_VK(vkGetSwapchainImagesKHR(device.device_, swapchain.swapchain_,
&SwapchainImagesCount, nullptr));
swapchain.displayImages_ = new VkImage[SwapchainImagesCount];
CALL_VK(vkGetSwapchainImagesKHR(device.device_, swapchain.swapchain_,
&SwapchainImagesCount,
swapchain.displayImages_));
// create image view for each swapchain image
swapchain.displayViews_ = new VkImageView[SwapchainImagesCount];
for (uint32_t i = 0; i < SwapchainImagesCount; i++) {
VkImageViewCreateInfo viewCreateInfo = {
.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
.pNext = nullptr,
.flags = 0,
.image = swapchain.displayImages_[i],
.viewType = VK_IMAGE_VIEW_TYPE_2D,
.format = swapchain.displayFormat_,
.components =
{
.r = VK_COMPONENT_SWIZZLE_R,
.g = VK_COMPONENT_SWIZZLE_G,
.b = VK_COMPONENT_SWIZZLE_B,
.a = VK_COMPONENT_SWIZZLE_A,
},
.subresourceRange =
{
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1,
},
};
CALL_VK(vkCreateImageView(device.device_, &viewCreateInfo, nullptr,
&swapchain.displayViews_[i]));
}
// create a framebuffer from each swapchain image
swapchain.framebuffers_ = new VkFramebuffer[swapchain.swapchainLength_];
for (uint32_t i = 0; i < swapchain.swapchainLength_; i++) {
VkImageView attachments[2] = {
swapchain.displayViews_[i], depthView,
};
VkFramebufferCreateInfo fbCreateInfo{
.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO,
.pNext = nullptr,
.renderPass = renderPass,
.attachmentCount = 1, // 2 if using depth
.pAttachments = attachments,
.width = static_cast<uint32_t>(swapchain.displaySize_.width),
.height = static_cast<uint32_t>(swapchain.displaySize_.height),
.layers = 1,
};
fbCreateInfo.attachmentCount = (depthView == VK_NULL_HANDLE ? 1 : 2);
CALL_VK(vkCreateFramebuffer(device.device_, &fbCreateInfo, nullptr,
&swapchain.framebuffers_[i]));
}
}
// A help function to map required memory property into a VK memory type
// memory type is an index into the array of 32 entries; or the bit index
// for the memory type ( each BIT of an 32 bit integer is a type ).
VkResult AllocateMemoryTypeFromProperties(uint32_t typeBits,
VkFlags requirements_mask,
uint32_t* typeIndex) {
// Search memtypes to find first index with those properties
for (uint32_t i = 0; i < 32; i++) {
if ((typeBits & 1) == 1) {
// Type is available, does it match user properties?
if ((device.gpuMemoryProperties_.memoryTypes[i].propertyFlags &
requirements_mask) == requirements_mask) {
*typeIndex = i;
return VK_SUCCESS;
}
}
typeBits >>= 1;
}
// No memory types matched, return failure
return VK_ERROR_MEMORY_MAP_FAILED;
}
VkResult LoadTextureFromFile(const char* filePath,
struct texture_object* tex_obj,
VkImageUsageFlags usage, VkFlags required_props) {
if (!(usage | required_props)) {
__android_log_print(ANDROID_LOG_ERROR, "tutorial texture",
"No usage and required_pros");
return VK_ERROR_FORMAT_NOT_SUPPORTED;
}
// Check for linear supportability
VkFormatProperties props;
bool needBlit = true;
vkGetPhysicalDeviceFormatProperties(device.gpuDevice_, kTexFmt, &props);
assert((props.linearTilingFeatures | props.optimalTilingFeatures) &
VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT);
if (props.linearTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) {
// linear format supporting the required texture
needBlit = false;
}
// Read the file:
AAsset* file = AAssetManager_open(androidAppCtx->activity->assetManager,
filePath, AASSET_MODE_BUFFER);
size_t fileLength = AAsset_getLength(file);
stbi_uc* fileContent = new unsigned char[fileLength];
AAsset_read(file, fileContent, fileLength);
AAsset_close(file);
uint32_t imgWidth, imgHeight, n;
unsigned char* imageData = stbi_load_from_memory(
fileContent, fileLength, reinterpret_cast<int*>(&imgWidth),
reinterpret_cast<int*>(&imgHeight), reinterpret_cast<int*>(&n), 4);
assert(n == 4);
tex_obj->tex_width = imgWidth;
tex_obj->tex_height = imgHeight;
// Allocate the linear texture so texture could be copied over
VkImageCreateInfo image_create_info = {
.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
.pNext = nullptr,
.flags = 0,
.imageType = VK_IMAGE_TYPE_2D,
.format = kTexFmt,
.extent = {static_cast<uint32_t>(imgWidth),
static_cast<uint32_t>(imgHeight), 1},
.mipLevels = 1,
.arrayLayers = 1,
.samples = VK_SAMPLE_COUNT_1_BIT,
.tiling = VK_IMAGE_TILING_LINEAR,
.usage = (needBlit ? VK_IMAGE_USAGE_TRANSFER_SRC_BIT
: VK_IMAGE_USAGE_SAMPLED_BIT),
.sharingMode = VK_SHARING_MODE_EXCLUSIVE,
.queueFamilyIndexCount = 1,
.pQueueFamilyIndices = &device.queueFamilyIndex_,
.initialLayout = VK_IMAGE_LAYOUT_PREINITIALIZED,
};
VkMemoryAllocateInfo mem_alloc = {
.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
.pNext = nullptr,
.allocationSize = 0,
.memoryTypeIndex = 0,
};
VkMemoryRequirements mem_reqs;
CALL_VK(vkCreateImage(device.device_, &image_create_info, nullptr,
&tex_obj->image));
vkGetImageMemoryRequirements(device.device_, tex_obj->image, &mem_reqs);
mem_alloc.allocationSize = mem_reqs.size;
VK_CHECK(AllocateMemoryTypeFromProperties(mem_reqs.memoryTypeBits,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
&mem_alloc.memoryTypeIndex));
CALL_VK(vkAllocateMemory(device.device_, &mem_alloc, nullptr, &tex_obj->mem));
CALL_VK(vkBindImageMemory(device.device_, tex_obj->image, tex_obj->mem, 0));
if (required_props & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) {
const VkImageSubresource subres = {
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, .mipLevel = 0, .arrayLayer = 0,
};
VkSubresourceLayout layout;
void* data;
vkGetImageSubresourceLayout(device.device_, tex_obj->image, &subres,
&layout);
CALL_VK(vkMapMemory(device.device_, tex_obj->mem, 0,
mem_alloc.allocationSize, 0, &data));
for (int32_t y = 0; y < imgHeight; y++) {
unsigned char* row = (unsigned char*)((char*)data + layout.rowPitch * y);
for (int32_t x = 0; x < imgWidth; x++) {
row[x * 4] = imageData[(x + y * imgWidth) * 4];
row[x * 4 + 1] = imageData[(x + y * imgWidth) * 4 + 1];
row[x * 4 + 2] = imageData[(x + y * imgWidth) * 4 + 2];
row[x * 4 + 3] = imageData[(x + y * imgWidth) * 4 + 3];
}
}
vkUnmapMemory(device.device_, tex_obj->mem);
stbi_image_free(imageData);
}
delete[] fileContent;
tex_obj->imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
VkCommandPoolCreateInfo cmdPoolCreateInfo{
.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
.pNext = nullptr,
.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT,
.queueFamilyIndex = device.queueFamilyIndex_,
};
VkCommandPool cmdPool;
CALL_VK(vkCreateCommandPool(device.device_, &cmdPoolCreateInfo, nullptr,
&cmdPool));
VkCommandBuffer gfxCmd;
const VkCommandBufferAllocateInfo cmd = {
.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
.pNext = nullptr,
.commandPool = cmdPool,
.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY,
.commandBufferCount = 1,
};
CALL_VK(vkAllocateCommandBuffers(device.device_, &cmd, &gfxCmd));
VkCommandBufferBeginInfo cmd_buf_info = {
.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
.pNext = nullptr,
.flags = 0,
.pInheritanceInfo = nullptr};
CALL_VK(vkBeginCommandBuffer(gfxCmd, &cmd_buf_info));
// If linear is supported, we are done
VkImage stageImage = VK_NULL_HANDLE;
VkDeviceMemory stageMem = VK_NULL_HANDLE;
if (!needBlit) {
setImageLayout(gfxCmd, tex_obj->image, VK_IMAGE_LAYOUT_PREINITIALIZED,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
VK_PIPELINE_STAGE_HOST_BIT,
VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT);
} else {
// save current image and mem as staging image and memory
stageImage = tex_obj->image;
stageMem = tex_obj->mem;
tex_obj->image = VK_NULL_HANDLE;
tex_obj->mem = VK_NULL_HANDLE;
// Create a tile texture to blit into
image_create_info.tiling = VK_IMAGE_TILING_OPTIMAL;
image_create_info.usage =
VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT;
image_create_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
CALL_VK(vkCreateImage(device.device_, &image_create_info, nullptr,
&tex_obj->image));
vkGetImageMemoryRequirements(device.device_, tex_obj->image, &mem_reqs);
mem_alloc.allocationSize = mem_reqs.size;
VK_CHECK(AllocateMemoryTypeFromProperties(
mem_reqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
&mem_alloc.memoryTypeIndex));
CALL_VK(
vkAllocateMemory(device.device_, &mem_alloc, nullptr, &tex_obj->mem));
CALL_VK(vkBindImageMemory(device.device_, tex_obj->image, tex_obj->mem, 0));
// transitions image out of UNDEFINED type
setImageLayout(gfxCmd, stageImage, VK_IMAGE_LAYOUT_PREINITIALIZED,
VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT);
setImageLayout(gfxCmd, tex_obj->image, VK_IMAGE_LAYOUT_UNDEFINED,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT);
VkImageCopy bltInfo{
.srcSubresource {
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
.mipLevel = 0,
.baseArrayLayer = 0,
.layerCount = 1,
},
.srcOffset { .x = 0, .y = 0, .z = 0 },
.dstSubresource {
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
.mipLevel = 0,
.baseArrayLayer = 0,
.layerCount = 1,
},
.dstOffset { .x = 0, .y = 0, .z = 0},
.extent { .width = imgWidth, .height = imgHeight, .depth = 1,},
};
vkCmdCopyImage(gfxCmd, stageImage, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
tex_obj->image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1,
&bltInfo);
setImageLayout(gfxCmd, tex_obj->image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
VK_PIPELINE_STAGE_TRANSFER_BIT,
VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT);
}
CALL_VK(vkEndCommandBuffer(gfxCmd));
VkFenceCreateInfo fenceInfo = {
.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO,
.pNext = nullptr,
.flags = 0,
};
VkFence fence;
CALL_VK(vkCreateFence(device.device_, &fenceInfo, nullptr, &fence));
VkSubmitInfo submitInfo = {
.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
.pNext = nullptr,
.waitSemaphoreCount = 0,
.pWaitSemaphores = nullptr,
.pWaitDstStageMask = nullptr,
.commandBufferCount = 1,
.pCommandBuffers = &gfxCmd,
.signalSemaphoreCount = 0,
.pSignalSemaphores = nullptr,
};
CALL_VK(vkQueueSubmit(device.queue_, 1, &submitInfo, fence) != VK_SUCCESS);
CALL_VK(vkWaitForFences(device.device_, 1, &fence, VK_TRUE, 100000000) !=
VK_SUCCESS);
vkDestroyFence(device.device_, fence, nullptr);
vkFreeCommandBuffers(device.device_, cmdPool, 1, &gfxCmd);
vkDestroyCommandPool(device.device_, cmdPool, nullptr);
if (stageImage != VK_NULL_HANDLE) {
vkDestroyImage(device.device_, stageImage, nullptr);
vkFreeMemory(device.device_, stageMem, nullptr);
}
return VK_SUCCESS;
}
void CreateTexture(void) {
for (uint32_t i = 0; i < TUTORIAL_TEXTURE_COUNT; i++) {
LoadTextureFromFile(texFiles[i], &textures[i], VK_IMAGE_USAGE_SAMPLED_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT);
const VkSamplerCreateInfo sampler = {
.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO,
.pNext = nullptr,
.magFilter = VK_FILTER_NEAREST,
.minFilter = VK_FILTER_NEAREST,
.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST,
.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT,
.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT,
.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT,
.mipLodBias = 0.0f,
.maxAnisotropy = 1,
.compareOp = VK_COMPARE_OP_NEVER,
.minLod = 0.0f,
.maxLod = 0.0f,
.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE,
.unnormalizedCoordinates = VK_FALSE,
};
VkImageViewCreateInfo view = {
.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
.pNext = nullptr,
.flags = 0,
.image = VK_NULL_HANDLE,
.viewType = VK_IMAGE_VIEW_TYPE_2D,
.format = kTexFmt,
.components =
{
VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_G,
VK_COMPONENT_SWIZZLE_B, VK_COMPONENT_SWIZZLE_A,
},
.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1},
};
CALL_VK(vkCreateSampler(device.device_, &sampler, nullptr,
&textures[i].sampler));
view.image = textures[i].image;
CALL_VK(
vkCreateImageView(device.device_, &view, nullptr, &textures[i].view));
}
}
// A helper function
bool MapMemoryTypeToIndex(uint32_t typeBits, VkFlags requirements_mask,
uint32_t* typeIndex) {
VkPhysicalDeviceMemoryProperties memoryProperties;
vkGetPhysicalDeviceMemoryProperties(device.gpuDevice_, &memoryProperties);
// Search memtypes to find first index with those properties
for (uint32_t i = 0; i < 32; i++) {
if ((typeBits & 1) == 1) {
// Type is available, does it match user properties?
if ((memoryProperties.memoryTypes[i].propertyFlags & requirements_mask) ==
requirements_mask) {
*typeIndex = i;
return true;
}
}
typeBits >>= 1;
}
return false;
}
// Create our vertex buffer
bool CreateBuffers(void) {
// Vertex positions
const float vertexData[] = {
-1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, -1.0f, 0.0f,
1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.5f, 1.0f,
};
// Create a vertex buffer
VkBufferCreateInfo createBufferInfo{
.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
.pNext = nullptr,
.flags = 0,
.size = sizeof(vertexData),
.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT,
.sharingMode = VK_SHARING_MODE_EXCLUSIVE,
.queueFamilyIndexCount = 1,
.pQueueFamilyIndices = &device.queueFamilyIndex_,
};
CALL_VK(vkCreateBuffer(device.device_, &createBufferInfo, nullptr,
&buffers.vertexBuf_));
VkMemoryRequirements memReq;
vkGetBufferMemoryRequirements(device.device_, buffers.vertexBuf_, &memReq);
VkMemoryAllocateInfo allocInfo{
.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
.pNext = nullptr,
.allocationSize = memReq.size,
.memoryTypeIndex = 0, // Memory type assigned in the next step
};
// Assign the proper memory type for that buffer
MapMemoryTypeToIndex(memReq.memoryTypeBits,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
&allocInfo.memoryTypeIndex);
// Allocate memory for the buffer
VkDeviceMemory deviceMemory;
CALL_VK(vkAllocateMemory(device.device_, &allocInfo, nullptr, &deviceMemory));
void* data;
CALL_VK(vkMapMemory(device.device_, deviceMemory, 0, allocInfo.allocationSize,
0, &data));
memcpy(data, vertexData, sizeof(vertexData));
vkUnmapMemory(device.device_, deviceMemory);
CALL_VK(
vkBindBufferMemory(device.device_, buffers.vertexBuf_, deviceMemory, 0));
return true;
}
void DeleteBuffers(void) {
vkDestroyBuffer(device.device_, buffers.vertexBuf_, nullptr);
}
// Create Graphics Pipeline
VkResult CreateGraphicsPipeline(void) {
memset(&gfxPipeline, 0, sizeof(gfxPipeline));
const VkDescriptorSetLayoutBinding descriptorSetLayoutBinding{
.binding = 0,
.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
.descriptorCount = TUTORIAL_TEXTURE_COUNT,
.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT,
.pImmutableSamplers = nullptr,
};
const VkDescriptorSetLayoutCreateInfo descriptorSetLayoutCreateInfo = {
.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO,
.pNext = nullptr,
.bindingCount = 1,
.pBindings = &descriptorSetLayoutBinding,
};
CALL_VK(vkCreateDescriptorSetLayout(device.device_,
&descriptorSetLayoutCreateInfo, nullptr,
&gfxPipeline.dscLayout_));
VkPipelineLayoutCreateInfo pipelineLayoutCreateInfo{
.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO,
.pNext = nullptr,
.setLayoutCount = 1,
.pSetLayouts = &gfxPipeline.dscLayout_,
.pushConstantRangeCount = 0,
.pPushConstantRanges = nullptr,
};
CALL_VK(vkCreatePipelineLayout(device.device_, &pipelineLayoutCreateInfo,
nullptr, &gfxPipeline.layout_));
// No dynamic state in that tutorial
VkPipelineDynamicStateCreateInfo dynamicStateInfo{
.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO,
.pNext = nullptr,
.dynamicStateCount = 0,
.pDynamicStates = nullptr};
VkShaderModule vertexShader, fragmentShader;
buildShaderFromFile(androidAppCtx, "shaders/tri.vert",
VK_SHADER_STAGE_VERTEX_BIT, device.device_,
&vertexShader);
buildShaderFromFile(androidAppCtx, "shaders/tri.frag",
VK_SHADER_STAGE_FRAGMENT_BIT, device.device_,
&fragmentShader);
// Specify vertex and fragment shader stages
VkPipelineShaderStageCreateInfo shaderStages[2]{
{
.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,
.pNext = nullptr,
.flags = 0,
.stage = VK_SHADER_STAGE_VERTEX_BIT,
.module = vertexShader,
.pName = "main",
.pSpecializationInfo = nullptr,
},
{
.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,
.pNext = nullptr,
.flags = 0,
.stage = VK_SHADER_STAGE_FRAGMENT_BIT,
.module = fragmentShader,
.pName = "main",
.pSpecializationInfo = nullptr,
}};
VkViewport viewports {
.x = 0,
.y = 0,
.width = (float)swapchain.displaySize_.width,
.height = (float)swapchain.displaySize_.height,
.minDepth = 0.0f,
.maxDepth = 1.0f,
};
VkRect2D scissor = {
.offset = {.x = 0, .y = 0,},
.extent = swapchain.displaySize_,
};
// Specify viewport info
VkPipelineViewportStateCreateInfo viewportInfo{
.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO,
.pNext = nullptr,
.viewportCount = 1,
.pViewports = &viewports,
.scissorCount = 1,
.pScissors = &scissor,
};
// Specify multisample info
VkSampleMask sampleMask = ~0u;
VkPipelineMultisampleStateCreateInfo multisampleInfo{
.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO,
.pNext = nullptr,
.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT,
.sampleShadingEnable = VK_FALSE,
.minSampleShading = 0,
.pSampleMask = &sampleMask,
.alphaToCoverageEnable = VK_FALSE,
.alphaToOneEnable = VK_FALSE,
};
// Specify color blend state
VkPipelineColorBlendAttachmentState attachmentStates{
.blendEnable = VK_FALSE,
.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT |
VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT,
};
VkPipelineColorBlendStateCreateInfo colorBlendInfo{
.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO,
.pNext = nullptr,
.flags = 0,
.logicOpEnable = VK_FALSE,
.logicOp = VK_LOGIC_OP_COPY,
.attachmentCount = 1,
.pAttachments = &attachmentStates,
};
// Specify rasterizer info
VkPipelineRasterizationStateCreateInfo rasterInfo{
.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO,
.pNext = nullptr,
.depthClampEnable = VK_FALSE,
.rasterizerDiscardEnable = VK_FALSE,
.polygonMode = VK_POLYGON_MODE_FILL,
.cullMode = VK_CULL_MODE_NONE,
.frontFace = VK_FRONT_FACE_CLOCKWISE,
.depthBiasEnable = VK_FALSE,
.lineWidth = 1,
};
// Specify input assembler state
VkPipelineInputAssemblyStateCreateInfo inputAssemblyInfo{
.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO,
.pNext = nullptr,
.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST,
.primitiveRestartEnable = VK_FALSE,
};
// Specify vertex input state
VkVertexInputBindingDescription vertex_input_bindings{
.binding = 0,
.stride = 5 * sizeof(float),
.inputRate = VK_VERTEX_INPUT_RATE_VERTEX,
};
VkVertexInputAttributeDescription vertex_input_attributes[2]{
{
.location = 0,
.binding = 0,
.format = VK_FORMAT_R32G32B32_SFLOAT,
.offset = 0,
},
{
.location = 1,
.binding = 0,
.format = VK_FORMAT_R32G32_SFLOAT,
.offset = sizeof(float) * 3,
}};
VkPipelineVertexInputStateCreateInfo vertexInputInfo{
.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO,
.pNext = nullptr,
.vertexBindingDescriptionCount = 1,
.pVertexBindingDescriptions = &vertex_input_bindings,
.vertexAttributeDescriptionCount = 2,
.pVertexAttributeDescriptions = vertex_input_attributes,
};
// Create the pipeline cache
VkPipelineCacheCreateInfo pipelineCacheInfo{
.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO,
.pNext = nullptr,
.flags = 0, // reserved, must be 0
.initialDataSize = 0,
.pInitialData = nullptr,
};
CALL_VK(vkCreatePipelineCache(device.device_, &pipelineCacheInfo, nullptr,
&gfxPipeline.cache_));
// Create the pipeline
VkGraphicsPipelineCreateInfo pipelineCreateInfo{
.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO,
.pNext = nullptr,
.flags = 0,
.stageCount = 2,
.pStages = shaderStages,
.pVertexInputState = &vertexInputInfo,
.pInputAssemblyState = &inputAssemblyInfo,
.pTessellationState = nullptr,
.pViewportState = &viewportInfo,
.pRasterizationState = &rasterInfo,
.pMultisampleState = &multisampleInfo,
.pDepthStencilState = nullptr,
.pColorBlendState = &colorBlendInfo,
.pDynamicState = &dynamicStateInfo,
.layout = gfxPipeline.layout_,
.renderPass = render.renderPass_,
.subpass = 0,
.basePipelineHandle = VK_NULL_HANDLE,
.basePipelineIndex = 0,
};
VkResult pipelineResult = vkCreateGraphicsPipelines(
device.device_, gfxPipeline.cache_, 1, &pipelineCreateInfo, nullptr,
&gfxPipeline.pipeline_);
// We don't need the shaders anymore, we can release their memory
vkDestroyShaderModule(device.device_, vertexShader, nullptr);
vkDestroyShaderModule(device.device_, fragmentShader, nullptr);
return pipelineResult;
}
void DeleteGraphicsPipeline(void) {
if (gfxPipeline.pipeline_ == VK_NULL_HANDLE) return;
vkDestroyPipeline(device.device_, gfxPipeline.pipeline_, nullptr);
vkDestroyPipelineCache(device.device_, gfxPipeline.cache_, nullptr);
vkFreeDescriptorSets(device.device_, gfxPipeline.descPool_, 1,
&gfxPipeline.descSet_);
vkDestroyDescriptorPool(device.device_, gfxPipeline.descPool_, nullptr);
vkDestroyPipelineLayout(device.device_, gfxPipeline.layout_, nullptr);
}
// initialize descriptor set
VkResult CreateDescriptorSet(void) {
const VkDescriptorPoolSize type_count = {
.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
.descriptorCount = TUTORIAL_TEXTURE_COUNT,
};
const VkDescriptorPoolCreateInfo descriptor_pool = {
.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO,
.pNext = nullptr,
.maxSets = 1,
.poolSizeCount = 1,
.pPoolSizes = &type_count,
};
CALL_VK(vkCreateDescriptorPool(device.device_, &descriptor_pool, nullptr,
&gfxPipeline.descPool_));
VkDescriptorSetAllocateInfo alloc_info{
.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO,
.pNext = nullptr,
.descriptorPool = gfxPipeline.descPool_,
.descriptorSetCount = 1,
.pSetLayouts = &gfxPipeline.dscLayout_};
CALL_VK(vkAllocateDescriptorSets(device.device_, &alloc_info,
&gfxPipeline.descSet_));
VkDescriptorImageInfo texDsts[TUTORIAL_TEXTURE_COUNT];
memset(texDsts, 0, sizeof(texDsts));
for (int32_t idx = 0; idx < TUTORIAL_TEXTURE_COUNT; idx++) {
texDsts[idx].sampler = textures[idx].sampler;
texDsts[idx].imageView = textures[idx].view;
texDsts[idx].imageLayout = VK_IMAGE_LAYOUT_GENERAL;
}
VkWriteDescriptorSet writeDst{
.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
.pNext = nullptr,
.dstSet = gfxPipeline.descSet_,
.dstBinding = 0,
.dstArrayElement = 0,
.descriptorCount = TUTORIAL_TEXTURE_COUNT,
.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
.pImageInfo = texDsts,
.pBufferInfo = nullptr,