-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsample.save.cpp
More file actions
3818 lines (3066 loc) · 111 KB
/
Copy pathsample.save.cpp
File metadata and controls
3818 lines (3066 loc) · 111 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ****************************************************************************************************
// This is a program for teaching Vulkan
// As such, it is deliberately verbose so that it is obvious (as possible, at least) what is being done
//
// Mike Bailey, Oregon State University
// mjb@cs.oregonstate.edu
//
// The class notes for which this program was written can be found here:
// http://cs.oregonstate.edu/~mjb/cs519v
//
// Keyboard commands:
// 'i', 'I': Toggle using the mouse for object rotation
// 'm', 'M': Toggle display mode (textures vs. colors, for now)
// 'p', 'P': Pause the animation
// 'q', 'Q', Esc: exit the program
//
// Latest update: January 9, 2018
// ****************************************************************************************************
// *********
// INCLUDES:
// *********
#ifdef _WIN32
#include <io.h>
#endif
#include <stdlib.h>
#include <stdio.h>
//#include <unistd.h>
#include <math.h>
#ifndef M_PI
#define M_PI 3.14159265f
#endif
#include <stdarg.h>
#include <string.h>
#include <string>
#include <stdbool.h>
#include <assert.h>
#include <signal.h>
#ifndef _WIN32
typedef int errno_t;
int fopen_s( FILE**, const char *, const char * );
#endif
#define GLFW_INCLUDE_VULKAN
#include "glfw3.h"
#define GLM_FORCE_RADIANS
#define GLM_FORCE_DEPTH_ZERO_TO_ONE
#include "glm/vec2.hpp"
#include "glm/vec3.hpp"
#include "glm/mat4x4.hpp"
#include "glm/gtc/matrix_transform.hpp"
#include "glm/gtc/matrix_inverse.hpp"
//#include "glm/gtc/type_ptr.hpp"
#ifdef _WIN32
#pragma comment(linker, "/subsystem:windows")
#define APP_NAME_STR_LEN 80
#endif
#include "vulkan.h"
#include "vk_sdk_platform.h"
// these are here to flag why addresses are being passed into a vulkan function --
// 1. is it because the function wants to consume the contents of that tructure or array (IN)?
// or, 2. is it because that function is going to fill that staructure or array (OUT)?
#define IN
#define OUT
#define INOUT
// ******************
// DEFINED CONSTANTS:
// ******************
// useful stuff:
#define DEBUGFILE "VulkanDebug.txt"
#define nullptr (void *)NULL
#define MILLION 1000000L
#define BILLION 1000000000L
#define TEXTURE_COUNT 1
#define APP_SHORT_NAME "cube"
#define APP_LONG_NAME "Vulkan Cube Demo Program"
#define SECONDS_PER_CYCLE 3.f
#define FRAME_LAG 2
#define SWAPCHAINIMAGECOUNT 2
// multiplication factors for input interaction:
// // (these are known from previous experience)
const float ANGFACT = { M_PI/180.f };
const float SCLFACT = { 0.005f };
// minimum allowable scale factor:
const float MINSCALE = { 0.05f };
// active mouse buttons (or them together):
const int LEFT = { 4 };
const int MIDDLE = { 2 };
const int RIGHT = { 1 };
// the allocation callbacks could look like this:
//typedef struct VkAllocationCallbacks {
//void* pUserData;
//PFN_vkAllocationFunction pfnAllocation;
//PFN_vkReallocationFunction pfnReallocation;
//PFN_vkFreeFunction pfnFree;
//PFN_vkInternalAllocationNotification pfnInternalAllocation;
//PFN_vkInternalFreeNotification pfnInternalFree;
//} VkAllocationCallbacks;
// but we are not going to use them for now:
#define PALLOCATOR (VkAllocationCallbacks *)nullptr
// report on a result return:
#define REPORT(s) { PrintVkError( result, s ); fflush(FpDebug); }
#define HERE_I_AM(s) if( Verbose ) { fprintf( FpDebug, "\n***** %s *****\n", s ); fflush(FpDebug); }
// graphics parameters:
const double FOV = glm::radians(60.); // field-of-view angle
const float EYEDIST = 3.; // eye distance
const float OMEGA = 2.*M_PI; // angular velocity, radians/sec
#define SPIRV_MAGIC 0x07230203
// if you do an od -x, the magic number looks like this:
// 0000000 0203 0723 . . .
#define NUM_QUEUES_WANTED 1
#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
// these are here for convenience and readability:
#define VK_FORMAT_VEC4 VK_FORMAT_R32G32B32A32_SFLOAT
#define VK_FORMAT_XYZW VK_FORMAT_R32G32B32A32_SFLOAT
#define VK_FORMAT_VEC3 VK_FORMAT_R32G32B32_SFLOAT
#define VK_FORMAT_STP VK_FORMAT_R32G32B32_SFLOAT
#define VK_FORMAT_XYZ VK_FORMAT_R32G32B32_SFLOAT
#define VK_FORMAT_VEC2 VK_FORMAT_R32G32_SFLOAT
#define VK_FORMAT_ST VK_FORMAT_R32G32_SFLOAT
#define VK_FORMAT_XY VK_FORMAT_R32G32_SFLOAT
#define VK_FORMAT_FLOAT VK_FORMAT_R32_SFLOAT
#define VK_FORMAT_S VK_FORMAT_R32_SFLOAT
#define VK_FORMAT_X VK_FORMAT_R32_SFLOAT
// my own error codes:
#define VK_FAILURE (VkResult)( -2000000000 )
#define VK_SHOULD_EXIT (VkResult)( -2000000001 )
#define VK_ERROR_SOMETHING_ELSE (VkResult)( -2000000002 )
// ***********************************************
// MY HELPER TYPEDEFS AND STRUCTS FOR VULKAN WORK:
// ***********************************************
typedef VkBuffer VkDataBuffer;
typedef VkDevice VkLogicalDevice;
typedef VkDeviceCreateInfo VkLogicalDeviceCreateInfo;
#define vkCreateLogicalDevice vkCreateDevice
// holds all the information about a data buffer so it can be encapsulated in one variable:
typedef struct MyBuffer
{
VkDataBuffer buffer;
VkDeviceMemory vdm;
VkDeviceSize size;
} MyBuffer;
typedef struct MyTexture
{
uint32_t width;
uint32_t height;
unsigned char * pixels;
VkImage texImage;
VkImageView texImageView;
VkSampler texSampler;
VkDeviceMemory vdm;
} MyTexture;
// bmp file headers:
struct bmfh
{
short bfType;
int bfSize;
short bfReserved1;
short bfReserved2;
int bfOffBits;
} FileHeader;
struct bmih
{
int biSize;
int biWidth;
int biHeight;
short biPlanes;
short biBitCount;
int biCompression;
int biSizeImage;
int biXPelsPerMeter;
int biYPelsPerMeter;
int biClrUsed;
int biClrImportant;
} InfoHeader;
// *****************************
// STRUCTS FOR THIS APPLICATION:
// *****************************
// uniform variable block:
struct matBuf
{
glm::mat4 uModelMatrix;
glm::mat4 uViewMatrix;
glm::mat4 uProjectionMatrix;
glm::mat3 uNormalMatrix;
};
// uniform variable block:
struct lightBuf
{
glm::vec4 uLightPos;
};
// uniform variable block:
struct miscBuf
{
float uTime;
int uMode;
};
// an array of this struct will hold all vertex information:
struct vertex
{
glm::vec3 position;
glm::vec3 normal;
glm::vec3 color;
glm::vec2 texCoord;
};
// ********************************
// VULKAN-RELATED GLOBAL VARIABLES:
// ********************************
VkCommandBuffer CommandBuffers[2]; // 2, because of double-buffering
VkCommandPool CommandPool;
VkPipeline ComputePipeline;
VkPipelineCache ComputePipelineCache;
VkPipelineLayout ComputePipelineLayout;
VkDataBuffer DataBuffer;
VkImage DepthImage;
VkImageView DepthImageView;
VkDescriptorSetLayout DescriptorSetLayouts[4];
VkDescriptorSet DescriptorSets[4];
VkDebugReportCallbackEXT ErrorCallback = VK_NULL_HANDLE;
VkEvent Event;
VkFence Fence;
VkDescriptorPool DescriptorPool;
VkFramebuffer Framebuffers[2];
VkPipeline GraphicsPipeline;
VkPipelineCache GraphicsPipelineCache;
VkPipelineLayout GraphicsPipelineLayout;
uint32_t Height;
VkInstance Instance;
VkExtensionProperties * InstanceExtensions;
VkLayerProperties * InstanceLayers;
VkLogicalDevice LogicalDevice;
GLFWwindow * MainWindow;
VkPhysicalDevice PhysicalDevice;
VkPhysicalDeviceProperties PhysicalDeviceProperties;
uint32_t PhysicalDeviceCount;
VkPhysicalDeviceFeatures PhysicalDeviceFeatures;
VkImage * PresentImages;
VkImageView * PresentImageViews; // the swap chain image views
VkQueue Queue;
VkRect2D RenderArea;
VkRenderPass RenderPass;
VkSemaphore SemaphoreImageAvailable;
VkSemaphore SemaphoreRenderFinished;
VkShaderModule ShaderModuleFragment;
VkShaderModule ShaderModuleVertex;
VkBuffer StagingBuffer;
VkDeviceMemory StagingBufferMemory;
VkSurfaceKHR Surface;
VkSwapchainKHR SwapChain;
VkCommandBuffer TextureCommandBuffer; // used for transfering texture from staging buffer to actual texture buffer
VkImage TextureImage;
VkDeviceMemory TextureImageMemory;
VkDebugReportCallbackEXT WarningCallback;
uint32_t Width;
#include "SampleVertexData.cpp"
// *************************************
// APPLICATION-RELATED GLOBAL VARIABLES:
// *************************************
int ActiveButton; // current button that is down
FILE * FpDebug; // where to send debugging messages
struct lightBuf Light; // cpu struct to hold light information
struct matBuf Matrices; // cpu struct to hold matrix information
struct miscBuf Misc; // cpu struct to hold miscellaneous information information
int Mode; // 0 = use colors, 1 = use textures, ...
MyBuffer MyLightUniformBuffer;
MyTexture MyPuppyTexture; // the cute puppy texture struct
MyBuffer MyMatrixUniformBuffer;
MyBuffer MyMiscUniformBuffer;
MyBuffer MyVertexDataBuffer;
bool NeedToExit; // true means the program should exit
int NumRenders; // how many times the render loop has been called
bool Paused; // true means don't animate
float Scale; // scaling factor
double Time;
bool Verbose; // true = write messages into a file
int Xmouse, Ymouse; // mouse values
float Xrot, Yrot; // rotation angles in degrees
bool UseMouse; // true = use mouse for interaction, false = animate
// ********************
// FUNCTION PROTOTYPES:
// ********************
VkResult DestroyAllVulkan( );
//VkBool32 ErrorCallback( VkDebugReportFlagsEXT, VkDebugReportObjectTypeEXT, uint64_t, size_t, int32_t, const char *, const char *, void * );
int FindMemoryThatIsDeviceLocal( );
int FindMemoryThatIsHostVisible( );
int FindMemoryWithTypeBits( uint32_t );
void InitGraphics( );
VkResult Init01Instance( );
VkResult Init02CreateDebugCallbacks( );
VkResult Init03PhysicalDeviceAndGetQueueFamilyProperties( );
VkResult Init04LogicalDeviceAndQueue( );
VkResult Init05DataBuffer( VkDeviceSize, VkBufferUsageFlags, OUT MyBuffer * );
VkResult Init05UniformBuffer( VkDeviceSize, OUT MyBuffer * );
VkResult Init05MyVertexDataBuffer( VkDeviceSize, OUT MyBuffer * );
VkResult Fill05DataBuffer( IN MyBuffer, IN void * );
VkResult Init06CommandPool( );
VkResult Init06CommandBuffers( );
VkResult Init07TextureSampler( OUT MyTexture * );
VkResult Init07TextureBuffer( INOUT MyTexture * );
VkResult Init07TextureBufferAndFillFromBmpFile( IN std::string, OUT MyTexture * );
VkResult Init08Swapchain( );
VkResult Init09DepthStencilImage( );
VkResult Init10RenderPasses( );
VkResult Init11Framebuffers( );
VkResult Init12SpirvShader( std::string, OUT VkShaderModule * );
VkResult Init13DescriptorSetPool( );
VkResult Init13DescriptorSetLayouts( );
VkResult Init13DescriptorSets( );
VkResult Init14GraphicsPipelineLayout( );
VkResult Init14GraphicsVertexFragmentPipeline( VkShaderModule, VkShaderModule, VkPrimitiveTopology, OUT VkPipeline * );
VkResult Init14ComputePipeline( VkShaderModule, OUT VkPipeline * );
VkResult RenderScene( );
void UpdateScene( );
//VkBool32 WarningCallback( VkDebugReportFlagsEXT, VkDebugReportObjectTypeEXT, uint64_t, size_t, int32_t, const char *, const char *, void * );
void PrintVkError( VkResult, std::string = "" );
void Reset( );
void InitGLFW( );
void GLFWErrorCallback( int, const char * );
void GLFWKeyboard( GLFWwindow *, int, int, int, int );
void GLFWMouseButton( GLFWwindow *, int, int, int );
void GLFWMouseMotion( GLFWwindow *, double, double );
double GLFWGetTime( );
int ReadInt( FILE * );
short ReadShort( FILE * );
// *************
// MAIN PROGRAM:
// *************
int
main( int argc, char * argv[ ] )
{
Width = 800;
Height = 600;
//FpDebug = stderr;
errno_t err = fopen_s( &FpDebug, DEBUGFILE, "w" );
if( err != 0 )
{
fprintf( stderr, "Cannot open debug print file '%s'\n", DEBUGFILE );
FpDebug = stderr;
}
else
{
//int old = _dup(2);
//_dup2( _fileno(FpDebug), 2 );
}
fprintf(stderr, "stderr: Width = %d ; Height = %d\n", Width, Height);
fprintf(FpDebug, "FpDebug: Width = %d ; Height = %d\n", Width, Height);
Reset( );
InitGraphics( );
// loop until the user closes the window:
while( glfwWindowShouldClose( MainWindow ) == 0 )
{
glfwPollEvents( );
Time = glfwGetTime( ); // elapsed time, in double-precision seconds
UpdateScene( );
RenderScene( );
if( NeedToExit )
break;
}
fprintf(FpDebug, "Closing the GLFW window\n");
vkQueueWaitIdle( Queue );
vkDeviceWaitIdle( LogicalDevice );
DestroyAllVulkan( );
glfwDestroyWindow( MainWindow );
glfwTerminate( );
return 0;
}
void
InitGraphics( )
{
HERE_I_AM( "InitGraphics" );
VkResult result = VK_SUCCESS;
Init01Instance( );
InitGLFW( );
Init02CreateDebugCallbacks( );
Init03PhysicalDeviceAndGetQueueFamilyProperties( );
Init04LogicalDeviceAndQueue( );
Init05UniformBuffer( sizeof(Matrices), &MyMatrixUniformBuffer );
Fill05DataBuffer( MyMatrixUniformBuffer,(void *) &Matrices );
Init05UniformBuffer( sizeof(Light), &MyLightUniformBuffer );
Fill05DataBuffer( MyLightUniformBuffer, (void *) &Light );
Init05UniformBuffer( sizeof(Misc), &MyMiscUniformBuffer );
Fill05DataBuffer( MyMiscUniformBuffer, (void *) &Misc );
Init05MyVertexDataBuffer( sizeof(VertexData), &MyVertexDataBuffer );
Fill05DataBuffer( MyVertexDataBuffer, (void *) VertexData );
Init06CommandPool();
Init06CommandBuffers();
Init07TextureSampler( &MyPuppyTexture );
Init07TextureBufferAndFillFromBmpFile("puppy.bmp", &MyPuppyTexture);
Init08Swapchain( );
Init09DepthStencilImage( );
Init10RenderPasses( );
Init11Framebuffers( );
Init12SpirvShader( "sample-vert.spv", &ShaderModuleVertex );
Init12SpirvShader( "sample-frag.spv", &ShaderModuleFragment );
Init13DescriptorSetPool( );
Init13DescriptorSetLayouts();
Init13DescriptorSets( );
Init14GraphicsVertexFragmentPipeline( ShaderModuleVertex, ShaderModuleFragment, VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, &GraphicsPipeline );
}
// **********************
// CREATING THE INSTANCE:
// **********************
VkResult
Init01Instance( )
{
HERE_I_AM( "Init01Instance" );
VkResult result = VK_SUCCESS;
VkApplicationInfo vai;
vai.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
vai.pNext = nullptr;
vai.pApplicationName = "Vulkan Sample";
vai.applicationVersion = 100;
vai.pEngineName = "";
vai.engineVersion = 1;
vai.apiVersion = VK_MAKE_VERSION(1, 0, 0);
// these are the layers and extensions we would like to have:
const char * instanceLayers[ ] =
{
////"VK_LAYER_LUNARG_api_dump",
////"VK_LAYER_LUNARG_core_validation",
//"VK_LAYER_LUNARG_image",
"VK_LAYER_LUNARG_object_tracker",
"VK_LAYER_LUNARG_parameter_validation",
//"VK_LAYER_NV_optimus"
};
const char * instanceExtensions[ ] =
{
"VK_KHR_surface",
"VK_KHR_win32_surface",
"VK_EXT_debug_report"
//"VK_KHR_swapchains"
};
// see what layers are available:
uint32_t count;
vkEnumerateInstanceLayerProperties( &count, (VkLayerProperties *)nullptr );
InstanceLayers = new VkLayerProperties[ count ];
result = vkEnumerateInstanceLayerProperties( &count, InstanceLayers );
REPORT( "vkEnumerateInstanceLayerProperties" );
if( result != VK_SUCCESS )
{
return result;
}
fprintf( FpDebug, "\n%d instance layers enumerated:\n", count );
for( unsigned int i = 0; i < count; i++ )
{
fprintf( FpDebug, "0x%08x %2d '%s' '%s'\n",
InstanceLayers[i].specVersion,
InstanceLayers[i].implementationVersion,
InstanceLayers[i].layerName,
InstanceLayers[i].description );
}
// see what extensions are available:
vkEnumerateInstanceExtensionProperties( (char *)nullptr, &count, (VkExtensionProperties *)nullptr );
InstanceExtensions = new VkExtensionProperties[ count ];
result = vkEnumerateInstanceExtensionProperties( (char *)nullptr, &count, InstanceExtensions );
REPORT( "vkEnumerateInstanceExtensionProperties" );
if( result != VK_SUCCESS )
{
return result;
}
fprintf( FpDebug, "\n%d extensions enumerated:\n", count );
for( unsigned int i = 0; i < count; i++ )
{
fprintf( FpDebug, "0x%08x '%s'\n",
InstanceExtensions[i].specVersion,
InstanceExtensions[i].extensionName );
}
// create the instance, asking for the layers and extensions:
VkInstanceCreateInfo vici;
vici.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
vici.pNext = nullptr;
vici.flags = 0;
vici.pApplicationInfo = &vai;
vici.enabledLayerCount = sizeof(instanceLayers) / sizeof(char *);
vici.ppEnabledLayerNames = instanceLayers;
vici.enabledExtensionCount = sizeof(instanceExtensions) / sizeof(char *);
vici.ppEnabledExtensionNames = instanceExtensions;
result = vkCreateInstance( IN &vici, PALLOCATOR, OUT &Instance );
REPORT( "vkCreateInstance" );
return result;
}
// ***************************
// CREATE THE DEBUG CALLBACKS:
// ***************************
VkResult
Init02CreateDebugCallbacks( )
{
HERE_I_AM( "Init02CreateDebugCallbacks" );
VkResult result = VK_SUCCESS;
PFN_vkCreateDebugReportCallbackEXT vkCreateDebugReportCallbackEXT = (PFN_vkCreateDebugReportCallbackEXT)nullptr;
*(void **) &vkCreateDebugReportCallbackEXT = vkGetInstanceProcAddr( Instance, "vkCreateDebugReportCallbackEXT" );
#ifdef NOTDEF
VkDebugReportCallbackCreateInfoEXT vdrcci;
vdrcci.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT;
vdrcci.pNext = nullptr;
vdrcci.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT;
vdrcci.pfnCallback = (PFN_vkDebugReportCallbackEXT) &DebugReportCallback;
vdrcci.pUserData = nullptr;
result = vkCreateDebugReportCallbackEXT( Instance, IN &vdrcci, PALLOCATOR, OUT &ErrorCallback );
REPORT( "vkCreateDebugReportCallbackEXT - 1" );
vdrcci.flags = VK_DEBUG_REPORT_WARNING_BIT_EXT | VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT;
result = vkCreateDebugReportCallbackEXT( Instance, IN &vdrcci, PALLOCATOR, OUT &WarningCallback );
REPORT( "vkCreateDebugReportCallbackEXT - 2" );
#endif
return result;
}
#ifdef NOTYET
PFN_vkDebugReportCallbackEXT
DebugReportCallback(VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT objectType,
uint64_t object, size_t location, int32_t messageCode,
const char * pLayerPrefix, const char * pMessage, void * pUserData)
{
}
VkBool32
ErrorCallback( VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT objectType,
uint64_t object, size_t location, int32_t messageCode,
const char * pLayerPrefix, const char * pMessage, void * pUserData )
{
fprintf( FpDebug, "ErrorCallback: ObjectType = 0x%0x ; object = %ld ; LayerPrefix = '%s' ; Message = '%s'\n", objectType, object, pLayerPrefix, pMessage );
return VK_TRUE;
}
VkBool32
WarningCallback( VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT objectType,
uint64_t object, size_t location, int32_t messageCode,
const char * pLayerPrefix, const char * pMessage, void * pUserData )
{
fprintf( FpDebug, "WarningCallback: ObjectType = 0x%0x ; object = %ld ; LayerPrefix = '%s' ; Message = '%s'\n", objectType, object, pLayerPrefix, pMessage );
return VK_TRUE;
}
#endif
// *************************************************************
// FINDING THE PHYSICAL DEVICES AND GET QUEUE FAMILY PROPERTIES:
// *************************************************************
VkResult
Init03PhysicalDeviceAndGetQueueFamilyProperties( )
{
HERE_I_AM( "Init03PhysicalDeviceAndGetQueueFamilyProperties" );
VkResult result = VK_SUCCESS;
result = vkEnumeratePhysicalDevices( Instance, OUT &PhysicalDeviceCount, (VkPhysicalDevice *)nullptr );
REPORT( "vkEnumeratePhysicalDevices - 1" );
if( result != VK_SUCCESS || PhysicalDeviceCount <= 0 )
{
fprintf( FpDebug, "Could not count the physical devices\n" );
return VK_SHOULD_EXIT;
}
fprintf(FpDebug, "\n%d physical devices found.\n", PhysicalDeviceCount);
VkPhysicalDevice * physicalDevices = new VkPhysicalDevice[ PhysicalDeviceCount ];
result = vkEnumeratePhysicalDevices( Instance, OUT &PhysicalDeviceCount, OUT physicalDevices );
REPORT( "vkEnumeratePhysicalDevices - 2" );
if( result != VK_SUCCESS )
{
fprintf( FpDebug, "Could not enumerate the %d physical devices\n", PhysicalDeviceCount );
return VK_SHOULD_EXIT;
}
int discreteSelect = -1;
int integratedSelect = -1;
for( unsigned int i = 0; i < PhysicalDeviceCount; i++ )
{
VkPhysicalDeviceProperties vpdp;
vkGetPhysicalDeviceProperties( IN physicalDevices[i], OUT &vpdp );
if( result != VK_SUCCESS )
{
fprintf( FpDebug, "Could not get the physical device properties of device %d\n", i );
return VK_SHOULD_EXIT;
}
fprintf( FpDebug, " \n\nDevice %2d:\n", i );
fprintf( FpDebug, "\tAPI version: %d\n", vpdp.apiVersion );
fprintf( FpDebug, "\tDriver version: %d\n", vpdp.apiVersion );
fprintf( FpDebug, "\tVendor ID: 0x%04x\n", vpdp.vendorID );
fprintf( FpDebug, "\tDevice ID: 0x%04x\n", vpdp.deviceID );
fprintf( FpDebug, "\tPhysical Device Type: %d =", vpdp.deviceType );
if( vpdp.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU ) fprintf( FpDebug, " (Discrete GPU)\n" );
if( vpdp.deviceType == VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU ) fprintf( FpDebug, " (Integrated GPU)\n" );
if( vpdp.deviceType == VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU ) fprintf( FpDebug, " (Virtual GPU)\n" );
if( vpdp.deviceType == VK_PHYSICAL_DEVICE_TYPE_CPU ) fprintf( FpDebug, " (CPU)\n" );
fprintf( FpDebug, "\tDevice Name: %s\n", vpdp.deviceName );
fprintf( FpDebug, "\tPipeline Cache Size: %d\n", vpdp.pipelineCacheUUID[0] );
//fprintf( FpDebug, "?", vpdp.limits );
//fprintf( FpDebug, "?", vpdp.sparseProperties );
// need some logical here to decide which physical device to select:
if( vpdp.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU )
discreteSelect = i;
if( vpdp.deviceType == VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU )
integratedSelect = i;
}
int which = -1;
if( discreteSelect >= 0 )
{
which = discreteSelect;
PhysicalDevice = physicalDevices[which];
}
else if( integratedSelect >= 0 )
{
which = integratedSelect;
PhysicalDevice = physicalDevices[which];
}
else
{
fprintf( FpDebug, "Could not select a Physical Device\n" );
return VK_SHOULD_EXIT;
}
vkGetPhysicalDeviceProperties( PhysicalDevice, OUT &PhysicalDeviceProperties );
fprintf( FpDebug, "Device #%d selected ('%s')\n", which, PhysicalDeviceProperties.deviceName );
vkGetPhysicalDeviceFeatures( IN PhysicalDevice, OUT &PhysicalDeviceFeatures );
fprintf( FpDebug, "\nPhysical Device Features:\n");
fprintf( FpDebug, "geometryShader = %2d\n", PhysicalDeviceFeatures.geometryShader);
fprintf( FpDebug, "tessellationShader = %2d\n", PhysicalDeviceFeatures.tessellationShader );
fprintf( FpDebug, "multiDrawIndirect = %2d\n", PhysicalDeviceFeatures.multiDrawIndirect );
fprintf( FpDebug, "wideLines = %2d\n", PhysicalDeviceFeatures.wideLines );
fprintf( FpDebug, "largePoints = %2d\n", PhysicalDeviceFeatures.largePoints );
fprintf( FpDebug, "multiViewport = %2d\n", PhysicalDeviceFeatures.multiViewport );
fprintf( FpDebug, "occlusionQueryPrecise = %2d\n", PhysicalDeviceFeatures.occlusionQueryPrecise );
fprintf( FpDebug, "pipelineStatisticsQuery = %2d\n", PhysicalDeviceFeatures.pipelineStatisticsQuery );
fprintf( FpDebug, "shaderFloat64 = %2d\n", PhysicalDeviceFeatures.shaderFloat64 );
fprintf( FpDebug, "shaderInt64 = %2d\n", PhysicalDeviceFeatures.shaderInt64 );
fprintf( FpDebug, "shaderInt16 = %2d\n", PhysicalDeviceFeatures.shaderInt16 );
#ifdef COMMENT
All of these VkPhysicalDeviceFeatures are VkBool32s:
robustBufferAccess;
fullDrawIndexUint32;
imageCubeArray;
independentBlend;
geometryShader;
tessellationShader;
sampleRateShading;
dualSrcBlend;
logicOp;
multiDrawIndirect;
drawIndirectFirstInstance;
depthClamp;
depthBiasClamp;
fillModeNonSolid;
depthBounds;
wideLines;
largePoints;
alphaToOne;
multiViewport;
samplerAnisotropy;
textureCompressionETC2;
textureCompressionASTC_LDR;
textureCompressionBC;
occlusionQueryPrecise;
pipelineStatisticsQuery;
vertexPipelineStoresAndAtomics;
fragmentStoresAndAtomics;
shaderTessellationAndGeometryPointSize;
shaderImageGatherExtended;
shaderStorageImageExtendedFormats;
shaderStorageImageMultisample;
shaderStorageImageReadWithoutFormat;
shaderStorageImageWriteWithoutFormat;
shaderUniformBufferArrayDynamicIndexing;
shaderSampledImageArrayDynamicIndexing;
shaderStorageBufferArrayDynamicIndexing;
shaderStorageImageArrayDynamicIndexing;
shaderClipDistance;
shaderCullDistance;
shaderFloat64;
shaderInt64;
shaderInt16;
shaderResourceResidency;
shaderResourceMinLod;
sparseBinding;
sparseResidencyBuffer;
sparseResidencyImage2D;
sparseResidencyImage3D;
sparseResidency2Samples;
sparseResidency4Samples;
sparseResidency8Samples;
sparseResidency16Samples;
sparseResidencyAliased;
variableMultisampleRate;
inheritedQueries;
#endif
VkFormatProperties vfp;
#ifdef CHOICES
VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT = 0x00000001,
VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT = 0x00000002,
VK_FORMAT_FEATURE_STORAGE_IMAGE_ATOMIC_BIT = 0x00000004,
VK_FORMAT_FEATURE_UNIFORM_TEXEL_BUFFER_BIT = 0x00000008,
VK_FORMAT_FEATURE_STORAGE_TEXEL_BUFFER_BIT = 0x00000010,
VK_FORMAT_FEATURE_STORAGE_TEXEL_BUFFER_ATOMIC_BIT = 0x00000020,
VK_FORMAT_FEATURE_VERTEX_BUFFER_BIT = 0x00000040,
VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT = 0x00000080,
VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BLEND_BIT = 0x00000100,
VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT = 0x00000200,
VK_FORMAT_FEATURE_BLIT_SRC_BIT = 0x00000400,
VK_FORMAT_FEATURE_BLIT_DST_BIT = 0x00000800,
VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT = 0x00001000,
VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_CUBIC_BIT_IMG = 0x00002000,
#endif
fprintf( FpDebug, "\nImage Formats Checked:\n" );
vkGetPhysicalDeviceFormatProperties( PhysicalDevice, IN VK_FORMAT_R32G32B32A32_SFLOAT, &vfp );
fprintf( FpDebug, "Format VK_FORMAT_R32G32B32A32_SFLOAT: 0x%08x 0x%08x 0x%08x\n",
vfp.linearTilingFeatures, vfp.optimalTilingFeatures, vfp.bufferFeatures );
vkGetPhysicalDeviceFormatProperties( PhysicalDevice, IN VK_FORMAT_R8G8B8A8_UNORM, &vfp );
fprintf( FpDebug, "Format VK_FORMAT_R8G8B8A8_UNORM: 0x%08x 0x%08x 0x%08x\n",
vfp.linearTilingFeatures, vfp.optimalTilingFeatures, vfp.bufferFeatures );
vkGetPhysicalDeviceFormatProperties( PhysicalDevice, IN VK_FORMAT_B8G8R8A8_UNORM, &vfp );
fprintf( FpDebug, "Format VK_FORMAT_B8G8R8A8_UNORM: 0x%08x 0x%08x 0x%08x\n",
vfp.linearTilingFeatures, vfp.optimalTilingFeatures, vfp.bufferFeatures );
VkPhysicalDeviceMemoryProperties vpdmp;
vkGetPhysicalDeviceMemoryProperties( PhysicalDevice, OUT &vpdmp );
fprintf( FpDebug, "\n%d Memory Types:\n", vpdmp.memoryTypeCount );
for( unsigned int i = 0; i < vpdmp.memoryTypeCount; i++ )
{
VkMemoryType vmt = vpdmp.memoryTypes[i];
fprintf( FpDebug, "Memory %2d: ", i );
if( ( vmt.propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT ) != 0 ) fprintf( FpDebug, " DeviceLocal" );
if( ( vmt.propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT ) != 0 ) fprintf( FpDebug, " HostVisible" );
if( ( vmt.propertyFlags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT ) != 0 ) fprintf( FpDebug, " HostCoherent" );
if( ( vmt.propertyFlags & VK_MEMORY_PROPERTY_HOST_CACHED_BIT ) != 0 ) fprintf( FpDebug, " HostCached" );
if( ( vmt.propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT ) != 0 ) fprintf( FpDebug, " LazilyAllocated" );
fprintf(FpDebug, "\n");
}
fprintf( FpDebug, "\n%d Memory Heaps:\n", vpdmp.memoryHeapCount );
for( unsigned int i = 0; i < vpdmp.memoryHeapCount; i++ )
{
fprintf(FpDebug, "Heap %d: ", i);
VkMemoryHeap vmh = vpdmp.memoryHeaps[i];
fprintf( FpDebug, " size = 0x%08lx", (unsigned long int)vmh.size );
if( ( vmh.flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT ) != 0 ) fprintf( FpDebug, " DeviceLocal" ); // only one in use
fprintf(FpDebug, "\n");
}
uint32_t count = -1;
vkGetPhysicalDeviceQueueFamilyProperties( IN PhysicalDevice, &count, OUT (VkQueueFamilyProperties *)nullptr );
fprintf( FpDebug, "\nFound %d Queue Families:\n", count );
VkQueueFamilyProperties *vqfp = new VkQueueFamilyProperties[ count ];
vkGetPhysicalDeviceQueueFamilyProperties( IN PhysicalDevice, &count, OUT vqfp );
for( unsigned int i = 0; i < count; i++ )
{
fprintf( FpDebug, "\t%d: queueCount = %2d ; ", i, vqfp[i].queueCount );
if( ( vqfp[i].queueFlags & VK_QUEUE_GRAPHICS_BIT ) != 0 ) fprintf( FpDebug, " Graphics" );
if( ( vqfp[i].queueFlags & VK_QUEUE_COMPUTE_BIT ) != 0 ) fprintf( FpDebug, " Compute " );
if( ( vqfp[i].queueFlags & VK_QUEUE_TRANSFER_BIT ) != 0 ) fprintf( FpDebug, " Transfer" );
fprintf(FpDebug, "\n");
}
return result;
}
// ************************************
// CREATE THE LOGICAL DEVICE AND QUEUE:
// ************************************
VkResult
Init04LogicalDeviceAndQueue( )
{
HERE_I_AM( "Init04LogicalDeviceAndQueue" );
VkResult result = VK_SUCCESS;
float queuePriorities[NUM_QUEUES_WANTED] =
{
1.
};
VkDeviceQueueCreateInfo vdqci[NUM_QUEUES_WANTED];
vdqci[0].sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
vdqci[0].pNext = nullptr;
vdqci[0].flags = 0;
vdqci[0].queueFamilyIndex = 0; // which queue family
vdqci[0].queueCount = 1; // how many queues to create
vdqci[0].pQueuePriorities = queuePriorities; // array of queue priorities [0.,1.]
const char * myDeviceLayers[ ] =
{
////"VK_LAYER_LUNARG_api_dump",
////"VK_LAYER_LUNARG_core_validation",
//"VK_LAYER_LUNARG_image",
"VK_LAYER_LUNARG_object_tracker",
"VK_LAYER_LUNARG_parameter_validation",
//"VK_LAYER_NV_optimus"
};
const char * myDeviceExtensions[ ] =
{
"VK_KHR_surface",
"VK_KHR_win32_surface",
"VK_EXT_debug_report"
//"VK_KHR_swapchains"
};
// see what device layers are available:
uint32_t layerCount;
vkEnumerateDeviceLayerProperties(PhysicalDevice, &layerCount, (VkLayerProperties *)nullptr);
VkLayerProperties * deviceLayers = new VkLayerProperties[layerCount];
result = vkEnumerateDeviceLayerProperties( PhysicalDevice, &layerCount, deviceLayers);
REPORT("vkEnumerateDeviceLayerProperties");
if (result != VK_SUCCESS)
{
return result;
}