-
Notifications
You must be signed in to change notification settings - Fork 0
/
VkResample.cpp
1977 lines (1852 loc) · 89.1 KB
/
VkResample.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 VkResample, a Vulkan real-time FFT resampling tool
//
// Copyright (C) 2020 Dmitrii Tolmachev <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
#include <vector>
#include <memory>
#include <string.h>
#include <chrono>
#include <thread>
#include <array>
#include <iostream>
#include <algorithm>
#include "vkFFT.h"
#include "vulkan/vulkan.h"
#include "half.hpp"
#define STB_IMAGE_IMPLEMENTATION
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image.h"
#include "stb_image_write.h"
#include "glslang_c_interface.h"
using half_float::half;
typedef half half2[2];
const bool enableValidationLayers = false;
typedef struct {
VkInstance instance;//a connection between the application and the Vulkan library
VkPhysicalDevice physicalDevice;//a handle for the graphics card used in the application
VkPhysicalDeviceProperties physicalDeviceProperties;//bastic device properties
VkPhysicalDeviceMemoryProperties physicalDeviceMemoryProperties;//bastic memory properties of the device
VkDevice device;//a logical device, interacting with physical device
VkDebugUtilsMessengerEXT debugMessenger;//extension for debugging
uint32_t queueFamilyIndex;//if multiple queues are available, specify the used one
VkQueue queue;//a place, where all operations are submitted
VkCommandPool commandPool;//an opaque objects that command buffer memory is allocated from
VkFence fence;//a vkGPU->fence used to synchronize dispatches
uint32_t device_id;//an id of a device, reported by Vulkan device list
std::vector<const char*> enabledDeviceExtensions;
} VkGPU;//an example structure containing Vulkan primitives
typedef struct {
char* png_input_name;
char* png_output_name;
char* ifolder_prefix;
char* ofolder_prefix;
float upscale;
uint32_t fileUpload;
uint32_t precision;
uint32_t numIter;
uint32_t numFiles;
uint32_t device_id;
float sharpenConst;
uint32_t numThreads;
uint32_t threadId;
}VkResampleConfiguration;
const char validationLayers[28] = "VK_LAYER_KHRONOS_validation";
typedef struct {
//system size
uint32_t localSize[3];
uint32_t size[3];
uint32_t inputStride[3];
uint32_t outputStride[3];
float upscale;
float sharpenCoeff;
//how much memory is coalesced (in bytes) - 32 for Nvidia, 64 for Intel, 64 for AMD. Maximum value: 128
uint32_t coalescedMemory;
//bridging information, that allows shaders to freely access resources like buffers and images
VkDescriptorPool descriptorPool;
VkDescriptorSetLayout descriptorSetLayout;
VkDescriptorSet descriptorSet;
//pipeline used for graphics applications, we only use compute part of it in this example
VkPipelineLayout pipelineLayout;
VkPipeline pipeline;
//input buffer
VkDeviceSize inputBufferSize;//the size of buffer (in bytes)
VkBuffer* inputBuffer;//pointer to the buffer object
//VkDeviceMemory* inputBufferDeviceMemory;//pointer to the memory object, corresponding to the buffer
//output buffer
VkDeviceSize outputBufferSize;
VkBuffer* outputBuffer;
//VkDeviceMemory* outputBufferDeviceMemory;
uint32_t numCoordinates;
uint32_t precision; //0-single, 1-double, 2-half
uint32_t r2c;
char* code0;
} VkShiftApplication;//sample shader specific data
/*static VKAPI_ATTR VkBool32 VKAPI_CALL debugReportCallbackFn(
VkDebugReportFlagsEXT flags,
VkDebugReportObjectTypeEXT objectType,
uint64_t object,
size_t location,
int32_t messageCode,
const char* pLayerPrefix,
const char* pMessage,
void* pUserData) {
printf("Debug Report: %s: %s\n", pLayerPrefix, pMessage);
return VK_FALSE;
}*/
VkResult CreateDebugUtilsMessengerEXT(VkGPU* vkGPU, const VkDebugUtilsMessengerCreateInfoEXT* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkDebugUtilsMessengerEXT* pDebugMessenger) {
//pointer to the function, as it is not part of the core. Function creates debugging messenger
PFN_vkCreateDebugUtilsMessengerEXT func = (PFN_vkCreateDebugUtilsMessengerEXT)vkGetInstanceProcAddr(vkGPU->instance, "vkCreateDebugUtilsMessengerEXT");
if (func != NULL) {
return func(vkGPU->instance, pCreateInfo, pAllocator, pDebugMessenger);
}
else {
return VK_ERROR_EXTENSION_NOT_PRESENT;
}
}
void DestroyDebugUtilsMessengerEXT(VkGPU* vkGPU, const VkAllocationCallbacks* pAllocator) {
//pointer to the function, as it is not part of the core. Function destroys debugging messenger
PFN_vkDestroyDebugUtilsMessengerEXT func = (PFN_vkDestroyDebugUtilsMessengerEXT)vkGetInstanceProcAddr(vkGPU->instance, "vkDestroyDebugUtilsMessengerEXT");
if (func != NULL) {
func(vkGPU->instance, vkGPU->debugMessenger, pAllocator);
}
}
static VKAPI_ATTR VkBool32 VKAPI_CALL debugCallback(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity, VkDebugUtilsMessageTypeFlagsEXT messageType, const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData, void* pUserData) {
printf("validation layer: %s\n", pCallbackData->pMessage);
return VK_FALSE;
}
VkResult setupDebugMessenger(VkGPU* vkGPU) {
//function that sets up the debugging messenger
if (enableValidationLayers == 0) return VK_SUCCESS;
VkDebugUtilsMessengerCreateInfoEXT createInfo = { VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT };
createInfo.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT;
createInfo.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
createInfo.pfnUserCallback = debugCallback;
if (CreateDebugUtilsMessengerEXT(vkGPU, &createInfo, NULL, &vkGPU->debugMessenger) != VK_SUCCESS) {
return VK_ERROR_INITIALIZATION_FAILED;
}
return VK_SUCCESS;
}
VkResult checkValidationLayerSupport() {
//check if validation layers are supported when an instance is created
uint32_t layerCount;
vkEnumerateInstanceLayerProperties(&layerCount, NULL);
VkLayerProperties* availableLayers = (VkLayerProperties*)malloc(sizeof(VkLayerProperties) * layerCount);
vkEnumerateInstanceLayerProperties(&layerCount, availableLayers);
for (uint32_t i = 0; i < layerCount; i++) {
if (strcmp("VK_LAYER_KHRONOS_validation", availableLayers[i].layerName) == 0) {
free(availableLayers);
return VK_SUCCESS;
}
}
free(availableLayers);
return VK_ERROR_LAYER_NOT_PRESENT;
}
std::vector<const char*> getRequiredExtensions() {
std::vector<const char*> extensions;
if (enableValidationLayers) {
extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
}
extensions.push_back("VK_KHR_get_physical_device_properties2");
return extensions;
}
VkResult createInstance(VkGPU* vkGPU) {
//create instance - a connection between the application and the Vulkan library
VkResult res = VK_SUCCESS;
//check if validation layers are supported
if (enableValidationLayers == 1) {
res = checkValidationLayerSupport();
if (res != VK_SUCCESS) return res;
}
VkApplicationInfo applicationInfo = { VK_STRUCTURE_TYPE_APPLICATION_INFO };
applicationInfo.pApplicationName = "VkFFT";
applicationInfo.applicationVersion = 1.0;
applicationInfo.pEngineName = "VkFFT";
applicationInfo.engineVersion = 1.0;
applicationInfo.apiVersion = VK_API_VERSION_1_1;
VkInstanceCreateInfo createInfo = { VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO };
createInfo.flags = 0;
createInfo.pApplicationInfo = &applicationInfo;
auto extensions = getRequiredExtensions();
createInfo.enabledExtensionCount = static_cast<uint32_t>(extensions.size());
createInfo.ppEnabledExtensionNames = extensions.data();
VkDebugUtilsMessengerCreateInfoEXT debugCreateInfo = { VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT };
if (enableValidationLayers) {
//query for the validation layer support in the instance
createInfo.enabledLayerCount = 1;
const char* validationLayers = "VK_LAYER_KHRONOS_validation";
createInfo.ppEnabledLayerNames = &validationLayers;
debugCreateInfo.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT;
debugCreateInfo.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
debugCreateInfo.pfnUserCallback = debugCallback;
createInfo.pNext = (VkDebugUtilsMessengerCreateInfoEXT*)&debugCreateInfo;
}
else {
createInfo.enabledLayerCount = 0;
createInfo.pNext = nullptr;
}
res = vkCreateInstance(&createInfo, NULL, &vkGPU->instance);
if (res != VK_SUCCESS) return res;
return res;
}
VkResult findPhysicalDevice(VkGPU* vkGPU) {
//check if there are GPUs that support Vulkan and select one
VkResult res = VK_SUCCESS;
uint32_t deviceCount;
res = vkEnumeratePhysicalDevices(vkGPU->instance, &deviceCount, NULL);
if (res != VK_SUCCESS) return res;
if (deviceCount == 0) {
return VK_ERROR_DEVICE_LOST;
}
VkPhysicalDevice* devices = (VkPhysicalDevice*)malloc(sizeof(VkPhysicalDevice) * deviceCount);
res = vkEnumeratePhysicalDevices(vkGPU->instance, &deviceCount, devices);
if (res != VK_SUCCESS) return res;
vkGPU->physicalDevice = devices[vkGPU->device_id];
free(devices);
return VK_SUCCESS;
}
VkResult devices_list() {
//this function creates an instance and prints the list of available devices
VkResult res = VK_SUCCESS;
VkInstance local_instance = { 0 };
VkInstanceCreateInfo createInfo = { VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO };
createInfo.flags = 0;
createInfo.pApplicationInfo = NULL;
VkDebugUtilsMessengerCreateInfoEXT debugCreateInfo = { VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT };
createInfo.enabledLayerCount = 0;
createInfo.enabledExtensionCount = 0;
createInfo.pNext = NULL;
res = vkCreateInstance(&createInfo, NULL, &local_instance);
if (res != VK_SUCCESS) return res;
uint32_t deviceCount;
res = vkEnumeratePhysicalDevices(local_instance, &deviceCount, NULL);
if (res != VK_SUCCESS) return res;
VkPhysicalDevice* devices = (VkPhysicalDevice*)malloc(sizeof(VkPhysicalDevice) * deviceCount);
res = vkEnumeratePhysicalDevices(local_instance, &deviceCount, devices);
if (res != VK_SUCCESS) return res;
for (uint32_t i = 0; i < deviceCount; i++) {
VkPhysicalDeviceProperties device_properties;
vkGetPhysicalDeviceProperties(devices[i], &device_properties);
printf("Device id: %d name: %s API:%d.%d.%d\n", i, device_properties.deviceName, (device_properties.apiVersion >> 22), ((device_properties.apiVersion >> 12) & 0x3ff), (device_properties.apiVersion & 0xfff));
}
free(devices);
vkDestroyInstance(local_instance, NULL);
return res;
}
VkResult getComputeQueueFamilyIndex(VkGPU* vkGPU) {
//find a queue family for a selected GPU, select the first available for use
uint32_t queueFamilyCount;
vkGetPhysicalDeviceQueueFamilyProperties(vkGPU->physicalDevice, &queueFamilyCount, NULL);
VkQueueFamilyProperties* queueFamilies = (VkQueueFamilyProperties*)malloc(sizeof(VkQueueFamilyProperties) * queueFamilyCount);
vkGetPhysicalDeviceQueueFamilyProperties(vkGPU->physicalDevice, &queueFamilyCount, queueFamilies);
uint32_t i = 0;
for (; i < queueFamilyCount; i++) {
VkQueueFamilyProperties props = queueFamilies[i];
if (props.queueCount > 0 && (props.queueFlags & VK_QUEUE_COMPUTE_BIT)) {
break;
}
}
free(queueFamilies);
if (i == queueFamilyCount) {
return VK_ERROR_INITIALIZATION_FAILED;
}
vkGPU->queueFamilyIndex = i;
return VK_SUCCESS;
}
VkResult createDevice(VkGPU* vkGPU) {
//create logical device representation
VkResult res = VK_SUCCESS;
VkDeviceQueueCreateInfo queueCreateInfo = { VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO };
res = getComputeQueueFamilyIndex(vkGPU);
if (res != VK_SUCCESS) return res;
queueCreateInfo.queueFamilyIndex = vkGPU->queueFamilyIndex;
queueCreateInfo.queueCount = 1;
float queuePriorities = 1.0;
queueCreateInfo.pQueuePriorities = &queuePriorities;
VkDeviceCreateInfo deviceCreateInfo = { VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO };
VkPhysicalDeviceFeatures deviceFeatures = {};
deviceFeatures.shaderFloat64 = true;
VkPhysicalDeviceFeatures2 deviceFeatures2 = {};
VkPhysicalDeviceShaderFloat16Int8Features shaderFloat16 = {};
shaderFloat16.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_FLOAT16_INT8_FEATURES;
shaderFloat16.shaderFloat16 = true;
shaderFloat16.shaderInt8 = true;
deviceFeatures2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
deviceFeatures2.pNext = &shaderFloat16;
deviceFeatures2.features = deviceFeatures;
vkGetPhysicalDeviceFeatures2(vkGPU->physicalDevice, &deviceFeatures2);
deviceCreateInfo.pNext = &deviceFeatures2;
vkGPU->enabledDeviceExtensions.push_back("VK_KHR_16bit_storage");
vkGPU->enabledDeviceExtensions.push_back("VK_KHR_shader_float16_int8");
deviceCreateInfo.enabledExtensionCount = vkGPU->enabledDeviceExtensions.size();
deviceCreateInfo.ppEnabledExtensionNames = vkGPU->enabledDeviceExtensions.data();
deviceCreateInfo.pQueueCreateInfos = &queueCreateInfo;
deviceCreateInfo.queueCreateInfoCount = 1;
deviceCreateInfo.pEnabledFeatures = NULL;
res = vkCreateDevice(vkGPU->physicalDevice, &deviceCreateInfo, NULL, &vkGPU->device);
if (res != VK_SUCCESS) return res;
vkGetDeviceQueue(vkGPU->device, vkGPU->queueFamilyIndex, 0, &vkGPU->queue);
return res;
}
VkResult createFence(VkGPU* vkGPU) {
//create fence for synchronization
VkResult res = VK_SUCCESS;
VkFenceCreateInfo fenceCreateInfo = { VK_STRUCTURE_TYPE_FENCE_CREATE_INFO };
fenceCreateInfo.flags = 0;
res = vkCreateFence(vkGPU->device, &fenceCreateInfo, NULL, &vkGPU->fence);
return res;
}
VkResult createCommandPool(VkGPU* vkGPU) {
//create a place, command buffer memory is allocated from
VkResult res = VK_SUCCESS;
VkCommandPoolCreateInfo commandPoolCreateInfo = { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO };
commandPoolCreateInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
commandPoolCreateInfo.queueFamilyIndex = vkGPU->queueFamilyIndex;
res = vkCreateCommandPool(vkGPU->device, &commandPoolCreateInfo, NULL, &vkGPU->commandPool);
return res;
}
VkResult findMemoryType(VkGPU* vkGPU, uint32_t memoryTypeBits, uint32_t memorySize, VkMemoryPropertyFlags properties, uint32_t* memoryTypeIndex) {
VkPhysicalDeviceMemoryProperties memoryProperties = { 0 };
vkGetPhysicalDeviceMemoryProperties(vkGPU->physicalDevice, &memoryProperties);
for (uint32_t i = 0; i < memoryProperties.memoryTypeCount; ++i) {
if ((memoryTypeBits & (1 << i)) && ((memoryProperties.memoryTypes[i].propertyFlags & properties) == properties) && (memoryProperties.memoryHeaps[memoryProperties.memoryTypes[i].heapIndex].size >= memorySize))
{
memoryTypeIndex[0] = i;
return VK_SUCCESS;
}
}
return VK_ERROR_OUT_OF_DEVICE_MEMORY;
}
VkResult allocateFFTBuffer(VkGPU* vkGPU, VkBuffer* buffer, VkDeviceMemory* deviceMemory, VkBufferUsageFlags usageFlags, VkMemoryPropertyFlags propertyFlags, VkDeviceSize size) {
//allocate the buffer used by the GPU with specified properties
VkResult res = VK_SUCCESS;
uint32_t queueFamilyIndices;
VkBufferCreateInfo bufferCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
bufferCreateInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
bufferCreateInfo.queueFamilyIndexCount = 1;
bufferCreateInfo.pQueueFamilyIndices = &queueFamilyIndices;
bufferCreateInfo.size = size;
bufferCreateInfo.usage = usageFlags;
res = vkCreateBuffer(vkGPU->device, &bufferCreateInfo, NULL, buffer);
if (res != VK_SUCCESS) return res;
VkMemoryRequirements memoryRequirements = { 0 };
vkGetBufferMemoryRequirements(vkGPU->device, buffer[0], &memoryRequirements);
VkMemoryAllocateInfo memoryAllocateInfo = { VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO };
memoryAllocateInfo.allocationSize = memoryRequirements.size;
res = findMemoryType(vkGPU, memoryRequirements.memoryTypeBits, memoryRequirements.size, propertyFlags, &memoryAllocateInfo.memoryTypeIndex);
if (res != VK_SUCCESS) return res;
res = vkAllocateMemory(vkGPU->device, &memoryAllocateInfo, NULL, deviceMemory);
if (res != VK_SUCCESS) return res;
res = vkBindBufferMemory(vkGPU->device, buffer[0], deviceMemory[0], 0);
if (res != VK_SUCCESS) return res;
return res;
}
VkResult transferDataFromCPU(VkGPU* vkGPU, void* arr, VkBuffer* buffer, VkDeviceSize bufferSize) {
//a function that transfers data from the CPU to the GPU using staging buffer, because the GPU memory is not host-coherent
VkResult res = VK_SUCCESS;
VkDeviceSize stagingBufferSize = bufferSize;
VkBuffer stagingBuffer = { 0 };
VkDeviceMemory stagingBufferMemory = { 0 };
res = allocateFFTBuffer(vkGPU, &stagingBuffer, &stagingBufferMemory, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, stagingBufferSize);
if (res != VK_SUCCESS) return res;
void* data;
res = vkMapMemory(vkGPU->device, stagingBufferMemory, 0, stagingBufferSize, 0, &data);
if (res != VK_SUCCESS) return res;
memcpy(data, arr, stagingBufferSize);
vkUnmapMemory(vkGPU->device, stagingBufferMemory);
VkCommandBufferAllocateInfo commandBufferAllocateInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO };
commandBufferAllocateInfo.commandPool = vkGPU->commandPool;
commandBufferAllocateInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
commandBufferAllocateInfo.commandBufferCount = 1;
VkCommandBuffer commandBuffer = { 0 };
res = vkAllocateCommandBuffers(vkGPU->device, &commandBufferAllocateInfo, &commandBuffer);
if (res != VK_SUCCESS) return res;
VkCommandBufferBeginInfo commandBufferBeginInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO };
commandBufferBeginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
res = vkBeginCommandBuffer(commandBuffer, &commandBufferBeginInfo);
if (res != VK_SUCCESS) return res;
VkBufferCopy copyRegion = { 0 };
copyRegion.srcOffset = 0;
copyRegion.dstOffset = 0;
copyRegion.size = stagingBufferSize;
vkCmdCopyBuffer(commandBuffer, stagingBuffer, buffer[0], 1, ©Region);
res = vkEndCommandBuffer(commandBuffer);
if (res != VK_SUCCESS) return res;
VkSubmitInfo submitInfo = { VK_STRUCTURE_TYPE_SUBMIT_INFO };
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &commandBuffer;
res = vkQueueSubmit(vkGPU->queue, 1, &submitInfo, vkGPU->fence);
if (res != VK_SUCCESS) return res;
res = vkWaitForFences(vkGPU->device, 1, &vkGPU->fence, VK_TRUE, 100000000000);
if (res != VK_SUCCESS) return res;
res = vkResetFences(vkGPU->device, 1, &vkGPU->fence);
if (res != VK_SUCCESS) return res;
vkFreeCommandBuffers(vkGPU->device, vkGPU->commandPool, 1, &commandBuffer);
vkDestroyBuffer(vkGPU->device, stagingBuffer, NULL);
vkFreeMemory(vkGPU->device, stagingBufferMemory, NULL);
return res;
}
VkResult transferDataToCPU(VkGPU* vkGPU, void* arr, VkBuffer* buffer, VkDeviceSize bufferSize) {
//a function that transfers data from the GPU to the CPU using staging buffer, because the GPU memory is not host-coherent
VkResult res = VK_SUCCESS;
VkDeviceSize stagingBufferSize = bufferSize;
VkBuffer stagingBuffer = { 0 };
VkDeviceMemory stagingBufferMemory = { 0 };
res = allocateFFTBuffer(vkGPU, &stagingBuffer, &stagingBufferMemory, VK_BUFFER_USAGE_TRANSFER_DST_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, stagingBufferSize);
if (res != VK_SUCCESS) return res;
VkCommandBufferAllocateInfo commandBufferAllocateInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO };
commandBufferAllocateInfo.commandPool = vkGPU->commandPool;
commandBufferAllocateInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
commandBufferAllocateInfo.commandBufferCount = 1;
VkCommandBuffer commandBuffer = { 0 };
res = vkAllocateCommandBuffers(vkGPU->device, &commandBufferAllocateInfo, &commandBuffer);
if (res != VK_SUCCESS) return res;
VkCommandBufferBeginInfo commandBufferBeginInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO };
commandBufferBeginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
res = vkBeginCommandBuffer(commandBuffer, &commandBufferBeginInfo);
if (res != VK_SUCCESS) return res;
VkBufferCopy copyRegion = { 0 };
copyRegion.srcOffset = 0;
copyRegion.dstOffset = 0;
copyRegion.size = stagingBufferSize;
vkCmdCopyBuffer(commandBuffer, buffer[0], stagingBuffer, 1, ©Region);
vkEndCommandBuffer(commandBuffer);
VkSubmitInfo submitInfo = { VK_STRUCTURE_TYPE_SUBMIT_INFO };
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &commandBuffer;
res = vkQueueSubmit(vkGPU->queue, 1, &submitInfo, vkGPU->fence);
if (res != VK_SUCCESS) return res;
res = vkWaitForFences(vkGPU->device, 1, &vkGPU->fence, VK_TRUE, 100000000000);
if (res != VK_SUCCESS) return res;
res = vkResetFences(vkGPU->device, 1, &vkGPU->fence);
if (res != VK_SUCCESS) return res;
vkFreeCommandBuffers(vkGPU->device, vkGPU->commandPool, 1, &commandBuffer);
void* data;
res = vkMapMemory(vkGPU->device, stagingBufferMemory, 0, stagingBufferSize, 0, &data);
if (res != VK_SUCCESS) return res;
memcpy(arr, data, stagingBufferSize);
vkUnmapMemory(vkGPU->device, stagingBufferMemory);
vkDestroyBuffer(vkGPU->device, stagingBuffer, NULL);
vkFreeMemory(vkGPU->device, stagingBufferMemory, NULL);
return res;
}
static inline void shaderGenShift(VkShiftApplication* app) {
sprintf(app->code0, "#version 450\n");
if (app->precision == 2) {
sprintf(app->code0 + strlen(app->code0), "#extension GL_EXT_shader_16bit_storage : require\n");
}
sprintf(app->code0 + strlen(app->code0), "layout (local_size_x = %d, local_size_y = %d, local_size_z = %d) in;\n", app->localSize[0], app->localSize[1], app->localSize[2]);
char vecType[10];
switch (app->precision) {
case 0: {
sprintf(vecType, "vec2");
break;
}
case 1: {
sprintf(vecType, "dvec2");
break;
}
case 2: {
sprintf(vecType, "f16vec2");
break;
}
}
sprintf(app->code0 + strlen(app->code0), "\
layout(std430, binding = 0) buffer Input\n\
{\n\
%s inputs[];\n\
};\n\
layout(std430, binding = 1) buffer Output\n\
{\n\
%s outputs[];\n\
};\n", vecType, vecType);
sprintf(app->code0 + strlen(app->code0), "\
uint index(uint index_x, uint index_y) {\n\
return index_x + index_y * %d + gl_GlobalInvocationID.z * %d;\n\
}\n", app->inputStride[0], app->inputStride[2]);
sprintf(app->code0 + strlen(app->code0), "\
void main()\n\
{\n");
if (app->r2c)
{
sprintf(app->code0 + strlen(app->code0), "\
if (gl_GlobalInvocationID.x + gl_GlobalInvocationID.y*%d < %d){\n\
outputs[index(%d - (gl_GlobalInvocationID.x + gl_GlobalInvocationID.y*%d), %d)] = inputs[index(%d - (gl_GlobalInvocationID.x + gl_GlobalInvocationID.y*%d), %d)];\n\
}\n\
if ((gl_GlobalInvocationID.y < %d)&&(gl_GlobalInvocationID.x < %d)) {; \n", app->size[0], app->size[1] / 2, app->inputStride[1] - 1, app->size[0], app->inputStride[1], app->size[1] - 1, app->size[0], app->inputStride[1], app->size[1] / 2, app->size[0]);
sprintf(app->code0 + strlen(app->code0), "\
uint id = index(gl_GlobalInvocationID.x, %d - gl_GlobalInvocationID.y);\n\
uint id_out = index(gl_GlobalInvocationID.x, %d - gl_GlobalInvocationID.y);\n\
outputs[id_out] = inputs[id];\n\
}}", app->size[1] - 1, app->inputStride[1] - 1);
}
else {
sprintf(app->code0 + strlen(app->code0), "\
if (((gl_GlobalInvocationID.x >= %d) || (gl_GlobalInvocationID.y >= %d)) && (gl_GlobalInvocationID.x < %d) && (gl_GlobalInvocationID.y < %d)){;\n\
uint id;\n\
uint id_out;\n", app->size[0] / 2, app->size[1] / 2, app->size[0], app->size[1]);
sprintf(app->code0 + strlen(app->code0), "\
if ((gl_GlobalInvocationID.x >= %d) && (gl_GlobalInvocationID.y < %d)){\n\
id = index(%d - gl_GlobalInvocationID.x, gl_GlobalInvocationID.y);\n\
id_out = index(%d - gl_GlobalInvocationID.x, gl_GlobalInvocationID.y);}\n", app->size[0] / 2, app->size[1] / 2, 3 * app->size[0] / 2 - 1, app->inputStride[0] + app->size[0] / 2 - 1);
sprintf(app->code0 + strlen(app->code0), "\
if ((gl_GlobalInvocationID.x >= %d) && (gl_GlobalInvocationID.y >= %d)){\n\
id = index(%d - gl_GlobalInvocationID.x, %d - gl_GlobalInvocationID.y);\n\
id_out = index( %d - gl_GlobalInvocationID.x, %d - gl_GlobalInvocationID.y);}\n", app->size[0] / 2, app->size[1] / 2, 3 * app->size[0] / 2 - 1, 3 * app->size[1] / 2 - 1, app->inputStride[0] + app->size[0] / 2 - 1, app->inputStride[1] + app->size[1] / 2 - 1);
sprintf(app->code0 + strlen(app->code0), "\
if ((gl_GlobalInvocationID.x < %d) && (gl_GlobalInvocationID.y >= %d)){\n\
id = index(gl_GlobalInvocationID.x, %d - gl_GlobalInvocationID.y);\n\
id_out = index(gl_GlobalInvocationID.x, %d - gl_GlobalInvocationID.y);}\n\
outputs[id_out] = inputs[id];\n\
}}", app->size[0] / 2, app->size[1] / 2, 3 * app->size[1] / 2 - 1, app->inputStride[1] + app->size[1] / 2 - 1);
}
//printf("%s\n", app->code0);
}
VkResult createShiftApp(VkGPU* vkGPU, VkShiftApplication* app) {
//create an application interface to Vulkan. This function binds the shader to the compute pipeline, so it can be used as a part of the command buffer later
VkResult res = VK_SUCCESS;
//we have two storage buffer objects in one set in one pool
VkDescriptorPoolSize descriptorPoolSize = { VK_DESCRIPTOR_TYPE_STORAGE_BUFFER };
descriptorPoolSize.descriptorCount = 2;
VkDescriptorPoolCreateInfo descriptorPoolCreateInfo = { VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO };
descriptorPoolCreateInfo.poolSizeCount = 1;
descriptorPoolCreateInfo.pPoolSizes = &descriptorPoolSize;
descriptorPoolCreateInfo.maxSets = 1;
res = vkCreateDescriptorPool(vkGPU->device, &descriptorPoolCreateInfo, NULL, &app->descriptorPool);
if (res != VK_SUCCESS) return res;
//specify each object from the set as a storage buffer
const VkDescriptorType descriptorType[2] = { VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER };
VkDescriptorSetLayoutBinding* descriptorSetLayoutBindings = (VkDescriptorSetLayoutBinding*)malloc(descriptorPoolSize.descriptorCount * sizeof(VkDescriptorSetLayoutBinding));
for (uint32_t i = 0; i < descriptorPoolSize.descriptorCount; ++i) {
descriptorSetLayoutBindings[i].binding = i;
descriptorSetLayoutBindings[i].descriptorType = descriptorType[i];
descriptorSetLayoutBindings[i].descriptorCount = 1;
descriptorSetLayoutBindings[i].stageFlags = VK_SHADER_STAGE_COMPUTE_BIT;
}
VkDescriptorSetLayoutCreateInfo descriptorSetLayoutCreateInfo = { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO };
descriptorSetLayoutCreateInfo.bindingCount = descriptorPoolSize.descriptorCount;
descriptorSetLayoutCreateInfo.pBindings = descriptorSetLayoutBindings;
//create layout
res = vkCreateDescriptorSetLayout(vkGPU->device, &descriptorSetLayoutCreateInfo, NULL, &app->descriptorSetLayout);
if (res != VK_SUCCESS) return res;
free(descriptorSetLayoutBindings);
//provide the layout with actual buffers and their sizes
VkDescriptorSetAllocateInfo descriptorSetAllocateInfo = { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO };
descriptorSetAllocateInfo.descriptorPool = app->descriptorPool;
descriptorSetAllocateInfo.descriptorSetCount = 1;
descriptorSetAllocateInfo.pSetLayouts = &app->descriptorSetLayout;
res = vkAllocateDescriptorSets(vkGPU->device, &descriptorSetAllocateInfo, &app->descriptorSet);
if (res != VK_SUCCESS) return res;
for (uint32_t i = 0; i < descriptorPoolSize.descriptorCount; ++i) {
VkDescriptorBufferInfo descriptorBufferInfo = { 0 };
if (i == 0) {
descriptorBufferInfo.buffer = app->inputBuffer[0];
descriptorBufferInfo.range = app->inputBufferSize;
descriptorBufferInfo.offset = 0;
}
if (i == 1) {
descriptorBufferInfo.buffer = app->outputBuffer[0];
descriptorBufferInfo.range = app->outputBufferSize;
descriptorBufferInfo.offset = 0;
}
VkWriteDescriptorSet writeDescriptorSet = { VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET };
writeDescriptorSet.dstSet = app->descriptorSet;
writeDescriptorSet.dstBinding = i;
writeDescriptorSet.dstArrayElement = 0;
writeDescriptorSet.descriptorType = descriptorType[i];
writeDescriptorSet.descriptorCount = 1;
writeDescriptorSet.pBufferInfo = &descriptorBufferInfo;
vkUpdateDescriptorSets(vkGPU->device, 1, &writeDescriptorSet, 0, NULL);
}
VkPipelineLayoutCreateInfo pipelineLayoutCreateInfo = { VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO };
pipelineLayoutCreateInfo.setLayoutCount = 1;
pipelineLayoutCreateInfo.pSetLayouts = &app->descriptorSetLayout;
//create pipeline layout
res = vkCreatePipelineLayout(vkGPU->device, &pipelineLayoutCreateInfo, NULL, &app->pipelineLayout);
if (res != VK_SUCCESS) return res;
VkPipelineShaderStageCreateInfo pipelineShaderStageCreateInfo = { VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO };
VkComputePipelineCreateInfo computePipelineCreateInfo = { VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO };
//specify specialization constants - structure that sets constants in the shader after first compilation (done by glslangvalidator, for example) but before final shader module creation
//first three values - workgroup dimensions
pipelineShaderStageCreateInfo.stage = VK_SHADER_STAGE_COMPUTE_BIT;
//create a shader module from the byte code
uint32_t filelength;
app->code0 = (char*)malloc(sizeof(char) * 100000);
shaderGenShift(app);
//printf("%s\n", app->code0);
const glslang_resource_t default_resource = {
/* .MaxLights = */ 32,
/* .MaxClipPlanes = */ 6,
/* .MaxTextureUnits = */ 32,
/* .MaxTextureCoords = */ 32,
/* .MaxVertexAttribs = */ 64,
/* .MaxVertexUniformComponents = */ 4096,
/* .MaxVaryingFloats = */ 64,
/* .MaxVertexTextureImageUnits = */ 32,
/* .MaxCombinedTextureImageUnits = */ 80,
/* .MaxTextureImageUnits = */ 32,
/* .MaxFragmentUniformComponents = */ 4096,
/* .MaxDrawBuffers = */ 32,
/* .MaxVertexUniformVectors = */ 128,
/* .MaxVaryingVectors = */ 8,
/* .MaxFragmentUniformVectors = */ 16,
/* .MaxVertexOutputVectors = */ 16,
/* .MaxFragmentInputVectors = */ 15,
/* .MinProgramTexelOffset = */ -8,
/* .MaxProgramTexelOffset = */ 7,
/* .MaxClipDistances = */ 8,
/* .MaxComputeWorkGroupCountX = */ 65535,
/* .MaxComputeWorkGroupCountY = */ 65535,
/* .MaxComputeWorkGroupCountZ = */ 65535,
/* .MaxComputeWorkGroupSizeX = */ 1024,
/* .MaxComputeWorkGroupSizeY = */ 1024,
/* .MaxComputeWorkGroupSizeZ = */ 64,
/* .MaxComputeUniformComponents = */ 1024,
/* .MaxComputeTextureImageUnits = */ 16,
/* .MaxComputeImageUniforms = */ 8,
/* .MaxComputeAtomicCounters = */ 8,
/* .MaxComputeAtomicCounterBuffers = */ 1,
/* .MaxVaryingComponents = */ 60,
/* .MaxVertexOutputComponents = */ 64,
/* .MaxGeometryInputComponents = */ 64,
/* .MaxGeometryOutputComponents = */ 128,
/* .MaxFragmentInputComponents = */ 128,
/* .MaxImageUnits = */ 8,
/* .MaxCombinedImageUnitsAndFragmentOutputs = */ 8,
/* .MaxCombinedShaderOutputResources = */ 8,
/* .MaxImageSamples = */ 0,
/* .MaxVertexImageUniforms = */ 0,
/* .MaxTessControlImageUniforms = */ 0,
/* .MaxTessEvaluationImageUniforms = */ 0,
/* .MaxGeometryImageUniforms = */ 0,
/* .MaxFragmentImageUniforms = */ 8,
/* .MaxCombinedImageUniforms = */ 8,
/* .MaxGeometryTextureImageUnits = */ 16,
/* .MaxGeometryOutputVertices = */ 256,
/* .MaxGeometryTotalOutputComponents = */ 1024,
/* .MaxGeometryUniformComponents = */ 1024,
/* .MaxGeometryVaryingComponents = */ 64,
/* .MaxTessControlInputComponents = */ 128,
/* .MaxTessControlOutputComponents = */ 128,
/* .MaxTessControlTextureImageUnits = */ 16,
/* .MaxTessControlUniformComponents = */ 1024,
/* .MaxTessControlTotalOutputComponents = */ 4096,
/* .MaxTessEvaluationInputComponents = */ 128,
/* .MaxTessEvaluationOutputComponents = */ 128,
/* .MaxTessEvaluationTextureImageUnits = */ 16,
/* .MaxTessEvaluationUniformComponents = */ 1024,
/* .MaxTessPatchComponents = */ 120,
/* .MaxPatchVertices = */ 32,
/* .MaxTessGenLevel = */ 64,
/* .MaxViewports = */ 16,
/* .MaxVertexAtomicCounters = */ 0,
/* .MaxTessControlAtomicCounters = */ 0,
/* .MaxTessEvaluationAtomicCounters = */ 0,
/* .MaxGeometryAtomicCounters = */ 0,
/* .MaxFragmentAtomicCounters = */ 8,
/* .MaxCombinedAtomicCounters = */ 8,
/* .MaxAtomicCounterBindings = */ 1,
/* .MaxVertexAtomicCounterBuffers = */ 0,
/* .MaxTessControlAtomicCounterBuffers = */ 0,
/* .MaxTessEvaluationAtomicCounterBuffers = */ 0,
/* .MaxGeometryAtomicCounterBuffers = */ 0,
/* .MaxFragmentAtomicCounterBuffers = */ 1,
/* .MaxCombinedAtomicCounterBuffers = */ 1,
/* .MaxAtomicCounterBufferSize = */ 16384,
/* .MaxTransformFeedbackBuffers = */ 4,
/* .MaxTransformFeedbackInterleavedComponents = */ 64,
/* .MaxCullDistances = */ 8,
/* .MaxCombinedClipAndCullDistances = */ 8,
/* .MaxSamples = */ 4,
/* .maxMeshOutputVerticesNV = */ 256,
/* .maxMeshOutputPrimitivesNV = */ 512,
/* .maxMeshWorkGroupSizeX_NV = */ 32,
/* .maxMeshWorkGroupSizeY_NV = */ 1,
/* .maxMeshWorkGroupSizeZ_NV = */ 1,
/* .maxTaskWorkGroupSizeX_NV = */ 32,
/* .maxTaskWorkGroupSizeY_NV = */ 1,
/* .maxTaskWorkGroupSizeZ_NV = */ 1,
/* .maxMeshViewCountNV = */ 4,
/* .maxDualSourceDrawBuffersEXT = */ 1,
/* .limits = */ {
/* .nonInductiveForLoops = */ 1,
/* .whileLoops = */ 1,
/* .doWhileLoops = */ 1,
/* .generalUniformIndexing = */ 1,
/* .generalAttributeMatrixVectorIndexing = */ 1,
/* .generalVaryingIndexing = */ 1,
/* .generalSamplerIndexing = */ 1,
/* .generalVariableIndexing = */ 1,
/* .generalConstantMatrixVectorIndexing = */ 1,
} };
glslang_target_client_version_t client_version = (app->precision == 2) ? GLSLANG_TARGET_VULKAN_1_1 : GLSLANG_TARGET_VULKAN_1_0;
glslang_target_language_version_t target_language_version = (app->precision == 2) ? GLSLANG_TARGET_SPV_1_3 : GLSLANG_TARGET_SPV_1_0;
const glslang_input_t input =
{
GLSLANG_SOURCE_GLSL,
GLSLANG_STAGE_COMPUTE,
GLSLANG_CLIENT_VULKAN,
client_version,
GLSLANG_TARGET_SPV,
target_language_version,
app->code0,
450,
GLSLANG_NO_PROFILE,
1,
0,
GLSLANG_MSG_DEFAULT_BIT,
&default_resource,
};
glslang_shader_t* shader = glslang_shader_create(&input);
const char* err;
if (!glslang_shader_preprocess(shader, &input))
{
err = glslang_shader_get_info_log(shader);
printf("%s\n", app->code0);
printf("%s\n", err);
glslang_shader_delete(shader);
free(app->code0);
return VK_ERROR_INITIALIZATION_FAILED;
}
if (!glslang_shader_parse(shader, &input))
{
err = glslang_shader_get_info_log(shader);
printf("%s\n", app->code0);
printf("%s\n", err);
glslang_shader_delete(shader);
free(app->code0);
return VK_ERROR_INITIALIZATION_FAILED;
}
glslang_program_t* program = glslang_program_create();
glslang_program_add_shader(program, shader);
if (!glslang_program_link(program, GLSLANG_MSG_SPV_RULES_BIT | GLSLANG_MSG_VULKAN_RULES_BIT))
{
err = glslang_program_get_info_log(program);
printf("%s\n", app->code0);
printf("%s\n", err);
glslang_shader_delete(shader);
free(app->code0);
return VK_ERROR_INITIALIZATION_FAILED;
}
glslang_program_SPIRV_generate(program, input.stage);
if (glslang_program_SPIRV_get_messages(program))
{
printf("%s", glslang_program_SPIRV_get_messages(program));
}
glslang_shader_delete(shader);
free(app->code0);
VkShaderModuleCreateInfo createInfo = { VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO };
createInfo.pCode = glslang_program_SPIRV_get_ptr(program);
createInfo.codeSize = glslang_program_SPIRV_get_size(program) * sizeof(uint32_t);
vkCreateShaderModule(vkGPU->device, &createInfo, NULL, &pipelineShaderStageCreateInfo.module);
pipelineShaderStageCreateInfo.pName = "main";
pipelineShaderStageCreateInfo.pSpecializationInfo = 0;// &specializationInfo;
computePipelineCreateInfo.stage = pipelineShaderStageCreateInfo;
computePipelineCreateInfo.layout = app->pipelineLayout;
vkCreateComputePipelines(vkGPU->device, VK_NULL_HANDLE, 1, &computePipelineCreateInfo, NULL, &app->pipeline);
vkDestroyShaderModule(vkGPU->device, pipelineShaderStageCreateInfo.module, NULL);
glslang_program_delete(program);
return res;
}
static inline void shaderGenSharpen(VkShiftApplication* app) {
//FidelityFX-CAS sharpener implementation
sprintf(app->code0, "#version 450\n");
char endingNum[10] = "";
if (app->precision == 2) {
sprintf(app->code0 + strlen(app->code0), "#extension GL_EXT_shader_16bit_storage : require\n\
#extension GL_EXT_shader_explicit_arithmetic_types_float16 : require\n");
sprintf(endingNum, "HF");
}
sprintf(app->code0 + strlen(app->code0), "layout (local_size_x = %d, local_size_y = %d, local_size_z = %d) in;\n", app->localSize[0], app->localSize[1], app->localSize[2]);
char vecType[10];
char floatType[10];
switch (app->precision) {
case 0: {
sprintf(vecType, "vec2");
sprintf(floatType, "float");
break;
}
case 1: {
sprintf(vecType, "dvec2");
sprintf(floatType, "double");
break;
}
case 2: {
sprintf(vecType, "f16vec2");
sprintf(floatType, "float16_t");
break;
}
}
if (app->r2c)
sprintf(app->code0 + strlen(app->code0), "\
layout(std430, binding = 0) buffer Input\n\
{\n\
%s inputs[];\n\
};\n\
layout(std430, binding = 1) buffer Output\n\
{\n\
%s outputs[];\n\
};\n", floatType, floatType);
else
sprintf(app->code0 + strlen(app->code0), "\
layout(std430, binding = 0) buffer Input\n\
{\n\
%s inputs[];\n\
};\n\
layout(std430, binding = 1) buffer Output\n\
{\n\
%s outputs[];\n\
};\n", vecType, floatType);
sprintf(app->code0 + strlen(app->code0), "\
uint index(uint index_x, uint index_y) {\n\
return index_x + index_y * %d + gl_GlobalInvocationID.z * %d;\n\
}\n", app->inputStride[0], app->inputStride[2]);
sprintf(app->code0 + strlen(app->code0), "\
uint index_out(uint index_x, uint index_y) {\n\
return index_x + index_y * %d + gl_GlobalInvocationID.z * %d;\n\
}\n", app->outputStride[0], app->outputStride[2]);
sprintf(app->code0 + strlen(app->code0), "\
void main()\n\
{\n\
if((gl_GlobalInvocationID.x<%d)&&(gl_GlobalInvocationID.y<%d)){", app->size[0], app->size[1]);
if (app->r2c)
sprintf(app->code0 + strlen(app->code0), "\
%s tex[9];\n", floatType);
else
sprintf(app->code0 + strlen(app->code0), "\
%s tex[9];\n", vecType);
sprintf(app->code0 + strlen(app->code0), "\
%s len[9];\n\
uint id_x_m=(gl_GlobalInvocationID.x>0) ? gl_GlobalInvocationID.x-1 : gl_GlobalInvocationID.x;\n\
uint id_y_m=(gl_GlobalInvocationID.y>0) ? gl_GlobalInvocationID.y-1 : gl_GlobalInvocationID.y;\n\
uint id_x_p=(gl_GlobalInvocationID.x<%d) ? gl_GlobalInvocationID.x+1 : gl_GlobalInvocationID.x;\n\
uint id_y_p=(gl_GlobalInvocationID.y<%d) ? gl_GlobalInvocationID.y+1 : gl_GlobalInvocationID.y;\n\
tex[0]= %f%s*inputs[index(id_x_m, id_y_m)];\n\
tex[1]= %f%s*inputs[index(gl_GlobalInvocationID.x, id_y_m)];\n\
tex[2]= %f%s*inputs[index(id_x_p, id_y_m)];\n\
tex[3]= %f%s*inputs[index(id_x_m, gl_GlobalInvocationID.y)];\n\
tex[4]= %f%s*inputs[index(gl_GlobalInvocationID.x, gl_GlobalInvocationID.y)];\n\
tex[5]= %f%s*inputs[index(id_x_p, gl_GlobalInvocationID.y)];\n\
tex[6]= %f%s*inputs[index(id_x_m, id_y_p)];\n\
tex[7]= %f%s*inputs[index(gl_GlobalInvocationID.x, id_y_p)];\n\
tex[8]= %f%s*inputs[index(id_x_p, id_y_p)];\n", floatType, app->size[0], app->size[1], app->upscale, endingNum, app->upscale, endingNum, app->upscale, endingNum, app->upscale, endingNum, app->upscale, endingNum, app->upscale, endingNum, app->upscale, endingNum, app->upscale, endingNum, app->upscale, endingNum);
sprintf(app->code0 + strlen(app->code0), "\
for(uint i=0;i<9;i++){\n\
len[i]=length(tex[i]);\n\
if(len[i]>1.0%s) len[i]=1.0%s;\n\
if(len[i]<0.0%s) len[i]=0.0%s;\n\
}\n", endingNum, endingNum, endingNum, endingNum);
sprintf(app->code0 + strlen(app->code0), "\
%s minL[2];\n\
minL[0]= min(len[1], min(len[3], min(len[4], min(len[5],len[7]))));\n\
minL[1]= min(minL[0], min(len[0], min(len[2], min(len[6], len[8]))));\n\
%s maxL[2];\n\
maxL[0]= max(len[1], max(len[3], max(len[4], max(len[5],len[7]))));\n\
maxL[1]= max(maxL[0], max(len[0], max(len[2], max(len[6], len[8]))));\n\
%s minlen=0.5%s*(minL[0]+minL[1]);\n\
%s maxlen=0.5%s*(maxL[0]+maxL[1]);\n\
minlen=minlen/(1.0%s-minlen);\n\
maxlen=(1.0%s-maxlen)/maxlen;\n\
%s scale = (minlen<maxlen) ? minlen : maxlen;\n\
scale=-%f%s*sqrt(scale);\n", floatType, floatType, floatType, endingNum, floatType, endingNum, endingNum, endingNum, floatType, app->sharpenCoeff, endingNum);
sprintf(app->code0 + strlen(app->code0), "\
outputs[index_out(gl_GlobalInvocationID.x, gl_GlobalInvocationID.y)] = (len[4]+scale*(len[1]+len[3]+len[5]+len[7]))/(1.0%s+scale*4.0%s);\n\
}}", endingNum, endingNum);
//printf("%s\n", app->code0);
}
VkResult createSharpenApp(VkGPU* vkGPU, VkShiftApplication* app) {
//create an application interface to Vulkan. This function binds the shader to the compute pipeline, so it can be used as a part of the command buffer later
VkResult res = VK_SUCCESS;
//we have two storage buffer objects in one set in one pool
VkDescriptorPoolSize descriptorPoolSize = { VK_DESCRIPTOR_TYPE_STORAGE_BUFFER };
descriptorPoolSize.descriptorCount = 2;
VkDescriptorPoolCreateInfo descriptorPoolCreateInfo = { VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO };
descriptorPoolCreateInfo.poolSizeCount = 1;
descriptorPoolCreateInfo.pPoolSizes = &descriptorPoolSize;
descriptorPoolCreateInfo.maxSets = 1;
res = vkCreateDescriptorPool(vkGPU->device, &descriptorPoolCreateInfo, NULL, &app->descriptorPool);
if (res != VK_SUCCESS) return res;
//specify each object from the set as a storage buffer
const VkDescriptorType descriptorType[2] = { VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER };
VkDescriptorSetLayoutBinding* descriptorSetLayoutBindings = (VkDescriptorSetLayoutBinding*)malloc(descriptorPoolSize.descriptorCount * sizeof(VkDescriptorSetLayoutBinding));
for (uint32_t i = 0; i < descriptorPoolSize.descriptorCount; ++i) {
descriptorSetLayoutBindings[i].binding = i;
descriptorSetLayoutBindings[i].descriptorType = descriptorType[i];
descriptorSetLayoutBindings[i].descriptorCount = 1;
descriptorSetLayoutBindings[i].stageFlags = VK_SHADER_STAGE_COMPUTE_BIT;
}
VkDescriptorSetLayoutCreateInfo descriptorSetLayoutCreateInfo = { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO };
descriptorSetLayoutCreateInfo.bindingCount = descriptorPoolSize.descriptorCount;
descriptorSetLayoutCreateInfo.pBindings = descriptorSetLayoutBindings;
//create layout
res = vkCreateDescriptorSetLayout(vkGPU->device, &descriptorSetLayoutCreateInfo, NULL, &app->descriptorSetLayout);
if (res != VK_SUCCESS) return res;
free(descriptorSetLayoutBindings);
//provide the layout with actual buffers and their sizes
VkDescriptorSetAllocateInfo descriptorSetAllocateInfo = { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO };
descriptorSetAllocateInfo.descriptorPool = app->descriptorPool;
descriptorSetAllocateInfo.descriptorSetCount = 1;
descriptorSetAllocateInfo.pSetLayouts = &app->descriptorSetLayout;
res = vkAllocateDescriptorSets(vkGPU->device, &descriptorSetAllocateInfo, &app->descriptorSet);
if (res != VK_SUCCESS) return res;
for (uint32_t i = 0; i < descriptorPoolSize.descriptorCount; ++i) {
VkDescriptorBufferInfo descriptorBufferInfo = { 0 };
if (i == 0) {
descriptorBufferInfo.buffer = app->inputBuffer[0];
descriptorBufferInfo.range = app->inputBufferSize;
descriptorBufferInfo.offset = 0;
}
if (i == 1) {
descriptorBufferInfo.buffer = app->outputBuffer[0];
descriptorBufferInfo.range = app->outputBufferSize;
descriptorBufferInfo.offset = 0;
}
VkWriteDescriptorSet writeDescriptorSet = { VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET };
writeDescriptorSet.dstSet = app->descriptorSet;
writeDescriptorSet.dstBinding = i;
writeDescriptorSet.dstArrayElement = 0;
writeDescriptorSet.descriptorType = descriptorType[i];
writeDescriptorSet.descriptorCount = 1;
writeDescriptorSet.pBufferInfo = &descriptorBufferInfo;
vkUpdateDescriptorSets(vkGPU->device, 1, &writeDescriptorSet, 0, NULL);
}
VkPipelineLayoutCreateInfo pipelineLayoutCreateInfo = { VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO };
pipelineLayoutCreateInfo.setLayoutCount = 1;
pipelineLayoutCreateInfo.pSetLayouts = &app->descriptorSetLayout;
//create pipeline layout
res = vkCreatePipelineLayout(vkGPU->device, &pipelineLayoutCreateInfo, NULL, &app->pipelineLayout);
if (res != VK_SUCCESS) return res;
VkPipelineShaderStageCreateInfo pipelineShaderStageCreateInfo = { VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO };
VkComputePipelineCreateInfo computePipelineCreateInfo = { VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO };
//specify specialization constants - structure that sets constants in the shader after first compilation (done by glslangvalidator, for example) but before final shader module creation
//first three values - workgroup dimensions