forked from KhronosGroup/Vulkan-Tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cube.c
4307 lines (3780 loc) · 171 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 <olv@lunarg.com>
* Author: Courtney Goeltzenleuchter <courtney@LunarG.com>
* Author: Ian Elliott <ian@LunarG.com>
* Author: Ian Elliott <ianelliott@google.com>
* Author: Jon Ashburn <jon@lunarg.com>
* Author: Gwan-gyeong Mun <elongbug@gmail.com>
* Author: Tony Barbour <tony@LunarG.com>
* Author: Bill Hollings <bill.hollings@brenwill.com>
*/
#define _GNU_SOURCE
#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_XLIB_KHR) || defined(VK_USE_PLATFORM_XCB_KHR)
#include <X11/Xutil.h>
#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
#include <linux/input.h>
#include "xdg-shell-client-header.h"
#include "xdg-decoration-client-header.h"
#endif
#ifdef _WIN32
#ifdef _MSC_VER
#pragma comment(linker, "/subsystem:windows")
#endif // MSVC
#define APP_NAME_STR_LEN 80
#endif // _WIN32
#ifdef ANDROID
#include "vulkan_wrapper.h"
#else
#include <vulkan/vulkan.h>
#endif
#include <vulkan/vk_sdk_platform.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
#define GET_INSTANCE_PROC_ADDR(inst, entrypoint) \
{ \
demo->fp##entrypoint = (PFN_vk##entrypoint)vkGetInstanceProcAddr(inst, "vk" #entrypoint); \
if (demo->fp##entrypoint == NULL) { \
ERR_EXIT("vkGetInstanceProcAddr failed to find vk" #entrypoint, "vkGetInstanceProcAddr Failure"); \
} \
}
static PFN_vkGetDeviceProcAddr g_gdpa = NULL;
#define GET_DEVICE_PROC_ADDR(dev, entrypoint) \
{ \
if (!g_gdpa) g_gdpa = (PFN_vkGetDeviceProcAddr)vkGetInstanceProcAddr(demo->inst, "vkGetDeviceProcAddr"); \
demo->fp##entrypoint = (PFN_vk##entrypoint)g_gdpa(dev, "vk" #entrypoint); \
if (demo->fp##entrypoint == NULL) { \
ERR_EXIT("vkGetDeviceProcAddr failed to find vk" #entrypoint, "vkGetDeviceProcAddr Failure"); \
} \
}
/*
* 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);
}
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
#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Display *display;
Window xlib_window;
Atom xlib_wm_delete_window;
#elif defined(VK_USE_PLATFORM_XCB_KHR)
Display *display;
xcb_connection_t *connection;
xcb_screen_t *screen;
xcb_window_t xcb_window;
xcb_intern_atom_reply_t *atom_wm_delete_window;
#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
struct wl_display *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;
#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
IDirectFB *dfb;
IDirectFBSurface *window;
IDirectFBEventBuffer *event_buffer;
#elif defined(VK_USE_PLATFORM_ANDROID_KHR)
struct ANativeWindow *window;
#elif defined(VK_USE_PLATFORM_METAL_EXT)
void *caMetalLayer;
#endif
VkSurfaceKHR surface;
bool prepared;
bool use_staging_buffer;
bool separate_present_queue;
bool is_minimized;
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;
PFN_vkGetPhysicalDeviceSurfaceSupportKHR fpGetPhysicalDeviceSurfaceSupportKHR;
PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR fpGetPhysicalDeviceSurfaceCapabilitiesKHR;
PFN_vkGetPhysicalDeviceSurfaceFormatsKHR fpGetPhysicalDeviceSurfaceFormatsKHR;
PFN_vkGetPhysicalDeviceSurfacePresentModesKHR fpGetPhysicalDeviceSurfacePresentModesKHR;
PFN_vkCreateSwapchainKHR fpCreateSwapchainKHR;
PFN_vkDestroySwapchainKHR fpDestroySwapchainKHR;
PFN_vkGetSwapchainImagesKHR fpGetSwapchainImagesKHR;
PFN_vkAcquireNextImageKHR fpAcquireNextImageKHR;
PFN_vkQueuePresentKHR fpQueuePresentKHR;
PFN_vkGetRefreshCycleDurationGOOGLE fpGetRefreshCycleDurationGOOGLE;
PFN_vkGetPastPresentationTimingGOOGLE fpGetPastPresentationTimingGOOGLE;
uint32_t swapchainImageCount;
VkSwapchainKHR swapchain;
SwapchainImageResources *swapchain_image_resources;
VkPresentModeKHR presentMode;
VkFence fences[FRAME_LAG];
int frame_index;
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 validate_checks_disabled;
bool use_break;
bool suppress_popups;
bool force_errors;
PFN_vkCreateDebugUtilsMessengerEXT CreateDebugUtilsMessengerEXT;
PFN_vkDestroyDebugUtilsMessengerEXT DestroyDebugUtilsMessengerEXT;
PFN_vkSubmitDebugUtilsMessageEXT SubmitDebugUtilsMessageEXT;
PFN_vkCmdBeginDebugUtilsLabelEXT CmdBeginDebugUtilsLabelEXT;
PFN_vkCmdEndDebugUtilsLabelEXT CmdEndDebugUtilsLabelEXT;
PFN_vkCmdInsertDebugUtilsLabelEXT CmdInsertDebugUtilsLabelEXT;
PFN_vkSetDebugUtilsObjectNameEXT SetDebugUtilsObjectNameEXT;
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, 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) {
if (NULL != pCallbackData->pObjects[object].pObjectName && strlen(pCallbackData->pObjects[object].pObjectName) > 0) {
sprintf(tmp_message, "\t\tObject[%d] - %s, Handle %p, Name \"%s\"\n", object,
string_VkObjectType(pCallbackData->pObjects[object].objectType),
(void *)(pCallbackData->pObjects[object].objectHandle), pCallbackData->pObjects[object].pObjectName);
} else {
sprintf(tmp_message, "\t\tObject[%d] - %s, Handle %p\n", object,
string_VkObjectType(pCallbackData->pObjects[object].objectType),
(void *)(pCallbackData->pObjects[object].objectHandle));
}
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);
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);
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) {
VkDebugUtilsLabelEXT label;
memset(&label, 0, sizeof(label));
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);
if (demo->validate) {
// Set a name for the command buffer
VkDebugUtilsObjectNameInfoEXT cmd_buf_name = {
.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT,
.pNext = NULL,
.objectType = VK_OBJECT_TYPE_COMMAND_BUFFER,
.objectHandle = (uint64_t)cmd_buf,
.pObjectName = "CubeDrawCommandBuf",
};
demo->SetDebugUtilsObjectNameEXT(demo->device, &cmd_buf_name);
label.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT;
label.pNext = NULL;
label.pLabelName = "DrawBegin";
label.color[0] = 0.4f;
label.color[1] = 0.3f;
label.color[2] = 0.2f;
label.color[3] = 0.1f;
demo->CmdBeginDebugUtilsLabelEXT(cmd_buf, &label);
}
assert(!err);
vkCmdBeginRenderPass(cmd_buf, &rp_begin, VK_SUBPASS_CONTENTS_INLINE);
if (demo->validate) {
label.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT;
label.pNext = NULL;
label.pLabelName = "InsideRenderPass";
label.color[0] = 8.4f;
label.color[1] = 7.3f;
label.color[2] = 6.2f;
label.color[3] = 7.1f;
demo->CmdBeginDebugUtilsLabelEXT(cmd_buf, &label);
}
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);
if (demo->validate) {
label.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT;
label.pNext = NULL;
label.pLabelName = "ActualDraw";
label.color[0] = -0.4f;
label.color[1] = -0.3f;
label.color[2] = -0.2f;
label.color[3] = -0.1f;
demo->CmdBeginDebugUtilsLabelEXT(cmd_buf, &label);
}
vkCmdDraw(cmd_buf, 12 * 3, 1, 0, 0);
if (demo->validate) {
demo->CmdEndDebugUtilsLabelEXT(cmd_buf);
}
// Note that ending the renderpass changes the image's layout from
// COLOR_ATTACHMENT_OPTIMAL to PRESENT_SRC_KHR
vkCmdEndRenderPass(cmd_buf);
if (demo->validate) {
demo->CmdEndDebugUtilsLabelEXT(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);
}
if (demo->validate) {
demo->CmdEndDebugUtilsLabelEXT(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,
.dstQueueFamilyIndex = demo->present_queue_family_index,
.image = demo->swapchain_image_resources[i].image,
.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}};
vkCmdPipelineBarrier(demo->swapchain_image_resources[i].graphics_to_present_cmd, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, NULL, 0, NULL, 1, &image_ownership_barrier);
err = vkEndCommandBuffer(demo->swapchain_image_resources[i].graphics_to_present_cmd);
assert(!err);
}
void demo_update_data_buffer(struct demo *demo) {
mat4x4 MVP, Model, VP;
int matrixSize = sizeof(MVP);
mat4x4_mul(VP, demo->projection_matrix, demo->view_matrix);
// Rotate around the Y axis
mat4x4_dup(Model, demo->model_matrix);
mat4x4_rotate_Y(demo->model_matrix, Model, (float)degreesToRadians(demo->spin_angle));
mat4x4_orthonormalize(demo->model_matrix, demo->model_matrix);
mat4x4_mul(MVP, VP, demo->model_matrix);
memcpy(demo->swapchain_image_resources[demo->current_buffer].uniform_memory_ptr, (const void *)&MVP[0][0], matrixSize);
}
void DemoUpdateTargetIPD(struct demo *demo) {
// Look at what happened to previous presents, and make appropriate
// adjustments in timing:
VkResult U_ASSERT_ONLY err;
VkPastPresentationTimingGOOGLE *past = NULL;
uint32_t count = 0;
err = demo->fpGetPastPresentationTimingGOOGLE(demo->device, demo->swapchain, &count, NULL);
assert(!err);
if (count) {
past = (VkPastPresentationTimingGOOGLE *)malloc(sizeof(VkPastPresentationTimingGOOGLE) * count);
assert(past);
err = demo->fpGetPastPresentationTimingGOOGLE(demo->device, demo->swapchain, &count, past);
assert(!err);
bool early = false;
bool late = false;
bool calibrate_next = false;
for (uint32_t i = 0; i < count; i++) {
if (!demo->syncd_with_actual_presents) {
// This is the first time that we've received an
// actualPresentTime for this swapchain. In order to not
// perceive these early frames as "late", we need to sync-up
// our future desiredPresentTime's with the
// actualPresentTime(s) that we're receiving now.
calibrate_next = true;
// So that we don't suspect any pending presents as late,
// record them all as suspected-late presents:
demo->last_late_id = demo->next_present_id - 1;
demo->last_early_id = 0;
demo->syncd_with_actual_presents = true;
break;
} else if (CanPresentEarlier(past[i].earliestPresentTime, past[i].actualPresentTime, past[i].presentMargin,
demo->refresh_duration)) {
// This image could have been presented earlier. We don't want
// to decrease the target_IPD until we've seen early presents
// for at least two seconds.
if (demo->last_early_id == past[i].presentID) {
// We've now seen two seconds worth of early presents.
// Flag it as such, and reset the counter:
early = true;
demo->last_early_id = 0;
} else if (demo->last_early_id == 0) {
// This is the first early present we've seen.
// Calculate the presentID for two seconds from now.
uint64_t lastEarlyTime = past[i].actualPresentTime + (2 * BILLION);
uint32_t howManyPresents = (uint32_t)((lastEarlyTime - past[i].actualPresentTime) / demo->target_IPD);
demo->last_early_id = past[i].presentID + howManyPresents;
} else {
// We are in the midst of a set of early images,
// and so we won't do anything.
}
late = false;
demo->last_late_id = 0;
} else if (ActualTimeLate(past[i].desiredPresentTime, past[i].actualPresentTime, demo->refresh_duration)) {
// This image was presented after its desired time. Since
// there's a delay between calling vkQueuePresentKHR and when
// we get the timing data, several presents may have been late.
// Thus, we need to threat all of the outstanding presents as
// being likely late, so that we only increase the target_IPD
// once for all of those presents.
if ((demo->last_late_id == 0) || (demo->last_late_id < past[i].presentID)) {
late = true;
// Record the last suspected-late present:
demo->last_late_id = demo->next_present_id - 1;
} else {
// We are in the midst of a set of likely-late images,
// and so we won't do anything.
}
early = false;
demo->last_early_id = 0;
} else {
// Since this image was not presented early or late, reset
// any sets of early or late presentIDs:
early = false;
late = false;
calibrate_next = true;
demo->last_early_id = 0;
demo->last_late_id = 0;
}
}
if (early) {
// Since we've seen at least two-seconds worth of presnts that
// could have occured earlier than desired, let's decrease the
// target_IPD (i.e. increase the frame rate):
//
// TODO(ianelliott): Try to calculate a better target_IPD based
// on the most recently-seen present (this is overly-simplistic).
demo->refresh_duration_multiplier--;
if (demo->refresh_duration_multiplier == 0) {
// This should never happen, but in case it does, don't
// try to go faster.
demo->refresh_duration_multiplier = 1;
}
demo->target_IPD = demo->refresh_duration * demo->refresh_duration_multiplier;
}