aboutsummaryrefslogtreecommitdiff
path: root/pugl/examples/pugl_vulkan_demo.c
blob: 0dfbaddeef718a78545d80cc08280c7f785726fb (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
/*
  Copyright 2019-2020 David Robillard <d@drobilla.net>
  Copyright 2019 Jordan Halase <jordan@halase.me>

  Permission to use, copy, modify, and/or distribute this software for any
  purpose with or without fee is hereby granted, provided that the above
  copyright notice and this permission notice appear in all copies.

  THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/

/*
  A simple example of drawing with Vulkan.

  For a more advanced demo that actually draws something interesting, see
  pugl_vulkan_cxx_demo.cpp.
*/

#include "demo_utils.h"
#include "test/test_utils.h"

#include "pugl/pugl.h"
#include "pugl/vulkan.h"

#include <vulkan/vk_platform.h>
#include <vulkan/vulkan_core.h>

#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define CLAMP(x, l, h) ((x) <= (l) ? (l) : (x) >= (h) ? (h) : (x))

// Vulkan allocation callbacks which can be used for debugging
#define ALLOC_VK NULL

// Helper macro for allocating arrays by type, with C++ compatible cast
#define AALLOC(size, Type) ((Type*)calloc(size, sizeof(Type)))

// Helper macro for counted array arguments to make clang-format behave
#define COUNTED(count, ...) count, __VA_ARGS__

/// Dynamically loaded Vulkan API functions
typedef struct {
  PFN_vkCreateDebugReportCallbackEXT  vkCreateDebugReportCallbackEXT;
  PFN_vkDestroyDebugReportCallbackEXT vkDestroyDebugReportCallbackEXT;
} InstanceAPI;

/// Vulkan swapchain and everything that depends on it
typedef struct {
  VkSwapchainKHR   rawSwapchain;
  uint32_t         nImages;
  VkExtent2D       extent;
  VkImage*         images;
  VkImageView*     imageViews;
  VkFence*         fences;
  VkCommandBuffer* commandBuffers;
} Swapchain;

/// Synchronization semaphores
typedef struct {
  VkSemaphore presentComplete;
  VkSemaphore renderFinished;
} Sync;

/// Vulkan state, purely Vulkan functions can depend on only this
typedef struct {
  InstanceAPI                api;
  VkInstance                 instance;
  VkDebugReportCallbackEXT   debugCallback;
  VkSurfaceKHR               surface;
  VkSurfaceFormatKHR         surfaceFormat;
  VkPresentModeKHR           presentMode;
  VkPhysicalDeviceProperties deviceProperties;
  VkPhysicalDevice           physicalDevice;
  uint32_t                   graphicsIndex;
  VkDevice                   device;
  VkQueue                    graphicsQueue;
  VkCommandPool              commandPool;
  Swapchain*                 swapchain;
  Sync                       sync;
} VulkanState;

/// Complete application
typedef struct {
  PuglTestOptions opts;
  PuglWorld*      world;
  PuglView*       view;
  VulkanState     vk;
  uint32_t        framesDrawn;
  uint32_t        width;
  uint32_t        height;
  bool            quit;
} VulkanApp;

static VKAPI_ATTR VkBool32 VKAPI_CALL
debugCallback(VkDebugReportFlagsEXT      flags,
              VkDebugReportObjectTypeEXT objType,
              uint64_t                   obj,
              size_t                     location,
              int32_t                    code,
              const char*                layerPrefix,
              const char*                msg,
              void*                      userData)
{
  (void)userData;
  (void)objType;
  (void)obj;
  (void)location;
  (void)code;

  if (flags & VK_DEBUG_REPORT_INFORMATION_BIT_EXT) {
    fprintf(stderr, "note: ");
  } else if (flags & VK_DEBUG_REPORT_WARNING_BIT_EXT) {
    fprintf(stderr, "warning: ");
  } else if (flags & VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT) {
    fprintf(stderr, "performance warning: ");
  } else if (flags & VK_DEBUG_REPORT_ERROR_BIT_EXT) {
    fprintf(stderr, "error: ");
  } else if (flags & VK_DEBUG_REPORT_DEBUG_BIT_EXT) {
    fprintf(stderr, "debug: ");
  }

  fprintf(stderr, "%s: ", layerPrefix);
  fprintf(stderr, "%s\n", msg);
  return VK_FALSE;
}

static bool
hasExtension(const char* const                  name,
             const VkExtensionProperties* const properties,
             const uint32_t                     count)
{
  for (uint32_t i = 0; i < count; ++i) {
    if (!strcmp(properties[i].extensionName, name)) {
      return true;
    }
  }

  return false;
}

static bool
hasLayer(const char* const              name,
         const VkLayerProperties* const properties,
         const uint32_t                 count)
{
  for (uint32_t i = 0; i < count; ++i) {
    if (!strcmp(properties[i].layerName, name)) {
      return true;
    }
  }

  return false;
}

static void
pushString(const char*** const array,
           uint32_t* const     count,
           const char* const   string)
{
  *array = (const char**)realloc(*array, (*count + 1) * sizeof(const char*));
  (*array)[*count] = string;
  ++*count;
}

static VkResult
createInstance(VulkanApp* const app)
{
  const VkApplicationInfo appInfo = {
    VK_STRUCTURE_TYPE_APPLICATION_INFO,
    NULL,
    "Pugl Vulkan Test",
    VK_MAKE_VERSION(0, 1, 0),
    "Pugl Vulkan Test Engine",
    VK_MAKE_VERSION(0, 1, 0),
    VK_MAKE_VERSION(1, 0, 0),
  };

  // Get the number of supported extensions and layers
  VkResult vr          = VK_SUCCESS;
  uint32_t nExtProps   = 0;
  uint32_t nLayerProps = 0;
  if ((vr = vkEnumerateInstanceLayerProperties(&nLayerProps, NULL)) ||
      (vr = vkEnumerateInstanceExtensionProperties(NULL, &nExtProps, NULL))) {
    return vr;
  }

  // Get properties of supported extensions
  VkExtensionProperties* extProps = AALLOC(nExtProps, VkExtensionProperties);
  vkEnumerateInstanceExtensionProperties(NULL, &nExtProps, extProps);

  uint32_t     nExtensions = 0;
  const char** extensions  = NULL;

  // Add extensions required by pugl
  uint32_t           nPuglExts = 0;
  const char* const* puglExts  = puglGetInstanceExtensions(&nPuglExts);
  for (uint32_t i = 0; i < nPuglExts; ++i) {
    pushString(&extensions, &nExtensions, puglExts[i]);
  }

  // Add extra extensions we want to use if they are supported
  if (hasExtension("VK_EXT_debug_report", extProps, nExtProps)) {
    pushString(&extensions, &nExtensions, "VK_EXT_debug_report");
  }

  // Get properties of supported layers
  VkLayerProperties* layerProps = AALLOC(nLayerProps, VkLayerProperties);
  vkEnumerateInstanceLayerProperties(&nLayerProps, layerProps);

  // Add validation layers if error checking is enabled
  uint32_t     nLayers = 0;
  const char** layers  = NULL;
  if (app->opts.errorChecking) {
    const char* debugLayers[] = {"VK_LAYER_KHRONOS_validation",
                                 "VK_LAYER_LUNARG_standard_validation",
                                 NULL};

    for (const char** l = debugLayers; *l; ++l) {
      if (hasLayer(*l, layerProps, nLayerProps)) {
        pushString(&layers, &nLayers, *l);
      }
    }
  }

  for (uint32_t i = 0; i < nExtensions; ++i) {
    printf("Using instance extension:    %s\n", extensions[i]);
  }

  for (uint32_t i = 0; i < nLayers; ++i) {
    printf("Using instance layer:        %s\n", layers[i]);
  }

  const VkInstanceCreateInfo createInfo = {
    VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
    NULL,
    0,
    &appInfo,
    COUNTED(nLayers, layers),
    COUNTED(nExtensions, extensions),
  };

  if ((vr = vkCreateInstance(&createInfo, ALLOC_VK, &app->vk.instance))) {
    logError("Could not create Vulkan Instance: %d\n", vr);
  }

  free(layers);
  free(extensions);
  free(layerProps);
  free(extProps);

  return vr;
}

static VkResult
enableDebugging(VulkanState* const vk)
{
  vk->api.vkCreateDebugReportCallbackEXT =
    (PFN_vkCreateDebugReportCallbackEXT)vkGetInstanceProcAddr(
      vk->instance, "vkCreateDebugReportCallbackEXT");

  vk->api.vkDestroyDebugReportCallbackEXT =
    (PFN_vkDestroyDebugReportCallbackEXT)vkGetInstanceProcAddr(
      vk->instance, "vkDestroyDebugReportCallbackEXT");

  if (vk->api.vkCreateDebugReportCallbackEXT) {
    const VkDebugReportCallbackCreateInfoEXT info = {
      VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT,
      NULL,
      VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT,
      debugCallback,
      NULL,
    };

    VkResult vr = VK_SUCCESS;
    if ((vr = vk->api.vkCreateDebugReportCallbackEXT(
           vk->instance, &info, ALLOC_VK, &vk->debugCallback))) {
      logError("Could not create debug reporter: %d\n", vr);
      return vr;
    }
  }

  return VK_SUCCESS;
}

static VkResult
getGraphicsQueueIndex(VkSurfaceKHR     surface,
                      VkPhysicalDevice device,
                      uint32_t*        graphicsIndex)
{
  VkResult r = VK_SUCCESS;

  uint32_t nProps = 0;
  vkGetPhysicalDeviceQueueFamilyProperties(device, &nProps, NULL);

  VkQueueFamilyProperties* props = AALLOC(nProps, VkQueueFamilyProperties);
  vkGetPhysicalDeviceQueueFamilyProperties(device, &nProps, props);

  for (uint32_t q = 0; q < nProps; ++q) {
    if (props[q].queueFlags & VK_QUEUE_GRAPHICS_BIT) {
      VkBool32 supported = false;
      if ((r = vkGetPhysicalDeviceSurfaceSupportKHR(
             device, q, surface, &supported))) {
        free(props);
        return r;
      }

      if (supported) {
        *graphicsIndex = q;
        free(props);
        return VK_SUCCESS;
      }
    }
  }

  free(props);
  return VK_ERROR_FEATURE_NOT_PRESENT;
}

static bool
supportsRequiredExtensions(const VkPhysicalDevice device)
{
  uint32_t nExtProps = 0;
  vkEnumerateDeviceExtensionProperties(device, NULL, &nExtProps, NULL);

  VkExtensionProperties* extProps = AALLOC(nExtProps, VkExtensionProperties);
  vkEnumerateDeviceExtensionProperties(device, NULL, &nExtProps, extProps);

  for (uint32_t i = 0; i < nExtProps; ++i) {
    if (!strcmp(extProps[i].extensionName, VK_KHR_SWAPCHAIN_EXTENSION_NAME)) {
      free(extProps);
      return true;
    }
  }

  free(extProps);
  return false;
}

static bool
isDeviceSuitable(const VulkanState* const vk,
                 const VkPhysicalDevice   device,
                 uint32_t* const          graphicsIndex)
{
  if (!supportsRequiredExtensions(device) ||
      getGraphicsQueueIndex(vk->surface, device, graphicsIndex)) {
    return false;
  }

  return true;
}

/**
   Selects a physical graphics device.

   This doesn't try to be clever, and just selects the first suitable device.
*/
static VkResult
selectPhysicalDevice(VulkanState* const vk)
{
  VkResult vr = VK_SUCCESS;
  if (!vk->surface) {
    logError("Cannot select a physical device without a surface\n");
    return VK_ERROR_SURFACE_LOST_KHR;
  }

  uint32_t nDevices = 0;
  if ((vr = vkEnumeratePhysicalDevices(vk->instance, &nDevices, NULL))) {
    logError("Failed to get count of physical devices: %d\n", vr);
    return vr;
  }

  if (!nDevices) {
    logError("No physical devices found\n");
    return VK_ERROR_DEVICE_LOST;
  }

  VkPhysicalDevice* devices = AALLOC(nDevices, VkPhysicalDevice);
  if ((vr = vkEnumeratePhysicalDevices(vk->instance, &nDevices, devices))) {
    logError("Failed to enumerate physical devices: %d\n", vr);
    free(devices);
    return vr;
  }

  uint32_t i = 0;
  for (i = 0; i < nDevices; ++i) {
    VkPhysicalDeviceProperties deviceProps = {0};
    vkGetPhysicalDeviceProperties(devices[i], &deviceProps);

    uint32_t graphicsIndex = 0;
    if (isDeviceSuitable(vk, devices[i], &graphicsIndex)) {
      printf("Using device %u/%u:            \"%s\"\n",
             i + 1,
             nDevices,
             deviceProps.deviceName);
      vk->deviceProperties = deviceProps;
      vk->physicalDevice   = devices[i];
      vk->graphicsIndex    = graphicsIndex;
      printf("Using graphics queue family: %u\n", vk->graphicsIndex);
      break;
    }

    printf("Device \"%s\" not suitable\n", deviceProps.deviceName);
  }

  if (i >= nDevices) {
    logError("No suitable devices found\n");
    vr = VK_ERROR_DEVICE_LOST;
  }

  free(devices);
  return vr;
}

/// Opens the logical device and sets up the queue and command pool
static VkResult
openDevice(VulkanState* const vk)
{
  if (vk->device) {
    logError("Renderer already has an opened device\n");
    return VK_NOT_READY;
  }

  const float       graphicsQueuePriority = 1.0f;
  const char* const swapchainName         = VK_KHR_SWAPCHAIN_EXTENSION_NAME;

  const VkDeviceQueueCreateInfo queueCreateInfo = {
    VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO,
    NULL,
    0,
    vk->graphicsIndex,
    COUNTED(1, &graphicsQueuePriority),
  };

  const VkDeviceCreateInfo createInfo = {
    VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO,
    NULL,
    0,
    COUNTED(1, &queueCreateInfo),
    COUNTED(0, NULL),
    COUNTED(1, &swapchainName),
    NULL,
  };

  VkDevice device = NULL;
  VkResult vr     = VK_SUCCESS;
  if ((vr =
         vkCreateDevice(vk->physicalDevice, &createInfo, ALLOC_VK, &device))) {
    logError("Could not open device \"%s\": %d\n",
             vk->deviceProperties.deviceName,
             vr);
    return vr;
  }

  vk->device = device;
  vkGetDeviceQueue(vk->device, vk->graphicsIndex, 0, &vk->graphicsQueue);

  const VkCommandPoolCreateInfo commandInfo = {
    VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
    NULL,
    0,
    vk->graphicsIndex,
  };

  if ((vr = vkCreateCommandPool(
         vk->device, &commandInfo, ALLOC_VK, &vk->commandPool))) {
    logError("Could not create command pool: %d\n", vr);
    return vr;
  }

  return VK_SUCCESS;
}

static const char*
presentModeString(const VkPresentModeKHR presentMode)
{
  switch (presentMode) {
  case VK_PRESENT_MODE_IMMEDIATE_KHR:
    return "Immediate";
  case VK_PRESENT_MODE_MAILBOX_KHR:
    return "Mailbox";
  case VK_PRESENT_MODE_FIFO_KHR:
    return "FIFO";
  case VK_PRESENT_MODE_FIFO_RELAXED_KHR:
    return "FIFO relaxed";
  default:
    return "Other";
  }
}

static bool
hasPresentMode(const VkPresentModeKHR        mode,
               const VkPresentModeKHR* const presentModes,
               const uint32_t                nPresentModes)
{
  for (uint32_t i = 0; i < nPresentModes; ++i) {
    if (presentModes[i] == mode) {
      return true;
    }
  }

  return false;
}

/// Configure the surface for the currently opened device
static VkResult
configureSurface(VulkanState* const vk)
{
  uint32_t nFormats = 0;
  vkGetPhysicalDeviceSurfaceFormatsKHR(
    vk->physicalDevice, vk->surface, &nFormats, NULL);
  if (!nFormats) {
    logError("No surface formats available\n");
    return VK_ERROR_FORMAT_NOT_SUPPORTED;
  }

  VkSurfaceFormatKHR* surfaceFormats = AALLOC(nFormats, VkSurfaceFormatKHR);
  vkGetPhysicalDeviceSurfaceFormatsKHR(
    vk->physicalDevice, vk->surface, &nFormats, surfaceFormats);

  const VkSurfaceFormatKHR want = {VK_FORMAT_B8G8R8A8_UNORM,
                                   VK_COLOR_SPACE_SRGB_NONLINEAR_KHR};

  uint32_t formatIndex = 0;
  for (formatIndex = 0; formatIndex < nFormats; ++formatIndex) {
    if (surfaceFormats[formatIndex].format == want.format &&
        surfaceFormats[formatIndex].colorSpace == want.colorSpace) {
      vk->surfaceFormat = want;
      break;
    }
  }
  free(surfaceFormats);
  if (formatIndex >= nFormats) {
    logError("Could not find a suitable surface format\n");
    return VK_ERROR_FORMAT_NOT_SUPPORTED;
  }

  uint32_t nPresentModes = 0;
  vkGetPhysicalDeviceSurfacePresentModesKHR(
    vk->physicalDevice, vk->surface, &nPresentModes, NULL);
  if (!nPresentModes) {
    logError("No present modes available\n");
    return VK_ERROR_FORMAT_NOT_SUPPORTED;
  }

  VkPresentModeKHR* presentModes = AALLOC(nPresentModes, VkPresentModeKHR);
  vkGetPhysicalDeviceSurfacePresentModesKHR(
    vk->physicalDevice, vk->surface, &nPresentModes, presentModes);

  const VkPresentModeKHR tryModes[] = {
    VK_PRESENT_MODE_MAILBOX_KHR,
    VK_PRESENT_MODE_FIFO_RELAXED_KHR,
    VK_PRESENT_MODE_FIFO_KHR,
    VK_PRESENT_MODE_IMMEDIATE_KHR,
  };

  VkPresentModeKHR presentMode = VK_PRESENT_MODE_FIFO_KHR;
  for (uint32_t i = 0; i < sizeof(tryModes) / sizeof(VkPresentModeKHR); ++i) {
    if (hasPresentMode(tryModes[i], presentModes, nPresentModes)) {
      presentMode = tryModes[i];
      break;
    }
  }

  free(presentModes);
  vk->presentMode = presentMode;
  printf("Using present mode:          \"%s\" (%u)\n",
         presentModeString(presentMode),
         presentMode);

  return VK_SUCCESS;
}

static VkResult
createRawSwapchain(VulkanState* const vk,
                   const uint32_t     width,
                   const uint32_t     height)
{
  VkSurfaceCapabilitiesKHR surfaceCapabilities;
  VkResult                 vr = VK_SUCCESS;
  if ((vr = vkGetPhysicalDeviceSurfaceCapabilitiesKHR(
         vk->physicalDevice, vk->surface, &surfaceCapabilities))) {
    logError("Could not get surface capabilities: %d\n", vr);
    return vr;
  }

  /* There is a known race condition with window/surface sizes, so we clamp
     to what Vulkan reports and hope for the best. */

  vk->swapchain->extent.width = CLAMP(width,
                                      surfaceCapabilities.minImageExtent.width,
                                      surfaceCapabilities.maxImageExtent.width);

  vk->swapchain->extent.height =
    CLAMP(height,
          surfaceCapabilities.minImageExtent.height,
          surfaceCapabilities.maxImageExtent.height);

  vk->swapchain->nImages = surfaceCapabilities.minImageCount;

  const VkSwapchainCreateInfoKHR createInfo = {
    VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR,
    NULL,
    0,
    vk->surface,
    vk->swapchain->nImages,
    vk->surfaceFormat.format,
    VK_COLOR_SPACE_SRGB_NONLINEAR_KHR,
    vk->swapchain->extent,
    1,
    (VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT),
    VK_SHARING_MODE_EXCLUSIVE,
    COUNTED(0, NULL),
    surfaceCapabilities.currentTransform,
    VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR,
    vk->presentMode,
    VK_TRUE,
    0,
  };

  if ((vr = vkCreateSwapchainKHR(
         vk->device, &createInfo, ALLOC_VK, &vk->swapchain->rawSwapchain))) {
    logError("Could not create swapchain: %d\n", vr);
    return vr;
  }

  return VK_SUCCESS;
}

static VkResult
recordCommandBuffers(VulkanState* const vk)
{
  const VkClearColorValue clearValue = {{
    0xA4 / (float)0x100, // R
    0x1E / (float)0x100, // G
    0x22 / (float)0x100, // B
    0xFF / (float)0x100, // A
  }};

  const VkImageSubresourceRange range = {
    VK_IMAGE_ASPECT_COLOR_BIT,
    0,
    1,
    0,
    1,
  };

  const VkCommandBufferBeginInfo beginInfo = {
    VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
    NULL,
    VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT,
    NULL,
  };

  for (uint32_t i = 0; i < vk->swapchain->nImages; ++i) {
    const VkImageMemoryBarrier toClearBarrier = {
      VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
      NULL,
      VK_ACCESS_MEMORY_READ_BIT,
      VK_ACCESS_TRANSFER_WRITE_BIT,
      VK_IMAGE_LAYOUT_UNDEFINED,
      VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
      vk->graphicsIndex,
      vk->graphicsIndex,
      vk->swapchain->images[i],
      range,
    };

    const VkImageMemoryBarrier toPresentBarrier = {
      VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
      NULL,
      VK_ACCESS_TRANSFER_WRITE_BIT,
      VK_ACCESS_MEMORY_READ_BIT,
      VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
      VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
      vk->graphicsIndex,
      vk->graphicsIndex,
      vk->swapchain->images[i],
      range,
    };

    vkBeginCommandBuffer(vk->swapchain->commandBuffers[i], &beginInfo);

    vkCmdPipelineBarrier(vk->swapchain->commandBuffers[i],
                         VK_PIPELINE_STAGE_TRANSFER_BIT,
                         VK_PIPELINE_STAGE_TRANSFER_BIT,
                         0,
                         COUNTED(0, NULL),
                         COUNTED(0, NULL),
                         COUNTED(1, &toClearBarrier));

    vkCmdClearColorImage(vk->swapchain->commandBuffers[i],
                         vk->swapchain->images[i],
                         VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
                         &clearValue,
                         COUNTED(1, &range));

    vkCmdPipelineBarrier(vk->swapchain->commandBuffers[i],
                         VK_PIPELINE_STAGE_TRANSFER_BIT,
                         VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
                         0,
                         COUNTED(0, NULL),
                         COUNTED(0, NULL),
                         COUNTED(1, &toPresentBarrier));

    vkEndCommandBuffer(vk->swapchain->commandBuffers[i]);
  }

  return VK_SUCCESS;
}

static VkResult
createSwapchain(VulkanState* const vk,
                const uint32_t     width,
                const uint32_t     height)
{
  VkResult vr = VK_SUCCESS;

  vk->swapchain = AALLOC(1, Swapchain);
  if ((vr = createRawSwapchain(vk, width, height))) {
    return vr;
  }

  if ((vr = vkGetSwapchainImagesKHR(vk->device,
                                    vk->swapchain->rawSwapchain,
                                    &vk->swapchain->nImages,
                                    NULL))) {
    logError("Failed to query swapchain images: %d\n", vr);
    return vr;
  }

  vk->swapchain->images = AALLOC(vk->swapchain->nImages, VkImage);
  if ((vr = vkGetSwapchainImagesKHR(vk->device,
                                    vk->swapchain->rawSwapchain,
                                    &vk->swapchain->nImages,
                                    vk->swapchain->images))) {
    logError("Failed to get swapchain images: %d\n", vr);
    return vr;
  }

  const VkCommandBufferAllocateInfo allocInfo = {
    VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
    NULL,
    vk->commandPool,
    VK_COMMAND_BUFFER_LEVEL_PRIMARY,
    vk->swapchain->nImages,
  };

  vk->swapchain->commandBuffers =
    AALLOC(vk->swapchain->nImages, VkCommandBuffer);

  if ((vr = vkAllocateCommandBuffers(
         vk->device, &allocInfo, vk->swapchain->commandBuffers))) {
    logError("Could not allocate command buffers: %d\n", vr);
    return vr;
  }

  const VkFenceCreateInfo fenceInfo = {
    VK_STRUCTURE_TYPE_FENCE_CREATE_INFO,
    NULL,
    VK_FENCE_CREATE_SIGNALED_BIT,
  };
  vk->swapchain->fences = AALLOC(vk->swapchain->nImages, VkFence);

  for (uint32_t i = 0; i < vk->swapchain->nImages; ++i) {
    if ((vr = vkCreateFence(
           vk->device, &fenceInfo, ALLOC_VK, &vk->swapchain->fences[i]))) {
      logError("Could not create render finished fence: %d\n", vr);
      return vr;
    }
  }

  if ((vr = recordCommandBuffers(vk))) {
    logError("Failed to record command buffers\n");
    return vr;
  }

  return VK_SUCCESS;
}

static void
destroySwapchain(VulkanState* const vk, Swapchain* const swapchain)
{
  if (!swapchain) {
    return;
  }

  for (uint32_t i = 0; i < swapchain->nImages; ++i) {
    if (swapchain->fences[i]) {
      vkDestroyFence(vk->device, swapchain->fences[i], ALLOC_VK);
    }

    if (swapchain->imageViews && swapchain->imageViews[i]) {
      vkDestroyImageView(vk->device, swapchain->imageViews[i], ALLOC_VK);
    }
  }

  free(swapchain->fences);
  swapchain->fences = NULL;
  free(swapchain->imageViews);
  swapchain->imageViews = NULL;

  if (swapchain->images) {
    free(swapchain->images);
    swapchain->images = NULL;
  }

  if (swapchain->commandBuffers) {
    vkFreeCommandBuffers(vk->device,
                         vk->commandPool,
                         swapchain->nImages,
                         swapchain->commandBuffers);
    free(swapchain->commandBuffers);
  }

  if (swapchain->rawSwapchain) {
    vkDestroySwapchainKHR(vk->device, swapchain->rawSwapchain, ALLOC_VK);
  }

  free(swapchain);
}

static VkResult
createSyncObjects(VulkanState* const vk)
{
  const VkSemaphoreCreateInfo info = {
    VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
    NULL,
    0,
  };

  vkCreateSemaphore(vk->device, &info, ALLOC_VK, &vk->sync.presentComplete);
  vkCreateSemaphore(vk->device, &info, ALLOC_VK, &vk->sync.renderFinished);
  return VK_SUCCESS;
}

static void
destroySyncObjects(VulkanState* const vk)
{
  if (vk->sync.renderFinished) {
    vkDestroySemaphore(vk->device, vk->sync.renderFinished, ALLOC_VK);
    vk->sync.renderFinished = VK_NULL_HANDLE;
  }
  if (vk->sync.presentComplete) {
    vkDestroySemaphore(vk->device, vk->sync.presentComplete, ALLOC_VK);
    vk->sync.presentComplete = VK_NULL_HANDLE;
  }
}

static void
closeDevice(VulkanState* const vk)
{
  if (vk->device) {
    vkDeviceWaitIdle(vk->device);
    destroySyncObjects(vk);
    destroySwapchain(vk, vk->swapchain);
    if (vk->commandPool) {
      vkDestroyCommandPool(vk->device, vk->commandPool, ALLOC_VK);
      vk->commandPool = VK_NULL_HANDLE;
    }
    vk->graphicsQueue = VK_NULL_HANDLE;
    vkDestroyDevice(vk->device, ALLOC_VK);
    vk->device = VK_NULL_HANDLE;
  }
}

static void
destroyWorld(VulkanApp* const app)
{
  VulkanState* vk = &app->vk;

  if (vk) {
    closeDevice(vk);

    if (app->view) {
      puglHide(app->view);
      puglFreeView(app->view);
      app->view = NULL;
    }
    if (vk->debugCallback && vk->api.vkDestroyDebugReportCallbackEXT) {
      vk->api.vkDestroyDebugReportCallbackEXT(
        vk->instance, vk->debugCallback, ALLOC_VK);
      vk->debugCallback = VK_NULL_HANDLE;
    }
    if (vk->surface) {
      vkDestroySurfaceKHR(vk->instance, vk->surface, ALLOC_VK);
      vk->surface = VK_NULL_HANDLE;
    }
    if (vk->instance) {
      fflush(stderr);
      vkDestroyInstance(vk->instance, ALLOC_VK);
      vk->instance = VK_NULL_HANDLE;
    }
    if (app->world) {
      puglFreeWorld(app->world);
      app->world = NULL;
    }
  }
}

static PuglStatus
onConfigure(PuglView* const view, const double width, const double height)
{
  VulkanApp* const app = (VulkanApp*)puglGetHandle(view);

  // We just record the size here and lazily resize the surface when exposed
  app->width  = (uint32_t)width;
  app->height = (uint32_t)height;

  return PUGL_SUCCESS;
}

static PuglStatus
recreateSwapchain(VulkanState* const vk,
                  const uint32_t     width,
                  const uint32_t     height)
{
  vkDeviceWaitIdle(vk->device);
  destroySwapchain(vk, vk->swapchain);

  if (createSwapchain(vk, width, height)) {
    logError("Failed to recreate swapchain\n");
    return PUGL_UNKNOWN_ERROR;
  }

  return PUGL_SUCCESS;
}

static PuglStatus
onExpose(PuglView* const view)
{
  VulkanApp*   app        = (VulkanApp*)puglGetHandle(view);
  VulkanState* vk         = &app->vk;
  uint32_t     imageIndex = 0;
  VkResult     result     = VK_SUCCESS;

  // Recreate swapchain if the window size has changed
  const Swapchain* swapchain = vk->swapchain;
  if (swapchain->extent.width != app->width ||
      swapchain->extent.height != app->height) {
    recreateSwapchain(vk, app->width, app->height);
  }

  // Acquire the next image to render, rebuilding if necessary
  while ((result = vkAcquireNextImageKHR(vk->device,
                                         vk->swapchain->rawSwapchain,
                                         UINT64_MAX,
                                         vk->sync.presentComplete,
                                         VK_NULL_HANDLE,
                                         &imageIndex))) {
    switch (result) {
    case VK_SUCCESS:
      break;
    case VK_SUBOPTIMAL_KHR:
    case VK_ERROR_OUT_OF_DATE_KHR:
      recreateSwapchain(vk, app->width, app->height);
      continue;
    default:
      logError("Could not acquire swapchain image: %d\n", result);
      return PUGL_UNKNOWN_ERROR;
    }
  }

  // Wait until we can start rendering this frame
  vkWaitForFences(vk->device,
                  COUNTED(1, &vk->swapchain->fences[imageIndex]),
                  VK_TRUE,
                  UINT64_MAX);
  vkResetFences(vk->device, 1, &vk->swapchain->fences[imageIndex]);

  const VkPipelineStageFlags waitStage = VK_PIPELINE_STAGE_TRANSFER_BIT;

  // Submit command buffer to render this frame
  const VkSubmitInfo submitInfo = {
    VK_STRUCTURE_TYPE_SUBMIT_INFO,
    NULL,
    COUNTED(1, &vk->sync.presentComplete),
    &waitStage,
    COUNTED(1, &vk->swapchain->commandBuffers[imageIndex]),
    COUNTED(1, &vk->sync.renderFinished)};
  if ((result = vkQueueSubmit(vk->graphicsQueue,
                              1,
                              &submitInfo,
                              vk->swapchain->fences[imageIndex]))) {
    logError("Could not submit to queue: %d\n", result);
    return PUGL_FAILURE;
  }

  // Present this frame
  const VkPresentInfoKHR presentInfo = {
    VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
    NULL,
    COUNTED(1, &vk->sync.renderFinished),
    COUNTED(1, &vk->swapchain->rawSwapchain, &imageIndex, NULL),
  };
  if ((result = vkQueuePresentKHR(vk->graphicsQueue, &presentInfo))) {
    logError("Could not present image: %d\n", result);
  }

  if (app->opts.continuous) {
    ++app->framesDrawn;
  }

  return PUGL_SUCCESS;
}

static PuglStatus
onEvent(PuglView* const view, const PuglEvent* const e)
{
  VulkanApp* const app = (VulkanApp*)puglGetHandle(view);

  printEvent(e, "Event: ", app->opts.verbose);

  switch (e->type) {
  case PUGL_EXPOSE:
    return onExpose(view);
  case PUGL_CONFIGURE:
    return onConfigure(view, e->configure.width, e->configure.height);
  case PUGL_CLOSE:
    app->quit = 1;
    break;
  case PUGL_KEY_PRESS:
    switch (e->key.key) {
    case PUGL_KEY_ESCAPE:
    case 'q':
      app->quit = 1;
      break;
    }
    break;
  default:
    break;
  }
  return PUGL_SUCCESS;
}

int
main(int argc, char** argv)
{
  VulkanApp      app           = {0};
  VulkanState*   vk            = &app.vk;
  const uint32_t defaultWidth  = 640;
  const uint32_t defaultHeight = 360;
  const PuglRect frame         = {0, 0, defaultWidth, defaultHeight};

  // Parse command line options
  app.opts = puglParseTestOptions(&argc, &argv);
  if (app.opts.help) {
    puglPrintTestUsage(argv[0], "");
    return 0;
  }

  // Create world and view
  if (!(app.world = puglNewWorld(PUGL_PROGRAM, PUGL_WORLD_THREADS))) {
    return logError("Failed to create world\n");
  }

  if (!(app.view = puglNewView(app.world))) {
    puglFreeWorld(app.world);
    return logError("Failed to create Pugl World and View\n");
  }

  // Create Vulkan instance
  if (createInstance(&app)) {
    puglFreeWorld(app.world);
    return logError("Failed to create instance\n");
  }

  // Create window
  puglSetWindowTitle(app.view, "Pugl Vulkan");
  puglSetFrame(app.view, frame);
  puglSetHandle(app.view, &app);
  puglSetBackend(app.view, puglVulkanBackend());
  puglSetViewHint(app.view, PUGL_RESIZABLE, app.opts.resizable);
  puglSetEventFunc(app.view, onEvent);
  const PuglStatus st = puglRealize(app.view);
  if (st) {
    puglFreeWorld(app.world);
    puglFreeView(app.view);
    return logError("Failed to create window (%s)\n", puglStrerror(st));
  }

  // Create Vulkan surface for Window
  PuglVulkanLoader* loader = puglNewVulkanLoader(app.world);
  if (puglCreateSurface(puglGetInstanceProcAddrFunc(loader),
                        app.view,
                        vk->instance,
                        ALLOC_VK,
                        &vk->surface)) {
    return logError("Failed to create surface\n");
  }

  // Set up Vulkan
  VkResult vr = VK_SUCCESS;
  if ((vr = enableDebugging(vk)) ||                              //
      (vr = selectPhysicalDevice(vk)) ||                         //
      (vr = openDevice(vk)) ||                                   //
      (vr = configureSurface(vk)) ||                             //
      (vr = createSwapchain(vk, defaultWidth, defaultHeight)) || //
      (vr = createSyncObjects(vk))) {
    destroyWorld(&app);
    return logError("Failed to set up graphics (%d)\n", vr);
  }

  printf("Swapchain images:            %u\n", app.vk.swapchain->nImages);

  PuglFpsPrinter fpsPrinter = {puglGetTime(app.world)};
  puglShow(app.view);
  while (!app.quit) {
    puglUpdate(app.world, -1.0);

    if (app.opts.continuous) {
      puglPrintFps(app.world, &fpsPrinter, &app.framesDrawn);
    }
  }

  destroyWorld(&app);
  return 0;
}