-
Notifications
You must be signed in to change notification settings - Fork 158
/
cube.c
5096 lines (4540 loc) · 200 KB
/
cube.c
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 (c) 2015-2019 The Khronos Group Inc.
* Copyright (c) 2015-2019 Valve Corporation
* Copyright (c) 2015-2019 LunarG, Inc.
*
* 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.
*
* Author: Chia-I Wu <[email protected]>
* Author: Courtney Goeltzenleuchter <[email protected]>
* Author: Ian Elliott <[email protected]>
* Author: Ian Elliott <[email protected]>
* Author: Jon Ashburn <[email protected]>
* Author: Gwan-gyeong Mun <[email protected]>
* Author: Tony Barbour <[email protected]>
* Author: Bill Hollings <[email protected]>
*/
#define _GNU_SOURCE
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <assert.h>
#include <signal.h>
#if defined(VK_USE_PLATFORM_SCREEN_QNX)
#include <errno.h>
#endif
#if defined(VK_USE_PLATFORM_XLIB_KHR)
#include "xlib_loader.h"
#endif
#if defined(VK_USE_PLATFORM_XCB_KHR)
#include "xcb_loader.h"
#endif
#if defined(VK_USE_PLATFORM_WAYLAND_KHR)
#include <linux/input.h>
#include "wayland_loader.h"
#endif
#ifdef _WIN32
#ifdef _MSC_VER
#pragma comment(linker, "/subsystem:windows")
#endif // MSVC
#define APP_NAME_STR_LEN 80
#endif // _WIN32
// Volk requires VK_NO_PROTOTYPES before including vulkan.h
#define VK_NO_PROTOTYPES
#include <vulkan/vulkan.h>
#define VOLK_IMPLEMENTATION
#include "volk.h"
#include "linmath.h"
#include "object_type_string_helper.h"
#include "gettime.h"
#include "inttypes.h"
#define MILLION 1000000L
#define BILLION 1000000000L
#define DEMO_TEXTURE_COUNT 1
#define APP_SHORT_NAME "vkcube"
#define APP_LONG_NAME "Vulkan Cube"
// Allow a maximum of two outstanding presentation operations.
#define FRAME_LAG 2
#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
#if defined(NDEBUG) && defined(__GNUC__)
#define U_ASSERT_ONLY __attribute__((unused))
#else
#define U_ASSERT_ONLY
#endif
#if defined(__GNUC__)
#define UNUSED __attribute__((unused))
#else
#define UNUSED
#endif
#ifdef _WIN32
bool in_callback = false;
#define ERR_EXIT(err_msg, err_class) \
do { \
if (!demo->suppress_popups) MessageBox(NULL, err_msg, err_class, MB_OK); \
exit(1); \
} while (0)
void DbgMsg(char *fmt, ...) {
va_list va;
va_start(va, fmt);
vprintf(fmt, va);
va_end(va);
fflush(stdout);
}
#elif defined __ANDROID__
#include <android/log.h>
#define ERR_EXIT(err_msg, err_class) \
do { \
((void)__android_log_print(ANDROID_LOG_INFO, "Vulkan Cube", err_msg)); \
exit(1); \
} while (0)
#ifdef VARARGS_WORKS_ON_ANDROID
void DbgMsg(const char *fmt, ...) {
va_list va;
va_start(va, fmt);
__android_log_print(ANDROID_LOG_INFO, "Vulkan Cube", fmt, va);
va_end(va);
}
#else // VARARGS_WORKS_ON_ANDROID
#define DbgMsg(fmt, ...) \
do { \
((void)__android_log_print(ANDROID_LOG_INFO, "Vulkan Cube", fmt, ##__VA_ARGS__)); \
} while (0)
#endif // VARARGS_WORKS_ON_ANDROID
#else
#define ERR_EXIT(err_msg, err_class) \
do { \
printf("%s\n", err_msg); \
fflush(stdout); \
exit(1); \
} while (0)
void DbgMsg(char *fmt, ...) {
va_list va;
va_start(va, fmt);
vprintf(fmt, va);
va_end(va);
fflush(stdout);
}
#endif
/*
* structure to track all objects related to a texture.
*/
struct texture_object {
VkSampler sampler;
VkImage image;
VkBuffer buffer;
VkImageLayout imageLayout;
VkMemoryAllocateInfo mem_alloc;
VkDeviceMemory mem;
VkImageView view;
int32_t tex_width, tex_height;
};
static char *tex_files[] = {"lunarg.ppm"};
static int validation_error = 0;
struct vktexcube_vs_uniform {
// Must start with MVP
float mvp[4][4];
float position[12 * 3][4];
float attr[12 * 3][4];
};
//--------------------------------------------------------------------------------------
// Mesh and VertexFormat Data
//--------------------------------------------------------------------------------------
// clang-format off
static const float g_vertex_buffer_data[] = {
-1.0f,-1.0f,-1.0f, // -X side
-1.0f,-1.0f, 1.0f,
-1.0f, 1.0f, 1.0f,
-1.0f, 1.0f, 1.0f,
-1.0f, 1.0f,-1.0f,
-1.0f,-1.0f,-1.0f,
-1.0f,-1.0f,-1.0f, // -Z side
1.0f, 1.0f,-1.0f,
1.0f,-1.0f,-1.0f,
-1.0f,-1.0f,-1.0f,
-1.0f, 1.0f,-1.0f,
1.0f, 1.0f,-1.0f,
-1.0f,-1.0f,-1.0f, // -Y side
1.0f,-1.0f,-1.0f,
1.0f,-1.0f, 1.0f,
-1.0f,-1.0f,-1.0f,
1.0f,-1.0f, 1.0f,
-1.0f,-1.0f, 1.0f,
-1.0f, 1.0f,-1.0f, // +Y side
-1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
-1.0f, 1.0f,-1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f,-1.0f,
1.0f, 1.0f,-1.0f, // +X side
1.0f, 1.0f, 1.0f,
1.0f,-1.0f, 1.0f,
1.0f,-1.0f, 1.0f,
1.0f,-1.0f,-1.0f,
1.0f, 1.0f,-1.0f,
-1.0f, 1.0f, 1.0f, // +Z side
-1.0f,-1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
-1.0f,-1.0f, 1.0f,
1.0f,-1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
};
static const float g_uv_buffer_data[] = {
0.0f, 1.0f, // -X side
1.0f, 1.0f,
1.0f, 0.0f,
1.0f, 0.0f,
0.0f, 0.0f,
0.0f, 1.0f,
1.0f, 1.0f, // -Z side
0.0f, 0.0f,
0.0f, 1.0f,
1.0f, 1.0f,
1.0f, 0.0f,
0.0f, 0.0f,
1.0f, 0.0f, // -Y side
1.0f, 1.0f,
0.0f, 1.0f,
1.0f, 0.0f,
0.0f, 1.0f,
0.0f, 0.0f,
1.0f, 0.0f, // +Y side
0.0f, 0.0f,
0.0f, 1.0f,
1.0f, 0.0f,
0.0f, 1.0f,
1.0f, 1.0f,
1.0f, 0.0f, // +X side
0.0f, 0.0f,
0.0f, 1.0f,
0.0f, 1.0f,
1.0f, 1.0f,
1.0f, 0.0f,
0.0f, 0.0f, // +Z side
0.0f, 1.0f,
1.0f, 0.0f,
0.0f, 1.0f,
1.0f, 1.0f,
1.0f, 0.0f,
};
// clang-format on
void dumpMatrix(const char *note, mat4x4 MVP) {
int i;
printf("%s: \n", note);
for (i = 0; i < 4; i++) {
printf("%f, %f, %f, %f\n", MVP[i][0], MVP[i][1], MVP[i][2], MVP[i][3]);
}
printf("\n");
fflush(stdout);
}
void dumpVec4(const char *note, vec4 vector) {
printf("%s: \n", note);
printf("%f, %f, %f, %f\n", vector[0], vector[1], vector[2], vector[3]);
printf("\n");
fflush(stdout);
}
char const *to_string(VkPhysicalDeviceType const type) {
switch (type) {
case VK_PHYSICAL_DEVICE_TYPE_OTHER:
return "Other";
case VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU:
return "IntegratedGpu";
case VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU:
return "DiscreteGpu";
case VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU:
return "VirtualGpu";
case VK_PHYSICAL_DEVICE_TYPE_CPU:
return "Cpu";
default:
return "Unknown";
}
}
typedef enum WSI_PLATFORM {
WSI_PLATFORM_AUTO = 0,
WSI_PLATFORM_WIN32,
WSI_PLATFORM_METAL,
WSI_PLATFORM_ANDROID,
WSI_PLATFORM_QNX,
WSI_PLATFORM_XCB,
WSI_PLATFORM_XLIB,
WSI_PLATFORM_WAYLAND,
WSI_PLATFORM_DIRECTFB,
WSI_PLATFORM_DISPLAY,
WSI_PLATFORM_INVALID, // Sentinel just to indicate invalid user input
} WSI_PLATFORM;
WSI_PLATFORM wsi_from_string(const char *str) {
if (strcmp(str, "auto") == 0) return WSI_PLATFORM_AUTO;
#if defined(VK_USE_PLATFORM_WIN32_KHR)
if (strcmp(str, "win32") == 0) return WSI_PLATFORM_WIN32;
#endif
#if defined(VK_USE_PLATFORM_METAL_EXT)
if (strcmp(str, "metal") == 0) return WSI_PLATFORM_METAL;
#endif
#if defined(VK_USE_PLATFORM_ANDROID_KHR)
if (strcmp(str, "android") == 0) return WSI_PLATFORM_ANDROID;
#endif
#if defined(VK_USE_PLATFORM_SCREEN_QNX)
if (strcmp(str, "qnx") == 0) return WSI_PLATFORM_QNX;
#endif
#if defined(VK_USE_PLATFORM_XCB_KHR)
if (strcmp(str, "xcb") == 0) return WSI_PLATFORM_XCB;
#endif
#if defined(VK_USE_PLATFORM_XLIB_KHR)
if (strcmp(str, "xlib") == 0) return WSI_PLATFORM_XLIB;
#endif
#if defined(VK_USE_PLATFORM_WAYLAND_KHR)
if (strcmp(str, "wayland") == 0) return WSI_PLATFORM_WAYLAND;
#endif
#if defined(VK_USE_PLATFORM_DIRECTFB_EXT)
if (strcmp(str, "directfb") == 0) return WSI_PLATFORM_DIRECTFB;
#endif
#if defined(VK_USE_PLATFORM_DISPLAY_KHR)
if (strcmp(str, "display") == 0) return WSI_PLATFORM_DISPLAY;
#endif
return WSI_PLATFORM_INVALID;
};
const char *wsi_to_string(WSI_PLATFORM wsi_platform) {
switch (wsi_platform) {
case (WSI_PLATFORM_AUTO):
return "auto";
#if defined(VK_USE_PLATFORM_WIN32_KHR)
case (WSI_PLATFORM_WIN32):
return "win32";
#endif
#if defined(VK_USE_PLATFORM_METAL_EXT)
case (WSI_PLATFORM_METAL):
return "metal";
#endif
#if defined(VK_USE_PLATFORM_ANDROID_KHR)
case (WSI_PLATFORM_ANDROID):
return "android";
#endif
#if defined(VK_USE_PLATFORM_SCREEN_QNX)
case (WSI_PLATFORM_QNX):
return "qnx";
#endif
#if defined(VK_USE_PLATFORM_XCB_KHR)
case (WSI_PLATFORM_XCB):
return "xcb";
#endif
#if defined(VK_USE_PLATFORM_XLIB_KHR)
case (WSI_PLATFORM_XLIB):
return "xlib";
#endif
#if defined(VK_USE_PLATFORM_WAYLAND_KHR)
case (WSI_PLATFORM_WAYLAND):
return "wayland";
#endif
#if defined(VK_USE_PLATFORM_DIRECTFB_EXT)
case (WSI_PLATFORM_DIRECTFB):
return "directfb";
#endif
#if defined(VK_USE_PLATFORM_DISPLAY_KHR)
case (WSI_PLATFORM_DISPLAY):
return "display";
#endif
default:
return "unknown";
}
};
typedef struct {
VkImage image;
VkCommandBuffer cmd;
VkCommandBuffer graphics_to_present_cmd;
VkImageView view;
VkBuffer uniform_buffer;
VkDeviceMemory uniform_memory;
void *uniform_memory_ptr;
VkFramebuffer framebuffer;
VkDescriptorSet descriptor_set;
} SwapchainImageResources;
struct demo {
#if defined(VK_USE_PLATFORM_WIN32_KHR)
#define APP_NAME_STR_LEN 80
HINSTANCE connection; // hInstance - Windows Instance
char name[APP_NAME_STR_LEN]; // Name to put on the window/icon
HWND window; // hWnd - window handle
POINT minsize; // minimum window size
#endif
#if defined(VK_USE_PLATFORM_XLIB_KHR)
void *xlib_library;
Display *xlib_display;
Window xlib_window;
Atom xlib_wm_delete_window;
#endif
#if defined(VK_USE_PLATFORM_XCB_KHR)
void *xcb_library;
Display *xcb_display;
xcb_connection_t *connection;
xcb_screen_t *screen;
xcb_window_t xcb_window;
xcb_intern_atom_reply_t *atom_wm_delete_window;
#endif
#if defined(VK_USE_PLATFORM_WAYLAND_KHR)
void *wayland_library; // Dynamic library for wayland
struct wl_display *wayland_display;
struct wl_registry *registry;
struct wl_compositor *compositor;
struct wl_surface *window;
struct xdg_wm_base *xdg_wm_base;
struct zxdg_decoration_manager_v1 *xdg_decoration_mgr;
struct zxdg_toplevel_decoration_v1 *toplevel_decoration;
struct xdg_surface *xdg_surface;
int xdg_surface_has_been_configured;
struct xdg_toplevel *xdg_toplevel;
struct wl_seat *seat;
struct wl_pointer *pointer;
struct wl_keyboard *keyboard;
#endif
#if defined(VK_USE_PLATFORM_DIRECTFB_EXT)
IDirectFB *dfb;
IDirectFBSurface *directfb_window;
IDirectFBEventBuffer *event_buffer;
#endif
#if defined(VK_USE_PLATFORM_ANDROID_KHR)
struct ANativeWindow *window;
#endif
#if defined(VK_USE_PLATFORM_METAL_EXT)
void *caMetalLayer;
#endif
#if defined(VK_USE_PLATFORM_SCREEN_QNX)
screen_context_t screen_context;
screen_window_t screen_window;
screen_event_t screen_event;
#endif
WSI_PLATFORM wsi_platform;
VkSurfaceKHR surface;
bool prepared;
bool use_staging_buffer;
bool separate_present_queue;
bool is_minimized;
bool invalid_gpu_selection;
int32_t gpu_number;
bool VK_KHR_incremental_present_enabled;
bool VK_GOOGLE_display_timing_enabled;
bool syncd_with_actual_presents;
uint64_t refresh_duration;
uint64_t refresh_duration_multiplier;
uint64_t target_IPD; // image present duration (inverse of frame rate)
uint64_t prev_desired_present_time;
uint32_t next_present_id;
uint32_t last_early_id; // 0 if no early images
uint32_t last_late_id; // 0 if no late images
VkInstance inst;
VkPhysicalDevice gpu;
VkDevice device;
VkQueue graphics_queue;
VkQueue present_queue;
uint32_t graphics_queue_family_index;
uint32_t present_queue_family_index;
VkSemaphore image_acquired_semaphores[FRAME_LAG];
VkSemaphore draw_complete_semaphores[FRAME_LAG];
VkSemaphore image_ownership_semaphores[FRAME_LAG];
VkPhysicalDeviceProperties gpu_props;
VkQueueFamilyProperties *queue_props;
VkPhysicalDeviceMemoryProperties memory_properties;
uint32_t enabled_extension_count;
uint32_t enabled_layer_count;
char *extension_names[64];
char *enabled_layers[64];
int width, height;
VkFormat format;
VkColorSpaceKHR color_space;
uint32_t swapchainImageCount;
VkSwapchainKHR swapchain;
SwapchainImageResources *swapchain_image_resources;
VkPresentModeKHR presentMode;
VkFence fences[FRAME_LAG];
int frame_index;
bool first_swapchain_frame;
VkCommandPool cmd_pool;
VkCommandPool present_cmd_pool;
struct {
VkFormat format;
VkImage image;
VkMemoryAllocateInfo mem_alloc;
VkDeviceMemory mem;
VkImageView view;
} depth;
struct texture_object textures[DEMO_TEXTURE_COUNT];
struct texture_object staging_texture;
VkCommandBuffer cmd; // Buffer for initialization commands
VkPipelineLayout pipeline_layout;
VkDescriptorSetLayout desc_layout;
VkPipelineCache pipelineCache;
VkRenderPass render_pass;
VkPipeline pipeline;
mat4x4 projection_matrix;
mat4x4 view_matrix;
mat4x4 model_matrix;
float spin_angle;
float spin_increment;
bool pause;
VkShaderModule vert_shader_module;
VkShaderModule frag_shader_module;
VkDescriptorPool desc_pool;
bool quit;
int32_t curFrame;
int32_t frameCount;
bool validate;
bool use_break;
bool suppress_popups;
bool force_errors;
VkDebugUtilsMessengerEXT dbg_messenger;
uint32_t current_buffer;
uint32_t queue_family_count;
};
VKAPI_ATTR VkBool32 VKAPI_CALL debug_messenger_callback(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
VkDebugUtilsMessageTypeFlagsEXT messageType,
const VkDebugUtilsMessengerCallbackDataEXT *pCallbackData,
void *pUserData) {
char prefix[64] = "";
char *message = (char *)malloc(strlen(pCallbackData->pMessage) + 5000);
assert(message);
struct demo *demo = (struct demo *)pUserData;
if (demo->use_break) {
#ifndef WIN32
raise(SIGTRAP);
#else
DebugBreak();
#endif
}
if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT) {
strcat(prefix, "VERBOSE : ");
} else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT) {
strcat(prefix, "INFO : ");
} else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT) {
strcat(prefix, "WARNING : ");
} else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) {
strcat(prefix, "ERROR : ");
}
if (messageType & VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT) {
strcat(prefix, "GENERAL");
} else {
if (messageType & VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT) {
strcat(prefix, "VALIDATION");
validation_error = 1;
}
if (messageType & VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT) {
if (messageType & VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT) {
strcat(prefix, "|");
}
strcat(prefix, "PERFORMANCE");
}
}
sprintf(message, "%s - Message Id Number: %d | Message Id Name: %s\n\t%s\n", prefix, pCallbackData->messageIdNumber,
pCallbackData->pMessageIdName == NULL ? "" : pCallbackData->pMessageIdName, pCallbackData->pMessage);
if (pCallbackData->objectCount > 0) {
char tmp_message[500];
sprintf(tmp_message, "\n\tObjects - %d\n", pCallbackData->objectCount);
strcat(message, tmp_message);
for (uint32_t object = 0; object < pCallbackData->objectCount; ++object) {
sprintf(tmp_message, "\t\tObject[%d] - %s", object, string_VkObjectType(pCallbackData->pObjects[object].objectType));
strcat(message, tmp_message);
VkObjectType t = pCallbackData->pObjects[object].objectType;
if (t == VK_OBJECT_TYPE_INSTANCE || t == VK_OBJECT_TYPE_PHYSICAL_DEVICE || t == VK_OBJECT_TYPE_DEVICE ||
t == VK_OBJECT_TYPE_COMMAND_BUFFER || t == VK_OBJECT_TYPE_QUEUE) {
sprintf(tmp_message, ", Handle %p", (void *)(uintptr_t)(pCallbackData->pObjects[object].objectHandle));
strcat(message, tmp_message);
} else {
sprintf(tmp_message, ", Handle Ox%" PRIx64, (pCallbackData->pObjects[object].objectHandle));
strcat(message, tmp_message);
}
if (NULL != pCallbackData->pObjects[object].pObjectName && strlen(pCallbackData->pObjects[object].pObjectName) > 0) {
sprintf(tmp_message, ", Name \"%s\"", pCallbackData->pObjects[object].pObjectName);
strcat(message, tmp_message);
}
sprintf(tmp_message, "\n");
strcat(message, tmp_message);
}
}
if (pCallbackData->cmdBufLabelCount > 0) {
char tmp_message[500];
sprintf(tmp_message, "\n\tCommand Buffer Labels - %d\n", pCallbackData->cmdBufLabelCount);
strcat(message, tmp_message);
for (uint32_t cmd_buf_label = 0; cmd_buf_label < pCallbackData->cmdBufLabelCount; ++cmd_buf_label) {
sprintf(tmp_message, "\t\tLabel[%d] - %s { %f, %f, %f, %f}\n", cmd_buf_label,
pCallbackData->pCmdBufLabels[cmd_buf_label].pLabelName, pCallbackData->pCmdBufLabels[cmd_buf_label].color[0],
pCallbackData->pCmdBufLabels[cmd_buf_label].color[1], pCallbackData->pCmdBufLabels[cmd_buf_label].color[2],
pCallbackData->pCmdBufLabels[cmd_buf_label].color[3]);
strcat(message, tmp_message);
}
}
#ifdef _WIN32
in_callback = true;
if (!demo->suppress_popups) MessageBox(NULL, message, "Alert", MB_OK);
in_callback = false;
#elif defined(ANDROID)
if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT) {
__android_log_print(ANDROID_LOG_INFO, APP_SHORT_NAME, "%s", message);
} else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT) {
__android_log_print(ANDROID_LOG_WARN, APP_SHORT_NAME, "%s", message);
} else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) {
__android_log_print(ANDROID_LOG_ERROR, APP_SHORT_NAME, "%s", message);
} else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT) {
__android_log_print(ANDROID_LOG_VERBOSE, APP_SHORT_NAME, "%s", message);
} else {
__android_log_print(ANDROID_LOG_INFO, APP_SHORT_NAME, "%s", message);
}
#else
printf("%s\n", message);
fflush(stdout);
#endif
free(message);
// Don't bail out, but keep going.
return false;
}
bool ActualTimeLate(uint64_t desired, uint64_t actual, uint64_t rdur) {
// The desired time was the earliest time that the present should have
// occured. In almost every case, the actual time should be later than the
// desired time. We should only consider the actual time "late" if it is
// after "desired + rdur".
if (actual <= desired) {
// The actual time was before or equal to the desired time. This will
// probably never happen, but in case it does, return false since the
// present was obviously NOT late.
return false;
}
uint64_t deadline = desired + rdur;
if (actual > deadline) {
return true;
} else {
return false;
}
}
bool CanPresentEarlier(uint64_t earliest, uint64_t actual, uint64_t margin, uint64_t rdur) {
if (earliest < actual) {
// Consider whether this present could have occured earlier. Make sure
// that earliest time was at least 2msec earlier than actual time, and
// that the margin was at least 2msec:
uint64_t diff = actual - earliest;
if ((diff >= (2 * MILLION)) && (margin >= (2 * MILLION))) {
// This present could have occured earlier because both: 1) the
// earliest time was at least 2 msec before actual time, and 2) the
// margin was at least 2msec.
return true;
}
}
return false;
}
// Forward declarations:
static void demo_resize(struct demo *demo);
static void demo_create_surface(struct demo *demo);
#if defined(__GNUC__) || defined(__clang__)
#define DECORATE_PRINTF(_fmt_argnum, _first_param_num) __attribute__((format(printf, _fmt_argnum, _first_param_num)))
#else
#define DECORATE_PRINTF(_fmt_num, _first_param_num)
#endif
DECORATE_PRINTF(4, 5)
static void demo_name_object(struct demo *demo, VkObjectType object_type, uint64_t vulkan_handle, const char *format, ...) {
if (!demo->validate) {
return;
}
VkResult U_ASSERT_ONLY err;
char name[1024];
va_list argptr;
va_start(argptr, format);
vsnprintf(name, sizeof(name), format, argptr);
va_end(argptr);
name[sizeof(name) - 1] = '\0';
VkDebugUtilsObjectNameInfoEXT obj_name = {
.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT,
.pNext = NULL,
.objectType = object_type,
.objectHandle = vulkan_handle,
.pObjectName = name,
};
err = vkSetDebugUtilsObjectNameEXT(demo->device, &obj_name);
assert(!err);
}
DECORATE_PRINTF(4, 5)
static void demo_push_cb_label(struct demo *demo, VkCommandBuffer cb, const float *color, const char *format, ...) {
if (!demo->validate) {
return;
}
char name[1024];
va_list argptr;
va_start(argptr, format);
vsnprintf(name, sizeof(name), format, argptr);
va_end(argptr);
name[sizeof(name) - 1] = '\0';
VkDebugUtilsLabelEXT label = {
.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT,
.pNext = NULL,
.pLabelName = name,
};
if (color) {
memcpy(label.color, color, sizeof(label.color));
}
vkCmdBeginDebugUtilsLabelEXT(cb, &label);
}
static void demo_pop_cb_label(struct demo *demo, VkCommandBuffer cb) {
if (!demo->validate) {
return;
}
vkCmdEndDebugUtilsLabelEXT(cb);
}
static bool memory_type_from_properties(struct demo *demo, uint32_t typeBits, VkFlags requirements_mask, uint32_t *typeIndex) {
// Search memtypes to find first index with those properties
for (uint32_t i = 0; i < VK_MAX_MEMORY_TYPES; i++) {
if ((typeBits & 1) == 1) {
// Type is available, does it match user properties?
if ((demo->memory_properties.memoryTypes[i].propertyFlags & requirements_mask) == requirements_mask) {
*typeIndex = i;
return true;
}
}
typeBits >>= 1;
}
// No memory types matched, return failure
return false;
}
static void demo_flush_init_cmd(struct demo *demo) {
VkResult U_ASSERT_ONLY err;
// This function could get called twice if the texture uses a staging buffer
// In that case the second call should be ignored
if (demo->cmd == VK_NULL_HANDLE) return;
err = vkEndCommandBuffer(demo->cmd);
assert(!err);
VkFence fence;
VkFenceCreateInfo fence_ci = {.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, .pNext = NULL, .flags = 0};
if (demo->force_errors) {
// Remove sType to intentionally force validation layer errors.
fence_ci.sType = 0;
}
err = vkCreateFence(demo->device, &fence_ci, NULL, &fence);
assert(!err);
demo_name_object(demo, VK_OBJECT_TYPE_FENCE, (uint64_t)fence, "InitFence");
const VkCommandBuffer cmd_bufs[] = {demo->cmd};
VkSubmitInfo submit_info = {.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
.pNext = NULL,
.waitSemaphoreCount = 0,
.pWaitSemaphores = NULL,
.pWaitDstStageMask = NULL,
.commandBufferCount = 1,
.pCommandBuffers = cmd_bufs,
.signalSemaphoreCount = 0,
.pSignalSemaphores = NULL};
err = vkQueueSubmit(demo->graphics_queue, 1, &submit_info, fence);
assert(!err);
err = vkWaitForFences(demo->device, 1, &fence, VK_TRUE, UINT64_MAX);
assert(!err);
vkFreeCommandBuffers(demo->device, demo->cmd_pool, 1, cmd_bufs);
vkDestroyFence(demo->device, fence, NULL);
demo->cmd = VK_NULL_HANDLE;
}
static void demo_set_image_layout(struct demo *demo, VkImage image, VkImageAspectFlags aspectMask, VkImageLayout old_image_layout,
VkImageLayout new_image_layout, VkAccessFlagBits srcAccessMask, VkPipelineStageFlags src_stages,
VkPipelineStageFlags dest_stages) {
assert(demo->cmd);
VkImageMemoryBarrier image_memory_barrier = {.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
.pNext = NULL,
.srcAccessMask = srcAccessMask,
.dstAccessMask = 0,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.oldLayout = old_image_layout,
.newLayout = new_image_layout,
.image = image,
.subresourceRange = {aspectMask, 0, 1, 0, 1}};
switch (new_image_layout) {
case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL:
/* Make sure anything that was copying from this image has completed */
image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
break;
case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL:
image_memory_barrier.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
break;
case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL:
image_memory_barrier.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
break;
case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL:
image_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_INPUT_ATTACHMENT_READ_BIT;
break;
case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL:
image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
break;
case VK_IMAGE_LAYOUT_PRESENT_SRC_KHR:
image_memory_barrier.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT;
break;
default:
image_memory_barrier.dstAccessMask = 0;
break;
}
VkImageMemoryBarrier *pmemory_barrier = &image_memory_barrier;
vkCmdPipelineBarrier(demo->cmd, src_stages, dest_stages, 0, 0, NULL, 0, NULL, 1, pmemory_barrier);
}
static void demo_draw_build_cmd(struct demo *demo, VkCommandBuffer cmd_buf) {
const VkCommandBufferBeginInfo cmd_buf_info = {
.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
.pNext = NULL,
.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT,
.pInheritanceInfo = NULL,
};
const VkClearValue clear_values[2] = {
[0] = {.color.float32 = {0.2f, 0.2f, 0.2f, 0.2f}},
[1] = {.depthStencil = {1.0f, 0}},
};
const VkRenderPassBeginInfo rp_begin = {
.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO,
.pNext = NULL,
.renderPass = demo->render_pass,
.framebuffer = demo->swapchain_image_resources[demo->current_buffer].framebuffer,
.renderArea.offset.x = 0,
.renderArea.offset.y = 0,
.renderArea.extent.width = demo->width,
.renderArea.extent.height = demo->height,
.clearValueCount = 2,
.pClearValues = clear_values,
};
VkResult U_ASSERT_ONLY err;
err = vkBeginCommandBuffer(cmd_buf, &cmd_buf_info);
demo_name_object(demo, VK_OBJECT_TYPE_COMMAND_BUFFER, (uint64_t)cmd_buf, "CubeDrawCommandBuf");
const float begin_color[4] = {0.4f, 0.3f, 0.2f, 0.1f};
demo_push_cb_label(demo, cmd_buf, begin_color, "DrawBegin");
assert(!err);
vkCmdBeginRenderPass(cmd_buf, &rp_begin, VK_SUBPASS_CONTENTS_INLINE);
const float renderpass_color[4] = {8.4f, 7.3f, 6.2f, 7.1f};
demo_push_cb_label(demo, cmd_buf, renderpass_color, "InsideRenderPass");
vkCmdBindPipeline(cmd_buf, VK_PIPELINE_BIND_POINT_GRAPHICS, demo->pipeline);
vkCmdBindDescriptorSets(cmd_buf, VK_PIPELINE_BIND_POINT_GRAPHICS, demo->pipeline_layout, 0, 1,
&demo->swapchain_image_resources[demo->current_buffer].descriptor_set, 0, NULL);
VkViewport viewport;
memset(&viewport, 0, sizeof(viewport));
float viewport_dimension;
if (demo->width < demo->height) {
viewport_dimension = (float)demo->width;
viewport.y = (demo->height - demo->width) / 2.0f;
} else {
viewport_dimension = (float)demo->height;
viewport.x = (demo->width - demo->height) / 2.0f;
}
viewport.height = viewport_dimension;
viewport.width = viewport_dimension;
viewport.minDepth = (float)0.0f;
viewport.maxDepth = (float)1.0f;
vkCmdSetViewport(cmd_buf, 0, 1, &viewport);
VkRect2D scissor;
memset(&scissor, 0, sizeof(scissor));
scissor.extent.width = demo->width;
scissor.extent.height = demo->height;
scissor.offset.x = 0;
scissor.offset.y = 0;
vkCmdSetScissor(cmd_buf, 0, 1, &scissor);
const float draw_color[4] = {-0.4f, -0.3f, -0.2f, -0.1f};
demo_push_cb_label(demo, cmd_buf, draw_color, "ActualDraw");
vkCmdDraw(cmd_buf, 12 * 3, 1, 0, 0);
demo_pop_cb_label(demo, cmd_buf);
// Note that ending the renderpass changes the image's layout from
// COLOR_ATTACHMENT_OPTIMAL to PRESENT_SRC_KHR
vkCmdEndRenderPass(cmd_buf);
demo_pop_cb_label(demo, cmd_buf);
if (demo->separate_present_queue) {
// We have to transfer ownership from the graphics queue family to the
// present queue family to be able to present. Note that we don't have
// to transfer from present queue family back to graphics queue family at
// the start of the next frame because we don't care about the image's
// contents at that point.
VkImageMemoryBarrier image_ownership_barrier = {.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
.pNext = NULL,
.srcAccessMask = 0,
.dstAccessMask = 0,
.oldLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
.srcQueueFamilyIndex = demo->graphics_queue_family_index,
.dstQueueFamilyIndex = demo->present_queue_family_index,
.image = demo->swapchain_image_resources[demo->current_buffer].image,
.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}};
vkCmdPipelineBarrier(cmd_buf, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, NULL, 0,
NULL, 1, &image_ownership_barrier);
}
demo_pop_cb_label(demo, cmd_buf);
err = vkEndCommandBuffer(cmd_buf);
assert(!err);
}
void demo_build_image_ownership_cmd(struct demo *demo, int i) {
VkResult U_ASSERT_ONLY err;
const VkCommandBufferBeginInfo cmd_buf_info = {
.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
.pNext = NULL,
.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT,
.pInheritanceInfo = NULL,
};
err = vkBeginCommandBuffer(demo->swapchain_image_resources[i].graphics_to_present_cmd, &cmd_buf_info);
assert(!err);
VkImageMemoryBarrier image_ownership_barrier = {.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
.pNext = NULL,
.srcAccessMask = 0,
.dstAccessMask = 0,
.oldLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
.srcQueueFamilyIndex = demo->graphics_queue_family_index,